9e069fd05baf1b11c613217a86586b3a12111e87
[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/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ConstantRange.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     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
240                                    bool DoXform = true);
241
242   public:
243     // InsertNewInstBefore - insert an instruction New before instruction Old
244     // in the program.  Add the new instruction to the worklist.
245     //
246     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
247       assert(New && New->getParent() == 0 &&
248              "New instruction already inserted into a basic block!");
249       BasicBlock *BB = Old.getParent();
250       BB->getInstList().insert(&Old, New);  // Insert inst
251       AddToWorkList(New);
252       return New;
253     }
254
255     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
256     /// This also adds the cast to the worklist.  Finally, this returns the
257     /// cast.
258     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
259                             Instruction &Pos) {
260       if (V->getType() == Ty) return V;
261
262       if (Constant *CV = dyn_cast<Constant>(V))
263         return ConstantExpr::getCast(opc, CV, Ty);
264       
265       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
266       AddToWorkList(C);
267       return C;
268     }
269         
270     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
271       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
272     }
273
274
275     // ReplaceInstUsesWith - This method is to be used when an instruction is
276     // found to be dead, replacable with another preexisting expression.  Here
277     // we add all uses of I to the worklist, replace all uses of I with the new
278     // value, then return I, so that the inst combiner will know that I was
279     // modified.
280     //
281     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
282       AddUsersToWorkList(I);         // Add all modified instrs to worklist
283       if (&I != V) {
284         I.replaceAllUsesWith(V);
285         return &I;
286       } else {
287         // If we are replacing the instruction with itself, this must be in a
288         // segment of unreachable code, so just clobber the instruction.
289         I.replaceAllUsesWith(UndefValue::get(I.getType()));
290         return &I;
291       }
292     }
293
294     // UpdateValueUsesWith - This method is to be used when an value is
295     // found to be replacable with another preexisting expression or was
296     // updated.  Here we add all uses of I to the worklist, replace all uses of
297     // I with the new value (unless the instruction was just updated), then
298     // return true, so that the inst combiner will know that I was modified.
299     //
300     bool UpdateValueUsesWith(Value *Old, Value *New) {
301       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
302       if (Old != New)
303         Old->replaceAllUsesWith(New);
304       if (Instruction *I = dyn_cast<Instruction>(Old))
305         AddToWorkList(I);
306       if (Instruction *I = dyn_cast<Instruction>(New))
307         AddToWorkList(I);
308       return true;
309     }
310     
311     // EraseInstFromFunction - When dealing with an instruction that has side
312     // effects or produces a void value, we can't rely on DCE to delete the
313     // instruction.  Instead, visit methods should return the value returned by
314     // this function.
315     Instruction *EraseInstFromFunction(Instruction &I) {
316       assert(I.use_empty() && "Cannot erase instruction that is used!");
317       AddUsesToWorkList(I);
318       RemoveFromWorkList(&I);
319       I.eraseFromParent();
320       return 0;  // Don't do anything with FI
321     }
322
323   private:
324     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
325     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
326     /// casts that are known to not do anything...
327     ///
328     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
329                                    Value *V, const Type *DestTy,
330                                    Instruction *InsertBefore);
331
332     /// SimplifyCommutative - This performs a few simplifications for 
333     /// commutative operators.
334     bool SimplifyCommutative(BinaryOperator &I);
335
336     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
337     /// most-complex to least-complex order.
338     bool SimplifyCompare(CmpInst &I);
339
340     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
341     /// on the demanded bits.
342     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
343                               APInt& KnownZero, APInt& KnownOne,
344                               unsigned Depth = 0);
345
346     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
347                                       uint64_t &UndefElts, unsigned Depth = 0);
348       
349     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
350     // PHI node as operand #0, see if we can fold the instruction into the PHI
351     // (which is only possible if all operands to the PHI are constants).
352     Instruction *FoldOpIntoPhi(Instruction &I);
353
354     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
355     // operator and they all are only used by the PHI, PHI together their
356     // inputs, and do the operation once, to the result of the PHI.
357     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
358     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
359     
360     
361     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
362                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
363     
364     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
365                               bool isSub, Instruction &I);
366     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
367                                  bool isSigned, bool Inside, Instruction &IB);
368     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
369     Instruction *MatchBSwap(BinaryOperator &I);
370     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
371     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
372
373
374     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
375   };
376
377   char InstCombiner::ID = 0;
378   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
379 }
380
381 // getComplexity:  Assign a complexity or rank value to LLVM Values...
382 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
383 static unsigned getComplexity(Value *V) {
384   if (isa<Instruction>(V)) {
385     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
386       return 3;
387     return 4;
388   }
389   if (isa<Argument>(V)) return 3;
390   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
391 }
392
393 // isOnlyUse - Return true if this instruction will be deleted if we stop using
394 // it.
395 static bool isOnlyUse(Value *V) {
396   return V->hasOneUse() || isa<Constant>(V);
397 }
398
399 // getPromotedType - Return the specified type promoted as it would be to pass
400 // though a va_arg area...
401 static const Type *getPromotedType(const Type *Ty) {
402   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
403     if (ITy->getBitWidth() < 32)
404       return Type::Int32Ty;
405   }
406   return Ty;
407 }
408
409 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
410 /// expression bitcast,  return the operand value, otherwise return null.
411 static Value *getBitCastOperand(Value *V) {
412   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
413     return I->getOperand(0);
414   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
415     if (CE->getOpcode() == Instruction::BitCast)
416       return CE->getOperand(0);
417   return 0;
418 }
419
420 /// This function is a wrapper around CastInst::isEliminableCastPair. It
421 /// simply extracts arguments and returns what that function returns.
422 static Instruction::CastOps 
423 isEliminableCastPair(
424   const CastInst *CI, ///< The first cast instruction
425   unsigned opcode,       ///< The opcode of the second cast instruction
426   const Type *DstTy,     ///< The target type for the second cast instruction
427   TargetData *TD         ///< The target data for pointer size
428 ) {
429   
430   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
431   const Type *MidTy = CI->getType();                  // B from above
432
433   // Get the opcodes of the two Cast instructions
434   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
435   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
436
437   return Instruction::CastOps(
438       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
439                                      DstTy, TD->getIntPtrType()));
440 }
441
442 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443 /// in any code being generated.  It does not require codegen if V is simple
444 /// enough or if the cast can be folded into other casts.
445 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
446                               const Type *Ty, TargetData *TD) {
447   if (V->getType() == Ty || isa<Constant>(V)) return false;
448   
449   // If this is another cast that can be eliminated, it isn't codegen either.
450   if (const CastInst *CI = dyn_cast<CastInst>(V))
451     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
452       return false;
453   return true;
454 }
455
456 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
457 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
458 /// casts that are known to not do anything...
459 ///
460 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
461                                              Value *V, const Type *DestTy,
462                                              Instruction *InsertBefore) {
463   if (V->getType() == DestTy) return V;
464   if (Constant *C = dyn_cast<Constant>(V))
465     return ConstantExpr::getCast(opcode, C, DestTy);
466   
467   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
468 }
469
470 // SimplifyCommutative - This performs a few simplifications for commutative
471 // operators:
472 //
473 //  1. Order operands such that they are listed from right (least complex) to
474 //     left (most complex).  This puts constants before unary operators before
475 //     binary operators.
476 //
477 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
478 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
479 //
480 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
481   bool Changed = false;
482   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
483     Changed = !I.swapOperands();
484
485   if (!I.isAssociative()) return Changed;
486   Instruction::BinaryOps Opcode = I.getOpcode();
487   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
488     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
489       if (isa<Constant>(I.getOperand(1))) {
490         Constant *Folded = ConstantExpr::get(I.getOpcode(),
491                                              cast<Constant>(I.getOperand(1)),
492                                              cast<Constant>(Op->getOperand(1)));
493         I.setOperand(0, Op->getOperand(0));
494         I.setOperand(1, Folded);
495         return true;
496       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
497         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
498             isOnlyUse(Op) && isOnlyUse(Op1)) {
499           Constant *C1 = cast<Constant>(Op->getOperand(1));
500           Constant *C2 = cast<Constant>(Op1->getOperand(1));
501
502           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
503           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
504           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
505                                                     Op1->getOperand(0),
506                                                     Op1->getName(), &I);
507           AddToWorkList(New);
508           I.setOperand(0, New);
509           I.setOperand(1, Folded);
510           return true;
511         }
512     }
513   return Changed;
514 }
515
516 /// SimplifyCompare - For a CmpInst this function just orders the operands
517 /// so that theyare listed from right (least complex) to left (most complex).
518 /// This puts constants before unary operators before binary operators.
519 bool InstCombiner::SimplifyCompare(CmpInst &I) {
520   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
521     return false;
522   I.swapOperands();
523   // Compare instructions are not associative so there's nothing else we can do.
524   return true;
525 }
526
527 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
528 // if the LHS is a constant zero (which is the 'negate' form).
529 //
530 static inline Value *dyn_castNegVal(Value *V) {
531   if (BinaryOperator::isNeg(V))
532     return BinaryOperator::getNegArgument(V);
533
534   // Constants can be considered to be negated values if they can be folded.
535   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
536     return ConstantExpr::getNeg(C);
537   return 0;
538 }
539
540 static inline Value *dyn_castNotVal(Value *V) {
541   if (BinaryOperator::isNot(V))
542     return BinaryOperator::getNotArgument(V);
543
544   // Constants can be considered to be not'ed values...
545   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
546     return ConstantInt::get(~C->getValue());
547   return 0;
548 }
549
550 // dyn_castFoldableMul - If this value is a multiply that can be folded into
551 // other computations (because it has a constant operand), return the
552 // non-constant operand of the multiply, and set CST to point to the multiplier.
553 // Otherwise, return null.
554 //
555 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
556   if (V->hasOneUse() && V->getType()->isInteger())
557     if (Instruction *I = dyn_cast<Instruction>(V)) {
558       if (I->getOpcode() == Instruction::Mul)
559         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
560           return I->getOperand(0);
561       if (I->getOpcode() == Instruction::Shl)
562         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
563           // The multiplier is really 1 << CST.
564           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
565           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
566           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
567           return I->getOperand(0);
568         }
569     }
570   return 0;
571 }
572
573 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
574 /// expression, return it.
575 static User *dyn_castGetElementPtr(Value *V) {
576   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
577   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
578     if (CE->getOpcode() == Instruction::GetElementPtr)
579       return cast<User>(V);
580   return false;
581 }
582
583 /// AddOne - Add one to a ConstantInt
584 static ConstantInt *AddOne(ConstantInt *C) {
585   APInt Val(C->getValue());
586   return ConstantInt::get(++Val);
587 }
588 /// SubOne - Subtract one from a ConstantInt
589 static ConstantInt *SubOne(ConstantInt *C) {
590   APInt Val(C->getValue());
591   return ConstantInt::get(--Val);
592 }
593 /// Add - Add two ConstantInts together
594 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
595   return ConstantInt::get(C1->getValue() + C2->getValue());
596 }
597 /// And - Bitwise AND two ConstantInts together
598 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
599   return ConstantInt::get(C1->getValue() & C2->getValue());
600 }
601 /// Subtract - Subtract one ConstantInt from another
602 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
603   return ConstantInt::get(C1->getValue() - C2->getValue());
604 }
605 /// Multiply - Multiply two ConstantInts together
606 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
607   return ConstantInt::get(C1->getValue() * C2->getValue());
608 }
609 /// MultiplyOverflows - True if the multiply can not be expressed in an int
610 /// this size.
611 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
612   uint32_t W = C1->getBitWidth();
613   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
614   if (sign) {
615     LHSExt.sext(W * 2);
616     RHSExt.sext(W * 2);
617   } else {
618     LHSExt.zext(W * 2);
619     RHSExt.zext(W * 2);
620   }
621
622   APInt MulExt = LHSExt * RHSExt;
623
624   if (sign) {
625     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
626     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
627     return MulExt.slt(Min) || MulExt.sgt(Max);
628   } else 
629     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
630 }
631
632 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
633 /// known to be either zero or one and return them in the KnownZero/KnownOne
634 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
635 /// processing.
636 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
637 /// we cannot optimize based on the assumption that it is zero without changing
638 /// it to be an explicit zero.  If we don't change it to zero, other code could
639 /// optimized based on the contradictory assumption that it is non-zero.
640 /// Because instcombine aggressively folds operations with undef args anyway,
641 /// this won't lose us code quality.
642 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
643                               APInt& KnownOne, unsigned Depth = 0) {
644   assert(V && "No Value?");
645   assert(Depth <= 6 && "Limit Search Depth");
646   uint32_t BitWidth = Mask.getBitWidth();
647   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
648          KnownZero.getBitWidth() == BitWidth && 
649          KnownOne.getBitWidth() == BitWidth &&
650          "V, Mask, KnownOne and KnownZero should have same BitWidth");
651   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
652     // We know all of the bits for a constant!
653     KnownOne = CI->getValue() & Mask;
654     KnownZero = ~KnownOne & Mask;
655     return;
656   }
657
658   if (Depth == 6 || Mask == 0)
659     return;  // Limit search depth.
660
661   Instruction *I = dyn_cast<Instruction>(V);
662   if (!I) return;
663
664   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
665   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
666   
667   switch (I->getOpcode()) {
668   case Instruction::And: {
669     // If either the LHS or the RHS are Zero, the result is zero.
670     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
671     APInt Mask2(Mask & ~KnownZero);
672     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
673     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
674     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
675     
676     // Output known-1 bits are only known if set in both the LHS & RHS.
677     KnownOne &= KnownOne2;
678     // Output known-0 are known to be clear if zero in either the LHS | RHS.
679     KnownZero |= KnownZero2;
680     return;
681   }
682   case Instruction::Or: {
683     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
684     APInt Mask2(Mask & ~KnownOne);
685     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
686     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
687     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
688     
689     // Output known-0 bits are only known if clear in both the LHS & RHS.
690     KnownZero &= KnownZero2;
691     // Output known-1 are known to be set if set in either the LHS | RHS.
692     KnownOne |= KnownOne2;
693     return;
694   }
695   case Instruction::Xor: {
696     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
697     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
698     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
699     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
700     
701     // Output known-0 bits are known if clear or set in both the LHS & RHS.
702     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
703     // Output known-1 are known to be set if set in only one of the LHS, RHS.
704     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
705     KnownZero = KnownZeroOut;
706     return;
707   }
708   case Instruction::Select:
709     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
710     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
711     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
712     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
713
714     // Only known if known in both the LHS and RHS.
715     KnownOne &= KnownOne2;
716     KnownZero &= KnownZero2;
717     return;
718   case Instruction::FPTrunc:
719   case Instruction::FPExt:
720   case Instruction::FPToUI:
721   case Instruction::FPToSI:
722   case Instruction::SIToFP:
723   case Instruction::PtrToInt:
724   case Instruction::UIToFP:
725   case Instruction::IntToPtr:
726     return; // Can't work with floating point or pointers
727   case Instruction::Trunc: {
728     // All these have integer operands
729     uint32_t SrcBitWidth = 
730       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
731     APInt MaskIn(Mask);
732     MaskIn.zext(SrcBitWidth);
733     KnownZero.zext(SrcBitWidth);
734     KnownOne.zext(SrcBitWidth);
735     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
736     KnownZero.trunc(BitWidth);
737     KnownOne.trunc(BitWidth);
738     return;
739   }
740   case Instruction::BitCast: {
741     const Type *SrcTy = I->getOperand(0)->getType();
742     if (SrcTy->isInteger()) {
743       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
744       return;
745     }
746     break;
747   }
748   case Instruction::ZExt:  {
749     // Compute the bits in the result that are not present in the input.
750     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
751     uint32_t SrcBitWidth = SrcTy->getBitWidth();
752       
753     APInt MaskIn(Mask);
754     MaskIn.trunc(SrcBitWidth);
755     KnownZero.trunc(SrcBitWidth);
756     KnownOne.trunc(SrcBitWidth);
757     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
758     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
759     // The top bits are known to be zero.
760     KnownZero.zext(BitWidth);
761     KnownOne.zext(BitWidth);
762     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
763     return;
764   }
765   case Instruction::SExt: {
766     // Compute the bits in the result that are not present in the input.
767     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
768     uint32_t SrcBitWidth = SrcTy->getBitWidth();
769       
770     APInt MaskIn(Mask); 
771     MaskIn.trunc(SrcBitWidth);
772     KnownZero.trunc(SrcBitWidth);
773     KnownOne.trunc(SrcBitWidth);
774     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
775     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
776     KnownZero.zext(BitWidth);
777     KnownOne.zext(BitWidth);
778
779     // If the sign bit of the input is known set or clear, then we know the
780     // top bits of the result.
781     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
782       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
783     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
784       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
785     return;
786   }
787   case Instruction::Shl:
788     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
789     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
790       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
791       APInt Mask2(Mask.lshr(ShiftAmt));
792       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
793       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
794       KnownZero <<= ShiftAmt;
795       KnownOne  <<= ShiftAmt;
796       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
797       return;
798     }
799     break;
800   case Instruction::LShr:
801     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
802     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
803       // Compute the new bits that are at the top now.
804       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
805       
806       // Unsigned shift right.
807       APInt Mask2(Mask.shl(ShiftAmt));
808       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
809       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
810       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
811       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
812       // high bits known zero.
813       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
814       return;
815     }
816     break;
817   case Instruction::AShr:
818     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
819     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
820       // Compute the new bits that are at the top now.
821       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
822       
823       // Signed shift right.
824       APInt Mask2(Mask.shl(ShiftAmt));
825       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
826       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
827       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
828       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
829         
830       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
831       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
832         KnownZero |= HighBits;
833       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
834         KnownOne |= HighBits;
835       return;
836     }
837     break;
838   case Instruction::Add: {
839     // If either the LHS or the RHS are Zero, the result is zero.
840     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
841     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
842     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
843     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
844       
845     // Output known-0 bits are known if clear or set in both the low clear bits
846     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
847     // low 3 bits clear.
848     unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(), 
849                                      KnownZero2.countTrailingOnes());
850       
851     KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
852     KnownOne = APInt(BitWidth, 0);
853     return;
854   }
855   case Instruction::Sub: {
856     ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0));
857     if (!CLHS) break;
858         
859     // We know that the top bits of C-X are clear if X contains less bits
860     // than C (i.e. no wrap-around can happen).  For example, 20-X is
861     // positive if we can prove that X is >= 0 and < 16.
862     if (CLHS->getValue().isNegative())
863       break;
864     
865     unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
866     // NLZ can't be BitWidth with no sign bit
867     APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
868     ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
869     
870     // If all of the MaskV bits are known to be zero, then we know the output
871     // top bits are zero, because we now know that the output is from [0-C].
872     if ((KnownZero & MaskV) == MaskV) {
873       unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
874       // Top bits known zero.
875       KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
876       KnownOne = APInt(BitWidth, 0);   // No one bits known.
877     } else {
878       KnownZero = KnownOne = APInt(BitWidth, 0);  // Otherwise, nothing known.
879     }
880     return;
881   }        
882   case Instruction::SRem:
883     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
884       APInt RA = Rem->getValue();
885       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
886         APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
887         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
888         ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
889
890         // The sign of a remainder is equal to the sign of the first
891         // operand (zero being positive).
892         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
893           KnownZero2 |= ~LowBits;
894         else if (KnownOne2[BitWidth-1])
895           KnownOne2 |= ~LowBits;
896
897         KnownZero |= KnownZero2 & Mask;
898         KnownOne |= KnownOne2 & Mask;
899
900         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
901       }
902     }
903     break;
904   case Instruction::URem:
905     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
906       APInt RA = Rem->getValue();
907       if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
908         APInt LowBits = (RA - 1) | RA;
909         APInt Mask2 = LowBits & Mask;
910         KnownZero |= ~LowBits & Mask;
911         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
912         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
913       }
914     } else {
915       // Since the result is less than or equal to RHS, any leading zero bits
916       // in RHS must also exist in the result.
917       APInt AllOnes = APInt::getAllOnesValue(BitWidth);
918       ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
919                         Depth+1);
920
921       uint32_t Leaders = KnownZero2.countLeadingOnes();
922       KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
923       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924     }
925     break;
926   }
927 }
928
929 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
930 /// this predicate to simplify operations downstream.  Mask is known to be zero
931 /// for bits that V cannot have.
932 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
933   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
934   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
935   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
936   return (KnownZero & Mask) == Mask;
937 }
938
939 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
940 /// specified instruction is a constant integer.  If so, check to see if there
941 /// are any bits set in the constant that are not demanded.  If so, shrink the
942 /// constant and return true.
943 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
944                                    APInt Demanded) {
945   assert(I && "No instruction?");
946   assert(OpNo < I->getNumOperands() && "Operand index too large");
947
948   // If the operand is not a constant integer, nothing to do.
949   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
950   if (!OpC) return false;
951
952   // If there are no bits set that aren't demanded, nothing to do.
953   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
954   if ((~Demanded & OpC->getValue()) == 0)
955     return false;
956
957   // This instruction is producing bits that are not demanded. Shrink the RHS.
958   Demanded &= OpC->getValue();
959   I->setOperand(OpNo, ConstantInt::get(Demanded));
960   return true;
961 }
962
963 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
964 // set of known zero and one bits, compute the maximum and minimum values that
965 // could have the specified known zero and known one bits, returning them in
966 // min/max.
967 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
968                                                    const APInt& KnownZero,
969                                                    const APInt& KnownOne,
970                                                    APInt& Min, APInt& Max) {
971   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
972   assert(KnownZero.getBitWidth() == BitWidth && 
973          KnownOne.getBitWidth() == BitWidth &&
974          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
975          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
976   APInt UnknownBits = ~(KnownZero|KnownOne);
977
978   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
979   // bit if it is unknown.
980   Min = KnownOne;
981   Max = KnownOne|UnknownBits;
982   
983   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
984     Min.set(BitWidth-1);
985     Max.clear(BitWidth-1);
986   }
987 }
988
989 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
990 // a set of known zero and one bits, compute the maximum and minimum values that
991 // could have the specified known zero and known one bits, returning them in
992 // min/max.
993 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
994                                                      const APInt &KnownZero,
995                                                      const APInt &KnownOne,
996                                                      APInt &Min, APInt &Max) {
997   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
998   assert(KnownZero.getBitWidth() == BitWidth && 
999          KnownOne.getBitWidth() == BitWidth &&
1000          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1001          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1002   APInt UnknownBits = ~(KnownZero|KnownOne);
1003   
1004   // The minimum value is when the unknown bits are all zeros.
1005   Min = KnownOne;
1006   // The maximum value is when the unknown bits are all ones.
1007   Max = KnownOne|UnknownBits;
1008 }
1009
1010 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1011 /// value based on the demanded bits. When this function is called, it is known
1012 /// that only the bits set in DemandedMask of the result of V are ever used
1013 /// downstream. Consequently, depending on the mask and V, it may be possible
1014 /// to replace V with a constant or one of its operands. In such cases, this
1015 /// function does the replacement and returns true. In all other cases, it
1016 /// returns false after analyzing the expression and setting KnownOne and known
1017 /// to be one in the expression. KnownZero contains all the bits that are known
1018 /// to be zero in the expression. These are provided to potentially allow the
1019 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1020 /// the expression. KnownOne and KnownZero always follow the invariant that 
1021 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1022 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1023 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1024 /// and KnownOne must all be the same.
1025 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1026                                         APInt& KnownZero, APInt& KnownOne,
1027                                         unsigned Depth) {
1028   assert(V != 0 && "Null pointer of Value???");
1029   assert(Depth <= 6 && "Limit Search Depth");
1030   uint32_t BitWidth = DemandedMask.getBitWidth();
1031   const IntegerType *VTy = cast<IntegerType>(V->getType());
1032   assert(VTy->getBitWidth() == BitWidth && 
1033          KnownZero.getBitWidth() == BitWidth && 
1034          KnownOne.getBitWidth() == BitWidth &&
1035          "Value *V, DemandedMask, KnownZero and KnownOne \
1036           must have same BitWidth");
1037   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1038     // We know all of the bits for a constant!
1039     KnownOne = CI->getValue() & DemandedMask;
1040     KnownZero = ~KnownOne & DemandedMask;
1041     return false;
1042   }
1043   
1044   KnownZero.clear(); 
1045   KnownOne.clear();
1046   if (!V->hasOneUse()) {    // Other users may use these bits.
1047     if (Depth != 0) {       // Not at the root.
1048       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1049       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1050       return false;
1051     }
1052     // If this is the root being simplified, allow it to have multiple uses,
1053     // just set the DemandedMask to all bits.
1054     DemandedMask = APInt::getAllOnesValue(BitWidth);
1055   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1056     if (V != UndefValue::get(VTy))
1057       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1058     return false;
1059   } else if (Depth == 6) {        // Limit search depth.
1060     return false;
1061   }
1062   
1063   Instruction *I = dyn_cast<Instruction>(V);
1064   if (!I) return false;        // Only analyze instructions.
1065
1066   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1067   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1068   switch (I->getOpcode()) {
1069   default: break;
1070   case Instruction::And:
1071     // If either the LHS or the RHS are Zero, the result is zero.
1072     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1073                              RHSKnownZero, RHSKnownOne, Depth+1))
1074       return true;
1075     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1076            "Bits known to be one AND zero?"); 
1077
1078     // If something is known zero on the RHS, the bits aren't demanded on the
1079     // LHS.
1080     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1081                              LHSKnownZero, LHSKnownOne, Depth+1))
1082       return true;
1083     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1084            "Bits known to be one AND zero?"); 
1085
1086     // If all of the demanded bits are known 1 on one side, return the other.
1087     // These bits cannot contribute to the result of the 'and'.
1088     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1089         (DemandedMask & ~LHSKnownZero))
1090       return UpdateValueUsesWith(I, I->getOperand(0));
1091     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1092         (DemandedMask & ~RHSKnownZero))
1093       return UpdateValueUsesWith(I, I->getOperand(1));
1094     
1095     // If all of the demanded bits in the inputs are known zeros, return zero.
1096     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1097       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1098       
1099     // If the RHS is a constant, see if we can simplify it.
1100     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1101       return UpdateValueUsesWith(I, I);
1102       
1103     // Output known-1 bits are only known if set in both the LHS & RHS.
1104     RHSKnownOne &= LHSKnownOne;
1105     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1106     RHSKnownZero |= LHSKnownZero;
1107     break;
1108   case Instruction::Or:
1109     // If either the LHS or the RHS are One, the result is One.
1110     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1111                              RHSKnownZero, RHSKnownOne, Depth+1))
1112       return true;
1113     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1114            "Bits known to be one AND zero?"); 
1115     // If something is known one on the RHS, the bits aren't demanded on the
1116     // LHS.
1117     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1118                              LHSKnownZero, LHSKnownOne, Depth+1))
1119       return true;
1120     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1121            "Bits known to be one AND zero?"); 
1122     
1123     // If all of the demanded bits are known zero on one side, return the other.
1124     // These bits cannot contribute to the result of the 'or'.
1125     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1126         (DemandedMask & ~LHSKnownOne))
1127       return UpdateValueUsesWith(I, I->getOperand(0));
1128     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1129         (DemandedMask & ~RHSKnownOne))
1130       return UpdateValueUsesWith(I, I->getOperand(1));
1131
1132     // If all of the potentially set bits on one side are known to be set on
1133     // the other side, just use the 'other' side.
1134     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1135         (DemandedMask & (~RHSKnownZero)))
1136       return UpdateValueUsesWith(I, I->getOperand(0));
1137     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1138         (DemandedMask & (~LHSKnownZero)))
1139       return UpdateValueUsesWith(I, I->getOperand(1));
1140         
1141     // If the RHS is a constant, see if we can simplify it.
1142     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1143       return UpdateValueUsesWith(I, I);
1144           
1145     // Output known-0 bits are only known if clear in both the LHS & RHS.
1146     RHSKnownZero &= LHSKnownZero;
1147     // Output known-1 are known to be set if set in either the LHS | RHS.
1148     RHSKnownOne |= LHSKnownOne;
1149     break;
1150   case Instruction::Xor: {
1151     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1152                              RHSKnownZero, RHSKnownOne, Depth+1))
1153       return true;
1154     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1155            "Bits known to be one AND zero?"); 
1156     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1157                              LHSKnownZero, LHSKnownOne, Depth+1))
1158       return true;
1159     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1160            "Bits known to be one AND zero?"); 
1161     
1162     // If all of the demanded bits are known zero on one side, return the other.
1163     // These bits cannot contribute to the result of the 'xor'.
1164     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1165       return UpdateValueUsesWith(I, I->getOperand(0));
1166     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1167       return UpdateValueUsesWith(I, I->getOperand(1));
1168     
1169     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1170     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1171                          (RHSKnownOne & LHSKnownOne);
1172     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1173     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1174                         (RHSKnownOne & LHSKnownZero);
1175     
1176     // If all of the demanded bits are known to be zero on one side or the
1177     // other, turn this into an *inclusive* or.
1178     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1179     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1180       Instruction *Or =
1181         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1182                                  I->getName());
1183       InsertNewInstBefore(Or, *I);
1184       return UpdateValueUsesWith(I, Or);
1185     }
1186     
1187     // If all of the demanded bits on one side are known, and all of the set
1188     // bits on that side are also known to be set on the other side, turn this
1189     // into an AND, as we know the bits will be cleared.
1190     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1191     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1192       // all known
1193       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1194         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1195         Instruction *And = 
1196           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1197         InsertNewInstBefore(And, *I);
1198         return UpdateValueUsesWith(I, And);
1199       }
1200     }
1201     
1202     // If the RHS is a constant, see if we can simplify it.
1203     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1204     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1205       return UpdateValueUsesWith(I, I);
1206     
1207     RHSKnownZero = KnownZeroOut;
1208     RHSKnownOne  = KnownOneOut;
1209     break;
1210   }
1211   case Instruction::Select:
1212     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1213                              RHSKnownZero, RHSKnownOne, Depth+1))
1214       return true;
1215     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1216                              LHSKnownZero, LHSKnownOne, Depth+1))
1217       return true;
1218     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1219            "Bits known to be one AND zero?"); 
1220     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1221            "Bits known to be one AND zero?"); 
1222     
1223     // If the operands are constants, see if we can simplify them.
1224     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1225       return UpdateValueUsesWith(I, I);
1226     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1227       return UpdateValueUsesWith(I, I);
1228     
1229     // Only known if known in both the LHS and RHS.
1230     RHSKnownOne &= LHSKnownOne;
1231     RHSKnownZero &= LHSKnownZero;
1232     break;
1233   case Instruction::Trunc: {
1234     uint32_t truncBf = 
1235       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1236     DemandedMask.zext(truncBf);
1237     RHSKnownZero.zext(truncBf);
1238     RHSKnownOne.zext(truncBf);
1239     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1240                              RHSKnownZero, RHSKnownOne, Depth+1))
1241       return true;
1242     DemandedMask.trunc(BitWidth);
1243     RHSKnownZero.trunc(BitWidth);
1244     RHSKnownOne.trunc(BitWidth);
1245     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1246            "Bits known to be one AND zero?"); 
1247     break;
1248   }
1249   case Instruction::BitCast:
1250     if (!I->getOperand(0)->getType()->isInteger())
1251       return false;
1252       
1253     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1254                              RHSKnownZero, RHSKnownOne, Depth+1))
1255       return true;
1256     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1257            "Bits known to be one AND zero?"); 
1258     break;
1259   case Instruction::ZExt: {
1260     // Compute the bits in the result that are not present in the input.
1261     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1262     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1263     
1264     DemandedMask.trunc(SrcBitWidth);
1265     RHSKnownZero.trunc(SrcBitWidth);
1266     RHSKnownOne.trunc(SrcBitWidth);
1267     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1268                              RHSKnownZero, RHSKnownOne, Depth+1))
1269       return true;
1270     DemandedMask.zext(BitWidth);
1271     RHSKnownZero.zext(BitWidth);
1272     RHSKnownOne.zext(BitWidth);
1273     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1274            "Bits known to be one AND zero?"); 
1275     // The top bits are known to be zero.
1276     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1277     break;
1278   }
1279   case Instruction::SExt: {
1280     // Compute the bits in the result that are not present in the input.
1281     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1282     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1283     
1284     APInt InputDemandedBits = DemandedMask & 
1285                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1286
1287     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1288     // If any of the sign extended bits are demanded, we know that the sign
1289     // bit is demanded.
1290     if ((NewBits & DemandedMask) != 0)
1291       InputDemandedBits.set(SrcBitWidth-1);
1292       
1293     InputDemandedBits.trunc(SrcBitWidth);
1294     RHSKnownZero.trunc(SrcBitWidth);
1295     RHSKnownOne.trunc(SrcBitWidth);
1296     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1297                              RHSKnownZero, RHSKnownOne, Depth+1))
1298       return true;
1299     InputDemandedBits.zext(BitWidth);
1300     RHSKnownZero.zext(BitWidth);
1301     RHSKnownOne.zext(BitWidth);
1302     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1303            "Bits known to be one AND zero?"); 
1304       
1305     // If the sign bit of the input is known set or clear, then we know the
1306     // top bits of the result.
1307
1308     // If the input sign bit is known zero, or if the NewBits are not demanded
1309     // convert this into a zero extension.
1310     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1311     {
1312       // Convert to ZExt cast
1313       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1314       return UpdateValueUsesWith(I, NewCast);
1315     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1316       RHSKnownOne |= NewBits;
1317     }
1318     break;
1319   }
1320   case Instruction::Add: {
1321     // Figure out what the input bits are.  If the top bits of the and result
1322     // are not demanded, then the add doesn't demand them from its input
1323     // either.
1324     uint32_t NLZ = DemandedMask.countLeadingZeros();
1325       
1326     // If there is a constant on the RHS, there are a variety of xformations
1327     // we can do.
1328     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329       // If null, this should be simplified elsewhere.  Some of the xforms here
1330       // won't work if the RHS is zero.
1331       if (RHS->isZero())
1332         break;
1333       
1334       // If the top bit of the output is demanded, demand everything from the
1335       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1336       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1337
1338       // Find information about known zero/one bits in the input.
1339       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1340                                LHSKnownZero, LHSKnownOne, Depth+1))
1341         return true;
1342
1343       // If the RHS of the add has bits set that can't affect the input, reduce
1344       // the constant.
1345       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1346         return UpdateValueUsesWith(I, I);
1347       
1348       // Avoid excess work.
1349       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1350         break;
1351       
1352       // Turn it into OR if input bits are zero.
1353       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1354         Instruction *Or =
1355           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1356                                    I->getName());
1357         InsertNewInstBefore(Or, *I);
1358         return UpdateValueUsesWith(I, Or);
1359       }
1360       
1361       // We can say something about the output known-zero and known-one bits,
1362       // depending on potential carries from the input constant and the
1363       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1364       // bits set and the RHS constant is 0x01001, then we know we have a known
1365       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1366       
1367       // To compute this, we first compute the potential carry bits.  These are
1368       // the bits which may be modified.  I'm not aware of a better way to do
1369       // this scan.
1370       const APInt& RHSVal = RHS->getValue();
1371       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1372       
1373       // Now that we know which bits have carries, compute the known-1/0 sets.
1374       
1375       // Bits are known one if they are known zero in one operand and one in the
1376       // other, and there is no input carry.
1377       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1378                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1379       
1380       // Bits are known zero if they are known zero in both operands and there
1381       // is no input carry.
1382       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1383     } else {
1384       // If the high-bits of this ADD are not demanded, then it does not demand
1385       // the high bits of its LHS or RHS.
1386       if (DemandedMask[BitWidth-1] == 0) {
1387         // Right fill the mask of bits for this ADD to demand the most
1388         // significant bit and all those below it.
1389         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1390         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1391                                  LHSKnownZero, LHSKnownOne, Depth+1))
1392           return true;
1393         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1394                                  LHSKnownZero, LHSKnownOne, Depth+1))
1395           return true;
1396       }
1397     }
1398     break;
1399   }
1400   case Instruction::Sub:
1401     // If the high-bits of this SUB are not demanded, then it does not demand
1402     // the high bits of its LHS or RHS.
1403     if (DemandedMask[BitWidth-1] == 0) {
1404       // Right fill the mask of bits for this SUB to demand the most
1405       // significant bit and all those below it.
1406       uint32_t NLZ = DemandedMask.countLeadingZeros();
1407       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1408       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1409                                LHSKnownZero, LHSKnownOne, Depth+1))
1410         return true;
1411       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1412                                LHSKnownZero, LHSKnownOne, Depth+1))
1413         return true;
1414     }
1415     break;
1416   case Instruction::Shl:
1417     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1418       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1419       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1420       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1421                                RHSKnownZero, RHSKnownOne, Depth+1))
1422         return true;
1423       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1424              "Bits known to be one AND zero?"); 
1425       RHSKnownZero <<= ShiftAmt;
1426       RHSKnownOne  <<= ShiftAmt;
1427       // low bits known zero.
1428       if (ShiftAmt)
1429         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1430     }
1431     break;
1432   case Instruction::LShr:
1433     // For a logical shift right
1434     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1435       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1436       
1437       // Unsigned shift right.
1438       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1439       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1440                                RHSKnownZero, RHSKnownOne, Depth+1))
1441         return true;
1442       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1443              "Bits known to be one AND zero?"); 
1444       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1445       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1446       if (ShiftAmt) {
1447         // Compute the new bits that are at the top now.
1448         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1449         RHSKnownZero |= HighBits;  // high bits known zero.
1450       }
1451     }
1452     break;
1453   case Instruction::AShr:
1454     // If this is an arithmetic shift right and only the low-bit is set, we can
1455     // always convert this into a logical shr, even if the shift amount is
1456     // variable.  The low bit of the shift cannot be an input sign bit unless
1457     // the shift amount is >= the size of the datatype, which is undefined.
1458     if (DemandedMask == 1) {
1459       // Perform the logical shift right.
1460       Value *NewVal = BinaryOperator::createLShr(
1461                         I->getOperand(0), I->getOperand(1), I->getName());
1462       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1463       return UpdateValueUsesWith(I, NewVal);
1464     }    
1465
1466     // If the sign bit is the only bit demanded by this ashr, then there is no
1467     // need to do it, the shift doesn't change the high bit.
1468     if (DemandedMask.isSignBit())
1469       return UpdateValueUsesWith(I, I->getOperand(0));
1470     
1471     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1472       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1473       
1474       // Signed shift right.
1475       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1476       // If any of the "high bits" are demanded, we should set the sign bit as
1477       // demanded.
1478       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1479         DemandedMaskIn.set(BitWidth-1);
1480       if (SimplifyDemandedBits(I->getOperand(0),
1481                                DemandedMaskIn,
1482                                RHSKnownZero, RHSKnownOne, Depth+1))
1483         return true;
1484       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1485              "Bits known to be one AND zero?"); 
1486       // Compute the new bits that are at the top now.
1487       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1488       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1489       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1490         
1491       // Handle the sign bits.
1492       APInt SignBit(APInt::getSignBit(BitWidth));
1493       // Adjust to where it is now in the mask.
1494       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1495         
1496       // If the input sign bit is known to be zero, or if none of the top bits
1497       // are demanded, turn this into an unsigned shift right.
1498       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1499           (HighBits & ~DemandedMask) == HighBits) {
1500         // Perform the logical shift right.
1501         Value *NewVal = BinaryOperator::createLShr(
1502                           I->getOperand(0), SA, I->getName());
1503         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1504         return UpdateValueUsesWith(I, NewVal);
1505       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1506         RHSKnownOne |= HighBits;
1507       }
1508     }
1509     break;
1510   case Instruction::SRem:
1511     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1512       APInt RA = Rem->getValue();
1513       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1514         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1515         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1516         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1517                                  LHSKnownZero, LHSKnownOne, Depth+1))
1518           return true;
1519
1520         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1521           LHSKnownZero |= ~LowBits;
1522         else if (LHSKnownOne[BitWidth-1])
1523           LHSKnownOne |= ~LowBits;
1524
1525         KnownZero |= LHSKnownZero & DemandedMask;
1526         KnownOne |= LHSKnownOne & DemandedMask;
1527
1528         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1529       }
1530     }
1531     break;
1532   case Instruction::URem:
1533     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1534       APInt RA = Rem->getValue();
1535       if (RA.isPowerOf2()) {
1536         APInt LowBits = (RA - 1) | RA;
1537         APInt Mask2 = LowBits & DemandedMask;
1538         KnownZero |= ~LowBits & DemandedMask;
1539         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1540                                  KnownZero, KnownOne, Depth+1))
1541           return true;
1542
1543         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1544       }
1545     } else {
1546       APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1547       APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1548       if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1549                                KnownZero2, KnownOne2, Depth+1))
1550         return true;
1551
1552       uint32_t Leaders = KnownZero2.countLeadingOnes();
1553       KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1554     }
1555     break;
1556   }
1557   
1558   // If the client is only demanding bits that we know, return the known
1559   // constant.
1560   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1561     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1562   return false;
1563 }
1564
1565
1566 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1567 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1568 /// actually used by the caller.  This method analyzes which elements of the
1569 /// operand are undef and returns that information in UndefElts.
1570 ///
1571 /// If the information about demanded elements can be used to simplify the
1572 /// operation, the operation is simplified, then the resultant value is
1573 /// returned.  This returns null if no change was made.
1574 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1575                                                 uint64_t &UndefElts,
1576                                                 unsigned Depth) {
1577   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1578   assert(VWidth <= 64 && "Vector too wide to analyze!");
1579   uint64_t EltMask = ~0ULL >> (64-VWidth);
1580   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1581          "Invalid DemandedElts!");
1582
1583   if (isa<UndefValue>(V)) {
1584     // If the entire vector is undefined, just return this info.
1585     UndefElts = EltMask;
1586     return 0;
1587   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1588     UndefElts = EltMask;
1589     return UndefValue::get(V->getType());
1590   }
1591   
1592   UndefElts = 0;
1593   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1594     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1595     Constant *Undef = UndefValue::get(EltTy);
1596
1597     std::vector<Constant*> Elts;
1598     for (unsigned i = 0; i != VWidth; ++i)
1599       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1600         Elts.push_back(Undef);
1601         UndefElts |= (1ULL << i);
1602       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1603         Elts.push_back(Undef);
1604         UndefElts |= (1ULL << i);
1605       } else {                               // Otherwise, defined.
1606         Elts.push_back(CP->getOperand(i));
1607       }
1608         
1609     // If we changed the constant, return it.
1610     Constant *NewCP = ConstantVector::get(Elts);
1611     return NewCP != CP ? NewCP : 0;
1612   } else if (isa<ConstantAggregateZero>(V)) {
1613     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1614     // set to undef.
1615     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1616     Constant *Zero = Constant::getNullValue(EltTy);
1617     Constant *Undef = UndefValue::get(EltTy);
1618     std::vector<Constant*> Elts;
1619     for (unsigned i = 0; i != VWidth; ++i)
1620       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1621     UndefElts = DemandedElts ^ EltMask;
1622     return ConstantVector::get(Elts);
1623   }
1624   
1625   if (!V->hasOneUse()) {    // Other users may use these bits.
1626     if (Depth != 0) {       // Not at the root.
1627       // TODO: Just compute the UndefElts information recursively.
1628       return false;
1629     }
1630     return false;
1631   } else if (Depth == 10) {        // Limit search depth.
1632     return false;
1633   }
1634   
1635   Instruction *I = dyn_cast<Instruction>(V);
1636   if (!I) return false;        // Only analyze instructions.
1637   
1638   bool MadeChange = false;
1639   uint64_t UndefElts2;
1640   Value *TmpV;
1641   switch (I->getOpcode()) {
1642   default: break;
1643     
1644   case Instruction::InsertElement: {
1645     // If this is a variable index, we don't know which element it overwrites.
1646     // demand exactly the same input as we produce.
1647     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1648     if (Idx == 0) {
1649       // Note that we can't propagate undef elt info, because we don't know
1650       // which elt is getting updated.
1651       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1652                                         UndefElts2, Depth+1);
1653       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1654       break;
1655     }
1656     
1657     // If this is inserting an element that isn't demanded, remove this
1658     // insertelement.
1659     unsigned IdxNo = Idx->getZExtValue();
1660     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1661       return AddSoonDeadInstToWorklist(*I, 0);
1662     
1663     // Otherwise, the element inserted overwrites whatever was there, so the
1664     // input demanded set is simpler than the output set.
1665     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1666                                       DemandedElts & ~(1ULL << IdxNo),
1667                                       UndefElts, Depth+1);
1668     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1669
1670     // The inserted element is defined.
1671     UndefElts |= 1ULL << IdxNo;
1672     break;
1673   }
1674   case Instruction::BitCast: {
1675     // Vector->vector casts only.
1676     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1677     if (!VTy) break;
1678     unsigned InVWidth = VTy->getNumElements();
1679     uint64_t InputDemandedElts = 0;
1680     unsigned Ratio;
1681
1682     if (VWidth == InVWidth) {
1683       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1684       // elements as are demanded of us.
1685       Ratio = 1;
1686       InputDemandedElts = DemandedElts;
1687     } else if (VWidth > InVWidth) {
1688       // Untested so far.
1689       break;
1690       
1691       // If there are more elements in the result than there are in the source,
1692       // then an input element is live if any of the corresponding output
1693       // elements are live.
1694       Ratio = VWidth/InVWidth;
1695       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1696         if (DemandedElts & (1ULL << OutIdx))
1697           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1698       }
1699     } else {
1700       // Untested so far.
1701       break;
1702       
1703       // If there are more elements in the source than there are in the result,
1704       // then an input element is live if the corresponding output element is
1705       // live.
1706       Ratio = InVWidth/VWidth;
1707       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1708         if (DemandedElts & (1ULL << InIdx/Ratio))
1709           InputDemandedElts |= 1ULL << InIdx;
1710     }
1711     
1712     // div/rem demand all inputs, because they don't want divide by zero.
1713     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1714                                       UndefElts2, Depth+1);
1715     if (TmpV) {
1716       I->setOperand(0, TmpV);
1717       MadeChange = true;
1718     }
1719     
1720     UndefElts = UndefElts2;
1721     if (VWidth > InVWidth) {
1722       assert(0 && "Unimp");
1723       // If there are more elements in the result than there are in the source,
1724       // then an output element is undef if the corresponding input element is
1725       // undef.
1726       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1727         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1728           UndefElts |= 1ULL << OutIdx;
1729     } else if (VWidth < InVWidth) {
1730       assert(0 && "Unimp");
1731       // If there are more elements in the source than there are in the result,
1732       // then a result element is undef if all of the corresponding input
1733       // elements are undef.
1734       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1735       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1736         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1737           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1738     }
1739     break;
1740   }
1741   case Instruction::And:
1742   case Instruction::Or:
1743   case Instruction::Xor:
1744   case Instruction::Add:
1745   case Instruction::Sub:
1746   case Instruction::Mul:
1747     // div/rem demand all inputs, because they don't want divide by zero.
1748     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1749                                       UndefElts, Depth+1);
1750     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1751     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1752                                       UndefElts2, Depth+1);
1753     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1754       
1755     // Output elements are undefined if both are undefined.  Consider things
1756     // like undef&0.  The result is known zero, not undef.
1757     UndefElts &= UndefElts2;
1758     break;
1759     
1760   case Instruction::Call: {
1761     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1762     if (!II) break;
1763     switch (II->getIntrinsicID()) {
1764     default: break;
1765       
1766     // Binary vector operations that work column-wise.  A dest element is a
1767     // function of the corresponding input elements from the two inputs.
1768     case Intrinsic::x86_sse_sub_ss:
1769     case Intrinsic::x86_sse_mul_ss:
1770     case Intrinsic::x86_sse_min_ss:
1771     case Intrinsic::x86_sse_max_ss:
1772     case Intrinsic::x86_sse2_sub_sd:
1773     case Intrinsic::x86_sse2_mul_sd:
1774     case Intrinsic::x86_sse2_min_sd:
1775     case Intrinsic::x86_sse2_max_sd:
1776       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1777                                         UndefElts, Depth+1);
1778       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1779       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1780                                         UndefElts2, Depth+1);
1781       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1782
1783       // If only the low elt is demanded and this is a scalarizable intrinsic,
1784       // scalarize it now.
1785       if (DemandedElts == 1) {
1786         switch (II->getIntrinsicID()) {
1787         default: break;
1788         case Intrinsic::x86_sse_sub_ss:
1789         case Intrinsic::x86_sse_mul_ss:
1790         case Intrinsic::x86_sse2_sub_sd:
1791         case Intrinsic::x86_sse2_mul_sd:
1792           // TODO: Lower MIN/MAX/ABS/etc
1793           Value *LHS = II->getOperand(1);
1794           Value *RHS = II->getOperand(2);
1795           // Extract the element as scalars.
1796           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1797           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1798           
1799           switch (II->getIntrinsicID()) {
1800           default: assert(0 && "Case stmts out of sync!");
1801           case Intrinsic::x86_sse_sub_ss:
1802           case Intrinsic::x86_sse2_sub_sd:
1803             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1804                                                         II->getName()), *II);
1805             break;
1806           case Intrinsic::x86_sse_mul_ss:
1807           case Intrinsic::x86_sse2_mul_sd:
1808             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1809                                                          II->getName()), *II);
1810             break;
1811           }
1812           
1813           Instruction *New =
1814             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1815                                   II->getName());
1816           InsertNewInstBefore(New, *II);
1817           AddSoonDeadInstToWorklist(*II, 0);
1818           return New;
1819         }            
1820       }
1821         
1822       // Output elements are undefined if both are undefined.  Consider things
1823       // like undef&0.  The result is known zero, not undef.
1824       UndefElts &= UndefElts2;
1825       break;
1826     }
1827     break;
1828   }
1829   }
1830   return MadeChange ? I : 0;
1831 }
1832
1833 /// @returns true if the specified compare predicate is
1834 /// true when both operands are equal...
1835 /// @brief Determine if the icmp Predicate is true when both operands are equal
1836 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1837   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1838          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1839          pred == ICmpInst::ICMP_SLE;
1840 }
1841
1842 /// @returns true if the specified compare instruction is
1843 /// true when both operands are equal...
1844 /// @brief Determine if the ICmpInst returns true when both operands are equal
1845 static bool isTrueWhenEqual(ICmpInst &ICI) {
1846   return isTrueWhenEqual(ICI.getPredicate());
1847 }
1848
1849 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1850 /// function is designed to check a chain of associative operators for a
1851 /// potential to apply a certain optimization.  Since the optimization may be
1852 /// applicable if the expression was reassociated, this checks the chain, then
1853 /// reassociates the expression as necessary to expose the optimization
1854 /// opportunity.  This makes use of a special Functor, which must define
1855 /// 'shouldApply' and 'apply' methods.
1856 ///
1857 template<typename Functor>
1858 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1859   unsigned Opcode = Root.getOpcode();
1860   Value *LHS = Root.getOperand(0);
1861
1862   // Quick check, see if the immediate LHS matches...
1863   if (F.shouldApply(LHS))
1864     return F.apply(Root);
1865
1866   // Otherwise, if the LHS is not of the same opcode as the root, return.
1867   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1868   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1869     // Should we apply this transform to the RHS?
1870     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1871
1872     // If not to the RHS, check to see if we should apply to the LHS...
1873     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1874       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1875       ShouldApply = true;
1876     }
1877
1878     // If the functor wants to apply the optimization to the RHS of LHSI,
1879     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1880     if (ShouldApply) {
1881       BasicBlock *BB = Root.getParent();
1882
1883       // Now all of the instructions are in the current basic block, go ahead
1884       // and perform the reassociation.
1885       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1886
1887       // First move the selected RHS to the LHS of the root...
1888       Root.setOperand(0, LHSI->getOperand(1));
1889
1890       // Make what used to be the LHS of the root be the user of the root...
1891       Value *ExtraOperand = TmpLHSI->getOperand(1);
1892       if (&Root == TmpLHSI) {
1893         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1894         return 0;
1895       }
1896       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1897       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1898       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1899       BasicBlock::iterator ARI = &Root; ++ARI;
1900       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1901       ARI = Root;
1902
1903       // Now propagate the ExtraOperand down the chain of instructions until we
1904       // get to LHSI.
1905       while (TmpLHSI != LHSI) {
1906         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1907         // Move the instruction to immediately before the chain we are
1908         // constructing to avoid breaking dominance properties.
1909         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1910         BB->getInstList().insert(ARI, NextLHSI);
1911         ARI = NextLHSI;
1912
1913         Value *NextOp = NextLHSI->getOperand(1);
1914         NextLHSI->setOperand(1, ExtraOperand);
1915         TmpLHSI = NextLHSI;
1916         ExtraOperand = NextOp;
1917       }
1918
1919       // Now that the instructions are reassociated, have the functor perform
1920       // the transformation...
1921       return F.apply(Root);
1922     }
1923
1924     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1925   }
1926   return 0;
1927 }
1928
1929
1930 // AddRHS - Implements: X + X --> X << 1
1931 struct AddRHS {
1932   Value *RHS;
1933   AddRHS(Value *rhs) : RHS(rhs) {}
1934   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1935   Instruction *apply(BinaryOperator &Add) const {
1936     return BinaryOperator::createShl(Add.getOperand(0),
1937                                   ConstantInt::get(Add.getType(), 1));
1938   }
1939 };
1940
1941 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1942 //                 iff C1&C2 == 0
1943 struct AddMaskingAnd {
1944   Constant *C2;
1945   AddMaskingAnd(Constant *c) : C2(c) {}
1946   bool shouldApply(Value *LHS) const {
1947     ConstantInt *C1;
1948     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1949            ConstantExpr::getAnd(C1, C2)->isNullValue();
1950   }
1951   Instruction *apply(BinaryOperator &Add) const {
1952     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1953   }
1954 };
1955
1956 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1957                                              InstCombiner *IC) {
1958   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1959     if (Constant *SOC = dyn_cast<Constant>(SO))
1960       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1961
1962     return IC->InsertNewInstBefore(CastInst::create(
1963           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1964   }
1965
1966   // Figure out if the constant is the left or the right argument.
1967   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1968   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1969
1970   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1971     if (ConstIsRHS)
1972       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1973     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1974   }
1975
1976   Value *Op0 = SO, *Op1 = ConstOperand;
1977   if (!ConstIsRHS)
1978     std::swap(Op0, Op1);
1979   Instruction *New;
1980   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1981     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1982   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1983     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1984                           SO->getName()+".cmp");
1985   else {
1986     assert(0 && "Unknown binary instruction type!");
1987     abort();
1988   }
1989   return IC->InsertNewInstBefore(New, I);
1990 }
1991
1992 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1993 // constant as the other operand, try to fold the binary operator into the
1994 // select arguments.  This also works for Cast instructions, which obviously do
1995 // not have a second operand.
1996 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1997                                      InstCombiner *IC) {
1998   // Don't modify shared select instructions
1999   if (!SI->hasOneUse()) return 0;
2000   Value *TV = SI->getOperand(1);
2001   Value *FV = SI->getOperand(2);
2002
2003   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2004     // Bool selects with constant operands can be folded to logical ops.
2005     if (SI->getType() == Type::Int1Ty) return 0;
2006
2007     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2008     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2009
2010     return new SelectInst(SI->getCondition(), SelectTrueVal,
2011                           SelectFalseVal);
2012   }
2013   return 0;
2014 }
2015
2016
2017 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2018 /// node as operand #0, see if we can fold the instruction into the PHI (which
2019 /// is only possible if all operands to the PHI are constants).
2020 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2021   PHINode *PN = cast<PHINode>(I.getOperand(0));
2022   unsigned NumPHIValues = PN->getNumIncomingValues();
2023   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2024
2025   // Check to see if all of the operands of the PHI are constants.  If there is
2026   // one non-constant value, remember the BB it is.  If there is more than one
2027   // or if *it* is a PHI, bail out.
2028   BasicBlock *NonConstBB = 0;
2029   for (unsigned i = 0; i != NumPHIValues; ++i)
2030     if (!isa<Constant>(PN->getIncomingValue(i))) {
2031       if (NonConstBB) return 0;  // More than one non-const value.
2032       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2033       NonConstBB = PN->getIncomingBlock(i);
2034       
2035       // If the incoming non-constant value is in I's block, we have an infinite
2036       // loop.
2037       if (NonConstBB == I.getParent())
2038         return 0;
2039     }
2040   
2041   // If there is exactly one non-constant value, we can insert a copy of the
2042   // operation in that block.  However, if this is a critical edge, we would be
2043   // inserting the computation one some other paths (e.g. inside a loop).  Only
2044   // do this if the pred block is unconditionally branching into the phi block.
2045   if (NonConstBB) {
2046     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2047     if (!BI || !BI->isUnconditional()) return 0;
2048   }
2049
2050   // Okay, we can do the transformation: create the new PHI node.
2051   PHINode *NewPN = new PHINode(I.getType(), "");
2052   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2053   InsertNewInstBefore(NewPN, *PN);
2054   NewPN->takeName(PN);
2055
2056   // Next, add all of the operands to the PHI.
2057   if (I.getNumOperands() == 2) {
2058     Constant *C = cast<Constant>(I.getOperand(1));
2059     for (unsigned i = 0; i != NumPHIValues; ++i) {
2060       Value *InV = 0;
2061       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2062         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2063           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2064         else
2065           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2066       } else {
2067         assert(PN->getIncomingBlock(i) == NonConstBB);
2068         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2069           InV = BinaryOperator::create(BO->getOpcode(),
2070                                        PN->getIncomingValue(i), C, "phitmp",
2071                                        NonConstBB->getTerminator());
2072         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2073           InV = CmpInst::create(CI->getOpcode(), 
2074                                 CI->getPredicate(),
2075                                 PN->getIncomingValue(i), C, "phitmp",
2076                                 NonConstBB->getTerminator());
2077         else
2078           assert(0 && "Unknown binop!");
2079         
2080         AddToWorkList(cast<Instruction>(InV));
2081       }
2082       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2083     }
2084   } else { 
2085     CastInst *CI = cast<CastInst>(&I);
2086     const Type *RetTy = CI->getType();
2087     for (unsigned i = 0; i != NumPHIValues; ++i) {
2088       Value *InV;
2089       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2090         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2091       } else {
2092         assert(PN->getIncomingBlock(i) == NonConstBB);
2093         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
2094                                I.getType(), "phitmp", 
2095                                NonConstBB->getTerminator());
2096         AddToWorkList(cast<Instruction>(InV));
2097       }
2098       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2099     }
2100   }
2101   return ReplaceInstUsesWith(I, NewPN);
2102 }
2103
2104
2105 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
2106 /// value is never equal to -0.0.
2107 ///
2108 /// Note that this function will need to be revisited when we support nondefault
2109 /// rounding modes!
2110 ///
2111 static bool CannotBeNegativeZero(const Value *V) {
2112   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2113     return !CFP->getValueAPF().isNegZero();
2114
2115   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2116   if (const Instruction *I = dyn_cast<Instruction>(V)) {
2117     if (I->getOpcode() == Instruction::Add &&
2118         isa<ConstantFP>(I->getOperand(1)) && 
2119         cast<ConstantFP>(I->getOperand(1))->isNullValue())
2120       return true;
2121     
2122     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2123       if (II->getIntrinsicID() == Intrinsic::sqrt)
2124         return CannotBeNegativeZero(II->getOperand(1));
2125     
2126     if (const CallInst *CI = dyn_cast<CallInst>(I))
2127       if (const Function *F = CI->getCalledFunction()) {
2128         if (F->isDeclaration()) {
2129           switch (F->getNameLen()) {
2130           case 3:  // abs(x) != -0.0
2131             if (!strcmp(F->getNameStart(), "abs")) return true;
2132             break;
2133           case 4:  // abs[lf](x) != -0.0
2134             if (!strcmp(F->getNameStart(), "absf")) return true;
2135             if (!strcmp(F->getNameStart(), "absl")) return true;
2136             break;
2137           }
2138         }
2139       }
2140   }
2141   
2142   return false;
2143 }
2144
2145
2146 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2147   bool Changed = SimplifyCommutative(I);
2148   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2149
2150   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2151     // X + undef -> undef
2152     if (isa<UndefValue>(RHS))
2153       return ReplaceInstUsesWith(I, RHS);
2154
2155     // X + 0 --> X
2156     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2157       if (RHSC->isNullValue())
2158         return ReplaceInstUsesWith(I, LHS);
2159     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2160       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2161                               (I.getType())->getValueAPF()))
2162         return ReplaceInstUsesWith(I, LHS);
2163     }
2164
2165     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2166       // X + (signbit) --> X ^ signbit
2167       const APInt& Val = CI->getValue();
2168       uint32_t BitWidth = Val.getBitWidth();
2169       if (Val == APInt::getSignBit(BitWidth))
2170         return BinaryOperator::createXor(LHS, RHS);
2171       
2172       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2173       // (X & 254)+1 -> (X&254)|1
2174       if (!isa<VectorType>(I.getType())) {
2175         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2176         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2177                                  KnownZero, KnownOne))
2178           return &I;
2179       }
2180     }
2181
2182     if (isa<PHINode>(LHS))
2183       if (Instruction *NV = FoldOpIntoPhi(I))
2184         return NV;
2185     
2186     ConstantInt *XorRHS = 0;
2187     Value *XorLHS = 0;
2188     if (isa<ConstantInt>(RHSC) &&
2189         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2190       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2191       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2192       
2193       uint32_t Size = TySizeBits / 2;
2194       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2195       APInt CFF80Val(-C0080Val);
2196       do {
2197         if (TySizeBits > Size) {
2198           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2199           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2200           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2201               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2202             // This is a sign extend if the top bits are known zero.
2203             if (!MaskedValueIsZero(XorLHS, 
2204                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2205               Size = 0;  // Not a sign ext, but can't be any others either.
2206             break;
2207           }
2208         }
2209         Size >>= 1;
2210         C0080Val = APIntOps::lshr(C0080Val, Size);
2211         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2212       } while (Size >= 1);
2213       
2214       // FIXME: This shouldn't be necessary. When the backends can handle types
2215       // with funny bit widths then this whole cascade of if statements should
2216       // be removed. It is just here to get the size of the "middle" type back
2217       // up to something that the back ends can handle.
2218       const Type *MiddleType = 0;
2219       switch (Size) {
2220         default: break;
2221         case 32: MiddleType = Type::Int32Ty; break;
2222         case 16: MiddleType = Type::Int16Ty; break;
2223         case  8: MiddleType = Type::Int8Ty; break;
2224       }
2225       if (MiddleType) {
2226         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2227         InsertNewInstBefore(NewTrunc, I);
2228         return new SExtInst(NewTrunc, I.getType(), I.getName());
2229       }
2230     }
2231   }
2232
2233   // X + X --> X << 1
2234   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2235     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2236
2237     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2238       if (RHSI->getOpcode() == Instruction::Sub)
2239         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2240           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2241     }
2242     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2243       if (LHSI->getOpcode() == Instruction::Sub)
2244         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2245           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2246     }
2247   }
2248
2249   // -A + B  -->  B - A
2250   // -A + -B  -->  -(A + B)
2251   if (Value *LHSV = dyn_castNegVal(LHS)) {
2252     if (LHS->getType()->isIntOrIntVector()) {
2253       if (Value *RHSV = dyn_castNegVal(RHS)) {
2254         Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2255         InsertNewInstBefore(NewAdd, I);
2256         return BinaryOperator::createNeg(NewAdd);
2257       }
2258     }
2259     
2260     return BinaryOperator::createSub(RHS, LHSV);
2261   }
2262
2263   // A + -B  -->  A - B
2264   if (!isa<Constant>(RHS))
2265     if (Value *V = dyn_castNegVal(RHS))
2266       return BinaryOperator::createSub(LHS, V);
2267
2268
2269   ConstantInt *C2;
2270   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2271     if (X == RHS)   // X*C + X --> X * (C+1)
2272       return BinaryOperator::createMul(RHS, AddOne(C2));
2273
2274     // X*C1 + X*C2 --> X * (C1+C2)
2275     ConstantInt *C1;
2276     if (X == dyn_castFoldableMul(RHS, C1))
2277       return BinaryOperator::createMul(X, Add(C1, C2));
2278   }
2279
2280   // X + X*C --> X * (C+1)
2281   if (dyn_castFoldableMul(RHS, C2) == LHS)
2282     return BinaryOperator::createMul(LHS, AddOne(C2));
2283
2284   // X + ~X --> -1   since   ~X = -X-1
2285   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2286     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2287   
2288
2289   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2290   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2291     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2292       return R;
2293
2294   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2295   if (I.getType()->isIntOrIntVector()) {
2296     Value *W, *X, *Y, *Z;
2297     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2298         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2299       if (W != Y) {
2300         if (W == Z) {
2301           std::swap(Y, Z);
2302         } else if (Y == X) {
2303           std::swap(W, X);
2304         } else if (X == Z) {
2305           std::swap(Y, Z);
2306           std::swap(W, X);
2307         }
2308       }
2309
2310       if (W == Y) {
2311         Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2312                                                             LHS->getName()), I);
2313         return BinaryOperator::createMul(W, NewAdd);
2314       }
2315     }
2316   }
2317
2318   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2319     Value *X = 0;
2320     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2321       return BinaryOperator::createSub(SubOne(CRHS), X);
2322
2323     // (X & FF00) + xx00  -> (X+xx00) & FF00
2324     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2325       Constant *Anded = And(CRHS, C2);
2326       if (Anded == CRHS) {
2327         // See if all bits from the first bit set in the Add RHS up are included
2328         // in the mask.  First, get the rightmost bit.
2329         const APInt& AddRHSV = CRHS->getValue();
2330
2331         // Form a mask of all bits from the lowest bit added through the top.
2332         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2333
2334         // See if the and mask includes all of these bits.
2335         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2336
2337         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2338           // Okay, the xform is safe.  Insert the new add pronto.
2339           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2340                                                             LHS->getName()), I);
2341           return BinaryOperator::createAnd(NewAdd, C2);
2342         }
2343       }
2344     }
2345
2346     // Try to fold constant add into select arguments.
2347     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2348       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2349         return R;
2350   }
2351
2352   // add (cast *A to intptrtype) B -> 
2353   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2354   {
2355     CastInst *CI = dyn_cast<CastInst>(LHS);
2356     Value *Other = RHS;
2357     if (!CI) {
2358       CI = dyn_cast<CastInst>(RHS);
2359       Other = LHS;
2360     }
2361     if (CI && CI->getType()->isSized() && 
2362         (CI->getType()->getPrimitiveSizeInBits() == 
2363          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2364         && isa<PointerType>(CI->getOperand(0)->getType())) {
2365       unsigned AS =
2366         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2367       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2368                                       PointerType::get(Type::Int8Ty, AS), I);
2369       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2370       return new PtrToIntInst(I2, CI->getType());
2371     }
2372   }
2373   
2374   // add (select X 0 (sub n A)) A  -->  select X A n
2375   {
2376     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2377     Value *Other = RHS;
2378     if (!SI) {
2379       SI = dyn_cast<SelectInst>(RHS);
2380       Other = LHS;
2381     }
2382     if (SI && SI->hasOneUse()) {
2383       Value *TV = SI->getTrueValue();
2384       Value *FV = SI->getFalseValue();
2385       Value *A, *N;
2386
2387       // Can we fold the add into the argument of the select?
2388       // We check both true and false select arguments for a matching subtract.
2389       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2390           A == Other)  // Fold the add into the true select value.
2391         return new SelectInst(SI->getCondition(), N, A);
2392       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2393           A == Other)  // Fold the add into the false select value.
2394         return new SelectInst(SI->getCondition(), A, N);
2395     }
2396   }
2397   
2398   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2399   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2400     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2401       return ReplaceInstUsesWith(I, LHS);
2402
2403   return Changed ? &I : 0;
2404 }
2405
2406 // isSignBit - Return true if the value represented by the constant only has the
2407 // highest order bit set.
2408 static bool isSignBit(ConstantInt *CI) {
2409   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2410   return CI->getValue() == APInt::getSignBit(NumBits);
2411 }
2412
2413 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2414   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2415
2416   if (Op0 == Op1)         // sub X, X  -> 0
2417     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2418
2419   // If this is a 'B = x-(-A)', change to B = x+A...
2420   if (Value *V = dyn_castNegVal(Op1))
2421     return BinaryOperator::createAdd(Op0, V);
2422
2423   if (isa<UndefValue>(Op0))
2424     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2425   if (isa<UndefValue>(Op1))
2426     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2427
2428   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2429     // Replace (-1 - A) with (~A)...
2430     if (C->isAllOnesValue())
2431       return BinaryOperator::createNot(Op1);
2432
2433     // C - ~X == X + (1+C)
2434     Value *X = 0;
2435     if (match(Op1, m_Not(m_Value(X))))
2436       return BinaryOperator::createAdd(X, AddOne(C));
2437
2438     // -(X >>u 31) -> (X >>s 31)
2439     // -(X >>s 31) -> (X >>u 31)
2440     if (C->isZero()) {
2441       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2442         if (SI->getOpcode() == Instruction::LShr) {
2443           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2444             // Check to see if we are shifting out everything but the sign bit.
2445             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2446                 SI->getType()->getPrimitiveSizeInBits()-1) {
2447               // Ok, the transformation is safe.  Insert AShr.
2448               return BinaryOperator::create(Instruction::AShr, 
2449                                           SI->getOperand(0), CU, SI->getName());
2450             }
2451           }
2452         }
2453         else if (SI->getOpcode() == Instruction::AShr) {
2454           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2455             // Check to see if we are shifting out everything but the sign bit.
2456             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2457                 SI->getType()->getPrimitiveSizeInBits()-1) {
2458               // Ok, the transformation is safe.  Insert LShr. 
2459               return BinaryOperator::createLShr(
2460                                           SI->getOperand(0), CU, SI->getName());
2461             }
2462           }
2463         }
2464       }
2465     }
2466
2467     // Try to fold constant sub into select arguments.
2468     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2469       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2470         return R;
2471
2472     if (isa<PHINode>(Op0))
2473       if (Instruction *NV = FoldOpIntoPhi(I))
2474         return NV;
2475   }
2476
2477   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2478     if (Op1I->getOpcode() == Instruction::Add &&
2479         !Op0->getType()->isFPOrFPVector()) {
2480       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2481         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2482       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2483         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2484       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486           // C1-(X+C2) --> (C1-C2)-X
2487           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2488                                            Op1I->getOperand(0));
2489       }
2490     }
2491
2492     if (Op1I->hasOneUse()) {
2493       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494       // is not used by anyone else...
2495       //
2496       if (Op1I->getOpcode() == Instruction::Sub &&
2497           !Op1I->getType()->isFPOrFPVector()) {
2498         // Swap the two operands of the subexpr...
2499         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2500         Op1I->setOperand(0, IIOp1);
2501         Op1I->setOperand(1, IIOp0);
2502
2503         // Create the new top level add instruction...
2504         return BinaryOperator::createAdd(Op0, Op1);
2505       }
2506
2507       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2508       //
2509       if (Op1I->getOpcode() == Instruction::And &&
2510           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2511         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2512
2513         Value *NewNot =
2514           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2515         return BinaryOperator::createAnd(Op0, NewNot);
2516       }
2517
2518       // 0 - (X sdiv C)  -> (X sdiv -C)
2519       if (Op1I->getOpcode() == Instruction::SDiv)
2520         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2521           if (CSI->isZero())
2522             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2523               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2524                                                ConstantExpr::getNeg(DivRHS));
2525
2526       // X - X*C --> X * (1-C)
2527       ConstantInt *C2 = 0;
2528       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2529         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2530         return BinaryOperator::createMul(Op0, CP1);
2531       }
2532
2533       // X - ((X / Y) * Y) --> X % Y
2534       if (Op1I->getOpcode() == Instruction::Mul)
2535         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2536           if (Op0 == I->getOperand(0) &&
2537               Op1I->getOperand(1) == I->getOperand(1)) {
2538             if (I->getOpcode() == Instruction::SDiv)
2539               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2540             if (I->getOpcode() == Instruction::UDiv)
2541               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2542           }
2543     }
2544   }
2545
2546   if (!Op0->getType()->isFPOrFPVector())
2547     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2548       if (Op0I->getOpcode() == Instruction::Add) {
2549         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2550           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2551         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2552           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2553       } else if (Op0I->getOpcode() == Instruction::Sub) {
2554         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2555           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2556       }
2557     }
2558
2559   ConstantInt *C1;
2560   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2561     if (X == Op1)  // X*C - X --> X * (C-1)
2562       return BinaryOperator::createMul(Op1, SubOne(C1));
2563
2564     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2565     if (X == dyn_castFoldableMul(Op1, C2))
2566       return BinaryOperator::createMul(X, Subtract(C1, C2));
2567   }
2568   return 0;
2569 }
2570
2571 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2572 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2573 /// TrueIfSigned if the result of the comparison is true when the input value is
2574 /// signed.
2575 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2576                            bool &TrueIfSigned) {
2577   switch (pred) {
2578   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2579     TrueIfSigned = true;
2580     return RHS->isZero();
2581   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2582     TrueIfSigned = true;
2583     return RHS->isAllOnesValue();
2584   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2585     TrueIfSigned = false;
2586     return RHS->isAllOnesValue();
2587   case ICmpInst::ICMP_UGT:
2588     // True if LHS u> RHS and RHS == high-bit-mask - 1
2589     TrueIfSigned = true;
2590     return RHS->getValue() ==
2591       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2592   case ICmpInst::ICMP_UGE: 
2593     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2594     TrueIfSigned = true;
2595     return RHS->getValue() == 
2596       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2597   default:
2598     return false;
2599   }
2600 }
2601
2602 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2603   bool Changed = SimplifyCommutative(I);
2604   Value *Op0 = I.getOperand(0);
2605
2606   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2607     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2608
2609   // Simplify mul instructions with a constant RHS...
2610   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2611     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2612
2613       // ((X << C1)*C2) == (X * (C2 << C1))
2614       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2615         if (SI->getOpcode() == Instruction::Shl)
2616           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2617             return BinaryOperator::createMul(SI->getOperand(0),
2618                                              ConstantExpr::getShl(CI, ShOp));
2619
2620       if (CI->isZero())
2621         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2622       if (CI->equalsInt(1))                  // X * 1  == X
2623         return ReplaceInstUsesWith(I, Op0);
2624       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2625         return BinaryOperator::createNeg(Op0, I.getName());
2626
2627       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2628       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2629         return BinaryOperator::createShl(Op0,
2630                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2631       }
2632     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2633       if (Op1F->isNullValue())
2634         return ReplaceInstUsesWith(I, Op1);
2635
2636       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2637       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2638       // We need a better interface for long double here.
2639       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2640         if (Op1F->isExactlyValue(1.0))
2641           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2642     }
2643     
2644     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2645       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2646           isa<ConstantInt>(Op0I->getOperand(1))) {
2647         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2648         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2649                                                      Op1, "tmp");
2650         InsertNewInstBefore(Add, I);
2651         Value *C1C2 = ConstantExpr::getMul(Op1, 
2652                                            cast<Constant>(Op0I->getOperand(1)));
2653         return BinaryOperator::createAdd(Add, C1C2);
2654         
2655       }
2656
2657     // Try to fold constant mul into select arguments.
2658     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2659       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2660         return R;
2661
2662     if (isa<PHINode>(Op0))
2663       if (Instruction *NV = FoldOpIntoPhi(I))
2664         return NV;
2665   }
2666
2667   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2668     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2669       return BinaryOperator::createMul(Op0v, Op1v);
2670
2671   // If one of the operands of the multiply is a cast from a boolean value, then
2672   // we know the bool is either zero or one, so this is a 'masking' multiply.
2673   // See if we can simplify things based on how the boolean was originally
2674   // formed.
2675   CastInst *BoolCast = 0;
2676   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2677     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2678       BoolCast = CI;
2679   if (!BoolCast)
2680     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2681       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2682         BoolCast = CI;
2683   if (BoolCast) {
2684     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2685       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2686       const Type *SCOpTy = SCIOp0->getType();
2687       bool TIS = false;
2688       
2689       // If the icmp is true iff the sign bit of X is set, then convert this
2690       // multiply into a shift/and combination.
2691       if (isa<ConstantInt>(SCIOp1) &&
2692           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2693           TIS) {
2694         // Shift the X value right to turn it into "all signbits".
2695         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2696                                           SCOpTy->getPrimitiveSizeInBits()-1);
2697         Value *V =
2698           InsertNewInstBefore(
2699             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2700                                             BoolCast->getOperand(0)->getName()+
2701                                             ".mask"), I);
2702
2703         // If the multiply type is not the same as the source type, sign extend
2704         // or truncate to the multiply type.
2705         if (I.getType() != V->getType()) {
2706           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2707           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2708           Instruction::CastOps opcode = 
2709             (SrcBits == DstBits ? Instruction::BitCast : 
2710              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2711           V = InsertCastBefore(opcode, V, I.getType(), I);
2712         }
2713
2714         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2715         return BinaryOperator::createAnd(V, OtherOp);
2716       }
2717     }
2718   }
2719
2720   return Changed ? &I : 0;
2721 }
2722
2723 /// This function implements the transforms on div instructions that work
2724 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2725 /// used by the visitors to those instructions.
2726 /// @brief Transforms common to all three div instructions
2727 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2728   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2729
2730   // undef / X -> 0        for integer.
2731   // undef / X -> undef    for FP (the undef could be a snan).
2732   if (isa<UndefValue>(Op0)) {
2733     if (Op0->getType()->isFPOrFPVector())
2734       return ReplaceInstUsesWith(I, Op0);
2735     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2736   }
2737
2738   // X / undef -> undef
2739   if (isa<UndefValue>(Op1))
2740     return ReplaceInstUsesWith(I, Op1);
2741
2742   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2743   // This does not apply for fdiv.
2744   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2745     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2746     // the same basic block, then we replace the select with Y, and the
2747     // condition of the select with false (if the cond value is in the same BB).
2748     // If the select has uses other than the div, this allows them to be
2749     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2750     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2751       if (ST->isNullValue()) {
2752         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2753         if (CondI && CondI->getParent() == I.getParent())
2754           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2755         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2756           I.setOperand(1, SI->getOperand(2));
2757         else
2758           UpdateValueUsesWith(SI, SI->getOperand(2));
2759         return &I;
2760       }
2761
2762     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2763     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2764       if (ST->isNullValue()) {
2765         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2766         if (CondI && CondI->getParent() == I.getParent())
2767           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2768         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2769           I.setOperand(1, SI->getOperand(1));
2770         else
2771           UpdateValueUsesWith(SI, SI->getOperand(1));
2772         return &I;
2773       }
2774   }
2775
2776   return 0;
2777 }
2778
2779 /// This function implements the transforms common to both integer division
2780 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2781 /// division instructions.
2782 /// @brief Common integer divide transforms
2783 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2784   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2785
2786   if (Instruction *Common = commonDivTransforms(I))
2787     return Common;
2788
2789   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2790     // div X, 1 == X
2791     if (RHS->equalsInt(1))
2792       return ReplaceInstUsesWith(I, Op0);
2793
2794     // (X / C1) / C2  -> X / (C1*C2)
2795     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2796       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2797         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2798           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2799             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2800           else 
2801             return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2802                                           Multiply(RHS, LHSRHS));
2803         }
2804
2805     if (!RHS->isZero()) { // avoid X udiv 0
2806       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2807         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2808           return R;
2809       if (isa<PHINode>(Op0))
2810         if (Instruction *NV = FoldOpIntoPhi(I))
2811           return NV;
2812     }
2813   }
2814
2815   // 0 / X == 0, we don't need to preserve faults!
2816   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2817     if (LHS->equalsInt(0))
2818       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2819
2820   return 0;
2821 }
2822
2823 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2824   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2825
2826   // Handle the integer div common cases
2827   if (Instruction *Common = commonIDivTransforms(I))
2828     return Common;
2829
2830   // X udiv C^2 -> X >> C
2831   // Check to see if this is an unsigned division with an exact power of 2,
2832   // if so, convert to a right shift.
2833   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2834     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2835       return BinaryOperator::createLShr(Op0, 
2836                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2837   }
2838
2839   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2840   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2841     if (RHSI->getOpcode() == Instruction::Shl &&
2842         isa<ConstantInt>(RHSI->getOperand(0))) {
2843       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2844       if (C1.isPowerOf2()) {
2845         Value *N = RHSI->getOperand(1);
2846         const Type *NTy = N->getType();
2847         if (uint32_t C2 = C1.logBase2()) {
2848           Constant *C2V = ConstantInt::get(NTy, C2);
2849           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2850         }
2851         return BinaryOperator::createLShr(Op0, N);
2852       }
2853     }
2854   }
2855   
2856   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2857   // where C1&C2 are powers of two.
2858   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2859     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2860       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2861         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2862         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2863           // Compute the shift amounts
2864           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2865           // Construct the "on true" case of the select
2866           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2867           Instruction *TSI = BinaryOperator::createLShr(
2868                                                  Op0, TC, SI->getName()+".t");
2869           TSI = InsertNewInstBefore(TSI, I);
2870   
2871           // Construct the "on false" case of the select
2872           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2873           Instruction *FSI = BinaryOperator::createLShr(
2874                                                  Op0, FC, SI->getName()+".f");
2875           FSI = InsertNewInstBefore(FSI, I);
2876
2877           // construct the select instruction and return it.
2878           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2879         }
2880       }
2881   return 0;
2882 }
2883
2884 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2885   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2886
2887   // Handle the integer div common cases
2888   if (Instruction *Common = commonIDivTransforms(I))
2889     return Common;
2890
2891   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2892     // sdiv X, -1 == -X
2893     if (RHS->isAllOnesValue())
2894       return BinaryOperator::createNeg(Op0);
2895
2896     // -X/C -> X/-C
2897     if (Value *LHSNeg = dyn_castNegVal(Op0))
2898       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2899   }
2900
2901   // If the sign bits of both operands are zero (i.e. we can prove they are
2902   // unsigned inputs), turn this into a udiv.
2903   if (I.getType()->isInteger()) {
2904     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2905     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2906       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2907       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2908     }
2909   }      
2910   
2911   return 0;
2912 }
2913
2914 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2915   return commonDivTransforms(I);
2916 }
2917
2918 /// This function implements the transforms on rem instructions that work
2919 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2920 /// is used by the visitors to those instructions.
2921 /// @brief Transforms common to all three rem instructions
2922 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2923   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2924
2925   // 0 % X == 0 for integer, we don't need to preserve faults!
2926   if (Constant *LHS = dyn_cast<Constant>(Op0))
2927     if (LHS->isNullValue())
2928       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2929
2930   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2931     if (I.getType()->isFPOrFPVector())
2932       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2933     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2934   }
2935   if (isa<UndefValue>(Op1))
2936     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2937
2938   // Handle cases involving: rem X, (select Cond, Y, Z)
2939   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2940     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2941     // the same basic block, then we replace the select with Y, and the
2942     // condition of the select with false (if the cond value is in the same
2943     // BB).  If the select has uses other than the div, this allows them to be
2944     // simplified also.
2945     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2946       if (ST->isNullValue()) {
2947         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2948         if (CondI && CondI->getParent() == I.getParent())
2949           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2950         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2951           I.setOperand(1, SI->getOperand(2));
2952         else
2953           UpdateValueUsesWith(SI, SI->getOperand(2));
2954         return &I;
2955       }
2956     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2957     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2958       if (ST->isNullValue()) {
2959         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2960         if (CondI && CondI->getParent() == I.getParent())
2961           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2962         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2963           I.setOperand(1, SI->getOperand(1));
2964         else
2965           UpdateValueUsesWith(SI, SI->getOperand(1));
2966         return &I;
2967       }
2968   }
2969
2970   return 0;
2971 }
2972
2973 /// This function implements the transforms common to both integer remainder
2974 /// instructions (urem and srem). It is called by the visitors to those integer
2975 /// remainder instructions.
2976 /// @brief Common integer remainder transforms
2977 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2978   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2979
2980   if (Instruction *common = commonRemTransforms(I))
2981     return common;
2982
2983   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2984     // X % 0 == undef, we don't need to preserve faults!
2985     if (RHS->equalsInt(0))
2986       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2987     
2988     if (RHS->equalsInt(1))  // X % 1 == 0
2989       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2990
2991     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2992       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2993         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994           return R;
2995       } else if (isa<PHINode>(Op0I)) {
2996         if (Instruction *NV = FoldOpIntoPhi(I))
2997           return NV;
2998       }
2999
3000       // See if we can fold away this rem instruction.
3001       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3002       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3003       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3004                                KnownZero, KnownOne))
3005         return &I;
3006     }
3007   }
3008
3009   return 0;
3010 }
3011
3012 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3013   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
3015   if (Instruction *common = commonIRemTransforms(I))
3016     return common;
3017   
3018   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3019     // X urem C^2 -> X and C
3020     // Check to see if this is an unsigned remainder with an exact power of 2,
3021     // if so, convert to a bitwise and.
3022     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3023       if (C->getValue().isPowerOf2())
3024         return BinaryOperator::createAnd(Op0, SubOne(C));
3025   }
3026
3027   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3028     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3029     if (RHSI->getOpcode() == Instruction::Shl &&
3030         isa<ConstantInt>(RHSI->getOperand(0))) {
3031       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3032         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3033         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3034                                                                    "tmp"), I);
3035         return BinaryOperator::createAnd(Op0, Add);
3036       }
3037     }
3038   }
3039
3040   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3041   // where C1&C2 are powers of two.
3042   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3043     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3044       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3045         // STO == 0 and SFO == 0 handled above.
3046         if ((STO->getValue().isPowerOf2()) && 
3047             (SFO->getValue().isPowerOf2())) {
3048           Value *TrueAnd = InsertNewInstBefore(
3049             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3050           Value *FalseAnd = InsertNewInstBefore(
3051             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3052           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3053         }
3054       }
3055   }
3056   
3057   return 0;
3058 }
3059
3060 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3061   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3062
3063   // Handle the integer rem common cases
3064   if (Instruction *common = commonIRemTransforms(I))
3065     return common;
3066   
3067   if (Value *RHSNeg = dyn_castNegVal(Op1))
3068     if (!isa<ConstantInt>(RHSNeg) || 
3069         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3070       // X % -Y -> X % Y
3071       AddUsesToWorkList(I);
3072       I.setOperand(1, RHSNeg);
3073       return &I;
3074     }
3075  
3076   // If the sign bits of both operands are zero (i.e. we can prove they are
3077   // unsigned inputs), turn this into a urem.
3078   if (I.getType()->isInteger()) {
3079     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3080     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3081       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3082       return BinaryOperator::createURem(Op0, Op1, I.getName());
3083     }
3084   }
3085
3086   return 0;
3087 }
3088
3089 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3090   return commonRemTransforms(I);
3091 }
3092
3093 // isMaxValueMinusOne - return true if this is Max-1
3094 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3095   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3096   if (!isSigned)
3097     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3098   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3099 }
3100
3101 // isMinValuePlusOne - return true if this is Min+1
3102 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3103   if (!isSigned)
3104     return C->getValue() == 1; // unsigned
3105     
3106   // Calculate 1111111111000000000000
3107   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3108   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3109 }
3110
3111 // isOneBitSet - Return true if there is exactly one bit set in the specified
3112 // constant.
3113 static bool isOneBitSet(const ConstantInt *CI) {
3114   return CI->getValue().isPowerOf2();
3115 }
3116
3117 // isHighOnes - Return true if the constant is of the form 1+0+.
3118 // This is the same as lowones(~X).
3119 static bool isHighOnes(const ConstantInt *CI) {
3120   return (~CI->getValue() + 1).isPowerOf2();
3121 }
3122
3123 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3124 /// are carefully arranged to allow folding of expressions such as:
3125 ///
3126 ///      (A < B) | (A > B) --> (A != B)
3127 ///
3128 /// Note that this is only valid if the first and second predicates have the
3129 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3130 ///
3131 /// Three bits are used to represent the condition, as follows:
3132 ///   0  A > B
3133 ///   1  A == B
3134 ///   2  A < B
3135 ///
3136 /// <=>  Value  Definition
3137 /// 000     0   Always false
3138 /// 001     1   A >  B
3139 /// 010     2   A == B
3140 /// 011     3   A >= B
3141 /// 100     4   A <  B
3142 /// 101     5   A != B
3143 /// 110     6   A <= B
3144 /// 111     7   Always true
3145 ///  
3146 static unsigned getICmpCode(const ICmpInst *ICI) {
3147   switch (ICI->getPredicate()) {
3148     // False -> 0
3149   case ICmpInst::ICMP_UGT: return 1;  // 001
3150   case ICmpInst::ICMP_SGT: return 1;  // 001
3151   case ICmpInst::ICMP_EQ:  return 2;  // 010
3152   case ICmpInst::ICMP_UGE: return 3;  // 011
3153   case ICmpInst::ICMP_SGE: return 3;  // 011
3154   case ICmpInst::ICMP_ULT: return 4;  // 100
3155   case ICmpInst::ICMP_SLT: return 4;  // 100
3156   case ICmpInst::ICMP_NE:  return 5;  // 101
3157   case ICmpInst::ICMP_ULE: return 6;  // 110
3158   case ICmpInst::ICMP_SLE: return 6;  // 110
3159     // True -> 7
3160   default:
3161     assert(0 && "Invalid ICmp predicate!");
3162     return 0;
3163   }
3164 }
3165
3166 /// getICmpValue - This is the complement of getICmpCode, which turns an
3167 /// opcode and two operands into either a constant true or false, or a brand 
3168 /// new ICmp instruction. The sign is passed in to determine which kind
3169 /// of predicate to use in new icmp instructions.
3170 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3171   switch (code) {
3172   default: assert(0 && "Illegal ICmp code!");
3173   case  0: return ConstantInt::getFalse();
3174   case  1: 
3175     if (sign)
3176       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3177     else
3178       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3179   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3180   case  3: 
3181     if (sign)
3182       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3183     else
3184       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3185   case  4: 
3186     if (sign)
3187       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3188     else
3189       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3190   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3191   case  6: 
3192     if (sign)
3193       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3194     else
3195       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3196   case  7: return ConstantInt::getTrue();
3197   }
3198 }
3199
3200 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3201   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3202     (ICmpInst::isSignedPredicate(p1) && 
3203      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3204     (ICmpInst::isSignedPredicate(p2) && 
3205      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3206 }
3207
3208 namespace { 
3209 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3210 struct FoldICmpLogical {
3211   InstCombiner &IC;
3212   Value *LHS, *RHS;
3213   ICmpInst::Predicate pred;
3214   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3215     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3216       pred(ICI->getPredicate()) {}
3217   bool shouldApply(Value *V) const {
3218     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3219       if (PredicatesFoldable(pred, ICI->getPredicate()))
3220         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3221                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3222     return false;
3223   }
3224   Instruction *apply(Instruction &Log) const {
3225     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3226     if (ICI->getOperand(0) != LHS) {
3227       assert(ICI->getOperand(1) == LHS);
3228       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3229     }
3230
3231     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3232     unsigned LHSCode = getICmpCode(ICI);
3233     unsigned RHSCode = getICmpCode(RHSICI);
3234     unsigned Code;
3235     switch (Log.getOpcode()) {
3236     case Instruction::And: Code = LHSCode & RHSCode; break;
3237     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3238     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3239     default: assert(0 && "Illegal logical opcode!"); return 0;
3240     }
3241
3242     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3243                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3244       
3245     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3246     if (Instruction *I = dyn_cast<Instruction>(RV))
3247       return I;
3248     // Otherwise, it's a constant boolean value...
3249     return IC.ReplaceInstUsesWith(Log, RV);
3250   }
3251 };
3252 } // end anonymous namespace
3253
3254 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3255 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3256 // guaranteed to be a binary operator.
3257 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3258                                     ConstantInt *OpRHS,
3259                                     ConstantInt *AndRHS,
3260                                     BinaryOperator &TheAnd) {
3261   Value *X = Op->getOperand(0);
3262   Constant *Together = 0;
3263   if (!Op->isShift())
3264     Together = And(AndRHS, OpRHS);
3265
3266   switch (Op->getOpcode()) {
3267   case Instruction::Xor:
3268     if (Op->hasOneUse()) {
3269       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3270       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3271       InsertNewInstBefore(And, TheAnd);
3272       And->takeName(Op);
3273       return BinaryOperator::createXor(And, Together);
3274     }
3275     break;
3276   case Instruction::Or:
3277     if (Together == AndRHS) // (X | C) & C --> C
3278       return ReplaceInstUsesWith(TheAnd, AndRHS);
3279
3280     if (Op->hasOneUse() && Together != OpRHS) {
3281       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3282       Instruction *Or = BinaryOperator::createOr(X, Together);
3283       InsertNewInstBefore(Or, TheAnd);
3284       Or->takeName(Op);
3285       return BinaryOperator::createAnd(Or, AndRHS);
3286     }
3287     break;
3288   case Instruction::Add:
3289     if (Op->hasOneUse()) {
3290       // Adding a one to a single bit bit-field should be turned into an XOR
3291       // of the bit.  First thing to check is to see if this AND is with a
3292       // single bit constant.
3293       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3294
3295       // If there is only one bit set...
3296       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3297         // Ok, at this point, we know that we are masking the result of the
3298         // ADD down to exactly one bit.  If the constant we are adding has
3299         // no bits set below this bit, then we can eliminate the ADD.
3300         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3301
3302         // Check to see if any bits below the one bit set in AndRHSV are set.
3303         if ((AddRHS & (AndRHSV-1)) == 0) {
3304           // If not, the only thing that can effect the output of the AND is
3305           // the bit specified by AndRHSV.  If that bit is set, the effect of
3306           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3307           // no effect.
3308           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3309             TheAnd.setOperand(0, X);
3310             return &TheAnd;
3311           } else {
3312             // Pull the XOR out of the AND.
3313             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3314             InsertNewInstBefore(NewAnd, TheAnd);
3315             NewAnd->takeName(Op);
3316             return BinaryOperator::createXor(NewAnd, AndRHS);
3317           }
3318         }
3319       }
3320     }
3321     break;
3322
3323   case Instruction::Shl: {
3324     // We know that the AND will not produce any of the bits shifted in, so if
3325     // the anded constant includes them, clear them now!
3326     //
3327     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3328     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3329     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3330     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3331
3332     if (CI->getValue() == ShlMask) { 
3333     // Masking out bits that the shift already masks
3334       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3335     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3336       TheAnd.setOperand(1, CI);
3337       return &TheAnd;
3338     }
3339     break;
3340   }
3341   case Instruction::LShr:
3342   {
3343     // We know that the AND will not produce any of the bits shifted in, so if
3344     // the anded constant includes them, clear them now!  This only applies to
3345     // unsigned shifts, because a signed shr may bring in set bits!
3346     //
3347     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3348     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3349     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3350     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3351
3352     if (CI->getValue() == ShrMask) {   
3353     // Masking out bits that the shift already masks.
3354       return ReplaceInstUsesWith(TheAnd, Op);
3355     } else if (CI != AndRHS) {
3356       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3357       return &TheAnd;
3358     }
3359     break;
3360   }
3361   case Instruction::AShr:
3362     // Signed shr.
3363     // See if this is shifting in some sign extension, then masking it out
3364     // with an and.
3365     if (Op->hasOneUse()) {
3366       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3367       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3368       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3369       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3370       if (C == AndRHS) {          // Masking out bits shifted in.
3371         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3372         // Make the argument unsigned.
3373         Value *ShVal = Op->getOperand(0);
3374         ShVal = InsertNewInstBefore(
3375             BinaryOperator::createLShr(ShVal, OpRHS, 
3376                                    Op->getName()), TheAnd);
3377         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3378       }
3379     }
3380     break;
3381   }
3382   return 0;
3383 }
3384
3385
3386 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3387 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3388 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3389 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3390 /// insert new instructions.
3391 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3392                                            bool isSigned, bool Inside, 
3393                                            Instruction &IB) {
3394   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3395             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3396          "Lo is not <= Hi in range emission code!");
3397     
3398   if (Inside) {
3399     if (Lo == Hi)  // Trivially false.
3400       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3401
3402     // V >= Min && V < Hi --> V < Hi
3403     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3404       ICmpInst::Predicate pred = (isSigned ? 
3405         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3406       return new ICmpInst(pred, V, Hi);
3407     }
3408
3409     // Emit V-Lo <u Hi-Lo
3410     Constant *NegLo = ConstantExpr::getNeg(Lo);
3411     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3412     InsertNewInstBefore(Add, IB);
3413     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3414     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3415   }
3416
3417   if (Lo == Hi)  // Trivially true.
3418     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3419
3420   // V < Min || V >= Hi -> V > Hi-1
3421   Hi = SubOne(cast<ConstantInt>(Hi));
3422   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3423     ICmpInst::Predicate pred = (isSigned ? 
3424         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3425     return new ICmpInst(pred, V, Hi);
3426   }
3427
3428   // Emit V-Lo >u Hi-1-Lo
3429   // Note that Hi has already had one subtracted from it, above.
3430   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3431   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3432   InsertNewInstBefore(Add, IB);
3433   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3434   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3435 }
3436
3437 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3438 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3439 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3440 // not, since all 1s are not contiguous.
3441 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3442   const APInt& V = Val->getValue();
3443   uint32_t BitWidth = Val->getType()->getBitWidth();
3444   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3445
3446   // look for the first zero bit after the run of ones
3447   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3448   // look for the first non-zero bit
3449   ME = V.getActiveBits(); 
3450   return true;
3451 }
3452
3453 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3454 /// where isSub determines whether the operator is a sub.  If we can fold one of
3455 /// the following xforms:
3456 /// 
3457 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3458 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3459 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3460 ///
3461 /// return (A +/- B).
3462 ///
3463 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3464                                         ConstantInt *Mask, bool isSub,
3465                                         Instruction &I) {
3466   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3467   if (!LHSI || LHSI->getNumOperands() != 2 ||
3468       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3469
3470   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3471
3472   switch (LHSI->getOpcode()) {
3473   default: return 0;
3474   case Instruction::And:
3475     if (And(N, Mask) == Mask) {
3476       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3477       if ((Mask->getValue().countLeadingZeros() + 
3478            Mask->getValue().countPopulation()) == 
3479           Mask->getValue().getBitWidth())
3480         break;
3481
3482       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3483       // part, we don't need any explicit masks to take them out of A.  If that
3484       // is all N is, ignore it.
3485       uint32_t MB = 0, ME = 0;
3486       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3487         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3488         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3489         if (MaskedValueIsZero(RHS, Mask))
3490           break;
3491       }
3492     }
3493     return 0;
3494   case Instruction::Or:
3495   case Instruction::Xor:
3496     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3497     if ((Mask->getValue().countLeadingZeros() + 
3498          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3499         && And(N, Mask)->isZero())
3500       break;
3501     return 0;
3502   }
3503   
3504   Instruction *New;
3505   if (isSub)
3506     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3507   else
3508     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3509   return InsertNewInstBefore(New, I);
3510 }
3511
3512 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3513   bool Changed = SimplifyCommutative(I);
3514   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3515
3516   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3517     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3518
3519   // and X, X = X
3520   if (Op0 == Op1)
3521     return ReplaceInstUsesWith(I, Op1);
3522
3523   // See if we can simplify any instructions used by the instruction whose sole 
3524   // purpose is to compute bits we don't care about.
3525   if (!isa<VectorType>(I.getType())) {
3526     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3527     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3528     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3529                              KnownZero, KnownOne))
3530       return &I;
3531   } else {
3532     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3533       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3534         return ReplaceInstUsesWith(I, I.getOperand(0));
3535     } else if (isa<ConstantAggregateZero>(Op1)) {
3536       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3537     }
3538   }
3539   
3540   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3541     const APInt& AndRHSMask = AndRHS->getValue();
3542     APInt NotAndRHS(~AndRHSMask);
3543
3544     // Optimize a variety of ((val OP C1) & C2) combinations...
3545     if (isa<BinaryOperator>(Op0)) {
3546       Instruction *Op0I = cast<Instruction>(Op0);
3547       Value *Op0LHS = Op0I->getOperand(0);
3548       Value *Op0RHS = Op0I->getOperand(1);
3549       switch (Op0I->getOpcode()) {
3550       case Instruction::Xor:
3551       case Instruction::Or:
3552         // If the mask is only needed on one incoming arm, push it up.
3553         if (Op0I->hasOneUse()) {
3554           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3555             // Not masking anything out for the LHS, move to RHS.
3556             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3557                                                    Op0RHS->getName()+".masked");
3558             InsertNewInstBefore(NewRHS, I);
3559             return BinaryOperator::create(
3560                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3561           }
3562           if (!isa<Constant>(Op0RHS) &&
3563               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3564             // Not masking anything out for the RHS, move to LHS.
3565             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3566                                                    Op0LHS->getName()+".masked");
3567             InsertNewInstBefore(NewLHS, I);
3568             return BinaryOperator::create(
3569                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3570           }
3571         }
3572
3573         break;
3574       case Instruction::Add:
3575         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3576         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3577         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3578         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3579           return BinaryOperator::createAnd(V, AndRHS);
3580         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3581           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3582         break;
3583
3584       case Instruction::Sub:
3585         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3586         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3587         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3588         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3589           return BinaryOperator::createAnd(V, AndRHS);
3590         break;
3591       }
3592
3593       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3594         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3595           return Res;
3596     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3597       // If this is an integer truncation or change from signed-to-unsigned, and
3598       // if the source is an and/or with immediate, transform it.  This
3599       // frequently occurs for bitfield accesses.
3600       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3601         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3602             CastOp->getNumOperands() == 2)
3603           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3604             if (CastOp->getOpcode() == Instruction::And) {
3605               // Change: and (cast (and X, C1) to T), C2
3606               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3607               // This will fold the two constants together, which may allow 
3608               // other simplifications.
3609               Instruction *NewCast = CastInst::createTruncOrBitCast(
3610                 CastOp->getOperand(0), I.getType(), 
3611                 CastOp->getName()+".shrunk");
3612               NewCast = InsertNewInstBefore(NewCast, I);
3613               // trunc_or_bitcast(C1)&C2
3614               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3615               C3 = ConstantExpr::getAnd(C3, AndRHS);
3616               return BinaryOperator::createAnd(NewCast, C3);
3617             } else if (CastOp->getOpcode() == Instruction::Or) {
3618               // Change: and (cast (or X, C1) to T), C2
3619               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3620               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3621               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3622                 return ReplaceInstUsesWith(I, AndRHS);
3623             }
3624           }
3625       }
3626     }
3627
3628     // Try to fold constant and into select arguments.
3629     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3630       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3631         return R;
3632     if (isa<PHINode>(Op0))
3633       if (Instruction *NV = FoldOpIntoPhi(I))
3634         return NV;
3635   }
3636
3637   Value *Op0NotVal = dyn_castNotVal(Op0);
3638   Value *Op1NotVal = dyn_castNotVal(Op1);
3639
3640   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3641     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3642
3643   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3644   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3645     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3646                                                I.getName()+".demorgan");
3647     InsertNewInstBefore(Or, I);
3648     return BinaryOperator::createNot(Or);
3649   }
3650   
3651   {
3652     Value *A = 0, *B = 0, *C = 0, *D = 0;
3653     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3654       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3655         return ReplaceInstUsesWith(I, Op1);
3656     
3657       // (A|B) & ~(A&B) -> A^B
3658       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3659         if ((A == C && B == D) || (A == D && B == C))
3660           return BinaryOperator::createXor(A, B);
3661       }
3662     }
3663     
3664     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3665       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3666         return ReplaceInstUsesWith(I, Op0);
3667
3668       // ~(A&B) & (A|B) -> A^B
3669       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3670         if ((A == C && B == D) || (A == D && B == C))
3671           return BinaryOperator::createXor(A, B);
3672       }
3673     }
3674     
3675     if (Op0->hasOneUse() &&
3676         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3677       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3678         I.swapOperands();     // Simplify below
3679         std::swap(Op0, Op1);
3680       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3681         cast<BinaryOperator>(Op0)->swapOperands();
3682         I.swapOperands();     // Simplify below
3683         std::swap(Op0, Op1);
3684       }
3685     }
3686     if (Op1->hasOneUse() &&
3687         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3688       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3689         cast<BinaryOperator>(Op1)->swapOperands();
3690         std::swap(A, B);
3691       }
3692       if (A == Op0) {                                // A&(A^B) -> A & ~B
3693         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3694         InsertNewInstBefore(NotB, I);
3695         return BinaryOperator::createAnd(A, NotB);
3696       }
3697     }
3698   }
3699   
3700   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3701     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3702     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3703       return R;
3704
3705     Value *LHSVal, *RHSVal;
3706     ConstantInt *LHSCst, *RHSCst;
3707     ICmpInst::Predicate LHSCC, RHSCC;
3708     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3709       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3710         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3711             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3712             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3713             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3714             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3715             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3716             
3717             // Don't try to fold ICMP_SLT + ICMP_ULT.
3718             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3719              ICmpInst::isSignedPredicate(LHSCC) == 
3720                  ICmpInst::isSignedPredicate(RHSCC))) {
3721           // Ensure that the larger constant is on the RHS.
3722           ICmpInst::Predicate GT;
3723           if (ICmpInst::isSignedPredicate(LHSCC) ||
3724               (ICmpInst::isEquality(LHSCC) && 
3725                ICmpInst::isSignedPredicate(RHSCC)))
3726             GT = ICmpInst::ICMP_SGT;
3727           else
3728             GT = ICmpInst::ICMP_UGT;
3729           
3730           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3731           ICmpInst *LHS = cast<ICmpInst>(Op0);
3732           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3733             std::swap(LHS, RHS);
3734             std::swap(LHSCst, RHSCst);
3735             std::swap(LHSCC, RHSCC);
3736           }
3737
3738           // At this point, we know we have have two icmp instructions
3739           // comparing a value against two constants and and'ing the result
3740           // together.  Because of the above check, we know that we only have
3741           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3742           // (from the FoldICmpLogical check above), that the two constants 
3743           // are not equal and that the larger constant is on the RHS
3744           assert(LHSCst != RHSCst && "Compares not folded above?");
3745
3746           switch (LHSCC) {
3747           default: assert(0 && "Unknown integer condition code!");
3748           case ICmpInst::ICMP_EQ:
3749             switch (RHSCC) {
3750             default: assert(0 && "Unknown integer condition code!");
3751             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3752             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3753             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3754               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3755             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3756             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3757             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3758               return ReplaceInstUsesWith(I, LHS);
3759             }
3760           case ICmpInst::ICMP_NE:
3761             switch (RHSCC) {
3762             default: assert(0 && "Unknown integer condition code!");
3763             case ICmpInst::ICMP_ULT:
3764               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3765                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3766               break;                        // (X != 13 & X u< 15) -> no change
3767             case ICmpInst::ICMP_SLT:
3768               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3769                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3770               break;                        // (X != 13 & X s< 15) -> no change
3771             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3772             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3773             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3774               return ReplaceInstUsesWith(I, RHS);
3775             case ICmpInst::ICMP_NE:
3776               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3777                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3778                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3779                                                       LHSVal->getName()+".off");
3780                 InsertNewInstBefore(Add, I);
3781                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3782                                     ConstantInt::get(Add->getType(), 1));
3783               }
3784               break;                        // (X != 13 & X != 15) -> no change
3785             }
3786             break;
3787           case ICmpInst::ICMP_ULT:
3788             switch (RHSCC) {
3789             default: assert(0 && "Unknown integer condition code!");
3790             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3791             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3792               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3793             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3794               break;
3795             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3796             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3797               return ReplaceInstUsesWith(I, LHS);
3798             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3799               break;
3800             }
3801             break;
3802           case ICmpInst::ICMP_SLT:
3803             switch (RHSCC) {
3804             default: assert(0 && "Unknown integer condition code!");
3805             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3806             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3807               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3808             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3809               break;
3810             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3811             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3812               return ReplaceInstUsesWith(I, LHS);
3813             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3814               break;
3815             }
3816             break;
3817           case ICmpInst::ICMP_UGT:
3818             switch (RHSCC) {
3819             default: assert(0 && "Unknown integer condition code!");
3820             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3821               return ReplaceInstUsesWith(I, LHS);
3822             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3823               return ReplaceInstUsesWith(I, RHS);
3824             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3825               break;
3826             case ICmpInst::ICMP_NE:
3827               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3828                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3829               break;                        // (X u> 13 & X != 15) -> no change
3830             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3831               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3832                                      true, I);
3833             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3834               break;
3835             }
3836             break;
3837           case ICmpInst::ICMP_SGT:
3838             switch (RHSCC) {
3839             default: assert(0 && "Unknown integer condition code!");
3840             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3841             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3842               return ReplaceInstUsesWith(I, RHS);
3843             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3844               break;
3845             case ICmpInst::ICMP_NE:
3846               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3847                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3848               break;                        // (X s> 13 & X != 15) -> no change
3849             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3850               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3851                                      true, I);
3852             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3853               break;
3854             }
3855             break;
3856           }
3857         }
3858   }
3859
3860   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3861   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3862     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3863       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3864         const Type *SrcTy = Op0C->getOperand(0)->getType();
3865         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3866             // Only do this if the casts both really cause code to be generated.
3867             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3868                               I.getType(), TD) &&
3869             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3870                               I.getType(), TD)) {
3871           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3872                                                          Op1C->getOperand(0),
3873                                                          I.getName());
3874           InsertNewInstBefore(NewOp, I);
3875           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3876         }
3877       }
3878     
3879   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3880   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3881     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3882       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3883           SI0->getOperand(1) == SI1->getOperand(1) &&
3884           (SI0->hasOneUse() || SI1->hasOneUse())) {
3885         Instruction *NewOp =
3886           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3887                                                         SI1->getOperand(0),
3888                                                         SI0->getName()), I);
3889         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3890                                       SI1->getOperand(1));
3891       }
3892   }
3893
3894   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3895   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3896     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3897       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3898           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3899         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3900           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3901             // If either of the constants are nans, then the whole thing returns
3902             // false.
3903             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3904               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3905             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3906                                 RHS->getOperand(0));
3907           }
3908     }
3909   }
3910       
3911   return Changed ? &I : 0;
3912 }
3913
3914 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3915 /// in the result.  If it does, and if the specified byte hasn't been filled in
3916 /// yet, fill it in and return false.
3917 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3918   Instruction *I = dyn_cast<Instruction>(V);
3919   if (I == 0) return true;
3920
3921   // If this is an or instruction, it is an inner node of the bswap.
3922   if (I->getOpcode() == Instruction::Or)
3923     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3924            CollectBSwapParts(I->getOperand(1), ByteValues);
3925   
3926   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3927   // If this is a shift by a constant int, and it is "24", then its operand
3928   // defines a byte.  We only handle unsigned types here.
3929   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3930     // Not shifting the entire input by N-1 bytes?
3931     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3932         8*(ByteValues.size()-1))
3933       return true;
3934     
3935     unsigned DestNo;
3936     if (I->getOpcode() == Instruction::Shl) {
3937       // X << 24 defines the top byte with the lowest of the input bytes.
3938       DestNo = ByteValues.size()-1;
3939     } else {
3940       // X >>u 24 defines the low byte with the highest of the input bytes.
3941       DestNo = 0;
3942     }
3943     
3944     // If the destination byte value is already defined, the values are or'd
3945     // together, which isn't a bswap (unless it's an or of the same bits).
3946     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3947       return true;
3948     ByteValues[DestNo] = I->getOperand(0);
3949     return false;
3950   }
3951   
3952   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3953   // don't have this.
3954   Value *Shift = 0, *ShiftLHS = 0;
3955   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3956   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3957       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3958     return true;
3959   Instruction *SI = cast<Instruction>(Shift);
3960
3961   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3962   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3963       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3964     return true;
3965   
3966   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3967   unsigned DestByte;
3968   if (AndAmt->getValue().getActiveBits() > 64)
3969     return true;
3970   uint64_t AndAmtVal = AndAmt->getZExtValue();
3971   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3972     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3973       break;
3974   // Unknown mask for bswap.
3975   if (DestByte == ByteValues.size()) return true;
3976   
3977   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3978   unsigned SrcByte;
3979   if (SI->getOpcode() == Instruction::Shl)
3980     SrcByte = DestByte - ShiftBytes;
3981   else
3982     SrcByte = DestByte + ShiftBytes;
3983   
3984   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3985   if (SrcByte != ByteValues.size()-DestByte-1)
3986     return true;
3987   
3988   // If the destination byte value is already defined, the values are or'd
3989   // together, which isn't a bswap (unless it's an or of the same bits).
3990   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3991     return true;
3992   ByteValues[DestByte] = SI->getOperand(0);
3993   return false;
3994 }
3995
3996 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3997 /// If so, insert the new bswap intrinsic and return it.
3998 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3999   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4000   if (!ITy || ITy->getBitWidth() % 16) 
4001     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4002   
4003   /// ByteValues - For each byte of the result, we keep track of which value
4004   /// defines each byte.
4005   SmallVector<Value*, 8> ByteValues;
4006   ByteValues.resize(ITy->getBitWidth()/8);
4007     
4008   // Try to find all the pieces corresponding to the bswap.
4009   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4010       CollectBSwapParts(I.getOperand(1), ByteValues))
4011     return 0;
4012   
4013   // Check to see if all of the bytes come from the same value.
4014   Value *V = ByteValues[0];
4015   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4016   
4017   // Check to make sure that all of the bytes come from the same value.
4018   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4019     if (ByteValues[i] != V)
4020       return 0;
4021   const Type *Tys[] = { ITy };
4022   Module *M = I.getParent()->getParent()->getParent();
4023   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4024   return new CallInst(F, V);
4025 }
4026
4027
4028 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4029   bool Changed = SimplifyCommutative(I);
4030   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4031
4032   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4033     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4034
4035   // or X, X = X
4036   if (Op0 == Op1)
4037     return ReplaceInstUsesWith(I, Op0);
4038
4039   // See if we can simplify any instructions used by the instruction whose sole 
4040   // purpose is to compute bits we don't care about.
4041   if (!isa<VectorType>(I.getType())) {
4042     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4043     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4044     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4045                              KnownZero, KnownOne))
4046       return &I;
4047   } else if (isa<ConstantAggregateZero>(Op1)) {
4048     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4049   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4050     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4051       return ReplaceInstUsesWith(I, I.getOperand(1));
4052   }
4053     
4054
4055   
4056   // or X, -1 == -1
4057   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4058     ConstantInt *C1 = 0; Value *X = 0;
4059     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4060     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4061       Instruction *Or = BinaryOperator::createOr(X, RHS);
4062       InsertNewInstBefore(Or, I);
4063       Or->takeName(Op0);
4064       return BinaryOperator::createAnd(Or, 
4065                ConstantInt::get(RHS->getValue() | C1->getValue()));
4066     }
4067
4068     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4069     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4070       Instruction *Or = BinaryOperator::createOr(X, RHS);
4071       InsertNewInstBefore(Or, I);
4072       Or->takeName(Op0);
4073       return BinaryOperator::createXor(Or,
4074                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4075     }
4076
4077     // Try to fold constant and into select arguments.
4078     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4079       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4080         return R;
4081     if (isa<PHINode>(Op0))
4082       if (Instruction *NV = FoldOpIntoPhi(I))
4083         return NV;
4084   }
4085
4086   Value *A = 0, *B = 0;
4087   ConstantInt *C1 = 0, *C2 = 0;
4088
4089   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4090     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4091       return ReplaceInstUsesWith(I, Op1);
4092   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4093     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4094       return ReplaceInstUsesWith(I, Op0);
4095
4096   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4097   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4098   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4099       match(Op1, m_Or(m_Value(), m_Value())) ||
4100       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4101        match(Op1, m_Shift(m_Value(), m_Value())))) {
4102     if (Instruction *BSwap = MatchBSwap(I))
4103       return BSwap;
4104   }
4105   
4106   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4107   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4108       MaskedValueIsZero(Op1, C1->getValue())) {
4109     Instruction *NOr = BinaryOperator::createOr(A, Op1);
4110     InsertNewInstBefore(NOr, I);
4111     NOr->takeName(Op0);
4112     return BinaryOperator::createXor(NOr, C1);
4113   }
4114
4115   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4116   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4117       MaskedValueIsZero(Op0, C1->getValue())) {
4118     Instruction *NOr = BinaryOperator::createOr(A, Op0);
4119     InsertNewInstBefore(NOr, I);
4120     NOr->takeName(Op0);
4121     return BinaryOperator::createXor(NOr, C1);
4122   }
4123
4124   // (A & C)|(B & D)
4125   Value *C = 0, *D = 0;
4126   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4127       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4128     Value *V1 = 0, *V2 = 0, *V3 = 0;
4129     C1 = dyn_cast<ConstantInt>(C);
4130     C2 = dyn_cast<ConstantInt>(D);
4131     if (C1 && C2) {  // (A & C1)|(B & C2)
4132       // If we have: ((V + N) & C1) | (V & C2)
4133       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4134       // replace with V+N.
4135       if (C1->getValue() == ~C2->getValue()) {
4136         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4137             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4138           // Add commutes, try both ways.
4139           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4140             return ReplaceInstUsesWith(I, A);
4141           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4142             return ReplaceInstUsesWith(I, A);
4143         }
4144         // Or commutes, try both ways.
4145         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4146             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4147           // Add commutes, try both ways.
4148           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4149             return ReplaceInstUsesWith(I, B);
4150           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4151             return ReplaceInstUsesWith(I, B);
4152         }
4153       }
4154       V1 = 0; V2 = 0; V3 = 0;
4155     }
4156     
4157     // Check to see if we have any common things being and'ed.  If so, find the
4158     // terms for V1 & (V2|V3).
4159     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4160       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4161         V1 = A, V2 = C, V3 = D;
4162       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4163         V1 = A, V2 = B, V3 = C;
4164       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4165         V1 = C, V2 = A, V3 = D;
4166       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4167         V1 = C, V2 = A, V3 = B;
4168       
4169       if (V1) {
4170         Value *Or =
4171           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4172         return BinaryOperator::createAnd(V1, Or);
4173       }
4174     }
4175   }
4176   
4177   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4178   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4179     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4180       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4181           SI0->getOperand(1) == SI1->getOperand(1) &&
4182           (SI0->hasOneUse() || SI1->hasOneUse())) {
4183         Instruction *NewOp =
4184         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4185                                                      SI1->getOperand(0),
4186                                                      SI0->getName()), I);
4187         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4188                                       SI1->getOperand(1));
4189       }
4190   }
4191
4192   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4193     if (A == Op1)   // ~A | A == -1
4194       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4195   } else {
4196     A = 0;
4197   }
4198   // Note, A is still live here!
4199   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4200     if (Op0 == B)
4201       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4202
4203     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4204     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4205       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4206                                               I.getName()+".demorgan"), I);
4207       return BinaryOperator::createNot(And);
4208     }
4209   }
4210
4211   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4212   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4213     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4214       return R;
4215
4216     Value *LHSVal, *RHSVal;
4217     ConstantInt *LHSCst, *RHSCst;
4218     ICmpInst::Predicate LHSCC, RHSCC;
4219     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4222             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4223             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4226             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227             // We can't fold (ugt x, C) | (sgt x, C2).
4228             PredicatesFoldable(LHSCC, RHSCC)) {
4229           // Ensure that the larger constant is on the RHS.
4230           ICmpInst *LHS = cast<ICmpInst>(Op0);
4231           bool NeedsSwap;
4232           if (ICmpInst::isSignedPredicate(LHSCC))
4233             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4234           else
4235             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4236             
4237           if (NeedsSwap) {
4238             std::swap(LHS, RHS);
4239             std::swap(LHSCst, RHSCst);
4240             std::swap(LHSCC, RHSCC);
4241           }
4242
4243           // At this point, we know we have have two icmp instructions
4244           // comparing a value against two constants and or'ing the result
4245           // together.  Because of the above check, we know that we only have
4246           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4247           // FoldICmpLogical check above), that the two constants are not
4248           // equal.
4249           assert(LHSCst != RHSCst && "Compares not folded above?");
4250
4251           switch (LHSCC) {
4252           default: assert(0 && "Unknown integer condition code!");
4253           case ICmpInst::ICMP_EQ:
4254             switch (RHSCC) {
4255             default: assert(0 && "Unknown integer condition code!");
4256             case ICmpInst::ICMP_EQ:
4257               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4258                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4259                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4260                                                       LHSVal->getName()+".off");
4261                 InsertNewInstBefore(Add, I);
4262                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4263                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4264               }
4265               break;                         // (X == 13 | X == 15) -> no change
4266             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4267             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4268               break;
4269             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4270             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4271             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4272               return ReplaceInstUsesWith(I, RHS);
4273             }
4274             break;
4275           case ICmpInst::ICMP_NE:
4276             switch (RHSCC) {
4277             default: assert(0 && "Unknown integer condition code!");
4278             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4279             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4280             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4281               return ReplaceInstUsesWith(I, LHS);
4282             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4283             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4284             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4285               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4286             }
4287             break;
4288           case ICmpInst::ICMP_ULT:
4289             switch (RHSCC) {
4290             default: assert(0 && "Unknown integer condition code!");
4291             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4292               break;
4293             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4294               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4295               // this can cause overflow.
4296               if (RHSCst->isMaxValue(false))
4297                 return ReplaceInstUsesWith(I, LHS);
4298               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4299                                      false, I);
4300             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4301               break;
4302             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4303             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4304               return ReplaceInstUsesWith(I, RHS);
4305             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4306               break;
4307             }
4308             break;
4309           case ICmpInst::ICMP_SLT:
4310             switch (RHSCC) {
4311             default: assert(0 && "Unknown integer condition code!");
4312             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4313               break;
4314             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4315               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4316               // this can cause overflow.
4317               if (RHSCst->isMaxValue(true))
4318                 return ReplaceInstUsesWith(I, LHS);
4319               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4320                                      false, I);
4321             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4322               break;
4323             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4324             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4325               return ReplaceInstUsesWith(I, RHS);
4326             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4327               break;
4328             }
4329             break;
4330           case ICmpInst::ICMP_UGT:
4331             switch (RHSCC) {
4332             default: assert(0 && "Unknown integer condition code!");
4333             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4334             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4335               return ReplaceInstUsesWith(I, LHS);
4336             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4337               break;
4338             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4339             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4340               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4341             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4342               break;
4343             }
4344             break;
4345           case ICmpInst::ICMP_SGT:
4346             switch (RHSCC) {
4347             default: assert(0 && "Unknown integer condition code!");
4348             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4349             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4350               return ReplaceInstUsesWith(I, LHS);
4351             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4352               break;
4353             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4354             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4355               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4356             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4357               break;
4358             }
4359             break;
4360           }
4361         }
4362   }
4363     
4364   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4365   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4366     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4367       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4368         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4369             !isa<ICmpInst>(Op1C->getOperand(0))) {
4370           const Type *SrcTy = Op0C->getOperand(0)->getType();
4371           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4372               // Only do this if the casts both really cause code to be
4373               // generated.
4374               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4375                                 I.getType(), TD) &&
4376               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4377                                 I.getType(), TD)) {
4378             Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4379                                                           Op1C->getOperand(0),
4380                                                           I.getName());
4381             InsertNewInstBefore(NewOp, I);
4382             return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4383           }
4384         }
4385       }
4386   }
4387   
4388     
4389   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4390   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4391     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4392       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4393           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4394           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4395         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4396           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4397             // If either of the constants are nans, then the whole thing returns
4398             // true.
4399             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4400               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4401             
4402             // Otherwise, no need to compare the two constants, compare the
4403             // rest.
4404             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4405                                 RHS->getOperand(0));
4406           }
4407     }
4408   }
4409
4410   return Changed ? &I : 0;
4411 }
4412
4413 // XorSelf - Implements: X ^ X --> 0
4414 struct XorSelf {
4415   Value *RHS;
4416   XorSelf(Value *rhs) : RHS(rhs) {}
4417   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4418   Instruction *apply(BinaryOperator &Xor) const {
4419     return &Xor;
4420   }
4421 };
4422
4423
4424 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4425   bool Changed = SimplifyCommutative(I);
4426   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4427
4428   if (isa<UndefValue>(Op1)) {
4429     if (isa<UndefValue>(Op0))
4430       // Handle undef ^ undef -> 0 special case. This is a common
4431       // idiom (misuse).
4432       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4433     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4434   }
4435
4436   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4437   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4438     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4439     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4440   }
4441   
4442   // See if we can simplify any instructions used by the instruction whose sole 
4443   // purpose is to compute bits we don't care about.
4444   if (!isa<VectorType>(I.getType())) {
4445     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4446     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4447     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4448                              KnownZero, KnownOne))
4449       return &I;
4450   } else if (isa<ConstantAggregateZero>(Op1)) {
4451     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4452   }
4453
4454   // Is this a ~ operation?
4455   if (Value *NotOp = dyn_castNotVal(&I)) {
4456     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4457     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4458     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4459       if (Op0I->getOpcode() == Instruction::And || 
4460           Op0I->getOpcode() == Instruction::Or) {
4461         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4462         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4463           Instruction *NotY =
4464             BinaryOperator::createNot(Op0I->getOperand(1),
4465                                       Op0I->getOperand(1)->getName()+".not");
4466           InsertNewInstBefore(NotY, I);
4467           if (Op0I->getOpcode() == Instruction::And)
4468             return BinaryOperator::createOr(Op0NotVal, NotY);
4469           else
4470             return BinaryOperator::createAnd(Op0NotVal, NotY);
4471         }
4472       }
4473     }
4474   }
4475   
4476   
4477   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4478     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4479     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4480       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4481         return new ICmpInst(ICI->getInversePredicate(),
4482                             ICI->getOperand(0), ICI->getOperand(1));
4483
4484       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4485         return new FCmpInst(FCI->getInversePredicate(),
4486                             FCI->getOperand(0), FCI->getOperand(1));
4487     }
4488
4489     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4490       // ~(c-X) == X-c-1 == X+(-c-1)
4491       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4492         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4493           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4494           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4495                                               ConstantInt::get(I.getType(), 1));
4496           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4497         }
4498           
4499       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4500         if (Op0I->getOpcode() == Instruction::Add) {
4501           // ~(X-c) --> (-c-1)-X
4502           if (RHS->isAllOnesValue()) {
4503             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4504             return BinaryOperator::createSub(
4505                            ConstantExpr::getSub(NegOp0CI,
4506                                              ConstantInt::get(I.getType(), 1)),
4507                                           Op0I->getOperand(0));
4508           } else if (RHS->getValue().isSignBit()) {
4509             // (X + C) ^ signbit -> (X + C + signbit)
4510             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4511             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4512
4513           }
4514         } else if (Op0I->getOpcode() == Instruction::Or) {
4515           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4516           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4517             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4518             // Anything in both C1 and C2 is known to be zero, remove it from
4519             // NewRHS.
4520             Constant *CommonBits = And(Op0CI, RHS);
4521             NewRHS = ConstantExpr::getAnd(NewRHS, 
4522                                           ConstantExpr::getNot(CommonBits));
4523             AddToWorkList(Op0I);
4524             I.setOperand(0, Op0I->getOperand(0));
4525             I.setOperand(1, NewRHS);
4526             return &I;
4527           }
4528         }
4529       }
4530     }
4531
4532     // Try to fold constant and into select arguments.
4533     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4534       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4535         return R;
4536     if (isa<PHINode>(Op0))
4537       if (Instruction *NV = FoldOpIntoPhi(I))
4538         return NV;
4539   }
4540
4541   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4542     if (X == Op1)
4543       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4544
4545   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4546     if (X == Op0)
4547       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4548
4549   
4550   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4551   if (Op1I) {
4552     Value *A, *B;
4553     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4554       if (A == Op0) {              // B^(B|A) == (A|B)^B
4555         Op1I->swapOperands();
4556         I.swapOperands();
4557         std::swap(Op0, Op1);
4558       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4559         I.swapOperands();     // Simplified below.
4560         std::swap(Op0, Op1);
4561       }
4562     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4563       if (Op0 == A)                                          // A^(A^B) == B
4564         return ReplaceInstUsesWith(I, B);
4565       else if (Op0 == B)                                     // A^(B^A) == B
4566         return ReplaceInstUsesWith(I, A);
4567     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4568       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4569         Op1I->swapOperands();
4570         std::swap(A, B);
4571       }
4572       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4573         I.swapOperands();     // Simplified below.
4574         std::swap(Op0, Op1);
4575       }
4576     }
4577   }
4578   
4579   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4580   if (Op0I) {
4581     Value *A, *B;
4582     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4583       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4584         std::swap(A, B);
4585       if (B == Op1) {                                // (A|B)^B == A & ~B
4586         Instruction *NotB =
4587           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4588         return BinaryOperator::createAnd(A, NotB);
4589       }
4590     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4591       if (Op1 == A)                                          // (A^B)^A == B
4592         return ReplaceInstUsesWith(I, B);
4593       else if (Op1 == B)                                     // (B^A)^A == B
4594         return ReplaceInstUsesWith(I, A);
4595     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4596       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4597         std::swap(A, B);
4598       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4599           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4600         Instruction *N =
4601           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4602         return BinaryOperator::createAnd(N, Op1);
4603       }
4604     }
4605   }
4606   
4607   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4608   if (Op0I && Op1I && Op0I->isShift() && 
4609       Op0I->getOpcode() == Op1I->getOpcode() && 
4610       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4611       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4612     Instruction *NewOp =
4613       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4614                                                     Op1I->getOperand(0),
4615                                                     Op0I->getName()), I);
4616     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4617                                   Op1I->getOperand(1));
4618   }
4619     
4620   if (Op0I && Op1I) {
4621     Value *A, *B, *C, *D;
4622     // (A & B)^(A | B) -> A ^ B
4623     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4624         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4625       if ((A == C && B == D) || (A == D && B == C)) 
4626         return BinaryOperator::createXor(A, B);
4627     }
4628     // (A | B)^(A & B) -> A ^ B
4629     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4630         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4631       if ((A == C && B == D) || (A == D && B == C)) 
4632         return BinaryOperator::createXor(A, B);
4633     }
4634     
4635     // (A & B)^(C & D)
4636     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4637         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4638         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4639       // (X & Y)^(X & Y) -> (Y^Z) & X
4640       Value *X = 0, *Y = 0, *Z = 0;
4641       if (A == C)
4642         X = A, Y = B, Z = D;
4643       else if (A == D)
4644         X = A, Y = B, Z = C;
4645       else if (B == C)
4646         X = B, Y = A, Z = D;
4647       else if (B == D)
4648         X = B, Y = A, Z = C;
4649       
4650       if (X) {
4651         Instruction *NewOp =
4652         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4653         return BinaryOperator::createAnd(NewOp, X);
4654       }
4655     }
4656   }
4657     
4658   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4659   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4660     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4661       return R;
4662
4663   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4664   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4665     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4666       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4667         const Type *SrcTy = Op0C->getOperand(0)->getType();
4668         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4669             // Only do this if the casts both really cause code to be generated.
4670             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4671                               I.getType(), TD) &&
4672             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4673                               I.getType(), TD)) {
4674           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4675                                                          Op1C->getOperand(0),
4676                                                          I.getName());
4677           InsertNewInstBefore(NewOp, I);
4678           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4679         }
4680       }
4681   }
4682   return Changed ? &I : 0;
4683 }
4684
4685 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4686 /// overflowed for this type.
4687 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4688                             ConstantInt *In2, bool IsSigned = false) {
4689   Result = cast<ConstantInt>(Add(In1, In2));
4690
4691   if (IsSigned)
4692     if (In2->getValue().isNegative())
4693       return Result->getValue().sgt(In1->getValue());
4694     else
4695       return Result->getValue().slt(In1->getValue());
4696   else
4697     return Result->getValue().ult(In1->getValue());
4698 }
4699
4700 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4701 /// code necessary to compute the offset from the base pointer (without adding
4702 /// in the base pointer).  Return the result as a signed integer of intptr size.
4703 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4704   TargetData &TD = IC.getTargetData();
4705   gep_type_iterator GTI = gep_type_begin(GEP);
4706   const Type *IntPtrTy = TD.getIntPtrType();
4707   Value *Result = Constant::getNullValue(IntPtrTy);
4708
4709   // Build a mask for high order bits.
4710   unsigned IntPtrWidth = TD.getPointerSize()*8;
4711   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4712
4713   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4714     Value *Op = GEP->getOperand(i);
4715     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4716     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4717       if (OpC->isZero()) continue;
4718       
4719       // Handle a struct index, which adds its field offset to the pointer.
4720       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4721         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4722         
4723         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4724           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4725         else
4726           Result = IC.InsertNewInstBefore(
4727                    BinaryOperator::createAdd(Result,
4728                                              ConstantInt::get(IntPtrTy, Size),
4729                                              GEP->getName()+".offs"), I);
4730         continue;
4731       }
4732       
4733       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4734       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4735       Scale = ConstantExpr::getMul(OC, Scale);
4736       if (Constant *RC = dyn_cast<Constant>(Result))
4737         Result = ConstantExpr::getAdd(RC, Scale);
4738       else {
4739         // Emit an add instruction.
4740         Result = IC.InsertNewInstBefore(
4741            BinaryOperator::createAdd(Result, Scale,
4742                                      GEP->getName()+".offs"), I);
4743       }
4744       continue;
4745     }
4746     // Convert to correct type.
4747     if (Op->getType() != IntPtrTy) {
4748       if (Constant *OpC = dyn_cast<Constant>(Op))
4749         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4750       else
4751         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4752                                                  Op->getName()+".c"), I);
4753     }
4754     if (Size != 1) {
4755       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4756       if (Constant *OpC = dyn_cast<Constant>(Op))
4757         Op = ConstantExpr::getMul(OpC, Scale);
4758       else    // We'll let instcombine(mul) convert this to a shl if possible.
4759         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4760                                                   GEP->getName()+".idx"), I);
4761     }
4762
4763     // Emit an add instruction.
4764     if (isa<Constant>(Op) && isa<Constant>(Result))
4765       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4766                                     cast<Constant>(Result));
4767     else
4768       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4769                                                   GEP->getName()+".offs"), I);
4770   }
4771   return Result;
4772 }
4773
4774 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4775 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4776 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4777                                        ICmpInst::Predicate Cond,
4778                                        Instruction &I) {
4779   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4780
4781   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4782     if (isa<PointerType>(CI->getOperand(0)->getType()))
4783       RHS = CI->getOperand(0);
4784
4785   Value *PtrBase = GEPLHS->getOperand(0);
4786   if (PtrBase == RHS) {
4787     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4788     // This transformation is valid because we know pointers can't overflow.
4789     Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4790     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4791                         Constant::getNullValue(Offset->getType()));
4792   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4793     // If the base pointers are different, but the indices are the same, just
4794     // compare the base pointer.
4795     if (PtrBase != GEPRHS->getOperand(0)) {
4796       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4797       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4798                         GEPRHS->getOperand(0)->getType();
4799       if (IndicesTheSame)
4800         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4801           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4802             IndicesTheSame = false;
4803             break;
4804           }
4805
4806       // If all indices are the same, just compare the base pointers.
4807       if (IndicesTheSame)
4808         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4809                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4810
4811       // Otherwise, the base pointers are different and the indices are
4812       // different, bail out.
4813       return 0;
4814     }
4815
4816     // If one of the GEPs has all zero indices, recurse.
4817     bool AllZeros = true;
4818     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4819       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4820           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4821         AllZeros = false;
4822         break;
4823       }
4824     if (AllZeros)
4825       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4826                           ICmpInst::getSwappedPredicate(Cond), I);
4827
4828     // If the other GEP has all zero indices, recurse.
4829     AllZeros = true;
4830     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4831       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4832           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4833         AllZeros = false;
4834         break;
4835       }
4836     if (AllZeros)
4837       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4838
4839     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4840       // If the GEPs only differ by one index, compare it.
4841       unsigned NumDifferences = 0;  // Keep track of # differences.
4842       unsigned DiffOperand = 0;     // The operand that differs.
4843       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4844         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4845           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4846                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4847             // Irreconcilable differences.
4848             NumDifferences = 2;
4849             break;
4850           } else {
4851             if (NumDifferences++) break;
4852             DiffOperand = i;
4853           }
4854         }
4855
4856       if (NumDifferences == 0)   // SAME GEP?
4857         return ReplaceInstUsesWith(I, // No comparison is needed here.
4858                                    ConstantInt::get(Type::Int1Ty,
4859                                                     isTrueWhenEqual(Cond)));
4860
4861       else if (NumDifferences == 1) {
4862         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4863         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4864         // Make sure we do a signed comparison here.
4865         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4866       }
4867     }
4868
4869     // Only lower this if the icmp is the only user of the GEP or if we expect
4870     // the result to fold to a constant!
4871     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4872         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4873       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4874       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4875       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4876       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4877     }
4878   }
4879   return 0;
4880 }
4881
4882 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4883   bool Changed = SimplifyCompare(I);
4884   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4885
4886   // Fold trivial predicates.
4887   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4888     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4889   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4890     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4891   
4892   // Simplify 'fcmp pred X, X'
4893   if (Op0 == Op1) {
4894     switch (I.getPredicate()) {
4895     default: assert(0 && "Unknown predicate!");
4896     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4897     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4898     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4899       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4900     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4901     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4902     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4903       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4904       
4905     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4906     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4907     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4908     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4909       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4910       I.setPredicate(FCmpInst::FCMP_UNO);
4911       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4912       return &I;
4913       
4914     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4915     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4916     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4917     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4918       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4919       I.setPredicate(FCmpInst::FCMP_ORD);
4920       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4921       return &I;
4922     }
4923   }
4924     
4925   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4926     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4927
4928   // Handle fcmp with constant RHS
4929   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4930     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4931       switch (LHSI->getOpcode()) {
4932       case Instruction::PHI:
4933         if (Instruction *NV = FoldOpIntoPhi(I))
4934           return NV;
4935         break;
4936       case Instruction::Select:
4937         // If either operand of the select is a constant, we can fold the
4938         // comparison into the select arms, which will cause one to be
4939         // constant folded and the select turned into a bitwise or.
4940         Value *Op1 = 0, *Op2 = 0;
4941         if (LHSI->hasOneUse()) {
4942           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4943             // Fold the known value into the constant operand.
4944             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4945             // Insert a new FCmp of the other select operand.
4946             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4947                                                       LHSI->getOperand(2), RHSC,
4948                                                       I.getName()), I);
4949           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4950             // Fold the known value into the constant operand.
4951             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4952             // Insert a new FCmp of the other select operand.
4953             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4954                                                       LHSI->getOperand(1), RHSC,
4955                                                       I.getName()), I);
4956           }
4957         }
4958
4959         if (Op1)
4960           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4961         break;
4962       }
4963   }
4964
4965   return Changed ? &I : 0;
4966 }
4967
4968 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4969   bool Changed = SimplifyCompare(I);
4970   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4971   const Type *Ty = Op0->getType();
4972
4973   // icmp X, X
4974   if (Op0 == Op1)
4975     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4976                                                    isTrueWhenEqual(I)));
4977
4978   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4979     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4980   
4981   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4982   // addresses never equal each other!  We already know that Op0 != Op1.
4983   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4984        isa<ConstantPointerNull>(Op0)) &&
4985       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4986        isa<ConstantPointerNull>(Op1)))
4987     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4988                                                    !isTrueWhenEqual(I)));
4989
4990   // icmp's with boolean values can always be turned into bitwise operations
4991   if (Ty == Type::Int1Ty) {
4992     switch (I.getPredicate()) {
4993     default: assert(0 && "Invalid icmp instruction!");
4994     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4995       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4996       InsertNewInstBefore(Xor, I);
4997       return BinaryOperator::createNot(Xor);
4998     }
4999     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5000       return BinaryOperator::createXor(Op0, Op1);
5001
5002     case ICmpInst::ICMP_UGT:
5003     case ICmpInst::ICMP_SGT:
5004       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5005       // FALL THROUGH
5006     case ICmpInst::ICMP_ULT:
5007     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5008       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5009       InsertNewInstBefore(Not, I);
5010       return BinaryOperator::createAnd(Not, Op1);
5011     }
5012     case ICmpInst::ICMP_UGE:
5013     case ICmpInst::ICMP_SGE:
5014       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5015       // FALL THROUGH
5016     case ICmpInst::ICMP_ULE:
5017     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5018       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5019       InsertNewInstBefore(Not, I);
5020       return BinaryOperator::createOr(Not, Op1);
5021     }
5022     }
5023   }
5024
5025   // See if we are doing a comparison between a constant and an instruction that
5026   // can be folded into the comparison.
5027   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5028       Value *A, *B;
5029     
5030     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5031     if (I.isEquality() && CI->isNullValue() &&
5032         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5033       // (icmp cond A B) if cond is equality
5034       return new ICmpInst(I.getPredicate(), A, B);
5035     }
5036     
5037     switch (I.getPredicate()) {
5038     default: break;
5039     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5040       if (CI->isMinValue(false))
5041         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5042       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5043         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5044       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5045         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5046       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5047       if (CI->isMinValue(true))
5048         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5049                             ConstantInt::getAllOnesValue(Op0->getType()));
5050           
5051       break;
5052
5053     case ICmpInst::ICMP_SLT:
5054       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5055         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5056       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5057         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5058       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5059         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5060       break;
5061
5062     case ICmpInst::ICMP_UGT:
5063       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5064         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5065       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5066         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5067       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5068         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5069         
5070       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5071       if (CI->isMaxValue(true))
5072         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5073                             ConstantInt::getNullValue(Op0->getType()));
5074       break;
5075
5076     case ICmpInst::ICMP_SGT:
5077       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5078         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5079       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5080         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5081       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5082         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5083       break;
5084
5085     case ICmpInst::ICMP_ULE:
5086       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5087         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5088       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5089         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5090       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5091         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5092       break;
5093
5094     case ICmpInst::ICMP_SLE:
5095       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5096         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5097       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5098         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5099       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5100         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5101       break;
5102
5103     case ICmpInst::ICMP_UGE:
5104       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5105         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5106       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5107         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5108       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5109         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5110       break;
5111
5112     case ICmpInst::ICMP_SGE:
5113       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5114         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5115       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5116         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5117       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5118         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5119       break;
5120     }
5121
5122     // If we still have a icmp le or icmp ge instruction, turn it into the
5123     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5124     // already been handled above, this requires little checking.
5125     //
5126     switch (I.getPredicate()) {
5127     default: break;
5128     case ICmpInst::ICMP_ULE: 
5129       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5130     case ICmpInst::ICMP_SLE:
5131       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5132     case ICmpInst::ICMP_UGE:
5133       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5134     case ICmpInst::ICMP_SGE:
5135       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5136     }
5137     
5138     // See if we can fold the comparison based on bits known to be zero or one
5139     // in the input.  If this comparison is a normal comparison, it demands all
5140     // bits, if it is a sign bit comparison, it only demands the sign bit.
5141     
5142     bool UnusedBit;
5143     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5144     
5145     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5146     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5147     if (SimplifyDemandedBits(Op0, 
5148                              isSignBit ? APInt::getSignBit(BitWidth)
5149                                        : APInt::getAllOnesValue(BitWidth),
5150                              KnownZero, KnownOne, 0))
5151       return &I;
5152         
5153     // Given the known and unknown bits, compute a range that the LHS could be
5154     // in.
5155     if ((KnownOne | KnownZero) != 0) {
5156       // Compute the Min, Max and RHS values based on the known bits. For the
5157       // EQ and NE we use unsigned values.
5158       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5159       const APInt& RHSVal = CI->getValue();
5160       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5161         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5162                                                Max);
5163       } else {
5164         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5165                                                  Max);
5166       }
5167       switch (I.getPredicate()) {  // LE/GE have been folded already.
5168       default: assert(0 && "Unknown icmp opcode!");
5169       case ICmpInst::ICMP_EQ:
5170         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5171           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5172         break;
5173       case ICmpInst::ICMP_NE:
5174         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5175           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5176         break;
5177       case ICmpInst::ICMP_ULT:
5178         if (Max.ult(RHSVal))
5179           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5180         if (Min.uge(RHSVal))
5181           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5182         break;
5183       case ICmpInst::ICMP_UGT:
5184         if (Min.ugt(RHSVal))
5185           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5186         if (Max.ule(RHSVal))
5187           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5188         break;
5189       case ICmpInst::ICMP_SLT:
5190         if (Max.slt(RHSVal))
5191           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5192         if (Min.sgt(RHSVal))
5193           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5194         break;
5195       case ICmpInst::ICMP_SGT: 
5196         if (Min.sgt(RHSVal))
5197           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5198         if (Max.sle(RHSVal))
5199           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5200         break;
5201       }
5202     }
5203           
5204     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5205     // instruction, see if that instruction also has constants so that the 
5206     // instruction can be folded into the icmp 
5207     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5208       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5209         return Res;
5210   }
5211
5212   // Handle icmp with constant (but not simple integer constant) RHS
5213   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5214     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5215       switch (LHSI->getOpcode()) {
5216       case Instruction::GetElementPtr:
5217         if (RHSC->isNullValue()) {
5218           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5219           bool isAllZeros = true;
5220           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5221             if (!isa<Constant>(LHSI->getOperand(i)) ||
5222                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5223               isAllZeros = false;
5224               break;
5225             }
5226           if (isAllZeros)
5227             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5228                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5229         }
5230         break;
5231
5232       case Instruction::PHI:
5233         if (Instruction *NV = FoldOpIntoPhi(I))
5234           return NV;
5235         break;
5236       case Instruction::Select: {
5237         // If either operand of the select is a constant, we can fold the
5238         // comparison into the select arms, which will cause one to be
5239         // constant folded and the select turned into a bitwise or.
5240         Value *Op1 = 0, *Op2 = 0;
5241         if (LHSI->hasOneUse()) {
5242           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5243             // Fold the known value into the constant operand.
5244             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5245             // Insert a new ICmp of the other select operand.
5246             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5247                                                    LHSI->getOperand(2), RHSC,
5248                                                    I.getName()), I);
5249           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5250             // Fold the known value into the constant operand.
5251             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5252             // Insert a new ICmp of the other select operand.
5253             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5254                                                    LHSI->getOperand(1), RHSC,
5255                                                    I.getName()), I);
5256           }
5257         }
5258
5259         if (Op1)
5260           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5261         break;
5262       }
5263       case Instruction::Malloc:
5264         // If we have (malloc != null), and if the malloc has a single use, we
5265         // can assume it is successful and remove the malloc.
5266         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5267           AddToWorkList(LHSI);
5268           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5269                                                          !isTrueWhenEqual(I)));
5270         }
5271         break;
5272       }
5273   }
5274
5275   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5276   if (User *GEP = dyn_castGetElementPtr(Op0))
5277     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5278       return NI;
5279   if (User *GEP = dyn_castGetElementPtr(Op1))
5280     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5281                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5282       return NI;
5283
5284   // Test to see if the operands of the icmp are casted versions of other
5285   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5286   // now.
5287   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5288     if (isa<PointerType>(Op0->getType()) && 
5289         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5290       // We keep moving the cast from the left operand over to the right
5291       // operand, where it can often be eliminated completely.
5292       Op0 = CI->getOperand(0);
5293
5294       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5295       // so eliminate it as well.
5296       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5297         Op1 = CI2->getOperand(0);
5298
5299       // If Op1 is a constant, we can fold the cast into the constant.
5300       if (Op0->getType() != Op1->getType()) {
5301         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5302           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5303         } else {
5304           // Otherwise, cast the RHS right before the icmp
5305           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5306         }
5307       }
5308       return new ICmpInst(I.getPredicate(), Op0, Op1);
5309     }
5310   }
5311   
5312   if (isa<CastInst>(Op0)) {
5313     // Handle the special case of: icmp (cast bool to X), <cst>
5314     // This comes up when you have code like
5315     //   int X = A < B;
5316     //   if (X) ...
5317     // For generality, we handle any zero-extension of any operand comparison
5318     // with a constant or another cast from the same type.
5319     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5320       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5321         return R;
5322   }
5323   
5324   if (I.isEquality()) {
5325     Value *A, *B, *C, *D;
5326     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5327       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5328         Value *OtherVal = A == Op1 ? B : A;
5329         return new ICmpInst(I.getPredicate(), OtherVal,
5330                             Constant::getNullValue(A->getType()));
5331       }
5332
5333       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5334         // A^c1 == C^c2 --> A == C^(c1^c2)
5335         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5336           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5337             if (Op1->hasOneUse()) {
5338               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5339               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5340               return new ICmpInst(I.getPredicate(), A,
5341                                   InsertNewInstBefore(Xor, I));
5342             }
5343         
5344         // A^B == A^D -> B == D
5345         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5346         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5347         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5348         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5349       }
5350     }
5351     
5352     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5353         (A == Op0 || B == Op0)) {
5354       // A == (A^B)  ->  B == 0
5355       Value *OtherVal = A == Op0 ? B : A;
5356       return new ICmpInst(I.getPredicate(), OtherVal,
5357                           Constant::getNullValue(A->getType()));
5358     }
5359     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5360       // (A-B) == A  ->  B == 0
5361       return new ICmpInst(I.getPredicate(), B,
5362                           Constant::getNullValue(B->getType()));
5363     }
5364     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5365       // A == (A-B)  ->  B == 0
5366       return new ICmpInst(I.getPredicate(), B,
5367                           Constant::getNullValue(B->getType()));
5368     }
5369     
5370     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5371     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5372         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5373         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5374       Value *X = 0, *Y = 0, *Z = 0;
5375       
5376       if (A == C) {
5377         X = B; Y = D; Z = A;
5378       } else if (A == D) {
5379         X = B; Y = C; Z = A;
5380       } else if (B == C) {
5381         X = A; Y = D; Z = B;
5382       } else if (B == D) {
5383         X = A; Y = C; Z = B;
5384       }
5385       
5386       if (X) {   // Build (X^Y) & Z
5387         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5388         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5389         I.setOperand(0, Op1);
5390         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5391         return &I;
5392       }
5393     }
5394   }
5395   return Changed ? &I : 0;
5396 }
5397
5398
5399 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5400 /// and CmpRHS are both known to be integer constants.
5401 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5402                                           ConstantInt *DivRHS) {
5403   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5404   const APInt &CmpRHSV = CmpRHS->getValue();
5405   
5406   // FIXME: If the operand types don't match the type of the divide 
5407   // then don't attempt this transform. The code below doesn't have the
5408   // logic to deal with a signed divide and an unsigned compare (and
5409   // vice versa). This is because (x /s C1) <s C2  produces different 
5410   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5411   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5412   // work. :(  The if statement below tests that condition and bails 
5413   // if it finds it. 
5414   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5415   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5416     return 0;
5417   if (DivRHS->isZero())
5418     return 0; // The ProdOV computation fails on divide by zero.
5419
5420   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5421   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5422   // C2 (CI). By solving for X we can turn this into a range check 
5423   // instead of computing a divide. 
5424   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5425
5426   // Determine if the product overflows by seeing if the product is
5427   // not equal to the divide. Make sure we do the same kind of divide
5428   // as in the LHS instruction that we're folding. 
5429   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5430                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5431
5432   // Get the ICmp opcode
5433   ICmpInst::Predicate Pred = ICI.getPredicate();
5434
5435   // Figure out the interval that is being checked.  For example, a comparison
5436   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5437   // Compute this interval based on the constants involved and the signedness of
5438   // the compare/divide.  This computes a half-open interval, keeping track of
5439   // whether either value in the interval overflows.  After analysis each
5440   // overflow variable is set to 0 if it's corresponding bound variable is valid
5441   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5442   int LoOverflow = 0, HiOverflow = 0;
5443   ConstantInt *LoBound = 0, *HiBound = 0;
5444   
5445   
5446   if (!DivIsSigned) {  // udiv
5447     // e.g. X/5 op 3  --> [15, 20)
5448     LoBound = Prod;
5449     HiOverflow = LoOverflow = ProdOV;
5450     if (!HiOverflow)
5451       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5452   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5453     if (CmpRHSV == 0) {       // (X / pos) op 0
5454       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5455       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5456       HiBound = DivRHS;
5457     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5458       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5459       HiOverflow = LoOverflow = ProdOV;
5460       if (!HiOverflow)
5461         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5462     } else {                       // (X / pos) op neg
5463       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5464       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5465       LoOverflow = AddWithOverflow(LoBound, Prod,
5466                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5467       HiBound = AddOne(Prod);
5468       HiOverflow = ProdOV ? -1 : 0;
5469     }
5470   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5471     if (CmpRHSV == 0) {       // (X / neg) op 0
5472       // e.g. X/-5 op 0  --> [-4, 5)
5473       LoBound = AddOne(DivRHS);
5474       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5475       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5476         HiOverflow = 1;            // [INTMIN+1, overflow)
5477         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5478       }
5479     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5480       // e.g. X/-5 op 3  --> [-19, -14)
5481       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5482       if (!LoOverflow)
5483         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5484       HiBound = AddOne(Prod);
5485     } else {                       // (X / neg) op neg
5486       // e.g. X/-5 op -3  --> [15, 20)
5487       LoBound = Prod;
5488       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5489       HiBound = Subtract(Prod, DivRHS);
5490     }
5491     
5492     // Dividing by a negative swaps the condition.  LT <-> GT
5493     Pred = ICmpInst::getSwappedPredicate(Pred);
5494   }
5495
5496   Value *X = DivI->getOperand(0);
5497   switch (Pred) {
5498   default: assert(0 && "Unhandled icmp opcode!");
5499   case ICmpInst::ICMP_EQ:
5500     if (LoOverflow && HiOverflow)
5501       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5502     else if (HiOverflow)
5503       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5504                           ICmpInst::ICMP_UGE, X, LoBound);
5505     else if (LoOverflow)
5506       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5507                           ICmpInst::ICMP_ULT, X, HiBound);
5508     else
5509       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5510   case ICmpInst::ICMP_NE:
5511     if (LoOverflow && HiOverflow)
5512       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5513     else if (HiOverflow)
5514       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5515                           ICmpInst::ICMP_ULT, X, LoBound);
5516     else if (LoOverflow)
5517       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5518                           ICmpInst::ICMP_UGE, X, HiBound);
5519     else
5520       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5521   case ICmpInst::ICMP_ULT:
5522   case ICmpInst::ICMP_SLT:
5523     if (LoOverflow == +1)   // Low bound is greater than input range.
5524       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5525     if (LoOverflow == -1)   // Low bound is less than input range.
5526       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5527     return new ICmpInst(Pred, X, LoBound);
5528   case ICmpInst::ICMP_UGT:
5529   case ICmpInst::ICMP_SGT:
5530     if (HiOverflow == +1)       // High bound greater than input range.
5531       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5532     else if (HiOverflow == -1)  // High bound less than input range.
5533       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5534     if (Pred == ICmpInst::ICMP_UGT)
5535       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5536     else
5537       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5538   }
5539 }
5540
5541
5542 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5543 ///
5544 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5545                                                           Instruction *LHSI,
5546                                                           ConstantInt *RHS) {
5547   const APInt &RHSV = RHS->getValue();
5548   
5549   switch (LHSI->getOpcode()) {
5550   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5551     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5552       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5553       // fold the xor.
5554       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5555           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5556         Value *CompareVal = LHSI->getOperand(0);
5557         
5558         // If the sign bit of the XorCST is not set, there is no change to
5559         // the operation, just stop using the Xor.
5560         if (!XorCST->getValue().isNegative()) {
5561           ICI.setOperand(0, CompareVal);
5562           AddToWorkList(LHSI);
5563           return &ICI;
5564         }
5565         
5566         // Was the old condition true if the operand is positive?
5567         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5568         
5569         // If so, the new one isn't.
5570         isTrueIfPositive ^= true;
5571         
5572         if (isTrueIfPositive)
5573           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5574         else
5575           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5576       }
5577     }
5578     break;
5579   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5580     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5581         LHSI->getOperand(0)->hasOneUse()) {
5582       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5583       
5584       // If the LHS is an AND of a truncating cast, we can widen the
5585       // and/compare to be the input width without changing the value
5586       // produced, eliminating a cast.
5587       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5588         // We can do this transformation if either the AND constant does not
5589         // have its sign bit set or if it is an equality comparison. 
5590         // Extending a relational comparison when we're checking the sign
5591         // bit would not work.
5592         if (Cast->hasOneUse() &&
5593             (ICI.isEquality() ||
5594              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5595           uint32_t BitWidth = 
5596             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5597           APInt NewCST = AndCST->getValue();
5598           NewCST.zext(BitWidth);
5599           APInt NewCI = RHSV;
5600           NewCI.zext(BitWidth);
5601           Instruction *NewAnd = 
5602             BinaryOperator::createAnd(Cast->getOperand(0),
5603                                       ConstantInt::get(NewCST),LHSI->getName());
5604           InsertNewInstBefore(NewAnd, ICI);
5605           return new ICmpInst(ICI.getPredicate(), NewAnd,
5606                               ConstantInt::get(NewCI));
5607         }
5608       }
5609       
5610       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5611       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5612       // happens a LOT in code produced by the C front-end, for bitfield
5613       // access.
5614       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5615       if (Shift && !Shift->isShift())
5616         Shift = 0;
5617       
5618       ConstantInt *ShAmt;
5619       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5620       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5621       const Type *AndTy = AndCST->getType();          // Type of the and.
5622       
5623       // We can fold this as long as we can't shift unknown bits
5624       // into the mask.  This can only happen with signed shift
5625       // rights, as they sign-extend.
5626       if (ShAmt) {
5627         bool CanFold = Shift->isLogicalShift();
5628         if (!CanFold) {
5629           // To test for the bad case of the signed shr, see if any
5630           // of the bits shifted in could be tested after the mask.
5631           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5632           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5633           
5634           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5635           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5636                AndCST->getValue()) == 0)
5637             CanFold = true;
5638         }
5639         
5640         if (CanFold) {
5641           Constant *NewCst;
5642           if (Shift->getOpcode() == Instruction::Shl)
5643             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5644           else
5645             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5646           
5647           // Check to see if we are shifting out any of the bits being
5648           // compared.
5649           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5650             // If we shifted bits out, the fold is not going to work out.
5651             // As a special case, check to see if this means that the
5652             // result is always true or false now.
5653             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5654               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5655             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5656               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5657           } else {
5658             ICI.setOperand(1, NewCst);
5659             Constant *NewAndCST;
5660             if (Shift->getOpcode() == Instruction::Shl)
5661               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5662             else
5663               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5664             LHSI->setOperand(1, NewAndCST);
5665             LHSI->setOperand(0, Shift->getOperand(0));
5666             AddToWorkList(Shift); // Shift is dead.
5667             AddUsesToWorkList(ICI);
5668             return &ICI;
5669           }
5670         }
5671       }
5672       
5673       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5674       // preferable because it allows the C<<Y expression to be hoisted out
5675       // of a loop if Y is invariant and X is not.
5676       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5677           ICI.isEquality() && !Shift->isArithmeticShift() &&
5678           isa<Instruction>(Shift->getOperand(0))) {
5679         // Compute C << Y.
5680         Value *NS;
5681         if (Shift->getOpcode() == Instruction::LShr) {
5682           NS = BinaryOperator::createShl(AndCST, 
5683                                          Shift->getOperand(1), "tmp");
5684         } else {
5685           // Insert a logical shift.
5686           NS = BinaryOperator::createLShr(AndCST,
5687                                           Shift->getOperand(1), "tmp");
5688         }
5689         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5690         
5691         // Compute X & (C << Y).
5692         Instruction *NewAnd = 
5693           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5694         InsertNewInstBefore(NewAnd, ICI);
5695         
5696         ICI.setOperand(0, NewAnd);
5697         return &ICI;
5698       }
5699     }
5700     break;
5701     
5702   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5703     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5704     if (!ShAmt) break;
5705     
5706     uint32_t TypeBits = RHSV.getBitWidth();
5707     
5708     // Check that the shift amount is in range.  If not, don't perform
5709     // undefined shifts.  When the shift is visited it will be
5710     // simplified.
5711     if (ShAmt->uge(TypeBits))
5712       break;
5713     
5714     if (ICI.isEquality()) {
5715       // If we are comparing against bits always shifted out, the
5716       // comparison cannot succeed.
5717       Constant *Comp =
5718         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5719       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5720         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5721         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5722         return ReplaceInstUsesWith(ICI, Cst);
5723       }
5724       
5725       if (LHSI->hasOneUse()) {
5726         // Otherwise strength reduce the shift into an and.
5727         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5728         Constant *Mask =
5729           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5730         
5731         Instruction *AndI =
5732           BinaryOperator::createAnd(LHSI->getOperand(0),
5733                                     Mask, LHSI->getName()+".mask");
5734         Value *And = InsertNewInstBefore(AndI, ICI);
5735         return new ICmpInst(ICI.getPredicate(), And,
5736                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5737       }
5738     }
5739     
5740     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5741     bool TrueIfSigned = false;
5742     if (LHSI->hasOneUse() &&
5743         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5744       // (X << 31) <s 0  --> (X&1) != 0
5745       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5746                                            (TypeBits-ShAmt->getZExtValue()-1));
5747       Instruction *AndI =
5748         BinaryOperator::createAnd(LHSI->getOperand(0),
5749                                   Mask, LHSI->getName()+".mask");
5750       Value *And = InsertNewInstBefore(AndI, ICI);
5751       
5752       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5753                           And, Constant::getNullValue(And->getType()));
5754     }
5755     break;
5756   }
5757     
5758   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5759   case Instruction::AShr: {
5760     // Only handle equality comparisons of shift-by-constant.
5761     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5762     if (!ShAmt || !ICI.isEquality()) break;
5763
5764     // Check that the shift amount is in range.  If not, don't perform
5765     // undefined shifts.  When the shift is visited it will be
5766     // simplified.
5767     uint32_t TypeBits = RHSV.getBitWidth();
5768     if (ShAmt->uge(TypeBits))
5769       break;
5770     
5771     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5772       
5773     // If we are comparing against bits always shifted out, the
5774     // comparison cannot succeed.
5775     APInt Comp = RHSV << ShAmtVal;
5776     if (LHSI->getOpcode() == Instruction::LShr)
5777       Comp = Comp.lshr(ShAmtVal);
5778     else
5779       Comp = Comp.ashr(ShAmtVal);
5780     
5781     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5782       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5783       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5784       return ReplaceInstUsesWith(ICI, Cst);
5785     }
5786     
5787     // Otherwise, check to see if the bits shifted out are known to be zero.
5788     // If so, we can compare against the unshifted value:
5789     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
5790     if (MaskedValueIsZero(LHSI->getOperand(0), 
5791                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5792       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5793                           ConstantExpr::getShl(RHS, ShAmt));
5794     }
5795       
5796     if (LHSI->hasOneUse() || RHSV == 0) {
5797       // Otherwise strength reduce the shift into an and.
5798       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5799       Constant *Mask = ConstantInt::get(Val);
5800       
5801       Instruction *AndI =
5802         BinaryOperator::createAnd(LHSI->getOperand(0),
5803                                   Mask, LHSI->getName()+".mask");
5804       Value *And = InsertNewInstBefore(AndI, ICI);
5805       return new ICmpInst(ICI.getPredicate(), And,
5806                           ConstantExpr::getShl(RHS, ShAmt));
5807     }
5808     break;
5809   }
5810     
5811   case Instruction::SDiv:
5812   case Instruction::UDiv:
5813     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5814     // Fold this div into the comparison, producing a range check. 
5815     // Determine, based on the divide type, what the range is being 
5816     // checked.  If there is an overflow on the low or high side, remember 
5817     // it, otherwise compute the range [low, hi) bounding the new value.
5818     // See: InsertRangeTest above for the kinds of replacements possible.
5819     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5820       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5821                                           DivRHS))
5822         return R;
5823     break;
5824
5825   case Instruction::Add:
5826     // Fold: icmp pred (add, X, C1), C2
5827
5828     if (!ICI.isEquality()) {
5829       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5830       if (!LHSC) break;
5831       const APInt &LHSV = LHSC->getValue();
5832
5833       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5834                             .subtract(LHSV);
5835
5836       if (ICI.isSignedPredicate()) {
5837         if (CR.getLower().isSignBit()) {
5838           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5839                               ConstantInt::get(CR.getUpper()));
5840         } else if (CR.getUpper().isSignBit()) {
5841           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5842                               ConstantInt::get(CR.getLower()));
5843         }
5844       } else {
5845         if (CR.getLower().isMinValue()) {
5846           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5847                               ConstantInt::get(CR.getUpper()));
5848         } else if (CR.getUpper().isMinValue()) {
5849           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5850                               ConstantInt::get(CR.getLower()));
5851         }
5852       }
5853     }
5854     break;
5855   }
5856   
5857   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5858   if (ICI.isEquality()) {
5859     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5860     
5861     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5862     // the second operand is a constant, simplify a bit.
5863     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5864       switch (BO->getOpcode()) {
5865       case Instruction::SRem:
5866         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5867         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5868           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5869           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5870             Instruction *NewRem =
5871               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5872                                          BO->getName());
5873             InsertNewInstBefore(NewRem, ICI);
5874             return new ICmpInst(ICI.getPredicate(), NewRem, 
5875                                 Constant::getNullValue(BO->getType()));
5876           }
5877         }
5878         break;
5879       case Instruction::Add:
5880         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5881         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5882           if (BO->hasOneUse())
5883             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5884                                 Subtract(RHS, BOp1C));
5885         } else if (RHSV == 0) {
5886           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5887           // efficiently invertible, or if the add has just this one use.
5888           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5889           
5890           if (Value *NegVal = dyn_castNegVal(BOp1))
5891             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5892           else if (Value *NegVal = dyn_castNegVal(BOp0))
5893             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5894           else if (BO->hasOneUse()) {
5895             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5896             InsertNewInstBefore(Neg, ICI);
5897             Neg->takeName(BO);
5898             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5899           }
5900         }
5901         break;
5902       case Instruction::Xor:
5903         // For the xor case, we can xor two constants together, eliminating
5904         // the explicit xor.
5905         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5906           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5907                               ConstantExpr::getXor(RHS, BOC));
5908         
5909         // FALLTHROUGH
5910       case Instruction::Sub:
5911         // Replace (([sub|xor] A, B) != 0) with (A != B)
5912         if (RHSV == 0)
5913           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5914                               BO->getOperand(1));
5915         break;
5916         
5917       case Instruction::Or:
5918         // If bits are being or'd in that are not present in the constant we
5919         // are comparing against, then the comparison could never succeed!
5920         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5921           Constant *NotCI = ConstantExpr::getNot(RHS);
5922           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5923             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5924                                                              isICMP_NE));
5925         }
5926         break;
5927         
5928       case Instruction::And:
5929         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5930           // If bits are being compared against that are and'd out, then the
5931           // comparison can never succeed!
5932           if ((RHSV & ~BOC->getValue()) != 0)
5933             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5934                                                              isICMP_NE));
5935           
5936           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5937           if (RHS == BOC && RHSV.isPowerOf2())
5938             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5939                                 ICmpInst::ICMP_NE, LHSI,
5940                                 Constant::getNullValue(RHS->getType()));
5941           
5942           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5943           if (isSignBit(BOC)) {
5944             Value *X = BO->getOperand(0);
5945             Constant *Zero = Constant::getNullValue(X->getType());
5946             ICmpInst::Predicate pred = isICMP_NE ? 
5947               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5948             return new ICmpInst(pred, X, Zero);
5949           }
5950           
5951           // ((X & ~7) == 0) --> X < 8
5952           if (RHSV == 0 && isHighOnes(BOC)) {
5953             Value *X = BO->getOperand(0);
5954             Constant *NegX = ConstantExpr::getNeg(BOC);
5955             ICmpInst::Predicate pred = isICMP_NE ? 
5956               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5957             return new ICmpInst(pred, X, NegX);
5958           }
5959         }
5960       default: break;
5961       }
5962     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5963       // Handle icmp {eq|ne} <intrinsic>, intcst.
5964       if (II->getIntrinsicID() == Intrinsic::bswap) {
5965         AddToWorkList(II);
5966         ICI.setOperand(0, II->getOperand(1));
5967         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5968         return &ICI;
5969       }
5970     }
5971   } else {  // Not a ICMP_EQ/ICMP_NE
5972             // If the LHS is a cast from an integral value of the same size, 
5973             // then since we know the RHS is a constant, try to simlify.
5974     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5975       Value *CastOp = Cast->getOperand(0);
5976       const Type *SrcTy = CastOp->getType();
5977       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5978       if (SrcTy->isInteger() && 
5979           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5980         // If this is an unsigned comparison, try to make the comparison use
5981         // smaller constant values.
5982         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5983           // X u< 128 => X s> -1
5984           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5985                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5986         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5987                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5988           // X u> 127 => X s< 0
5989           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5990                               Constant::getNullValue(SrcTy));
5991         }
5992       }
5993     }
5994   }
5995   return 0;
5996 }
5997
5998 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5999 /// We only handle extending casts so far.
6000 ///
6001 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6002   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6003   Value *LHSCIOp        = LHSCI->getOperand(0);
6004   const Type *SrcTy     = LHSCIOp->getType();
6005   const Type *DestTy    = LHSCI->getType();
6006   Value *RHSCIOp;
6007
6008   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6009   // integer type is the same size as the pointer type.
6010   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6011       getTargetData().getPointerSizeInBits() == 
6012          cast<IntegerType>(DestTy)->getBitWidth()) {
6013     Value *RHSOp = 0;
6014     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6015       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6016     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6017       RHSOp = RHSC->getOperand(0);
6018       // If the pointer types don't match, insert a bitcast.
6019       if (LHSCIOp->getType() != RHSOp->getType())
6020         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6021     }
6022
6023     if (RHSOp)
6024       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6025   }
6026   
6027   // The code below only handles extension cast instructions, so far.
6028   // Enforce this.
6029   if (LHSCI->getOpcode() != Instruction::ZExt &&
6030       LHSCI->getOpcode() != Instruction::SExt)
6031     return 0;
6032
6033   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6034   bool isSignedCmp = ICI.isSignedPredicate();
6035
6036   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6037     // Not an extension from the same type?
6038     RHSCIOp = CI->getOperand(0);
6039     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6040       return 0;
6041     
6042     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6043     // and the other is a zext), then we can't handle this.
6044     if (CI->getOpcode() != LHSCI->getOpcode())
6045       return 0;
6046
6047     // Deal with equality cases early.
6048     if (ICI.isEquality())
6049       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6050
6051     // A signed comparison of sign extended values simplifies into a
6052     // signed comparison.
6053     if (isSignedCmp && isSignedExt)
6054       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6055
6056     // The other three cases all fold into an unsigned comparison.
6057     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6058   }
6059
6060   // If we aren't dealing with a constant on the RHS, exit early
6061   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6062   if (!CI)
6063     return 0;
6064
6065   // Compute the constant that would happen if we truncated to SrcTy then
6066   // reextended to DestTy.
6067   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6068   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6069
6070   // If the re-extended constant didn't change...
6071   if (Res2 == CI) {
6072     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6073     // For example, we might have:
6074     //    %A = sext short %X to uint
6075     //    %B = icmp ugt uint %A, 1330
6076     // It is incorrect to transform this into 
6077     //    %B = icmp ugt short %X, 1330 
6078     // because %A may have negative value. 
6079     //
6080     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6081     // OR operation is EQ/NE.
6082     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6083       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6084     else
6085       return 0;
6086   }
6087
6088   // The re-extended constant changed so the constant cannot be represented 
6089   // in the shorter type. Consequently, we cannot emit a simple comparison.
6090
6091   // First, handle some easy cases. We know the result cannot be equal at this
6092   // point so handle the ICI.isEquality() cases
6093   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6094     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6095   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6096     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6097
6098   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6099   // should have been folded away previously and not enter in here.
6100   Value *Result;
6101   if (isSignedCmp) {
6102     // We're performing a signed comparison.
6103     if (cast<ConstantInt>(CI)->getValue().isNegative())
6104       Result = ConstantInt::getFalse();          // X < (small) --> false
6105     else
6106       Result = ConstantInt::getTrue();           // X < (large) --> true
6107   } else {
6108     // We're performing an unsigned comparison.
6109     if (isSignedExt) {
6110       // We're performing an unsigned comp with a sign extended value.
6111       // This is true if the input is >= 0. [aka >s -1]
6112       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6113       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6114                                    NegOne, ICI.getName()), ICI);
6115     } else {
6116       // Unsigned extend & unsigned compare -> always true.
6117       Result = ConstantInt::getTrue();
6118     }
6119   }
6120
6121   // Finally, return the value computed.
6122   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6123       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6124     return ReplaceInstUsesWith(ICI, Result);
6125   } else {
6126     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6127             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6128            "ICmp should be folded!");
6129     if (Constant *CI = dyn_cast<Constant>(Result))
6130       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6131     else
6132       return BinaryOperator::createNot(Result);
6133   }
6134 }
6135
6136 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6137   return commonShiftTransforms(I);
6138 }
6139
6140 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6141   return commonShiftTransforms(I);
6142 }
6143
6144 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6145   if (Instruction *R = commonShiftTransforms(I))
6146     return R;
6147   
6148   Value *Op0 = I.getOperand(0);
6149   
6150   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6151   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6152     if (CSI->isAllOnesValue())
6153       return ReplaceInstUsesWith(I, CSI);
6154   
6155   // See if we can turn a signed shr into an unsigned shr.
6156   if (MaskedValueIsZero(Op0, 
6157                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6158     return BinaryOperator::createLShr(Op0, I.getOperand(1));
6159   
6160   return 0;
6161 }
6162
6163 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6164   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6165   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6166
6167   // shl X, 0 == X and shr X, 0 == X
6168   // shl 0, X == 0 and shr 0, X == 0
6169   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6170       Op0 == Constant::getNullValue(Op0->getType()))
6171     return ReplaceInstUsesWith(I, Op0);
6172   
6173   if (isa<UndefValue>(Op0)) {            
6174     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6175       return ReplaceInstUsesWith(I, Op0);
6176     else                                    // undef << X -> 0, undef >>u X -> 0
6177       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6178   }
6179   if (isa<UndefValue>(Op1)) {
6180     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6181       return ReplaceInstUsesWith(I, Op0);          
6182     else                                     // X << undef, X >>u undef -> 0
6183       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6184   }
6185
6186   // Try to fold constant and into select arguments.
6187   if (isa<Constant>(Op0))
6188     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6189       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6190         return R;
6191
6192   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6193     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6194       return Res;
6195   return 0;
6196 }
6197
6198 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6199                                                BinaryOperator &I) {
6200   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6201
6202   // See if we can simplify any instructions used by the instruction whose sole 
6203   // purpose is to compute bits we don't care about.
6204   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6205   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6206   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6207                            KnownZero, KnownOne))
6208     return &I;
6209   
6210   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6211   // of a signed value.
6212   //
6213   if (Op1->uge(TypeBits)) {
6214     if (I.getOpcode() != Instruction::AShr)
6215       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6216     else {
6217       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6218       return &I;
6219     }
6220   }
6221   
6222   // ((X*C1) << C2) == (X * (C1 << C2))
6223   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6224     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6225       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6226         return BinaryOperator::createMul(BO->getOperand(0),
6227                                          ConstantExpr::getShl(BOOp, Op1));
6228   
6229   // Try to fold constant and into select arguments.
6230   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6231     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6232       return R;
6233   if (isa<PHINode>(Op0))
6234     if (Instruction *NV = FoldOpIntoPhi(I))
6235       return NV;
6236   
6237   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6238   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6239     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6240     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6241     // place.  Don't try to do this transformation in this case.  Also, we
6242     // require that the input operand is a shift-by-constant so that we have
6243     // confidence that the shifts will get folded together.  We could do this
6244     // xform in more cases, but it is unlikely to be profitable.
6245     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6246         isa<ConstantInt>(TrOp->getOperand(1))) {
6247       // Okay, we'll do this xform.  Make the shift of shift.
6248       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6249       Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6250                                                 I.getName());
6251       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6252
6253       // For logical shifts, the truncation has the effect of making the high
6254       // part of the register be zeros.  Emulate this by inserting an AND to
6255       // clear the top bits as needed.  This 'and' will usually be zapped by
6256       // other xforms later if dead.
6257       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6258       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6259       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6260       
6261       // The mask we constructed says what the trunc would do if occurring
6262       // between the shifts.  We want to know the effect *after* the second
6263       // shift.  We know that it is a logical shift by a constant, so adjust the
6264       // mask as appropriate.
6265       if (I.getOpcode() == Instruction::Shl)
6266         MaskV <<= Op1->getZExtValue();
6267       else {
6268         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6269         MaskV = MaskV.lshr(Op1->getZExtValue());
6270       }
6271
6272       Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6273                                                    TI->getName());
6274       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6275
6276       // Return the value truncated to the interesting size.
6277       return new TruncInst(And, I.getType());
6278     }
6279   }
6280   
6281   if (Op0->hasOneUse()) {
6282     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6283       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6284       Value *V1, *V2;
6285       ConstantInt *CC;
6286       switch (Op0BO->getOpcode()) {
6287         default: break;
6288         case Instruction::Add:
6289         case Instruction::And:
6290         case Instruction::Or:
6291         case Instruction::Xor: {
6292           // These operators commute.
6293           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6294           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6295               match(Op0BO->getOperand(1),
6296                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6297             Instruction *YS = BinaryOperator::createShl(
6298                                             Op0BO->getOperand(0), Op1,
6299                                             Op0BO->getName());
6300             InsertNewInstBefore(YS, I); // (Y << C)
6301             Instruction *X = 
6302               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6303                                      Op0BO->getOperand(1)->getName());
6304             InsertNewInstBefore(X, I);  // (X + (Y << C))
6305             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6306             return BinaryOperator::createAnd(X, ConstantInt::get(
6307                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6308           }
6309           
6310           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6311           Value *Op0BOOp1 = Op0BO->getOperand(1);
6312           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6313               match(Op0BOOp1, 
6314                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6315               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6316               V2 == Op1) {
6317             Instruction *YS = BinaryOperator::createShl(
6318                                                      Op0BO->getOperand(0), Op1,
6319                                                      Op0BO->getName());
6320             InsertNewInstBefore(YS, I); // (Y << C)
6321             Instruction *XM =
6322               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6323                                         V1->getName()+".mask");
6324             InsertNewInstBefore(XM, I); // X & (CC << C)
6325             
6326             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6327           }
6328         }
6329           
6330         // FALL THROUGH.
6331         case Instruction::Sub: {
6332           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6333           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6334               match(Op0BO->getOperand(0),
6335                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6336             Instruction *YS = BinaryOperator::createShl(
6337                                                      Op0BO->getOperand(1), Op1,
6338                                                      Op0BO->getName());
6339             InsertNewInstBefore(YS, I); // (Y << C)
6340             Instruction *X =
6341               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6342                                      Op0BO->getOperand(0)->getName());
6343             InsertNewInstBefore(X, I);  // (X + (Y << C))
6344             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6345             return BinaryOperator::createAnd(X, ConstantInt::get(
6346                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6347           }
6348           
6349           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6350           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6351               match(Op0BO->getOperand(0),
6352                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6353                           m_ConstantInt(CC))) && V2 == Op1 &&
6354               cast<BinaryOperator>(Op0BO->getOperand(0))
6355                   ->getOperand(0)->hasOneUse()) {
6356             Instruction *YS = BinaryOperator::createShl(
6357                                                      Op0BO->getOperand(1), Op1,
6358                                                      Op0BO->getName());
6359             InsertNewInstBefore(YS, I); // (Y << C)
6360             Instruction *XM =
6361               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6362                                         V1->getName()+".mask");
6363             InsertNewInstBefore(XM, I); // X & (CC << C)
6364             
6365             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6366           }
6367           
6368           break;
6369         }
6370       }
6371       
6372       
6373       // If the operand is an bitwise operator with a constant RHS, and the
6374       // shift is the only use, we can pull it out of the shift.
6375       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6376         bool isValid = true;     // Valid only for And, Or, Xor
6377         bool highBitSet = false; // Transform if high bit of constant set?
6378         
6379         switch (Op0BO->getOpcode()) {
6380           default: isValid = false; break;   // Do not perform transform!
6381           case Instruction::Add:
6382             isValid = isLeftShift;
6383             break;
6384           case Instruction::Or:
6385           case Instruction::Xor:
6386             highBitSet = false;
6387             break;
6388           case Instruction::And:
6389             highBitSet = true;
6390             break;
6391         }
6392         
6393         // If this is a signed shift right, and the high bit is modified
6394         // by the logical operation, do not perform the transformation.
6395         // The highBitSet boolean indicates the value of the high bit of
6396         // the constant which would cause it to be modified for this
6397         // operation.
6398         //
6399         if (isValid && I.getOpcode() == Instruction::AShr)
6400           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6401         
6402         if (isValid) {
6403           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6404           
6405           Instruction *NewShift =
6406             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6407           InsertNewInstBefore(NewShift, I);
6408           NewShift->takeName(Op0BO);
6409           
6410           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6411                                         NewRHS);
6412         }
6413       }
6414     }
6415   }
6416   
6417   // Find out if this is a shift of a shift by a constant.
6418   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6419   if (ShiftOp && !ShiftOp->isShift())
6420     ShiftOp = 0;
6421   
6422   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6423     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6424     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6425     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6426     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6427     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6428     Value *X = ShiftOp->getOperand(0);
6429     
6430     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6431     if (AmtSum > TypeBits)
6432       AmtSum = TypeBits;
6433     
6434     const IntegerType *Ty = cast<IntegerType>(I.getType());
6435     
6436     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6437     if (I.getOpcode() == ShiftOp->getOpcode()) {
6438       return BinaryOperator::create(I.getOpcode(), X,
6439                                     ConstantInt::get(Ty, AmtSum));
6440     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6441                I.getOpcode() == Instruction::AShr) {
6442       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6443       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6444     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6445                I.getOpcode() == Instruction::LShr) {
6446       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6447       Instruction *Shift =
6448         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6449       InsertNewInstBefore(Shift, I);
6450
6451       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6452       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6453     }
6454     
6455     // Okay, if we get here, one shift must be left, and the other shift must be
6456     // right.  See if the amounts are equal.
6457     if (ShiftAmt1 == ShiftAmt2) {
6458       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6459       if (I.getOpcode() == Instruction::Shl) {
6460         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6461         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6462       }
6463       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6464       if (I.getOpcode() == Instruction::LShr) {
6465         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6466         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6467       }
6468       // We can simplify ((X << C) >>s C) into a trunc + sext.
6469       // NOTE: we could do this for any C, but that would make 'unusual' integer
6470       // types.  For now, just stick to ones well-supported by the code
6471       // generators.
6472       const Type *SExtType = 0;
6473       switch (Ty->getBitWidth() - ShiftAmt1) {
6474       case 1  :
6475       case 8  :
6476       case 16 :
6477       case 32 :
6478       case 64 :
6479       case 128:
6480         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6481         break;
6482       default: break;
6483       }
6484       if (SExtType) {
6485         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6486         InsertNewInstBefore(NewTrunc, I);
6487         return new SExtInst(NewTrunc, Ty);
6488       }
6489       // Otherwise, we can't handle it yet.
6490     } else if (ShiftAmt1 < ShiftAmt2) {
6491       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6492       
6493       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6494       if (I.getOpcode() == Instruction::Shl) {
6495         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6496                ShiftOp->getOpcode() == Instruction::AShr);
6497         Instruction *Shift =
6498           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6499         InsertNewInstBefore(Shift, I);
6500         
6501         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6502         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6503       }
6504       
6505       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6506       if (I.getOpcode() == Instruction::LShr) {
6507         assert(ShiftOp->getOpcode() == Instruction::Shl);
6508         Instruction *Shift =
6509           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6510         InsertNewInstBefore(Shift, I);
6511         
6512         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6513         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6514       }
6515       
6516       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6517     } else {
6518       assert(ShiftAmt2 < ShiftAmt1);
6519       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6520
6521       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6522       if (I.getOpcode() == Instruction::Shl) {
6523         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6524                ShiftOp->getOpcode() == Instruction::AShr);
6525         Instruction *Shift =
6526           BinaryOperator::create(ShiftOp->getOpcode(), X,
6527                                  ConstantInt::get(Ty, ShiftDiff));
6528         InsertNewInstBefore(Shift, I);
6529         
6530         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6531         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6532       }
6533       
6534       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6535       if (I.getOpcode() == Instruction::LShr) {
6536         assert(ShiftOp->getOpcode() == Instruction::Shl);
6537         Instruction *Shift =
6538           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6539         InsertNewInstBefore(Shift, I);
6540         
6541         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6542         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6543       }
6544       
6545       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6546     }
6547   }
6548   return 0;
6549 }
6550
6551
6552 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6553 /// expression.  If so, decompose it, returning some value X, such that Val is
6554 /// X*Scale+Offset.
6555 ///
6556 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6557                                         int &Offset) {
6558   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6559   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6560     Offset = CI->getZExtValue();
6561     Scale  = 0;
6562     return ConstantInt::get(Type::Int32Ty, 0);
6563   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6564     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6565       if (I->getOpcode() == Instruction::Shl) {
6566         // This is a value scaled by '1 << the shift amt'.
6567         Scale = 1U << RHS->getZExtValue();
6568         Offset = 0;
6569         return I->getOperand(0);
6570       } else if (I->getOpcode() == Instruction::Mul) {
6571         // This value is scaled by 'RHS'.
6572         Scale = RHS->getZExtValue();
6573         Offset = 0;
6574         return I->getOperand(0);
6575       } else if (I->getOpcode() == Instruction::Add) {
6576         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6577         // where C1 is divisible by C2.
6578         unsigned SubScale;
6579         Value *SubVal = 
6580           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6581         Offset += RHS->getZExtValue();
6582         Scale = SubScale;
6583         return SubVal;
6584       }
6585     }
6586   }
6587
6588   // Otherwise, we can't look past this.
6589   Scale = 1;
6590   Offset = 0;
6591   return Val;
6592 }
6593
6594
6595 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6596 /// try to eliminate the cast by moving the type information into the alloc.
6597 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6598                                                    AllocationInst &AI) {
6599   const PointerType *PTy = cast<PointerType>(CI.getType());
6600   
6601   // Remove any uses of AI that are dead.
6602   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6603   
6604   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6605     Instruction *User = cast<Instruction>(*UI++);
6606     if (isInstructionTriviallyDead(User)) {
6607       while (UI != E && *UI == User)
6608         ++UI; // If this instruction uses AI more than once, don't break UI.
6609       
6610       ++NumDeadInst;
6611       DOUT << "IC: DCE: " << *User;
6612       EraseInstFromFunction(*User);
6613     }
6614   }
6615   
6616   // Get the type really allocated and the type casted to.
6617   const Type *AllocElTy = AI.getAllocatedType();
6618   const Type *CastElTy = PTy->getElementType();
6619   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6620
6621   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6622   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6623   if (CastElTyAlign < AllocElTyAlign) return 0;
6624
6625   // If the allocation has multiple uses, only promote it if we are strictly
6626   // increasing the alignment of the resultant allocation.  If we keep it the
6627   // same, we open the door to infinite loops of various kinds.
6628   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6629
6630   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6631   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6632   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6633
6634   // See if we can satisfy the modulus by pulling a scale out of the array
6635   // size argument.
6636   unsigned ArraySizeScale;
6637   int ArrayOffset;
6638   Value *NumElements = // See if the array size is a decomposable linear expr.
6639     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6640  
6641   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6642   // do the xform.
6643   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6644       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6645
6646   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6647   Value *Amt = 0;
6648   if (Scale == 1) {
6649     Amt = NumElements;
6650   } else {
6651     // If the allocation size is constant, form a constant mul expression
6652     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6653     if (isa<ConstantInt>(NumElements))
6654       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6655     // otherwise multiply the amount and the number of elements
6656     else if (Scale != 1) {
6657       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6658       Amt = InsertNewInstBefore(Tmp, AI);
6659     }
6660   }
6661   
6662   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6663     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6664     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6665     Amt = InsertNewInstBefore(Tmp, AI);
6666   }
6667   
6668   AllocationInst *New;
6669   if (isa<MallocInst>(AI))
6670     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6671   else
6672     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6673   InsertNewInstBefore(New, AI);
6674   New->takeName(&AI);
6675   
6676   // If the allocation has multiple uses, insert a cast and change all things
6677   // that used it to use the new cast.  This will also hack on CI, but it will
6678   // die soon.
6679   if (!AI.hasOneUse()) {
6680     AddUsesToWorkList(AI);
6681     // New is the allocation instruction, pointer typed. AI is the original
6682     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6683     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6684     InsertNewInstBefore(NewCast, AI);
6685     AI.replaceAllUsesWith(NewCast);
6686   }
6687   return ReplaceInstUsesWith(CI, New);
6688 }
6689
6690 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6691 /// and return it as type Ty without inserting any new casts and without
6692 /// changing the computed value.  This is used by code that tries to decide
6693 /// whether promoting or shrinking integer operations to wider or smaller types
6694 /// will allow us to eliminate a truncate or extend.
6695 ///
6696 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6697 /// extension operation if Ty is larger.
6698 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6699                                        unsigned CastOpc, int &NumCastsRemoved) {
6700   // We can always evaluate constants in another type.
6701   if (isa<ConstantInt>(V))
6702     return true;
6703   
6704   Instruction *I = dyn_cast<Instruction>(V);
6705   if (!I) return false;
6706   
6707   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6708   
6709   // If this is an extension or truncate, we can often eliminate it.
6710   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6711     // If this is a cast from the destination type, we can trivially eliminate
6712     // it, and this will remove a cast overall.
6713     if (I->getOperand(0)->getType() == Ty) {
6714       // If the first operand is itself a cast, and is eliminable, do not count
6715       // this as an eliminable cast.  We would prefer to eliminate those two
6716       // casts first.
6717       if (!isa<CastInst>(I->getOperand(0)))
6718         ++NumCastsRemoved;
6719       return true;
6720     }
6721   }
6722
6723   // We can't extend or shrink something that has multiple uses: doing so would
6724   // require duplicating the instruction in general, which isn't profitable.
6725   if (!I->hasOneUse()) return false;
6726
6727   switch (I->getOpcode()) {
6728   case Instruction::Add:
6729   case Instruction::Sub:
6730   case Instruction::And:
6731   case Instruction::Or:
6732   case Instruction::Xor:
6733     // These operators can all arbitrarily be extended or truncated.
6734     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6735                                       NumCastsRemoved) &&
6736            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6737                                       NumCastsRemoved);
6738
6739   case Instruction::Mul:
6740     // A multiply can be truncated by truncating its operands.
6741     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6742            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6743                                       NumCastsRemoved) &&
6744            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6745                                       NumCastsRemoved);
6746
6747   case Instruction::Shl:
6748     // If we are truncating the result of this SHL, and if it's a shift of a
6749     // constant amount, we can always perform a SHL in a smaller type.
6750     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6751       uint32_t BitWidth = Ty->getBitWidth();
6752       if (BitWidth < OrigTy->getBitWidth() && 
6753           CI->getLimitedValue(BitWidth) < BitWidth)
6754         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6755                                           NumCastsRemoved);
6756     }
6757     break;
6758   case Instruction::LShr:
6759     // If this is a truncate of a logical shr, we can truncate it to a smaller
6760     // lshr iff we know that the bits we would otherwise be shifting in are
6761     // already zeros.
6762     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6763       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6764       uint32_t BitWidth = Ty->getBitWidth();
6765       if (BitWidth < OrigBitWidth &&
6766           MaskedValueIsZero(I->getOperand(0),
6767             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6768           CI->getLimitedValue(BitWidth) < BitWidth) {
6769         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6770                                           NumCastsRemoved);
6771       }
6772     }
6773     break;
6774   case Instruction::ZExt:
6775   case Instruction::SExt:
6776   case Instruction::Trunc:
6777     // If this is the same kind of case as our original (e.g. zext+zext), we
6778     // can safely replace it.  Note that replacing it does not reduce the number
6779     // of casts in the input.
6780     if (I->getOpcode() == CastOpc)
6781       return true;
6782     
6783     break;
6784   default:
6785     // TODO: Can handle more cases here.
6786     break;
6787   }
6788   
6789   return false;
6790 }
6791
6792 /// EvaluateInDifferentType - Given an expression that 
6793 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6794 /// evaluate the expression.
6795 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6796                                              bool isSigned) {
6797   if (Constant *C = dyn_cast<Constant>(V))
6798     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6799
6800   // Otherwise, it must be an instruction.
6801   Instruction *I = cast<Instruction>(V);
6802   Instruction *Res = 0;
6803   switch (I->getOpcode()) {
6804   case Instruction::Add:
6805   case Instruction::Sub:
6806   case Instruction::Mul:
6807   case Instruction::And:
6808   case Instruction::Or:
6809   case Instruction::Xor:
6810   case Instruction::AShr:
6811   case Instruction::LShr:
6812   case Instruction::Shl: {
6813     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6814     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6815     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6816                                  LHS, RHS, I->getName());
6817     break;
6818   }    
6819   case Instruction::Trunc:
6820   case Instruction::ZExt:
6821   case Instruction::SExt:
6822     // If the source type of the cast is the type we're trying for then we can
6823     // just return the source.  There's no need to insert it because it is not
6824     // new.
6825     if (I->getOperand(0)->getType() == Ty)
6826       return I->getOperand(0);
6827     
6828     // Otherwise, must be the same type of case, so just reinsert a new one.
6829     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6830                            Ty, I->getName());
6831     break;
6832   default: 
6833     // TODO: Can handle more cases here.
6834     assert(0 && "Unreachable!");
6835     break;
6836   }
6837   
6838   return InsertNewInstBefore(Res, *I);
6839 }
6840
6841 /// @brief Implement the transforms common to all CastInst visitors.
6842 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6843   Value *Src = CI.getOperand(0);
6844
6845   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6846   // eliminate it now.
6847   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6848     if (Instruction::CastOps opc = 
6849         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6850       // The first cast (CSrc) is eliminable so we need to fix up or replace
6851       // the second cast (CI). CSrc will then have a good chance of being dead.
6852       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6853     }
6854   }
6855
6856   // If we are casting a select then fold the cast into the select
6857   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6858     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6859       return NV;
6860
6861   // If we are casting a PHI then fold the cast into the PHI
6862   if (isa<PHINode>(Src))
6863     if (Instruction *NV = FoldOpIntoPhi(CI))
6864       return NV;
6865   
6866   return 0;
6867 }
6868
6869 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6870 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6871   Value *Src = CI.getOperand(0);
6872   
6873   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6874     // If casting the result of a getelementptr instruction with no offset, turn
6875     // this into a cast of the original pointer!
6876     if (GEP->hasAllZeroIndices()) {
6877       // Changing the cast operand is usually not a good idea but it is safe
6878       // here because the pointer operand is being replaced with another 
6879       // pointer operand so the opcode doesn't need to change.
6880       AddToWorkList(GEP);
6881       CI.setOperand(0, GEP->getOperand(0));
6882       return &CI;
6883     }
6884     
6885     // If the GEP has a single use, and the base pointer is a bitcast, and the
6886     // GEP computes a constant offset, see if we can convert these three
6887     // instructions into fewer.  This typically happens with unions and other
6888     // non-type-safe code.
6889     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6890       if (GEP->hasAllConstantIndices()) {
6891         // We are guaranteed to get a constant from EmitGEPOffset.
6892         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6893         int64_t Offset = OffsetV->getSExtValue();
6894         
6895         // Get the base pointer input of the bitcast, and the type it points to.
6896         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6897         const Type *GEPIdxTy =
6898           cast<PointerType>(OrigBase->getType())->getElementType();
6899         if (GEPIdxTy->isSized()) {
6900           SmallVector<Value*, 8> NewIndices;
6901           
6902           // Start with the index over the outer type.  Note that the type size
6903           // might be zero (even if the offset isn't zero) if the indexed type
6904           // is something like [0 x {int, int}]
6905           const Type *IntPtrTy = TD->getIntPtrType();
6906           int64_t FirstIdx = 0;
6907           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6908             FirstIdx = Offset/TySize;
6909             Offset %= TySize;
6910           
6911             // Handle silly modulus not returning values values [0..TySize).
6912             if (Offset < 0) {
6913               --FirstIdx;
6914               Offset += TySize;
6915               assert(Offset >= 0);
6916             }
6917             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6918           }
6919           
6920           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6921
6922           // Index into the types.  If we fail, set OrigBase to null.
6923           while (Offset) {
6924             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6925               const StructLayout *SL = TD->getStructLayout(STy);
6926               if (Offset < (int64_t)SL->getSizeInBytes()) {
6927                 unsigned Elt = SL->getElementContainingOffset(Offset);
6928                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6929               
6930                 Offset -= SL->getElementOffset(Elt);
6931                 GEPIdxTy = STy->getElementType(Elt);
6932               } else {
6933                 // Otherwise, we can't index into this, bail out.
6934                 Offset = 0;
6935                 OrigBase = 0;
6936               }
6937             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6938               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6939               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6940                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6941                 Offset %= EltSize;
6942               } else {
6943                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6944               }
6945               GEPIdxTy = STy->getElementType();
6946             } else {
6947               // Otherwise, we can't index into this, bail out.
6948               Offset = 0;
6949               OrigBase = 0;
6950             }
6951           }
6952           if (OrigBase) {
6953             // If we were able to index down into an element, create the GEP
6954             // and bitcast the result.  This eliminates one bitcast, potentially
6955             // two.
6956             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6957                                                       NewIndices.begin(),
6958                                                       NewIndices.end(), "");
6959             InsertNewInstBefore(NGEP, CI);
6960             NGEP->takeName(GEP);
6961             
6962             if (isa<BitCastInst>(CI))
6963               return new BitCastInst(NGEP, CI.getType());
6964             assert(isa<PtrToIntInst>(CI));
6965             return new PtrToIntInst(NGEP, CI.getType());
6966           }
6967         }
6968       }      
6969     }
6970   }
6971     
6972   return commonCastTransforms(CI);
6973 }
6974
6975
6976
6977 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6978 /// integer types. This function implements the common transforms for all those
6979 /// cases.
6980 /// @brief Implement the transforms common to CastInst with integer operands
6981 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6982   if (Instruction *Result = commonCastTransforms(CI))
6983     return Result;
6984
6985   Value *Src = CI.getOperand(0);
6986   const Type *SrcTy = Src->getType();
6987   const Type *DestTy = CI.getType();
6988   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6989   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6990
6991   // See if we can simplify any instructions used by the LHS whose sole 
6992   // purpose is to compute bits we don't care about.
6993   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6994   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6995                            KnownZero, KnownOne))
6996     return &CI;
6997
6998   // If the source isn't an instruction or has more than one use then we
6999   // can't do anything more. 
7000   Instruction *SrcI = dyn_cast<Instruction>(Src);
7001   if (!SrcI || !Src->hasOneUse())
7002     return 0;
7003
7004   // Attempt to propagate the cast into the instruction for int->int casts.
7005   int NumCastsRemoved = 0;
7006   if (!isa<BitCastInst>(CI) &&
7007       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7008                                  CI.getOpcode(), NumCastsRemoved)) {
7009     // If this cast is a truncate, evaluting in a different type always
7010     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7011     // we need to do an AND to maintain the clear top-part of the computation,
7012     // so we require that the input have eliminated at least one cast.  If this
7013     // is a sign extension, we insert two new casts (to do the extension) so we
7014     // require that two casts have been eliminated.
7015     bool DoXForm;
7016     switch (CI.getOpcode()) {
7017     default:
7018       // All the others use floating point so we shouldn't actually 
7019       // get here because of the check above.
7020       assert(0 && "Unknown cast type");
7021     case Instruction::Trunc:
7022       DoXForm = true;
7023       break;
7024     case Instruction::ZExt:
7025       DoXForm = NumCastsRemoved >= 1;
7026       break;
7027     case Instruction::SExt:
7028       DoXForm = NumCastsRemoved >= 2;
7029       break;
7030     }
7031     
7032     if (DoXForm) {
7033       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7034                                            CI.getOpcode() == Instruction::SExt);
7035       assert(Res->getType() == DestTy);
7036       switch (CI.getOpcode()) {
7037       default: assert(0 && "Unknown cast type!");
7038       case Instruction::Trunc:
7039       case Instruction::BitCast:
7040         // Just replace this cast with the result.
7041         return ReplaceInstUsesWith(CI, Res);
7042       case Instruction::ZExt: {
7043         // We need to emit an AND to clear the high bits.
7044         assert(SrcBitSize < DestBitSize && "Not a zext?");
7045         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7046                                                             SrcBitSize));
7047         return BinaryOperator::createAnd(Res, C);
7048       }
7049       case Instruction::SExt:
7050         // We need to emit a cast to truncate, then a cast to sext.
7051         return CastInst::create(Instruction::SExt,
7052             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7053                              CI), DestTy);
7054       }
7055     }
7056   }
7057   
7058   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7059   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7060
7061   switch (SrcI->getOpcode()) {
7062   case Instruction::Add:
7063   case Instruction::Mul:
7064   case Instruction::And:
7065   case Instruction::Or:
7066   case Instruction::Xor:
7067     // If we are discarding information, rewrite.
7068     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7069       // Don't insert two casts if they cannot be eliminated.  We allow 
7070       // two casts to be inserted if the sizes are the same.  This could 
7071       // only be converting signedness, which is a noop.
7072       if (DestBitSize == SrcBitSize || 
7073           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7074           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7075         Instruction::CastOps opcode = CI.getOpcode();
7076         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7077         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7078         return BinaryOperator::create(
7079             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7080       }
7081     }
7082
7083     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7084     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7085         SrcI->getOpcode() == Instruction::Xor &&
7086         Op1 == ConstantInt::getTrue() &&
7087         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7088       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7089       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7090     }
7091     break;
7092   case Instruction::SDiv:
7093   case Instruction::UDiv:
7094   case Instruction::SRem:
7095   case Instruction::URem:
7096     // If we are just changing the sign, rewrite.
7097     if (DestBitSize == SrcBitSize) {
7098       // Don't insert two casts if they cannot be eliminated.  We allow 
7099       // two casts to be inserted if the sizes are the same.  This could 
7100       // only be converting signedness, which is a noop.
7101       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7102           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7103         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7104                                               Op0, DestTy, SrcI);
7105         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7106                                               Op1, DestTy, SrcI);
7107         return BinaryOperator::create(
7108           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7109       }
7110     }
7111     break;
7112
7113   case Instruction::Shl:
7114     // Allow changing the sign of the source operand.  Do not allow 
7115     // changing the size of the shift, UNLESS the shift amount is a 
7116     // constant.  We must not change variable sized shifts to a smaller 
7117     // size, because it is undefined to shift more bits out than exist 
7118     // in the value.
7119     if (DestBitSize == SrcBitSize ||
7120         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7121       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7122           Instruction::BitCast : Instruction::Trunc);
7123       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7124       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7125       return BinaryOperator::createShl(Op0c, Op1c);
7126     }
7127     break;
7128   case Instruction::AShr:
7129     // If this is a signed shr, and if all bits shifted in are about to be
7130     // truncated off, turn it into an unsigned shr to allow greater
7131     // simplifications.
7132     if (DestBitSize < SrcBitSize &&
7133         isa<ConstantInt>(Op1)) {
7134       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7135       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7136         // Insert the new logical shift right.
7137         return BinaryOperator::createLShr(Op0, Op1);
7138       }
7139     }
7140     break;
7141   }
7142   return 0;
7143 }
7144
7145 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7146   if (Instruction *Result = commonIntCastTransforms(CI))
7147     return Result;
7148   
7149   Value *Src = CI.getOperand(0);
7150   const Type *Ty = CI.getType();
7151   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7152   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7153   
7154   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7155     switch (SrcI->getOpcode()) {
7156     default: break;
7157     case Instruction::LShr:
7158       // We can shrink lshr to something smaller if we know the bits shifted in
7159       // are already zeros.
7160       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7161         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7162         
7163         // Get a mask for the bits shifting in.
7164         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7165         Value* SrcIOp0 = SrcI->getOperand(0);
7166         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7167           if (ShAmt >= DestBitWidth)        // All zeros.
7168             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7169
7170           // Okay, we can shrink this.  Truncate the input, then return a new
7171           // shift.
7172           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7173           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7174                                        Ty, CI);
7175           return BinaryOperator::createLShr(V1, V2);
7176         }
7177       } else {     // This is a variable shr.
7178         
7179         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7180         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7181         // loop-invariant and CSE'd.
7182         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7183           Value *One = ConstantInt::get(SrcI->getType(), 1);
7184
7185           Value *V = InsertNewInstBefore(
7186               BinaryOperator::createShl(One, SrcI->getOperand(1),
7187                                      "tmp"), CI);
7188           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7189                                                             SrcI->getOperand(0),
7190                                                             "tmp"), CI);
7191           Value *Zero = Constant::getNullValue(V->getType());
7192           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7193         }
7194       }
7195       break;
7196     }
7197   }
7198   
7199   return 0;
7200 }
7201
7202 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7203 /// in order to eliminate the icmp.
7204 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7205                                              bool DoXform) {
7206   // If we are just checking for a icmp eq of a single bit and zext'ing it
7207   // to an integer, then shift the bit to the appropriate place and then
7208   // cast to integer to avoid the comparison.
7209   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7210     const APInt &Op1CV = Op1C->getValue();
7211       
7212     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7213     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7214     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7215         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7216       if (!DoXform) return ICI;
7217
7218       Value *In = ICI->getOperand(0);
7219       Value *Sh = ConstantInt::get(In->getType(),
7220                                    In->getType()->getPrimitiveSizeInBits()-1);
7221       In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7222                                                         In->getName()+".lobit"),
7223                                CI);
7224       if (In->getType() != CI.getType())
7225         In = CastInst::createIntegerCast(In, CI.getType(),
7226                                          false/*ZExt*/, "tmp", &CI);
7227
7228       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7229         Constant *One = ConstantInt::get(In->getType(), 1);
7230         In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7231                                                          In->getName()+".not"),
7232                                  CI);
7233       }
7234
7235       return ReplaceInstUsesWith(CI, In);
7236     }
7237       
7238       
7239       
7240     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7241     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7242     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7243     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7244     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7245     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7246     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7247     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7248     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7249         // This only works for EQ and NE
7250         ICI->isEquality()) {
7251       // If Op1C some other power of two, convert:
7252       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7253       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7254       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7255       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7256         
7257       APInt KnownZeroMask(~KnownZero);
7258       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7259         if (!DoXform) return ICI;
7260
7261         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7262         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7263           // (X&4) == 2 --> false
7264           // (X&4) != 2 --> true
7265           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7266           Res = ConstantExpr::getZExt(Res, CI.getType());
7267           return ReplaceInstUsesWith(CI, Res);
7268         }
7269           
7270         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7271         Value *In = ICI->getOperand(0);
7272         if (ShiftAmt) {
7273           // Perform a logical shr by shiftamt.
7274           // Insert the shift to put the result in the low bit.
7275           In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7276                                   ConstantInt::get(In->getType(), ShiftAmt),
7277                                                    In->getName()+".lobit"), CI);
7278         }
7279           
7280         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7281           Constant *One = ConstantInt::get(In->getType(), 1);
7282           In = BinaryOperator::createXor(In, One, "tmp");
7283           InsertNewInstBefore(cast<Instruction>(In), CI);
7284         }
7285           
7286         if (CI.getType() == In->getType())
7287           return ReplaceInstUsesWith(CI, In);
7288         else
7289           return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7290       }
7291     }
7292   }
7293
7294   return 0;
7295 }
7296
7297 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7298   // If one of the common conversion will work ..
7299   if (Instruction *Result = commonIntCastTransforms(CI))
7300     return Result;
7301
7302   Value *Src = CI.getOperand(0);
7303
7304   // If this is a cast of a cast
7305   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7306     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7307     // types and if the sizes are just right we can convert this into a logical
7308     // 'and' which will be much cheaper than the pair of casts.
7309     if (isa<TruncInst>(CSrc)) {
7310       // Get the sizes of the types involved
7311       Value *A = CSrc->getOperand(0);
7312       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7313       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7314       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7315       // If we're actually extending zero bits and the trunc is a no-op
7316       if (MidSize < DstSize && SrcSize == DstSize) {
7317         // Replace both of the casts with an And of the type mask.
7318         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7319         Constant *AndConst = ConstantInt::get(AndValue);
7320         Instruction *And = 
7321           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7322         // Unfortunately, if the type changed, we need to cast it back.
7323         if (And->getType() != CI.getType()) {
7324           And->setName(CSrc->getName()+".mask");
7325           InsertNewInstBefore(And, CI);
7326           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7327         }
7328         return And;
7329       }
7330     }
7331   }
7332
7333   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7334     return transformZExtICmp(ICI, CI);
7335
7336   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7337   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7338     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7339     // of the (zext icmp) will be transformed.
7340     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7341     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7342     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7343         (transformZExtICmp(LHS, CI, false) ||
7344          transformZExtICmp(RHS, CI, false))) {
7345       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7346       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7347       return BinaryOperator::create(Instruction::Or, LCast, RCast);
7348     }
7349   }
7350
7351   return 0;
7352 }
7353
7354 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7355   if (Instruction *I = commonIntCastTransforms(CI))
7356     return I;
7357   
7358   Value *Src = CI.getOperand(0);
7359   
7360   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7361   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7362   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7363     // If we are just checking for a icmp eq of a single bit and zext'ing it
7364     // to an integer, then shift the bit to the appropriate place and then
7365     // cast to integer to avoid the comparison.
7366     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7367       const APInt &Op1CV = Op1C->getValue();
7368       
7369       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7370       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7371       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7372           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7373         Value *In = ICI->getOperand(0);
7374         Value *Sh = ConstantInt::get(In->getType(),
7375                                      In->getType()->getPrimitiveSizeInBits()-1);
7376         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7377                                                         In->getName()+".lobit"),
7378                                  CI);
7379         if (In->getType() != CI.getType())
7380           In = CastInst::createIntegerCast(In, CI.getType(),
7381                                            true/*SExt*/, "tmp", &CI);
7382         
7383         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7384           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7385                                      In->getName()+".not"), CI);
7386         
7387         return ReplaceInstUsesWith(CI, In);
7388       }
7389     }
7390   }
7391       
7392   return 0;
7393 }
7394
7395 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7396 /// in the specified FP type without changing its value.
7397 static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy, 
7398                               const fltSemantics &Sem) {
7399   APFloat F = CFP->getValueAPF();
7400   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7401     return ConstantFP::get(FPTy, F);
7402   return 0;
7403 }
7404
7405 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7406 /// through it until we get the source value.
7407 static Value *LookThroughFPExtensions(Value *V) {
7408   if (Instruction *I = dyn_cast<Instruction>(V))
7409     if (I->getOpcode() == Instruction::FPExt)
7410       return LookThroughFPExtensions(I->getOperand(0));
7411   
7412   // If this value is a constant, return the constant in the smallest FP type
7413   // that can accurately represent it.  This allows us to turn
7414   // (float)((double)X+2.0) into x+2.0f.
7415   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7416     if (CFP->getType() == Type::PPC_FP128Ty)
7417       return V;  // No constant folding of this.
7418     // See if the value can be truncated to float and then reextended.
7419     if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7420       return V;
7421     if (CFP->getType() == Type::DoubleTy)
7422       return V;  // Won't shrink.
7423     if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7424       return V;
7425     // Don't try to shrink to various long double types.
7426   }
7427   
7428   return V;
7429 }
7430
7431 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7432   if (Instruction *I = commonCastTransforms(CI))
7433     return I;
7434   
7435   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7436   // smaller than the destination type, we can eliminate the truncate by doing
7437   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7438   // many builtins (sqrt, etc).
7439   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7440   if (OpI && OpI->hasOneUse()) {
7441     switch (OpI->getOpcode()) {
7442     default: break;
7443     case Instruction::Add:
7444     case Instruction::Sub:
7445     case Instruction::Mul:
7446     case Instruction::FDiv:
7447     case Instruction::FRem:
7448       const Type *SrcTy = OpI->getType();
7449       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7450       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7451       if (LHSTrunc->getType() != SrcTy && 
7452           RHSTrunc->getType() != SrcTy) {
7453         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7454         // If the source types were both smaller than the destination type of
7455         // the cast, do this xform.
7456         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7457             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7458           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7459                                       CI.getType(), CI);
7460           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7461                                       CI.getType(), CI);
7462           return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7463         }
7464       }
7465       break;  
7466     }
7467   }
7468   return 0;
7469 }
7470
7471 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7472   return commonCastTransforms(CI);
7473 }
7474
7475 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7476   return commonCastTransforms(CI);
7477 }
7478
7479 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7480   return commonCastTransforms(CI);
7481 }
7482
7483 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7484   return commonCastTransforms(CI);
7485 }
7486
7487 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7488   return commonCastTransforms(CI);
7489 }
7490
7491 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7492   return commonPointerCastTransforms(CI);
7493 }
7494
7495 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7496   if (Instruction *I = commonCastTransforms(CI))
7497     return I;
7498   
7499   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7500   if (!DestPointee->isSized()) return 0;
7501
7502   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7503   ConstantInt *Cst;
7504   Value *X;
7505   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7506                                     m_ConstantInt(Cst)))) {
7507     // If the source and destination operands have the same type, see if this
7508     // is a single-index GEP.
7509     if (X->getType() == CI.getType()) {
7510       // Get the size of the pointee type.
7511       uint64_t Size = TD->getABITypeSize(DestPointee);
7512
7513       // Convert the constant to intptr type.
7514       APInt Offset = Cst->getValue();
7515       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7516
7517       // If Offset is evenly divisible by Size, we can do this xform.
7518       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7519         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7520         return new GetElementPtrInst(X, ConstantInt::get(Offset));
7521       }
7522     }
7523     // TODO: Could handle other cases, e.g. where add is indexing into field of
7524     // struct etc.
7525   } else if (CI.getOperand(0)->hasOneUse() &&
7526              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7527     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7528     // "inttoptr+GEP" instead of "add+intptr".
7529     
7530     // Get the size of the pointee type.
7531     uint64_t Size = TD->getABITypeSize(DestPointee);
7532     
7533     // Convert the constant to intptr type.
7534     APInt Offset = Cst->getValue();
7535     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7536     
7537     // If Offset is evenly divisible by Size, we can do this xform.
7538     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7539       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7540       
7541       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7542                                                             "tmp"), CI);
7543       return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7544     }
7545   }
7546   return 0;
7547 }
7548
7549 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7550   // If the operands are integer typed then apply the integer transforms,
7551   // otherwise just apply the common ones.
7552   Value *Src = CI.getOperand(0);
7553   const Type *SrcTy = Src->getType();
7554   const Type *DestTy = CI.getType();
7555
7556   if (SrcTy->isInteger() && DestTy->isInteger()) {
7557     if (Instruction *Result = commonIntCastTransforms(CI))
7558       return Result;
7559   } else if (isa<PointerType>(SrcTy)) {
7560     if (Instruction *I = commonPointerCastTransforms(CI))
7561       return I;
7562   } else {
7563     if (Instruction *Result = commonCastTransforms(CI))
7564       return Result;
7565   }
7566
7567
7568   // Get rid of casts from one type to the same type. These are useless and can
7569   // be replaced by the operand.
7570   if (DestTy == Src->getType())
7571     return ReplaceInstUsesWith(CI, Src);
7572
7573   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7574     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7575     const Type *DstElTy = DstPTy->getElementType();
7576     const Type *SrcElTy = SrcPTy->getElementType();
7577     
7578     // If the address spaces don't match, don't eliminate the bitcast, which is
7579     // required for changing types.
7580     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7581       return 0;
7582     
7583     // If we are casting a malloc or alloca to a pointer to a type of the same
7584     // size, rewrite the allocation instruction to allocate the "right" type.
7585     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7586       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7587         return V;
7588     
7589     // If the source and destination are pointers, and this cast is equivalent
7590     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7591     // This can enhance SROA and other transforms that want type-safe pointers.
7592     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7593     unsigned NumZeros = 0;
7594     while (SrcElTy != DstElTy && 
7595            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7596            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7597       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7598       ++NumZeros;
7599     }
7600
7601     // If we found a path from the src to dest, create the getelementptr now.
7602     if (SrcElTy == DstElTy) {
7603       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7604       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7605                                    ((Instruction*) NULL));
7606     }
7607   }
7608
7609   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7610     if (SVI->hasOneUse()) {
7611       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7612       // a bitconvert to a vector with the same # elts.
7613       if (isa<VectorType>(DestTy) && 
7614           cast<VectorType>(DestTy)->getNumElements() == 
7615                 SVI->getType()->getNumElements()) {
7616         CastInst *Tmp;
7617         // If either of the operands is a cast from CI.getType(), then
7618         // evaluating the shuffle in the casted destination's type will allow
7619         // us to eliminate at least one cast.
7620         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7621              Tmp->getOperand(0)->getType() == DestTy) ||
7622             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7623              Tmp->getOperand(0)->getType() == DestTy)) {
7624           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7625                                                SVI->getOperand(0), DestTy, &CI);
7626           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7627                                                SVI->getOperand(1), DestTy, &CI);
7628           // Return a new shuffle vector.  Use the same element ID's, as we
7629           // know the vector types match #elts.
7630           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7631         }
7632       }
7633     }
7634   }
7635   return 0;
7636 }
7637
7638 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7639 ///   %C = or %A, %B
7640 ///   %D = select %cond, %C, %A
7641 /// into:
7642 ///   %C = select %cond, %B, 0
7643 ///   %D = or %A, %C
7644 ///
7645 /// Assuming that the specified instruction is an operand to the select, return
7646 /// a bitmask indicating which operands of this instruction are foldable if they
7647 /// equal the other incoming value of the select.
7648 ///
7649 static unsigned GetSelectFoldableOperands(Instruction *I) {
7650   switch (I->getOpcode()) {
7651   case Instruction::Add:
7652   case Instruction::Mul:
7653   case Instruction::And:
7654   case Instruction::Or:
7655   case Instruction::Xor:
7656     return 3;              // Can fold through either operand.
7657   case Instruction::Sub:   // Can only fold on the amount subtracted.
7658   case Instruction::Shl:   // Can only fold on the shift amount.
7659   case Instruction::LShr:
7660   case Instruction::AShr:
7661     return 1;
7662   default:
7663     return 0;              // Cannot fold
7664   }
7665 }
7666
7667 /// GetSelectFoldableConstant - For the same transformation as the previous
7668 /// function, return the identity constant that goes into the select.
7669 static Constant *GetSelectFoldableConstant(Instruction *I) {
7670   switch (I->getOpcode()) {
7671   default: assert(0 && "This cannot happen!"); abort();
7672   case Instruction::Add:
7673   case Instruction::Sub:
7674   case Instruction::Or:
7675   case Instruction::Xor:
7676   case Instruction::Shl:
7677   case Instruction::LShr:
7678   case Instruction::AShr:
7679     return Constant::getNullValue(I->getType());
7680   case Instruction::And:
7681     return Constant::getAllOnesValue(I->getType());
7682   case Instruction::Mul:
7683     return ConstantInt::get(I->getType(), 1);
7684   }
7685 }
7686
7687 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7688 /// have the same opcode and only one use each.  Try to simplify this.
7689 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7690                                           Instruction *FI) {
7691   if (TI->getNumOperands() == 1) {
7692     // If this is a non-volatile load or a cast from the same type,
7693     // merge.
7694     if (TI->isCast()) {
7695       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7696         return 0;
7697     } else {
7698       return 0;  // unknown unary op.
7699     }
7700
7701     // Fold this by inserting a select from the input values.
7702     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7703                                        FI->getOperand(0), SI.getName()+".v");
7704     InsertNewInstBefore(NewSI, SI);
7705     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7706                             TI->getType());
7707   }
7708
7709   // Only handle binary operators here.
7710   if (!isa<BinaryOperator>(TI))
7711     return 0;
7712
7713   // Figure out if the operations have any operands in common.
7714   Value *MatchOp, *OtherOpT, *OtherOpF;
7715   bool MatchIsOpZero;
7716   if (TI->getOperand(0) == FI->getOperand(0)) {
7717     MatchOp  = TI->getOperand(0);
7718     OtherOpT = TI->getOperand(1);
7719     OtherOpF = FI->getOperand(1);
7720     MatchIsOpZero = true;
7721   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7722     MatchOp  = TI->getOperand(1);
7723     OtherOpT = TI->getOperand(0);
7724     OtherOpF = FI->getOperand(0);
7725     MatchIsOpZero = false;
7726   } else if (!TI->isCommutative()) {
7727     return 0;
7728   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7729     MatchOp  = TI->getOperand(0);
7730     OtherOpT = TI->getOperand(1);
7731     OtherOpF = FI->getOperand(0);
7732     MatchIsOpZero = true;
7733   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7734     MatchOp  = TI->getOperand(1);
7735     OtherOpT = TI->getOperand(0);
7736     OtherOpF = FI->getOperand(1);
7737     MatchIsOpZero = true;
7738   } else {
7739     return 0;
7740   }
7741
7742   // If we reach here, they do have operations in common.
7743   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7744                                      OtherOpF, SI.getName()+".v");
7745   InsertNewInstBefore(NewSI, SI);
7746
7747   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7748     if (MatchIsOpZero)
7749       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7750     else
7751       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7752   }
7753   assert(0 && "Shouldn't get here");
7754   return 0;
7755 }
7756
7757 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7758   Value *CondVal = SI.getCondition();
7759   Value *TrueVal = SI.getTrueValue();
7760   Value *FalseVal = SI.getFalseValue();
7761
7762   // select true, X, Y  -> X
7763   // select false, X, Y -> Y
7764   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7765     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7766
7767   // select C, X, X -> X
7768   if (TrueVal == FalseVal)
7769     return ReplaceInstUsesWith(SI, TrueVal);
7770
7771   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7772     return ReplaceInstUsesWith(SI, FalseVal);
7773   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7774     return ReplaceInstUsesWith(SI, TrueVal);
7775   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7776     if (isa<Constant>(TrueVal))
7777       return ReplaceInstUsesWith(SI, TrueVal);
7778     else
7779       return ReplaceInstUsesWith(SI, FalseVal);
7780   }
7781
7782   if (SI.getType() == Type::Int1Ty) {
7783     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7784       if (C->getZExtValue()) {
7785         // Change: A = select B, true, C --> A = or B, C
7786         return BinaryOperator::createOr(CondVal, FalseVal);
7787       } else {
7788         // Change: A = select B, false, C --> A = and !B, C
7789         Value *NotCond =
7790           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7791                                              "not."+CondVal->getName()), SI);
7792         return BinaryOperator::createAnd(NotCond, FalseVal);
7793       }
7794     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7795       if (C->getZExtValue() == false) {
7796         // Change: A = select B, C, false --> A = and B, C
7797         return BinaryOperator::createAnd(CondVal, TrueVal);
7798       } else {
7799         // Change: A = select B, C, true --> A = or !B, C
7800         Value *NotCond =
7801           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7802                                              "not."+CondVal->getName()), SI);
7803         return BinaryOperator::createOr(NotCond, TrueVal);
7804       }
7805     }
7806     
7807     // select a, b, a  -> a&b
7808     // select a, a, b  -> a|b
7809     if (CondVal == TrueVal)
7810       return BinaryOperator::createOr(CondVal, FalseVal);
7811     else if (CondVal == FalseVal)
7812       return BinaryOperator::createAnd(CondVal, TrueVal);
7813   }
7814
7815   // Selecting between two integer constants?
7816   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7817     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7818       // select C, 1, 0 -> zext C to int
7819       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7820         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7821       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7822         // select C, 0, 1 -> zext !C to int
7823         Value *NotCond =
7824           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7825                                                "not."+CondVal->getName()), SI);
7826         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7827       }
7828       
7829       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7830
7831       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7832
7833         // (x <s 0) ? -1 : 0 -> ashr x, 31
7834         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7835           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7836             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7837               // The comparison constant and the result are not neccessarily the
7838               // same width. Make an all-ones value by inserting a AShr.
7839               Value *X = IC->getOperand(0);
7840               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7841               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7842               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7843                                                         ShAmt, "ones");
7844               InsertNewInstBefore(SRA, SI);
7845               
7846               // Finally, convert to the type of the select RHS.  We figure out
7847               // if this requires a SExt, Trunc or BitCast based on the sizes.
7848               Instruction::CastOps opc = Instruction::BitCast;
7849               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7850               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7851               if (SRASize < SISize)
7852                 opc = Instruction::SExt;
7853               else if (SRASize > SISize)
7854                 opc = Instruction::Trunc;
7855               return CastInst::create(opc, SRA, SI.getType());
7856             }
7857           }
7858
7859
7860         // If one of the constants is zero (we know they can't both be) and we
7861         // have an icmp instruction with zero, and we have an 'and' with the
7862         // non-constant value, eliminate this whole mess.  This corresponds to
7863         // cases like this: ((X & 27) ? 27 : 0)
7864         if (TrueValC->isZero() || FalseValC->isZero())
7865           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7866               cast<Constant>(IC->getOperand(1))->isNullValue())
7867             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7868               if (ICA->getOpcode() == Instruction::And &&
7869                   isa<ConstantInt>(ICA->getOperand(1)) &&
7870                   (ICA->getOperand(1) == TrueValC ||
7871                    ICA->getOperand(1) == FalseValC) &&
7872                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7873                 // Okay, now we know that everything is set up, we just don't
7874                 // know whether we have a icmp_ne or icmp_eq and whether the 
7875                 // true or false val is the zero.
7876                 bool ShouldNotVal = !TrueValC->isZero();
7877                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7878                 Value *V = ICA;
7879                 if (ShouldNotVal)
7880                   V = InsertNewInstBefore(BinaryOperator::create(
7881                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7882                 return ReplaceInstUsesWith(SI, V);
7883               }
7884       }
7885     }
7886
7887   // See if we are selecting two values based on a comparison of the two values.
7888   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7889     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7890       // Transform (X == Y) ? X : Y  -> Y
7891       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7892         // This is not safe in general for floating point:  
7893         // consider X== -0, Y== +0.
7894         // It becomes safe if either operand is a nonzero constant.
7895         ConstantFP *CFPt, *CFPf;
7896         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7897               !CFPt->getValueAPF().isZero()) ||
7898             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7899              !CFPf->getValueAPF().isZero()))
7900         return ReplaceInstUsesWith(SI, FalseVal);
7901       }
7902       // Transform (X != Y) ? X : Y  -> X
7903       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7904         return ReplaceInstUsesWith(SI, TrueVal);
7905       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7906
7907     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7908       // Transform (X == Y) ? Y : X  -> X
7909       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7910         // This is not safe in general for floating point:  
7911         // consider X== -0, Y== +0.
7912         // It becomes safe if either operand is a nonzero constant.
7913         ConstantFP *CFPt, *CFPf;
7914         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7915               !CFPt->getValueAPF().isZero()) ||
7916             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7917              !CFPf->getValueAPF().isZero()))
7918           return ReplaceInstUsesWith(SI, FalseVal);
7919       }
7920       // Transform (X != Y) ? Y : X  -> Y
7921       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7922         return ReplaceInstUsesWith(SI, TrueVal);
7923       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7924     }
7925   }
7926
7927   // See if we are selecting two values based on a comparison of the two values.
7928   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7929     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7930       // Transform (X == Y) ? X : Y  -> Y
7931       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7932         return ReplaceInstUsesWith(SI, FalseVal);
7933       // Transform (X != Y) ? X : Y  -> X
7934       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7935         return ReplaceInstUsesWith(SI, TrueVal);
7936       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7937
7938     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7939       // Transform (X == Y) ? Y : X  -> X
7940       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7941         return ReplaceInstUsesWith(SI, FalseVal);
7942       // Transform (X != Y) ? Y : X  -> Y
7943       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7944         return ReplaceInstUsesWith(SI, TrueVal);
7945       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7946     }
7947   }
7948
7949   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7950     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7951       if (TI->hasOneUse() && FI->hasOneUse()) {
7952         Instruction *AddOp = 0, *SubOp = 0;
7953
7954         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7955         if (TI->getOpcode() == FI->getOpcode())
7956           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7957             return IV;
7958
7959         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7960         // even legal for FP.
7961         if (TI->getOpcode() == Instruction::Sub &&
7962             FI->getOpcode() == Instruction::Add) {
7963           AddOp = FI; SubOp = TI;
7964         } else if (FI->getOpcode() == Instruction::Sub &&
7965                    TI->getOpcode() == Instruction::Add) {
7966           AddOp = TI; SubOp = FI;
7967         }
7968
7969         if (AddOp) {
7970           Value *OtherAddOp = 0;
7971           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7972             OtherAddOp = AddOp->getOperand(1);
7973           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7974             OtherAddOp = AddOp->getOperand(0);
7975           }
7976
7977           if (OtherAddOp) {
7978             // So at this point we know we have (Y -> OtherAddOp):
7979             //        select C, (add X, Y), (sub X, Z)
7980             Value *NegVal;  // Compute -Z
7981             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7982               NegVal = ConstantExpr::getNeg(C);
7983             } else {
7984               NegVal = InsertNewInstBefore(
7985                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7986             }
7987
7988             Value *NewTrueOp = OtherAddOp;
7989             Value *NewFalseOp = NegVal;
7990             if (AddOp != TI)
7991               std::swap(NewTrueOp, NewFalseOp);
7992             Instruction *NewSel =
7993               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7994
7995             NewSel = InsertNewInstBefore(NewSel, SI);
7996             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7997           }
7998         }
7999       }
8000
8001   // See if we can fold the select into one of our operands.
8002   if (SI.getType()->isInteger()) {
8003     // See the comment above GetSelectFoldableOperands for a description of the
8004     // transformation we are doing here.
8005     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8006       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8007           !isa<Constant>(FalseVal))
8008         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8009           unsigned OpToFold = 0;
8010           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8011             OpToFold = 1;
8012           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8013             OpToFold = 2;
8014           }
8015
8016           if (OpToFold) {
8017             Constant *C = GetSelectFoldableConstant(TVI);
8018             Instruction *NewSel =
8019               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
8020             InsertNewInstBefore(NewSel, SI);
8021             NewSel->takeName(TVI);
8022             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8023               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
8024             else {
8025               assert(0 && "Unknown instruction!!");
8026             }
8027           }
8028         }
8029
8030     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8031       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8032           !isa<Constant>(TrueVal))
8033         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8034           unsigned OpToFold = 0;
8035           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8036             OpToFold = 1;
8037           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8038             OpToFold = 2;
8039           }
8040
8041           if (OpToFold) {
8042             Constant *C = GetSelectFoldableConstant(FVI);
8043             Instruction *NewSel =
8044               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
8045             InsertNewInstBefore(NewSel, SI);
8046             NewSel->takeName(FVI);
8047             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8048               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
8049             else
8050               assert(0 && "Unknown instruction!!");
8051           }
8052         }
8053   }
8054
8055   if (BinaryOperator::isNot(CondVal)) {
8056     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8057     SI.setOperand(1, FalseVal);
8058     SI.setOperand(2, TrueVal);
8059     return &SI;
8060   }
8061
8062   return 0;
8063 }
8064
8065 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8066 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8067 /// and it is more than the alignment of the ultimate object, see if we can
8068 /// increase the alignment of the ultimate object, making this check succeed.
8069 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
8070                                            unsigned PrefAlign = 0) {
8071   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
8072     unsigned Align = GV->getAlignment();
8073     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
8074       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
8075
8076     // If there is a large requested alignment and we can, bump up the alignment
8077     // of the global.
8078     if (PrefAlign > Align && GV->hasInitializer()) {
8079       GV->setAlignment(PrefAlign);
8080       Align = PrefAlign;
8081     }
8082     return Align;
8083   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8084     unsigned Align = AI->getAlignment();
8085     if (Align == 0 && TD) {
8086       if (isa<AllocaInst>(AI))
8087         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
8088       else if (isa<MallocInst>(AI)) {
8089         // Malloc returns maximally aligned memory.
8090         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
8091         Align =
8092           std::max(Align,
8093                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
8094         Align =
8095           std::max(Align,
8096                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
8097       }
8098     }
8099     
8100     // If there is a requested alignment and if this is an alloca, round up.  We
8101     // don't do this for malloc, because some systems can't respect the request.
8102     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8103       AI->setAlignment(PrefAlign);
8104       Align = PrefAlign;
8105     }
8106     return Align;
8107   } else if (isa<BitCastInst>(V) ||
8108              (isa<ConstantExpr>(V) && 
8109               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
8110     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8111                                       TD, PrefAlign);
8112   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
8113     // If all indexes are zero, it is just the alignment of the base pointer.
8114     bool AllZeroOperands = true;
8115     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8116       if (!isa<Constant>(GEPI->getOperand(i)) ||
8117           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8118         AllZeroOperands = false;
8119         break;
8120       }
8121
8122     if (AllZeroOperands) {
8123       // Treat this like a bitcast.
8124       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8125     }
8126
8127     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8128     if (BaseAlignment == 0) return 0;
8129
8130     // Otherwise, if the base alignment is >= the alignment we expect for the
8131     // base pointer type, then we know that the resultant pointer is aligned at
8132     // least as much as its type requires.
8133     if (!TD) return 0;
8134
8135     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
8136     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
8137     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8138     if (Align <= BaseAlignment) {
8139       const Type *GEPTy = GEPI->getType();
8140       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
8141       Align = std::min(Align, (unsigned)
8142                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8143       return Align;
8144     }
8145     return 0;
8146   }
8147   return 0;
8148 }
8149
8150 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8151   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8152   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8153   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8154   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8155
8156   if (CopyAlign < MinAlign) {
8157     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8158     return MI;
8159   }
8160   
8161   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8162   // load/store.
8163   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8164   if (MemOpLength == 0) return 0;
8165   
8166   // Source and destination pointer types are always "i8*" for intrinsic.  See
8167   // if the size is something we can handle with a single primitive load/store.
8168   // A single load+store correctly handles overlapping memory in the memmove
8169   // case.
8170   unsigned Size = MemOpLength->getZExtValue();
8171   if (Size == 0 || Size > 8 || (Size&(Size-1)))
8172     return 0;  // If not 1/2/4/8 bytes, exit.
8173   
8174   // Use an integer load+store unless we can find something better.
8175   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8176   
8177   // Memcpy forces the use of i8* for the source and destination.  That means
8178   // that if you're using memcpy to move one double around, you'll get a cast
8179   // from double* to i8*.  We'd much rather use a double load+store rather than
8180   // an i64 load+store, here because this improves the odds that the source or
8181   // dest address will be promotable.  See if we can find a better type than the
8182   // integer datatype.
8183   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8184     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8185     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8186       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8187       // down through these levels if so.
8188       while (!SrcETy->isFirstClassType()) {
8189         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8190           if (STy->getNumElements() == 1)
8191             SrcETy = STy->getElementType(0);
8192           else
8193             break;
8194         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8195           if (ATy->getNumElements() == 1)
8196             SrcETy = ATy->getElementType();
8197           else
8198             break;
8199         } else
8200           break;
8201       }
8202       
8203       if (SrcETy->isFirstClassType())
8204         NewPtrTy = PointerType::getUnqual(SrcETy);
8205     }
8206   }
8207   
8208   
8209   // If the memcpy/memmove provides better alignment info than we can
8210   // infer, use it.
8211   SrcAlign = std::max(SrcAlign, CopyAlign);
8212   DstAlign = std::max(DstAlign, CopyAlign);
8213   
8214   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8215   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8216   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8217   InsertNewInstBefore(L, *MI);
8218   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8219
8220   // Set the size of the copy to 0, it will be deleted on the next iteration.
8221   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8222   return MI;
8223 }
8224
8225 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8226 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8227 /// the heavy lifting.
8228 ///
8229 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8230   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8231   if (!II) return visitCallSite(&CI);
8232   
8233   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8234   // visitCallSite.
8235   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8236     bool Changed = false;
8237
8238     // memmove/cpy/set of zero bytes is a noop.
8239     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8240       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8241
8242       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8243         if (CI->getZExtValue() == 1) {
8244           // Replace the instruction with just byte operations.  We would
8245           // transform other cases to loads/stores, but we don't know if
8246           // alignment is sufficient.
8247         }
8248     }
8249
8250     // If we have a memmove and the source operation is a constant global,
8251     // then the source and dest pointers can't alias, so we can change this
8252     // into a call to memcpy.
8253     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8254       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8255         if (GVSrc->isConstant()) {
8256           Module *M = CI.getParent()->getParent()->getParent();
8257           Intrinsic::ID MemCpyID;
8258           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8259             MemCpyID = Intrinsic::memcpy_i32;
8260           else
8261             MemCpyID = Intrinsic::memcpy_i64;
8262           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8263           Changed = true;
8264         }
8265     }
8266
8267     // If we can determine a pointer alignment that is bigger than currently
8268     // set, update the alignment.
8269     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8270       if (Instruction *I = SimplifyMemTransfer(MI))
8271         return I;
8272     } else if (isa<MemSetInst>(MI)) {
8273       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
8274       if (MI->getAlignment()->getZExtValue() < Alignment) {
8275         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8276         Changed = true;
8277       }
8278     }
8279           
8280     if (Changed) return II;
8281   } else {
8282     switch (II->getIntrinsicID()) {
8283     default: break;
8284     case Intrinsic::ppc_altivec_lvx:
8285     case Intrinsic::ppc_altivec_lvxl:
8286     case Intrinsic::x86_sse_loadu_ps:
8287     case Intrinsic::x86_sse2_loadu_pd:
8288     case Intrinsic::x86_sse2_loadu_dq:
8289       // Turn PPC lvx     -> load if the pointer is known aligned.
8290       // Turn X86 loadups -> load if the pointer is known aligned.
8291       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8292         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8293                                          PointerType::getUnqual(II->getType()),
8294                                          CI);
8295         return new LoadInst(Ptr);
8296       }
8297       break;
8298     case Intrinsic::ppc_altivec_stvx:
8299     case Intrinsic::ppc_altivec_stvxl:
8300       // Turn stvx -> store if the pointer is known aligned.
8301       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
8302         const Type *OpPtrTy = 
8303           PointerType::getUnqual(II->getOperand(1)->getType());
8304         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8305         return new StoreInst(II->getOperand(1), Ptr);
8306       }
8307       break;
8308     case Intrinsic::x86_sse_storeu_ps:
8309     case Intrinsic::x86_sse2_storeu_pd:
8310     case Intrinsic::x86_sse2_storeu_dq:
8311     case Intrinsic::x86_sse2_storel_dq:
8312       // Turn X86 storeu -> store if the pointer is known aligned.
8313       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8314         const Type *OpPtrTy = 
8315           PointerType::getUnqual(II->getOperand(2)->getType());
8316         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8317         return new StoreInst(II->getOperand(2), Ptr);
8318       }
8319       break;
8320       
8321     case Intrinsic::x86_sse_cvttss2si: {
8322       // These intrinsics only demands the 0th element of its input vector.  If
8323       // we can simplify the input based on that, do so now.
8324       uint64_t UndefElts;
8325       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8326                                                 UndefElts)) {
8327         II->setOperand(1, V);
8328         return II;
8329       }
8330       break;
8331     }
8332       
8333     case Intrinsic::ppc_altivec_vperm:
8334       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8335       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8336         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8337         
8338         // Check that all of the elements are integer constants or undefs.
8339         bool AllEltsOk = true;
8340         for (unsigned i = 0; i != 16; ++i) {
8341           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8342               !isa<UndefValue>(Mask->getOperand(i))) {
8343             AllEltsOk = false;
8344             break;
8345           }
8346         }
8347         
8348         if (AllEltsOk) {
8349           // Cast the input vectors to byte vectors.
8350           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8351           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8352           Value *Result = UndefValue::get(Op0->getType());
8353           
8354           // Only extract each element once.
8355           Value *ExtractedElts[32];
8356           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8357           
8358           for (unsigned i = 0; i != 16; ++i) {
8359             if (isa<UndefValue>(Mask->getOperand(i)))
8360               continue;
8361             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8362             Idx &= 31;  // Match the hardware behavior.
8363             
8364             if (ExtractedElts[Idx] == 0) {
8365               Instruction *Elt = 
8366                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8367               InsertNewInstBefore(Elt, CI);
8368               ExtractedElts[Idx] = Elt;
8369             }
8370           
8371             // Insert this value into the result vector.
8372             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8373             InsertNewInstBefore(cast<Instruction>(Result), CI);
8374           }
8375           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8376         }
8377       }
8378       break;
8379
8380     case Intrinsic::stackrestore: {
8381       // If the save is right next to the restore, remove the restore.  This can
8382       // happen when variable allocas are DCE'd.
8383       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8384         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8385           BasicBlock::iterator BI = SS;
8386           if (&*++BI == II)
8387             return EraseInstFromFunction(CI);
8388         }
8389       }
8390       
8391       // Scan down this block to see if there is another stack restore in the
8392       // same block without an intervening call/alloca.
8393       BasicBlock::iterator BI = II;
8394       TerminatorInst *TI = II->getParent()->getTerminator();
8395       bool CannotRemove = false;
8396       for (++BI; &*BI != TI; ++BI) {
8397         if (isa<AllocaInst>(BI)) {
8398           CannotRemove = true;
8399           break;
8400         }
8401         if (isa<CallInst>(BI)) {
8402           if (!isa<IntrinsicInst>(BI)) {
8403             CannotRemove = true;
8404             break;
8405           }
8406           // If there is a stackrestore below this one, remove this one.
8407           return EraseInstFromFunction(CI);
8408         }
8409       }
8410       
8411       // If the stack restore is in a return/unwind block and if there are no
8412       // allocas or calls between the restore and the return, nuke the restore.
8413       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8414         return EraseInstFromFunction(CI);
8415       break;
8416     }
8417     }
8418   }
8419
8420   return visitCallSite(II);
8421 }
8422
8423 // InvokeInst simplification
8424 //
8425 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8426   return visitCallSite(&II);
8427 }
8428
8429 // visitCallSite - Improvements for call and invoke instructions.
8430 //
8431 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8432   bool Changed = false;
8433
8434   // If the callee is a constexpr cast of a function, attempt to move the cast
8435   // to the arguments of the call/invoke.
8436   if (transformConstExprCastCall(CS)) return 0;
8437
8438   Value *Callee = CS.getCalledValue();
8439
8440   if (Function *CalleeF = dyn_cast<Function>(Callee))
8441     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8442       Instruction *OldCall = CS.getInstruction();
8443       // If the call and callee calling conventions don't match, this call must
8444       // be unreachable, as the call is undefined.
8445       new StoreInst(ConstantInt::getTrue(),
8446                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8447                                     OldCall);
8448       if (!OldCall->use_empty())
8449         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8450       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8451         return EraseInstFromFunction(*OldCall);
8452       return 0;
8453     }
8454
8455   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8456     // This instruction is not reachable, just remove it.  We insert a store to
8457     // undef so that we know that this code is not reachable, despite the fact
8458     // that we can't modify the CFG here.
8459     new StoreInst(ConstantInt::getTrue(),
8460                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8461                   CS.getInstruction());
8462
8463     if (!CS.getInstruction()->use_empty())
8464       CS.getInstruction()->
8465         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8466
8467     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8468       // Don't break the CFG, insert a dummy cond branch.
8469       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8470                      ConstantInt::getTrue(), II);
8471     }
8472     return EraseInstFromFunction(*CS.getInstruction());
8473   }
8474
8475   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8476     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8477       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8478         return transformCallThroughTrampoline(CS);
8479
8480   const PointerType *PTy = cast<PointerType>(Callee->getType());
8481   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8482   if (FTy->isVarArg()) {
8483     // See if we can optimize any arguments passed through the varargs area of
8484     // the call.
8485     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8486            E = CS.arg_end(); I != E; ++I)
8487       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8488         // If this cast does not effect the value passed through the varargs
8489         // area, we can eliminate the use of the cast.
8490         Value *Op = CI->getOperand(0);
8491         if (CI->isLosslessCast()) {
8492           *I = Op;
8493           Changed = true;
8494         }
8495       }
8496   }
8497
8498   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8499     // Inline asm calls cannot throw - mark them 'nounwind'.
8500     CS.setDoesNotThrow();
8501     Changed = true;
8502   }
8503
8504   return Changed ? CS.getInstruction() : 0;
8505 }
8506
8507 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8508 // attempt to move the cast to the arguments of the call/invoke.
8509 //
8510 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8511   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8512   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8513   if (CE->getOpcode() != Instruction::BitCast || 
8514       !isa<Function>(CE->getOperand(0)))
8515     return false;
8516   Function *Callee = cast<Function>(CE->getOperand(0));
8517   Instruction *Caller = CS.getInstruction();
8518   const PAListPtr &CallerPAL = CS.getParamAttrs();
8519
8520   // Okay, this is a cast from a function to a different type.  Unless doing so
8521   // would cause a type conversion of one of our arguments, change this call to
8522   // be a direct call with arguments casted to the appropriate types.
8523   //
8524   const FunctionType *FT = Callee->getFunctionType();
8525   const Type *OldRetTy = Caller->getType();
8526
8527   if (isa<StructType>(FT->getReturnType()))
8528     return false; // TODO: Handle multiple return values.
8529
8530   // Check to see if we are changing the return type...
8531   if (OldRetTy != FT->getReturnType()) {
8532     if (Callee->isDeclaration() && !Caller->use_empty() && 
8533         // Conversion is ok if changing from pointer to int of same size.
8534         !(isa<PointerType>(FT->getReturnType()) &&
8535           TD->getIntPtrType() == OldRetTy))
8536       return false;   // Cannot transform this return value.
8537
8538     if (!Caller->use_empty() &&
8539         // void -> non-void is handled specially
8540         FT->getReturnType() != Type::VoidTy &&
8541         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8542       return false;   // Cannot transform this return value.
8543
8544     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8545       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8546       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8547         return false;   // Attribute not compatible with transformed value.
8548     }
8549
8550     // If the callsite is an invoke instruction, and the return value is used by
8551     // a PHI node in a successor, we cannot change the return type of the call
8552     // because there is no place to put the cast instruction (without breaking
8553     // the critical edge).  Bail out in this case.
8554     if (!Caller->use_empty())
8555       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8556         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8557              UI != E; ++UI)
8558           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8559             if (PN->getParent() == II->getNormalDest() ||
8560                 PN->getParent() == II->getUnwindDest())
8561               return false;
8562   }
8563
8564   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8565   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8566
8567   CallSite::arg_iterator AI = CS.arg_begin();
8568   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8569     const Type *ParamTy = FT->getParamType(i);
8570     const Type *ActTy = (*AI)->getType();
8571
8572     if (!CastInst::isCastable(ActTy, ParamTy))
8573       return false;   // Cannot transform this parameter value.
8574
8575     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8576       return false;   // Attribute not compatible with transformed value.
8577
8578     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8579     // Some conversions are safe even if we do not have a body.
8580     // Either we can cast directly, or we can upconvert the argument
8581     bool isConvertible = ActTy == ParamTy ||
8582       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8583       (ParamTy->isInteger() && ActTy->isInteger() &&
8584        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8585       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8586        && c->getValue().isStrictlyPositive());
8587     if (Callee->isDeclaration() && !isConvertible) return false;
8588   }
8589
8590   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8591       Callee->isDeclaration())
8592     return false;   // Do not delete arguments unless we have a function body.
8593
8594   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8595       !CallerPAL.isEmpty())
8596     // In this case we have more arguments than the new function type, but we
8597     // won't be dropping them.  Check that these extra arguments have attributes
8598     // that are compatible with being a vararg call argument.
8599     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8600       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8601         break;
8602       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8603       if (PAttrs & ParamAttr::VarArgsIncompatible)
8604         return false;
8605     }
8606
8607   // Okay, we decided that this is a safe thing to do: go ahead and start
8608   // inserting cast instructions as necessary...
8609   std::vector<Value*> Args;
8610   Args.reserve(NumActualArgs);
8611   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8612   attrVec.reserve(NumCommonArgs);
8613
8614   // Get any return attributes.
8615   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8616
8617   // If the return value is not being used, the type may not be compatible
8618   // with the existing attributes.  Wipe out any problematic attributes.
8619   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
8620
8621   // Add the new return attributes.
8622   if (RAttrs)
8623     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8624
8625   AI = CS.arg_begin();
8626   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8627     const Type *ParamTy = FT->getParamType(i);
8628     if ((*AI)->getType() == ParamTy) {
8629       Args.push_back(*AI);
8630     } else {
8631       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8632           false, ParamTy, false);
8633       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8634       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8635     }
8636
8637     // Add any parameter attributes.
8638     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8639       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8640   }
8641
8642   // If the function takes more arguments than the call was taking, add them
8643   // now...
8644   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8645     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8646
8647   // If we are removing arguments to the function, emit an obnoxious warning...
8648   if (FT->getNumParams() < NumActualArgs) {
8649     if (!FT->isVarArg()) {
8650       cerr << "WARNING: While resolving call to function '"
8651            << Callee->getName() << "' arguments were dropped!\n";
8652     } else {
8653       // Add all of the arguments in their promoted form to the arg list...
8654       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8655         const Type *PTy = getPromotedType((*AI)->getType());
8656         if (PTy != (*AI)->getType()) {
8657           // Must promote to pass through va_arg area!
8658           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8659                                                                 PTy, false);
8660           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8661           InsertNewInstBefore(Cast, *Caller);
8662           Args.push_back(Cast);
8663         } else {
8664           Args.push_back(*AI);
8665         }
8666
8667         // Add any parameter attributes.
8668         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8669           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8670       }
8671     }
8672   }
8673
8674   if (FT->getReturnType() == Type::VoidTy)
8675     Caller->setName("");   // Void type should not have a name.
8676
8677   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
8678
8679   Instruction *NC;
8680   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8681     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8682                         Args.begin(), Args.end(), Caller->getName(), Caller);
8683     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8684     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8685   } else {
8686     NC = new CallInst(Callee, Args.begin(), Args.end(),
8687                       Caller->getName(), Caller);
8688     CallInst *CI = cast<CallInst>(Caller);
8689     if (CI->isTailCall())
8690       cast<CallInst>(NC)->setTailCall();
8691     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8692     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8693   }
8694
8695   // Insert a cast of the return type as necessary.
8696   Value *NV = NC;
8697   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8698     if (NV->getType() != Type::VoidTy) {
8699       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8700                                                             OldRetTy, false);
8701       NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
8702
8703       // If this is an invoke instruction, we should insert it after the first
8704       // non-phi, instruction in the normal successor block.
8705       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8706         BasicBlock::iterator I = II->getNormalDest()->begin();
8707         while (isa<PHINode>(I)) ++I;
8708         InsertNewInstBefore(NC, *I);
8709       } else {
8710         // Otherwise, it's a call, just insert cast right after the call instr
8711         InsertNewInstBefore(NC, *Caller);
8712       }
8713       AddUsersToWorkList(*Caller);
8714     } else {
8715       NV = UndefValue::get(Caller->getType());
8716     }
8717   }
8718
8719   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8720     Caller->replaceAllUsesWith(NV);
8721   Caller->eraseFromParent();
8722   RemoveFromWorkList(Caller);
8723   return true;
8724 }
8725
8726 // transformCallThroughTrampoline - Turn a call to a function created by the
8727 // init_trampoline intrinsic into a direct call to the underlying function.
8728 //
8729 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8730   Value *Callee = CS.getCalledValue();
8731   const PointerType *PTy = cast<PointerType>(Callee->getType());
8732   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8733   const PAListPtr &Attrs = CS.getParamAttrs();
8734
8735   // If the call already has the 'nest' attribute somewhere then give up -
8736   // otherwise 'nest' would occur twice after splicing in the chain.
8737   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
8738     return 0;
8739
8740   IntrinsicInst *Tramp =
8741     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8742
8743   Function *NestF =
8744     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8745   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8746   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8747
8748   const PAListPtr &NestAttrs = NestF->getParamAttrs();
8749   if (!NestAttrs.isEmpty()) {
8750     unsigned NestIdx = 1;
8751     const Type *NestTy = 0;
8752     ParameterAttributes NestAttr = ParamAttr::None;
8753
8754     // Look for a parameter marked with the 'nest' attribute.
8755     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8756          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8757       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
8758         // Record the parameter type and any other attributes.
8759         NestTy = *I;
8760         NestAttr = NestAttrs.getParamAttrs(NestIdx);
8761         break;
8762       }
8763
8764     if (NestTy) {
8765       Instruction *Caller = CS.getInstruction();
8766       std::vector<Value*> NewArgs;
8767       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8768
8769       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8770       NewAttrs.reserve(Attrs.getNumSlots() + 1);
8771
8772       // Insert the nest argument into the call argument list, which may
8773       // mean appending it.  Likewise for attributes.
8774
8775       // Add any function result attributes.
8776       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8777         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
8778
8779       {
8780         unsigned Idx = 1;
8781         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8782         do {
8783           if (Idx == NestIdx) {
8784             // Add the chain argument and attributes.
8785             Value *NestVal = Tramp->getOperand(3);
8786             if (NestVal->getType() != NestTy)
8787               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8788             NewArgs.push_back(NestVal);
8789             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8790           }
8791
8792           if (I == E)
8793             break;
8794
8795           // Add the original argument and attributes.
8796           NewArgs.push_back(*I);
8797           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
8798             NewAttrs.push_back
8799               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8800
8801           ++Idx, ++I;
8802         } while (1);
8803       }
8804
8805       // The trampoline may have been bitcast to a bogus type (FTy).
8806       // Handle this by synthesizing a new function type, equal to FTy
8807       // with the chain parameter inserted.
8808
8809       std::vector<const Type*> NewTypes;
8810       NewTypes.reserve(FTy->getNumParams()+1);
8811
8812       // Insert the chain's type into the list of parameter types, which may
8813       // mean appending it.
8814       {
8815         unsigned Idx = 1;
8816         FunctionType::param_iterator I = FTy->param_begin(),
8817           E = FTy->param_end();
8818
8819         do {
8820           if (Idx == NestIdx)
8821             // Add the chain's type.
8822             NewTypes.push_back(NestTy);
8823
8824           if (I == E)
8825             break;
8826
8827           // Add the original type.
8828           NewTypes.push_back(*I);
8829
8830           ++Idx, ++I;
8831         } while (1);
8832       }
8833
8834       // Replace the trampoline call with a direct call.  Let the generic
8835       // code sort out any function type mismatches.
8836       FunctionType *NewFTy =
8837         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8838       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8839         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8840       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
8841
8842       Instruction *NewCaller;
8843       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8844         NewCaller = new InvokeInst(NewCallee,
8845                                    II->getNormalDest(), II->getUnwindDest(),
8846                                    NewArgs.begin(), NewArgs.end(),
8847                                    Caller->getName(), Caller);
8848         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8849         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8850       } else {
8851         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8852                                  Caller->getName(), Caller);
8853         if (cast<CallInst>(Caller)->isTailCall())
8854           cast<CallInst>(NewCaller)->setTailCall();
8855         cast<CallInst>(NewCaller)->
8856           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8857         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8858       }
8859       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8860         Caller->replaceAllUsesWith(NewCaller);
8861       Caller->eraseFromParent();
8862       RemoveFromWorkList(Caller);
8863       return 0;
8864     }
8865   }
8866
8867   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8868   // parameter, there is no need to adjust the argument list.  Let the generic
8869   // code sort out any function type mismatches.
8870   Constant *NewCallee =
8871     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8872   CS.setCalledFunction(NewCallee);
8873   return CS.getInstruction();
8874 }
8875
8876 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8877 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8878 /// and a single binop.
8879 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8880   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8881   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8882          isa<CmpInst>(FirstInst));
8883   unsigned Opc = FirstInst->getOpcode();
8884   Value *LHSVal = FirstInst->getOperand(0);
8885   Value *RHSVal = FirstInst->getOperand(1);
8886     
8887   const Type *LHSType = LHSVal->getType();
8888   const Type *RHSType = RHSVal->getType();
8889   
8890   // Scan to see if all operands are the same opcode, all have one use, and all
8891   // kill their operands (i.e. the operands have one use).
8892   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8893     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8894     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8895         // Verify type of the LHS matches so we don't fold cmp's of different
8896         // types or GEP's with different index types.
8897         I->getOperand(0)->getType() != LHSType ||
8898         I->getOperand(1)->getType() != RHSType)
8899       return 0;
8900
8901     // If they are CmpInst instructions, check their predicates
8902     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8903       if (cast<CmpInst>(I)->getPredicate() !=
8904           cast<CmpInst>(FirstInst)->getPredicate())
8905         return 0;
8906     
8907     // Keep track of which operand needs a phi node.
8908     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8909     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8910   }
8911   
8912   // Otherwise, this is safe to transform, determine if it is profitable.
8913
8914   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8915   // Indexes are often folded into load/store instructions, so we don't want to
8916   // hide them behind a phi.
8917   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8918     return 0;
8919   
8920   Value *InLHS = FirstInst->getOperand(0);
8921   Value *InRHS = FirstInst->getOperand(1);
8922   PHINode *NewLHS = 0, *NewRHS = 0;
8923   if (LHSVal == 0) {
8924     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8925     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8926     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8927     InsertNewInstBefore(NewLHS, PN);
8928     LHSVal = NewLHS;
8929   }
8930   
8931   if (RHSVal == 0) {
8932     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8933     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8934     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8935     InsertNewInstBefore(NewRHS, PN);
8936     RHSVal = NewRHS;
8937   }
8938   
8939   // Add all operands to the new PHIs.
8940   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8941     if (NewLHS) {
8942       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8943       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8944     }
8945     if (NewRHS) {
8946       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8947       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8948     }
8949   }
8950     
8951   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8952     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8953   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8954     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8955                            RHSVal);
8956   else {
8957     assert(isa<GetElementPtrInst>(FirstInst));
8958     return new GetElementPtrInst(LHSVal, RHSVal);
8959   }
8960 }
8961
8962 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8963 /// of the block that defines it.  This means that it must be obvious the value
8964 /// of the load is not changed from the point of the load to the end of the
8965 /// block it is in.
8966 ///
8967 /// Finally, it is safe, but not profitable, to sink a load targetting a
8968 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8969 /// to a register.
8970 static bool isSafeToSinkLoad(LoadInst *L) {
8971   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8972   
8973   for (++BBI; BBI != E; ++BBI)
8974     if (BBI->mayWriteToMemory())
8975       return false;
8976   
8977   // Check for non-address taken alloca.  If not address-taken already, it isn't
8978   // profitable to do this xform.
8979   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8980     bool isAddressTaken = false;
8981     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8982          UI != E; ++UI) {
8983       if (isa<LoadInst>(UI)) continue;
8984       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8985         // If storing TO the alloca, then the address isn't taken.
8986         if (SI->getOperand(1) == AI) continue;
8987       }
8988       isAddressTaken = true;
8989       break;
8990     }
8991     
8992     if (!isAddressTaken)
8993       return false;
8994   }
8995   
8996   return true;
8997 }
8998
8999
9000 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9001 // operator and they all are only used by the PHI, PHI together their
9002 // inputs, and do the operation once, to the result of the PHI.
9003 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9004   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9005
9006   // Scan the instruction, looking for input operations that can be folded away.
9007   // If all input operands to the phi are the same instruction (e.g. a cast from
9008   // the same type or "+42") we can pull the operation through the PHI, reducing
9009   // code size and simplifying code.
9010   Constant *ConstantOp = 0;
9011   const Type *CastSrcTy = 0;
9012   bool isVolatile = false;
9013   if (isa<CastInst>(FirstInst)) {
9014     CastSrcTy = FirstInst->getOperand(0)->getType();
9015   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9016     // Can fold binop, compare or shift here if the RHS is a constant, 
9017     // otherwise call FoldPHIArgBinOpIntoPHI.
9018     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9019     if (ConstantOp == 0)
9020       return FoldPHIArgBinOpIntoPHI(PN);
9021   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9022     isVolatile = LI->isVolatile();
9023     // We can't sink the load if the loaded value could be modified between the
9024     // load and the PHI.
9025     if (LI->getParent() != PN.getIncomingBlock(0) ||
9026         !isSafeToSinkLoad(LI))
9027       return 0;
9028   } else if (isa<GetElementPtrInst>(FirstInst)) {
9029     if (FirstInst->getNumOperands() == 2)
9030       return FoldPHIArgBinOpIntoPHI(PN);
9031     // Can't handle general GEPs yet.
9032     return 0;
9033   } else {
9034     return 0;  // Cannot fold this operation.
9035   }
9036
9037   // Check to see if all arguments are the same operation.
9038   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9039     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9040     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9041     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9042       return 0;
9043     if (CastSrcTy) {
9044       if (I->getOperand(0)->getType() != CastSrcTy)
9045         return 0;  // Cast operation must match.
9046     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9047       // We can't sink the load if the loaded value could be modified between 
9048       // the load and the PHI.
9049       if (LI->isVolatile() != isVolatile ||
9050           LI->getParent() != PN.getIncomingBlock(i) ||
9051           !isSafeToSinkLoad(LI))
9052         return 0;
9053     } else if (I->getOperand(1) != ConstantOp) {
9054       return 0;
9055     }
9056   }
9057
9058   // Okay, they are all the same operation.  Create a new PHI node of the
9059   // correct type, and PHI together all of the LHS's of the instructions.
9060   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
9061                                PN.getName()+".in");
9062   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9063
9064   Value *InVal = FirstInst->getOperand(0);
9065   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9066
9067   // Add all operands to the new PHI.
9068   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9069     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9070     if (NewInVal != InVal)
9071       InVal = 0;
9072     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9073   }
9074
9075   Value *PhiVal;
9076   if (InVal) {
9077     // The new PHI unions all of the same values together.  This is really
9078     // common, so we handle it intelligently here for compile-time speed.
9079     PhiVal = InVal;
9080     delete NewPN;
9081   } else {
9082     InsertNewInstBefore(NewPN, PN);
9083     PhiVal = NewPN;
9084   }
9085
9086   // Insert and return the new operation.
9087   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9088     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
9089   else if (isa<LoadInst>(FirstInst))
9090     return new LoadInst(PhiVal, "", isVolatile);
9091   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9092     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
9093   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9094     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
9095                            PhiVal, ConstantOp);
9096   else
9097     assert(0 && "Unknown operation");
9098   return 0;
9099 }
9100
9101 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9102 /// that is dead.
9103 static bool DeadPHICycle(PHINode *PN,
9104                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9105   if (PN->use_empty()) return true;
9106   if (!PN->hasOneUse()) return false;
9107
9108   // Remember this node, and if we find the cycle, return.
9109   if (!PotentiallyDeadPHIs.insert(PN))
9110     return true;
9111   
9112   // Don't scan crazily complex things.
9113   if (PotentiallyDeadPHIs.size() == 16)
9114     return false;
9115
9116   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9117     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9118
9119   return false;
9120 }
9121
9122 /// PHIsEqualValue - Return true if this phi node is always equal to
9123 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9124 ///   z = some value; x = phi (y, z); y = phi (x, z)
9125 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9126                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9127   // See if we already saw this PHI node.
9128   if (!ValueEqualPHIs.insert(PN))
9129     return true;
9130   
9131   // Don't scan crazily complex things.
9132   if (ValueEqualPHIs.size() == 16)
9133     return false;
9134  
9135   // Scan the operands to see if they are either phi nodes or are equal to
9136   // the value.
9137   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9138     Value *Op = PN->getIncomingValue(i);
9139     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9140       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9141         return false;
9142     } else if (Op != NonPhiInVal)
9143       return false;
9144   }
9145   
9146   return true;
9147 }
9148
9149
9150 // PHINode simplification
9151 //
9152 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9153   // If LCSSA is around, don't mess with Phi nodes
9154   if (MustPreserveLCSSA) return 0;
9155   
9156   if (Value *V = PN.hasConstantValue())
9157     return ReplaceInstUsesWith(PN, V);
9158
9159   // If all PHI operands are the same operation, pull them through the PHI,
9160   // reducing code size.
9161   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9162       PN.getIncomingValue(0)->hasOneUse())
9163     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9164       return Result;
9165
9166   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9167   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9168   // PHI)... break the cycle.
9169   if (PN.hasOneUse()) {
9170     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9171     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9172       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9173       PotentiallyDeadPHIs.insert(&PN);
9174       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9175         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9176     }
9177    
9178     // If this phi has a single use, and if that use just computes a value for
9179     // the next iteration of a loop, delete the phi.  This occurs with unused
9180     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9181     // common case here is good because the only other things that catch this
9182     // are induction variable analysis (sometimes) and ADCE, which is only run
9183     // late.
9184     if (PHIUser->hasOneUse() &&
9185         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9186         PHIUser->use_back() == &PN) {
9187       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9188     }
9189   }
9190
9191   // We sometimes end up with phi cycles that non-obviously end up being the
9192   // same value, for example:
9193   //   z = some value; x = phi (y, z); y = phi (x, z)
9194   // where the phi nodes don't necessarily need to be in the same block.  Do a
9195   // quick check to see if the PHI node only contains a single non-phi value, if
9196   // so, scan to see if the phi cycle is actually equal to that value.
9197   {
9198     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9199     // Scan for the first non-phi operand.
9200     while (InValNo != NumOperandVals && 
9201            isa<PHINode>(PN.getIncomingValue(InValNo)))
9202       ++InValNo;
9203
9204     if (InValNo != NumOperandVals) {
9205       Value *NonPhiInVal = PN.getOperand(InValNo);
9206       
9207       // Scan the rest of the operands to see if there are any conflicts, if so
9208       // there is no need to recursively scan other phis.
9209       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9210         Value *OpVal = PN.getIncomingValue(InValNo);
9211         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9212           break;
9213       }
9214       
9215       // If we scanned over all operands, then we have one unique value plus
9216       // phi values.  Scan PHI nodes to see if they all merge in each other or
9217       // the value.
9218       if (InValNo == NumOperandVals) {
9219         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9220         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9221           return ReplaceInstUsesWith(PN, NonPhiInVal);
9222       }
9223     }
9224   }
9225   return 0;
9226 }
9227
9228 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9229                                    Instruction *InsertPoint,
9230                                    InstCombiner *IC) {
9231   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9232   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9233   // We must cast correctly to the pointer type. Ensure that we
9234   // sign extend the integer value if it is smaller as this is
9235   // used for address computation.
9236   Instruction::CastOps opcode = 
9237      (VTySize < PtrSize ? Instruction::SExt :
9238       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9239   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9240 }
9241
9242
9243 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9244   Value *PtrOp = GEP.getOperand(0);
9245   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9246   // If so, eliminate the noop.
9247   if (GEP.getNumOperands() == 1)
9248     return ReplaceInstUsesWith(GEP, PtrOp);
9249
9250   if (isa<UndefValue>(GEP.getOperand(0)))
9251     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9252
9253   bool HasZeroPointerIndex = false;
9254   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9255     HasZeroPointerIndex = C->isNullValue();
9256
9257   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9258     return ReplaceInstUsesWith(GEP, PtrOp);
9259
9260   // Eliminate unneeded casts for indices.
9261   bool MadeChange = false;
9262   
9263   gep_type_iterator GTI = gep_type_begin(GEP);
9264   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9265     if (isa<SequentialType>(*GTI)) {
9266       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9267         if (CI->getOpcode() == Instruction::ZExt ||
9268             CI->getOpcode() == Instruction::SExt) {
9269           const Type *SrcTy = CI->getOperand(0)->getType();
9270           // We can eliminate a cast from i32 to i64 iff the target 
9271           // is a 32-bit pointer target.
9272           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9273             MadeChange = true;
9274             GEP.setOperand(i, CI->getOperand(0));
9275           }
9276         }
9277       }
9278       // If we are using a wider index than needed for this platform, shrink it
9279       // to what we need.  If the incoming value needs a cast instruction,
9280       // insert it.  This explicit cast can make subsequent optimizations more
9281       // obvious.
9282       Value *Op = GEP.getOperand(i);
9283       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9284         if (Constant *C = dyn_cast<Constant>(Op)) {
9285           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9286           MadeChange = true;
9287         } else {
9288           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9289                                 GEP);
9290           GEP.setOperand(i, Op);
9291           MadeChange = true;
9292         }
9293       }
9294     }
9295   }
9296   if (MadeChange) return &GEP;
9297
9298   // If this GEP instruction doesn't move the pointer, and if the input operand
9299   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9300   // real input to the dest type.
9301   if (GEP.hasAllZeroIndices()) {
9302     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9303       // If the bitcast is of an allocation, and the allocation will be
9304       // converted to match the type of the cast, don't touch this.
9305       if (isa<AllocationInst>(BCI->getOperand(0))) {
9306         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9307         if (Instruction *I = visitBitCast(*BCI)) {
9308           if (I != BCI) {
9309             I->takeName(BCI);
9310             BCI->getParent()->getInstList().insert(BCI, I);
9311             ReplaceInstUsesWith(*BCI, I);
9312           }
9313           return &GEP;
9314         }
9315       }
9316       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9317     }
9318   }
9319   
9320   // Combine Indices - If the source pointer to this getelementptr instruction
9321   // is a getelementptr instruction, combine the indices of the two
9322   // getelementptr instructions into a single instruction.
9323   //
9324   SmallVector<Value*, 8> SrcGEPOperands;
9325   if (User *Src = dyn_castGetElementPtr(PtrOp))
9326     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9327
9328   if (!SrcGEPOperands.empty()) {
9329     // Note that if our source is a gep chain itself that we wait for that
9330     // chain to be resolved before we perform this transformation.  This
9331     // avoids us creating a TON of code in some cases.
9332     //
9333     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9334         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9335       return 0;   // Wait until our source is folded to completion.
9336
9337     SmallVector<Value*, 8> Indices;
9338
9339     // Find out whether the last index in the source GEP is a sequential idx.
9340     bool EndsWithSequential = false;
9341     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9342            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9343       EndsWithSequential = !isa<StructType>(*I);
9344
9345     // Can we combine the two pointer arithmetics offsets?
9346     if (EndsWithSequential) {
9347       // Replace: gep (gep %P, long B), long A, ...
9348       // With:    T = long A+B; gep %P, T, ...
9349       //
9350       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9351       if (SO1 == Constant::getNullValue(SO1->getType())) {
9352         Sum = GO1;
9353       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9354         Sum = SO1;
9355       } else {
9356         // If they aren't the same type, convert both to an integer of the
9357         // target's pointer size.
9358         if (SO1->getType() != GO1->getType()) {
9359           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9360             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9361           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9362             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9363           } else {
9364             unsigned PS = TD->getPointerSizeInBits();
9365             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9366               // Convert GO1 to SO1's type.
9367               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9368
9369             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9370               // Convert SO1 to GO1's type.
9371               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9372             } else {
9373               const Type *PT = TD->getIntPtrType();
9374               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9375               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9376             }
9377           }
9378         }
9379         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9380           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9381         else {
9382           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9383           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9384         }
9385       }
9386
9387       // Recycle the GEP we already have if possible.
9388       if (SrcGEPOperands.size() == 2) {
9389         GEP.setOperand(0, SrcGEPOperands[0]);
9390         GEP.setOperand(1, Sum);
9391         return &GEP;
9392       } else {
9393         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9394                        SrcGEPOperands.end()-1);
9395         Indices.push_back(Sum);
9396         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9397       }
9398     } else if (isa<Constant>(*GEP.idx_begin()) &&
9399                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9400                SrcGEPOperands.size() != 1) {
9401       // Otherwise we can do the fold if the first index of the GEP is a zero
9402       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9403                      SrcGEPOperands.end());
9404       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9405     }
9406
9407     if (!Indices.empty())
9408       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9409                                    Indices.end(), GEP.getName());
9410
9411   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9412     // GEP of global variable.  If all of the indices for this GEP are
9413     // constants, we can promote this to a constexpr instead of an instruction.
9414
9415     // Scan for nonconstants...
9416     SmallVector<Constant*, 8> Indices;
9417     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9418     for (; I != E && isa<Constant>(*I); ++I)
9419       Indices.push_back(cast<Constant>(*I));
9420
9421     if (I == E) {  // If they are all constants...
9422       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9423                                                     &Indices[0],Indices.size());
9424
9425       // Replace all uses of the GEP with the new constexpr...
9426       return ReplaceInstUsesWith(GEP, CE);
9427     }
9428   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9429     if (!isa<PointerType>(X->getType())) {
9430       // Not interesting.  Source pointer must be a cast from pointer.
9431     } else if (HasZeroPointerIndex) {
9432       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9433       // into     : GEP [10 x i8]* X, i32 0, ...
9434       //
9435       // This occurs when the program declares an array extern like "int X[];"
9436       //
9437       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9438       const PointerType *XTy = cast<PointerType>(X->getType());
9439       if (const ArrayType *XATy =
9440           dyn_cast<ArrayType>(XTy->getElementType()))
9441         if (const ArrayType *CATy =
9442             dyn_cast<ArrayType>(CPTy->getElementType()))
9443           if (CATy->getElementType() == XATy->getElementType()) {
9444             // At this point, we know that the cast source type is a pointer
9445             // to an array of the same type as the destination pointer
9446             // array.  Because the array type is never stepped over (there
9447             // is a leading zero) we can fold the cast into this GEP.
9448             GEP.setOperand(0, X);
9449             return &GEP;
9450           }
9451     } else if (GEP.getNumOperands() == 2) {
9452       // Transform things like:
9453       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9454       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9455       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9456       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9457       if (isa<ArrayType>(SrcElTy) &&
9458           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9459           TD->getABITypeSize(ResElTy)) {
9460         Value *Idx[2];
9461         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9462         Idx[1] = GEP.getOperand(1);
9463         Value *V = InsertNewInstBefore(
9464                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
9465         // V and GEP are both pointer types --> BitCast
9466         return new BitCastInst(V, GEP.getType());
9467       }
9468       
9469       // Transform things like:
9470       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9471       //   (where tmp = 8*tmp2) into:
9472       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9473       
9474       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9475         uint64_t ArrayEltSize =
9476             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9477         
9478         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9479         // allow either a mul, shift, or constant here.
9480         Value *NewIdx = 0;
9481         ConstantInt *Scale = 0;
9482         if (ArrayEltSize == 1) {
9483           NewIdx = GEP.getOperand(1);
9484           Scale = ConstantInt::get(NewIdx->getType(), 1);
9485         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9486           NewIdx = ConstantInt::get(CI->getType(), 1);
9487           Scale = CI;
9488         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9489           if (Inst->getOpcode() == Instruction::Shl &&
9490               isa<ConstantInt>(Inst->getOperand(1))) {
9491             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9492             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9493             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9494             NewIdx = Inst->getOperand(0);
9495           } else if (Inst->getOpcode() == Instruction::Mul &&
9496                      isa<ConstantInt>(Inst->getOperand(1))) {
9497             Scale = cast<ConstantInt>(Inst->getOperand(1));
9498             NewIdx = Inst->getOperand(0);
9499           }
9500         }
9501         
9502         // If the index will be to exactly the right offset with the scale taken
9503         // out, perform the transformation. Note, we don't know whether Scale is
9504         // signed or not. We'll use unsigned version of division/modulo
9505         // operation after making sure Scale doesn't have the sign bit set.
9506         if (Scale && Scale->getSExtValue() >= 0LL &&
9507             Scale->getZExtValue() % ArrayEltSize == 0) {
9508           Scale = ConstantInt::get(Scale->getType(),
9509                                    Scale->getZExtValue() / ArrayEltSize);
9510           if (Scale->getZExtValue() != 1) {
9511             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9512                                                        false /*ZExt*/);
9513             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9514             NewIdx = InsertNewInstBefore(Sc, GEP);
9515           }
9516
9517           // Insert the new GEP instruction.
9518           Value *Idx[2];
9519           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9520           Idx[1] = NewIdx;
9521           Instruction *NewGEP =
9522             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9523           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9524           // The NewGEP must be pointer typed, so must the old one -> BitCast
9525           return new BitCastInst(NewGEP, GEP.getType());
9526         }
9527       }
9528     }
9529   }
9530
9531   return 0;
9532 }
9533
9534 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9535   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9536   if (AI.isArrayAllocation()) {  // Check C != 1
9537     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9538       const Type *NewTy = 
9539         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9540       AllocationInst *New = 0;
9541
9542       // Create and insert the replacement instruction...
9543       if (isa<MallocInst>(AI))
9544         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9545       else {
9546         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9547         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9548       }
9549
9550       InsertNewInstBefore(New, AI);
9551
9552       // Scan to the end of the allocation instructions, to skip over a block of
9553       // allocas if possible...
9554       //
9555       BasicBlock::iterator It = New;
9556       while (isa<AllocationInst>(*It)) ++It;
9557
9558       // Now that I is pointing to the first non-allocation-inst in the block,
9559       // insert our getelementptr instruction...
9560       //
9561       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9562       Value *Idx[2];
9563       Idx[0] = NullIdx;
9564       Idx[1] = NullIdx;
9565       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9566                                        New->getName()+".sub", It);
9567
9568       // Now make everything use the getelementptr instead of the original
9569       // allocation.
9570       return ReplaceInstUsesWith(AI, V);
9571     } else if (isa<UndefValue>(AI.getArraySize())) {
9572       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9573     }
9574   }
9575
9576   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9577   // Note that we only do this for alloca's, because malloc should allocate and
9578   // return a unique pointer, even for a zero byte allocation.
9579   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9580       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9581     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9582
9583   return 0;
9584 }
9585
9586 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9587   Value *Op = FI.getOperand(0);
9588
9589   // free undef -> unreachable.
9590   if (isa<UndefValue>(Op)) {
9591     // Insert a new store to null because we cannot modify the CFG here.
9592     new StoreInst(ConstantInt::getTrue(),
9593                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9594     return EraseInstFromFunction(FI);
9595   }
9596   
9597   // If we have 'free null' delete the instruction.  This can happen in stl code
9598   // when lots of inlining happens.
9599   if (isa<ConstantPointerNull>(Op))
9600     return EraseInstFromFunction(FI);
9601   
9602   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9603   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9604     FI.setOperand(0, CI->getOperand(0));
9605     return &FI;
9606   }
9607   
9608   // Change free (gep X, 0,0,0,0) into free(X)
9609   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9610     if (GEPI->hasAllZeroIndices()) {
9611       AddToWorkList(GEPI);
9612       FI.setOperand(0, GEPI->getOperand(0));
9613       return &FI;
9614     }
9615   }
9616   
9617   // Change free(malloc) into nothing, if the malloc has a single use.
9618   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9619     if (MI->hasOneUse()) {
9620       EraseInstFromFunction(FI);
9621       return EraseInstFromFunction(*MI);
9622     }
9623
9624   return 0;
9625 }
9626
9627
9628 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9629 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9630                                         const TargetData *TD) {
9631   User *CI = cast<User>(LI.getOperand(0));
9632   Value *CastOp = CI->getOperand(0);
9633
9634   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9635     // Instead of loading constant c string, use corresponding integer value
9636     // directly if string length is small enough.
9637     const std::string &Str = CE->getOperand(0)->getStringValue();
9638     if (!Str.empty()) {
9639       unsigned len = Str.length();
9640       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9641       unsigned numBits = Ty->getPrimitiveSizeInBits();
9642       // Replace LI with immediate integer store.
9643       if ((numBits >> 3) == len + 1) {
9644         APInt StrVal(numBits, 0);
9645         APInt SingleChar(numBits, 0);
9646         if (TD->isLittleEndian()) {
9647           for (signed i = len-1; i >= 0; i--) {
9648             SingleChar = (uint64_t) Str[i];
9649             StrVal = (StrVal << 8) | SingleChar;
9650           }
9651         } else {
9652           for (unsigned i = 0; i < len; i++) {
9653             SingleChar = (uint64_t) Str[i];
9654             StrVal = (StrVal << 8) | SingleChar;
9655           }
9656           // Append NULL at the end.
9657           SingleChar = 0;
9658           StrVal = (StrVal << 8) | SingleChar;
9659         }
9660         Value *NL = ConstantInt::get(StrVal);
9661         return IC.ReplaceInstUsesWith(LI, NL);
9662       }
9663     }
9664   }
9665
9666   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9667   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9668     const Type *SrcPTy = SrcTy->getElementType();
9669
9670     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9671          isa<VectorType>(DestPTy)) {
9672       // If the source is an array, the code below will not succeed.  Check to
9673       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9674       // constants.
9675       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9676         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9677           if (ASrcTy->getNumElements() != 0) {
9678             Value *Idxs[2];
9679             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9680             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9681             SrcTy = cast<PointerType>(CastOp->getType());
9682             SrcPTy = SrcTy->getElementType();
9683           }
9684
9685       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9686             isa<VectorType>(SrcPTy)) &&
9687           // Do not allow turning this into a load of an integer, which is then
9688           // casted to a pointer, this pessimizes pointer analysis a lot.
9689           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9690           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9691                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9692
9693         // Okay, we are casting from one integer or pointer type to another of
9694         // the same size.  Instead of casting the pointer before the load, cast
9695         // the result of the loaded value.
9696         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9697                                                              CI->getName(),
9698                                                          LI.isVolatile()),LI);
9699         // Now cast the result of the load.
9700         return new BitCastInst(NewLoad, LI.getType());
9701       }
9702     }
9703   }
9704   return 0;
9705 }
9706
9707 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9708 /// from this value cannot trap.  If it is not obviously safe to load from the
9709 /// specified pointer, we do a quick local scan of the basic block containing
9710 /// ScanFrom, to determine if the address is already accessed.
9711 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9712   // If it is an alloca it is always safe to load from.
9713   if (isa<AllocaInst>(V)) return true;
9714
9715   // If it is a global variable it is mostly safe to load from.
9716   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9717     // Don't try to evaluate aliases.  External weak GV can be null.
9718     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9719
9720   // Otherwise, be a little bit agressive by scanning the local block where we
9721   // want to check to see if the pointer is already being loaded or stored
9722   // from/to.  If so, the previous load or store would have already trapped,
9723   // so there is no harm doing an extra load (also, CSE will later eliminate
9724   // the load entirely).
9725   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9726
9727   while (BBI != E) {
9728     --BBI;
9729
9730     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9731       if (LI->getOperand(0) == V) return true;
9732     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9733       if (SI->getOperand(1) == V) return true;
9734
9735   }
9736   return false;
9737 }
9738
9739 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9740 /// until we find the underlying object a pointer is referring to or something
9741 /// we don't understand.  Note that the returned pointer may be offset from the
9742 /// input, because we ignore GEP indices.
9743 static Value *GetUnderlyingObject(Value *Ptr) {
9744   while (1) {
9745     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9746       if (CE->getOpcode() == Instruction::BitCast ||
9747           CE->getOpcode() == Instruction::GetElementPtr)
9748         Ptr = CE->getOperand(0);
9749       else
9750         return Ptr;
9751     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9752       Ptr = BCI->getOperand(0);
9753     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9754       Ptr = GEP->getOperand(0);
9755     } else {
9756       return Ptr;
9757     }
9758   }
9759 }
9760
9761 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9762   Value *Op = LI.getOperand(0);
9763
9764   // Attempt to improve the alignment.
9765   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9766   if (KnownAlign > LI.getAlignment())
9767     LI.setAlignment(KnownAlign);
9768
9769   // load (cast X) --> cast (load X) iff safe
9770   if (isa<CastInst>(Op))
9771     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9772       return Res;
9773
9774   // None of the following transforms are legal for volatile loads.
9775   if (LI.isVolatile()) return 0;
9776   
9777   if (&LI.getParent()->front() != &LI) {
9778     BasicBlock::iterator BBI = &LI; --BBI;
9779     // If the instruction immediately before this is a store to the same
9780     // address, do a simple form of store->load forwarding.
9781     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9782       if (SI->getOperand(1) == LI.getOperand(0))
9783         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9784     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9785       if (LIB->getOperand(0) == LI.getOperand(0))
9786         return ReplaceInstUsesWith(LI, LIB);
9787   }
9788
9789   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9790     const Value *GEPI0 = GEPI->getOperand(0);
9791     // TODO: Consider a target hook for valid address spaces for this xform.
9792     if (isa<ConstantPointerNull>(GEPI0) &&
9793         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
9794       // Insert a new store to null instruction before the load to indicate
9795       // that this code is not reachable.  We do this instead of inserting
9796       // an unreachable instruction directly because we cannot modify the
9797       // CFG.
9798       new StoreInst(UndefValue::get(LI.getType()),
9799                     Constant::getNullValue(Op->getType()), &LI);
9800       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9801     }
9802   } 
9803
9804   if (Constant *C = dyn_cast<Constant>(Op)) {
9805     // load null/undef -> undef
9806     // TODO: Consider a target hook for valid address spaces for this xform.
9807     if (isa<UndefValue>(C) || (C->isNullValue() && 
9808         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
9809       // Insert a new store to null instruction before the load to indicate that
9810       // this code is not reachable.  We do this instead of inserting an
9811       // unreachable instruction directly because we cannot modify the CFG.
9812       new StoreInst(UndefValue::get(LI.getType()),
9813                     Constant::getNullValue(Op->getType()), &LI);
9814       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9815     }
9816
9817     // Instcombine load (constant global) into the value loaded.
9818     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9819       if (GV->isConstant() && !GV->isDeclaration())
9820         return ReplaceInstUsesWith(LI, GV->getInitializer());
9821
9822     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9823     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
9824       if (CE->getOpcode() == Instruction::GetElementPtr) {
9825         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9826           if (GV->isConstant() && !GV->isDeclaration())
9827             if (Constant *V = 
9828                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9829               return ReplaceInstUsesWith(LI, V);
9830         if (CE->getOperand(0)->isNullValue()) {
9831           // Insert a new store to null instruction before the load to indicate
9832           // that this code is not reachable.  We do this instead of inserting
9833           // an unreachable instruction directly because we cannot modify the
9834           // CFG.
9835           new StoreInst(UndefValue::get(LI.getType()),
9836                         Constant::getNullValue(Op->getType()), &LI);
9837           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9838         }
9839
9840       } else if (CE->isCast()) {
9841         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9842           return Res;
9843       }
9844     }
9845   }
9846     
9847   // If this load comes from anywhere in a constant global, and if the global
9848   // is all undef or zero, we know what it loads.
9849   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9850     if (GV->isConstant() && GV->hasInitializer()) {
9851       if (GV->getInitializer()->isNullValue())
9852         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9853       else if (isa<UndefValue>(GV->getInitializer()))
9854         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9855     }
9856   }
9857
9858   if (Op->hasOneUse()) {
9859     // Change select and PHI nodes to select values instead of addresses: this
9860     // helps alias analysis out a lot, allows many others simplifications, and
9861     // exposes redundancy in the code.
9862     //
9863     // Note that we cannot do the transformation unless we know that the
9864     // introduced loads cannot trap!  Something like this is valid as long as
9865     // the condition is always false: load (select bool %C, int* null, int* %G),
9866     // but it would not be valid if we transformed it to load from null
9867     // unconditionally.
9868     //
9869     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9870       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9871       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9872           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9873         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9874                                      SI->getOperand(1)->getName()+".val"), LI);
9875         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9876                                      SI->getOperand(2)->getName()+".val"), LI);
9877         return new SelectInst(SI->getCondition(), V1, V2);
9878       }
9879
9880       // load (select (cond, null, P)) -> load P
9881       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9882         if (C->isNullValue()) {
9883           LI.setOperand(0, SI->getOperand(2));
9884           return &LI;
9885         }
9886
9887       // load (select (cond, P, null)) -> load P
9888       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9889         if (C->isNullValue()) {
9890           LI.setOperand(0, SI->getOperand(1));
9891           return &LI;
9892         }
9893     }
9894   }
9895   return 0;
9896 }
9897
9898 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9899 /// when possible.
9900 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9901   User *CI = cast<User>(SI.getOperand(1));
9902   Value *CastOp = CI->getOperand(0);
9903
9904   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9905   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9906     const Type *SrcPTy = SrcTy->getElementType();
9907
9908     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9909       // If the source is an array, the code below will not succeed.  Check to
9910       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9911       // constants.
9912       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9913         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9914           if (ASrcTy->getNumElements() != 0) {
9915             Value* Idxs[2];
9916             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9917             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9918             SrcTy = cast<PointerType>(CastOp->getType());
9919             SrcPTy = SrcTy->getElementType();
9920           }
9921
9922       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9923           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9924                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9925
9926         // Okay, we are casting from one integer or pointer type to another of
9927         // the same size.  Instead of casting the pointer before 
9928         // the store, cast the value to be stored.
9929         Value *NewCast;
9930         Value *SIOp0 = SI.getOperand(0);
9931         Instruction::CastOps opcode = Instruction::BitCast;
9932         const Type* CastSrcTy = SIOp0->getType();
9933         const Type* CastDstTy = SrcPTy;
9934         if (isa<PointerType>(CastDstTy)) {
9935           if (CastSrcTy->isInteger())
9936             opcode = Instruction::IntToPtr;
9937         } else if (isa<IntegerType>(CastDstTy)) {
9938           if (isa<PointerType>(SIOp0->getType()))
9939             opcode = Instruction::PtrToInt;
9940         }
9941         if (Constant *C = dyn_cast<Constant>(SIOp0))
9942           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9943         else
9944           NewCast = IC.InsertNewInstBefore(
9945             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9946             SI);
9947         return new StoreInst(NewCast, CastOp);
9948       }
9949     }
9950   }
9951   return 0;
9952 }
9953
9954 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9955   Value *Val = SI.getOperand(0);
9956   Value *Ptr = SI.getOperand(1);
9957
9958   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9959     EraseInstFromFunction(SI);
9960     ++NumCombined;
9961     return 0;
9962   }
9963   
9964   // If the RHS is an alloca with a single use, zapify the store, making the
9965   // alloca dead.
9966   if (Ptr->hasOneUse()) {
9967     if (isa<AllocaInst>(Ptr)) {
9968       EraseInstFromFunction(SI);
9969       ++NumCombined;
9970       return 0;
9971     }
9972     
9973     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9974       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9975           GEP->getOperand(0)->hasOneUse()) {
9976         EraseInstFromFunction(SI);
9977         ++NumCombined;
9978         return 0;
9979       }
9980   }
9981
9982   // Attempt to improve the alignment.
9983   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9984   if (KnownAlign > SI.getAlignment())
9985     SI.setAlignment(KnownAlign);
9986
9987   // Do really simple DSE, to catch cases where there are several consequtive
9988   // stores to the same location, separated by a few arithmetic operations. This
9989   // situation often occurs with bitfield accesses.
9990   BasicBlock::iterator BBI = &SI;
9991   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9992        --ScanInsts) {
9993     --BBI;
9994     
9995     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9996       // Prev store isn't volatile, and stores to the same location?
9997       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9998         ++NumDeadStore;
9999         ++BBI;
10000         EraseInstFromFunction(*PrevSI);
10001         continue;
10002       }
10003       break;
10004     }
10005     
10006     // If this is a load, we have to stop.  However, if the loaded value is from
10007     // the pointer we're loading and is producing the pointer we're storing,
10008     // then *this* store is dead (X = load P; store X -> P).
10009     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10010       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10011         EraseInstFromFunction(SI);
10012         ++NumCombined;
10013         return 0;
10014       }
10015       // Otherwise, this is a load from some other location.  Stores before it
10016       // may not be dead.
10017       break;
10018     }
10019     
10020     // Don't skip over loads or things that can modify memory.
10021     if (BBI->mayWriteToMemory())
10022       break;
10023   }
10024   
10025   
10026   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10027
10028   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10029   if (isa<ConstantPointerNull>(Ptr)) {
10030     if (!isa<UndefValue>(Val)) {
10031       SI.setOperand(0, UndefValue::get(Val->getType()));
10032       if (Instruction *U = dyn_cast<Instruction>(Val))
10033         AddToWorkList(U);  // Dropped a use.
10034       ++NumCombined;
10035     }
10036     return 0;  // Do not modify these!
10037   }
10038
10039   // store undef, Ptr -> noop
10040   if (isa<UndefValue>(Val)) {
10041     EraseInstFromFunction(SI);
10042     ++NumCombined;
10043     return 0;
10044   }
10045
10046   // If the pointer destination is a cast, see if we can fold the cast into the
10047   // source instead.
10048   if (isa<CastInst>(Ptr))
10049     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10050       return Res;
10051   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10052     if (CE->isCast())
10053       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10054         return Res;
10055
10056   
10057   // If this store is the last instruction in the basic block, and if the block
10058   // ends with an unconditional branch, try to move it to the successor block.
10059   BBI = &SI; ++BBI;
10060   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10061     if (BI->isUnconditional())
10062       if (SimplifyStoreAtEndOfBlock(SI))
10063         return 0;  // xform done!
10064   
10065   return 0;
10066 }
10067
10068 /// SimplifyStoreAtEndOfBlock - Turn things like:
10069 ///   if () { *P = v1; } else { *P = v2 }
10070 /// into a phi node with a store in the successor.
10071 ///
10072 /// Simplify things like:
10073 ///   *P = v1; if () { *P = v2; }
10074 /// into a phi node with a store in the successor.
10075 ///
10076 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10077   BasicBlock *StoreBB = SI.getParent();
10078   
10079   // Check to see if the successor block has exactly two incoming edges.  If
10080   // so, see if the other predecessor contains a store to the same location.
10081   // if so, insert a PHI node (if needed) and move the stores down.
10082   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10083   
10084   // Determine whether Dest has exactly two predecessors and, if so, compute
10085   // the other predecessor.
10086   pred_iterator PI = pred_begin(DestBB);
10087   BasicBlock *OtherBB = 0;
10088   if (*PI != StoreBB)
10089     OtherBB = *PI;
10090   ++PI;
10091   if (PI == pred_end(DestBB))
10092     return false;
10093   
10094   if (*PI != StoreBB) {
10095     if (OtherBB)
10096       return false;
10097     OtherBB = *PI;
10098   }
10099   if (++PI != pred_end(DestBB))
10100     return false;
10101   
10102   
10103   // Verify that the other block ends in a branch and is not otherwise empty.
10104   BasicBlock::iterator BBI = OtherBB->getTerminator();
10105   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10106   if (!OtherBr || BBI == OtherBB->begin())
10107     return false;
10108   
10109   // If the other block ends in an unconditional branch, check for the 'if then
10110   // else' case.  there is an instruction before the branch.
10111   StoreInst *OtherStore = 0;
10112   if (OtherBr->isUnconditional()) {
10113     // If this isn't a store, or isn't a store to the same location, bail out.
10114     --BBI;
10115     OtherStore = dyn_cast<StoreInst>(BBI);
10116     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10117       return false;
10118   } else {
10119     // Otherwise, the other block ended with a conditional branch. If one of the
10120     // destinations is StoreBB, then we have the if/then case.
10121     if (OtherBr->getSuccessor(0) != StoreBB && 
10122         OtherBr->getSuccessor(1) != StoreBB)
10123       return false;
10124     
10125     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10126     // if/then triangle.  See if there is a store to the same ptr as SI that
10127     // lives in OtherBB.
10128     for (;; --BBI) {
10129       // Check to see if we find the matching store.
10130       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10131         if (OtherStore->getOperand(1) != SI.getOperand(1))
10132           return false;
10133         break;
10134       }
10135       // If we find something that may be using the stored value, or if we run
10136       // out of instructions, we can't do the xform.
10137       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10138           BBI == OtherBB->begin())
10139         return false;
10140     }
10141     
10142     // In order to eliminate the store in OtherBr, we have to
10143     // make sure nothing reads the stored value in StoreBB.
10144     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10145       // FIXME: This should really be AA driven.
10146       if (isa<LoadInst>(I) || I->mayWriteToMemory())
10147         return false;
10148     }
10149   }
10150   
10151   // Insert a PHI node now if we need it.
10152   Value *MergedVal = OtherStore->getOperand(0);
10153   if (MergedVal != SI.getOperand(0)) {
10154     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10155     PN->reserveOperandSpace(2);
10156     PN->addIncoming(SI.getOperand(0), SI.getParent());
10157     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10158     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10159   }
10160   
10161   // Advance to a place where it is safe to insert the new store and
10162   // insert it.
10163   BBI = DestBB->begin();
10164   while (isa<PHINode>(BBI)) ++BBI;
10165   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10166                                     OtherStore->isVolatile()), *BBI);
10167   
10168   // Nuke the old stores.
10169   EraseInstFromFunction(SI);
10170   EraseInstFromFunction(*OtherStore);
10171   ++NumCombined;
10172   return true;
10173 }
10174
10175
10176 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10177   // Change br (not X), label True, label False to: br X, label False, True
10178   Value *X = 0;
10179   BasicBlock *TrueDest;
10180   BasicBlock *FalseDest;
10181   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10182       !isa<Constant>(X)) {
10183     // Swap Destinations and condition...
10184     BI.setCondition(X);
10185     BI.setSuccessor(0, FalseDest);
10186     BI.setSuccessor(1, TrueDest);
10187     return &BI;
10188   }
10189
10190   // Cannonicalize fcmp_one -> fcmp_oeq
10191   FCmpInst::Predicate FPred; Value *Y;
10192   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10193                              TrueDest, FalseDest)))
10194     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10195          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10196       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10197       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10198       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10199       NewSCC->takeName(I);
10200       // Swap Destinations and condition...
10201       BI.setCondition(NewSCC);
10202       BI.setSuccessor(0, FalseDest);
10203       BI.setSuccessor(1, TrueDest);
10204       RemoveFromWorkList(I);
10205       I->eraseFromParent();
10206       AddToWorkList(NewSCC);
10207       return &BI;
10208     }
10209
10210   // Cannonicalize icmp_ne -> icmp_eq
10211   ICmpInst::Predicate IPred;
10212   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10213                       TrueDest, FalseDest)))
10214     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10215          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10216          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10217       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10218       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10219       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10220       NewSCC->takeName(I);
10221       // Swap Destinations and condition...
10222       BI.setCondition(NewSCC);
10223       BI.setSuccessor(0, FalseDest);
10224       BI.setSuccessor(1, TrueDest);
10225       RemoveFromWorkList(I);
10226       I->eraseFromParent();;
10227       AddToWorkList(NewSCC);
10228       return &BI;
10229     }
10230
10231   return 0;
10232 }
10233
10234 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10235   Value *Cond = SI.getCondition();
10236   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10237     if (I->getOpcode() == Instruction::Add)
10238       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10239         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10240         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10241           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10242                                                 AddRHS));
10243         SI.setOperand(0, I->getOperand(0));
10244         AddToWorkList(I);
10245         return &SI;
10246       }
10247   }
10248   return 0;
10249 }
10250
10251 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10252 /// is to leave as a vector operation.
10253 static bool CheapToScalarize(Value *V, bool isConstant) {
10254   if (isa<ConstantAggregateZero>(V)) 
10255     return true;
10256   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10257     if (isConstant) return true;
10258     // If all elts are the same, we can extract.
10259     Constant *Op0 = C->getOperand(0);
10260     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10261       if (C->getOperand(i) != Op0)
10262         return false;
10263     return true;
10264   }
10265   Instruction *I = dyn_cast<Instruction>(V);
10266   if (!I) return false;
10267   
10268   // Insert element gets simplified to the inserted element or is deleted if
10269   // this is constant idx extract element and its a constant idx insertelt.
10270   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10271       isa<ConstantInt>(I->getOperand(2)))
10272     return true;
10273   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10274     return true;
10275   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10276     if (BO->hasOneUse() &&
10277         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10278          CheapToScalarize(BO->getOperand(1), isConstant)))
10279       return true;
10280   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10281     if (CI->hasOneUse() &&
10282         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10283          CheapToScalarize(CI->getOperand(1), isConstant)))
10284       return true;
10285   
10286   return false;
10287 }
10288
10289 /// Read and decode a shufflevector mask.
10290 ///
10291 /// It turns undef elements into values that are larger than the number of
10292 /// elements in the input.
10293 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10294   unsigned NElts = SVI->getType()->getNumElements();
10295   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10296     return std::vector<unsigned>(NElts, 0);
10297   if (isa<UndefValue>(SVI->getOperand(2)))
10298     return std::vector<unsigned>(NElts, 2*NElts);
10299
10300   std::vector<unsigned> Result;
10301   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10302   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10303     if (isa<UndefValue>(CP->getOperand(i)))
10304       Result.push_back(NElts*2);  // undef -> 8
10305     else
10306       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10307   return Result;
10308 }
10309
10310 /// FindScalarElement - Given a vector and an element number, see if the scalar
10311 /// value is already around as a register, for example if it were inserted then
10312 /// extracted from the vector.
10313 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10314   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10315   const VectorType *PTy = cast<VectorType>(V->getType());
10316   unsigned Width = PTy->getNumElements();
10317   if (EltNo >= Width)  // Out of range access.
10318     return UndefValue::get(PTy->getElementType());
10319   
10320   if (isa<UndefValue>(V))
10321     return UndefValue::get(PTy->getElementType());
10322   else if (isa<ConstantAggregateZero>(V))
10323     return Constant::getNullValue(PTy->getElementType());
10324   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10325     return CP->getOperand(EltNo);
10326   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10327     // If this is an insert to a variable element, we don't know what it is.
10328     if (!isa<ConstantInt>(III->getOperand(2))) 
10329       return 0;
10330     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10331     
10332     // If this is an insert to the element we are looking for, return the
10333     // inserted value.
10334     if (EltNo == IIElt) 
10335       return III->getOperand(1);
10336     
10337     // Otherwise, the insertelement doesn't modify the value, recurse on its
10338     // vector input.
10339     return FindScalarElement(III->getOperand(0), EltNo);
10340   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10341     unsigned InEl = getShuffleMask(SVI)[EltNo];
10342     if (InEl < Width)
10343       return FindScalarElement(SVI->getOperand(0), InEl);
10344     else if (InEl < Width*2)
10345       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10346     else
10347       return UndefValue::get(PTy->getElementType());
10348   }
10349   
10350   // Otherwise, we don't know.
10351   return 0;
10352 }
10353
10354 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10355
10356   // If vector val is undef, replace extract with scalar undef.
10357   if (isa<UndefValue>(EI.getOperand(0)))
10358     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10359
10360   // If vector val is constant 0, replace extract with scalar 0.
10361   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10362     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10363   
10364   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10365     // If vector val is constant with uniform operands, replace EI
10366     // with that operand
10367     Constant *op0 = C->getOperand(0);
10368     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10369       if (C->getOperand(i) != op0) {
10370         op0 = 0; 
10371         break;
10372       }
10373     if (op0)
10374       return ReplaceInstUsesWith(EI, op0);
10375   }
10376   
10377   // If extracting a specified index from the vector, see if we can recursively
10378   // find a previously computed scalar that was inserted into the vector.
10379   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10380     unsigned IndexVal = IdxC->getZExtValue();
10381     unsigned VectorWidth = 
10382       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10383       
10384     // If this is extracting an invalid index, turn this into undef, to avoid
10385     // crashing the code below.
10386     if (IndexVal >= VectorWidth)
10387       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10388     
10389     // This instruction only demands the single element from the input vector.
10390     // If the input vector has a single use, simplify it based on this use
10391     // property.
10392     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10393       uint64_t UndefElts;
10394       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10395                                                 1 << IndexVal,
10396                                                 UndefElts)) {
10397         EI.setOperand(0, V);
10398         return &EI;
10399       }
10400     }
10401     
10402     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10403       return ReplaceInstUsesWith(EI, Elt);
10404     
10405     // If the this extractelement is directly using a bitcast from a vector of
10406     // the same number of elements, see if we can find the source element from
10407     // it.  In this case, we will end up needing to bitcast the scalars.
10408     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10409       if (const VectorType *VT = 
10410               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10411         if (VT->getNumElements() == VectorWidth)
10412           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10413             return new BitCastInst(Elt, EI.getType());
10414     }
10415   }
10416   
10417   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10418     if (I->hasOneUse()) {
10419       // Push extractelement into predecessor operation if legal and
10420       // profitable to do so
10421       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10422         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10423         if (CheapToScalarize(BO, isConstantElt)) {
10424           ExtractElementInst *newEI0 = 
10425             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10426                                    EI.getName()+".lhs");
10427           ExtractElementInst *newEI1 =
10428             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10429                                    EI.getName()+".rhs");
10430           InsertNewInstBefore(newEI0, EI);
10431           InsertNewInstBefore(newEI1, EI);
10432           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10433         }
10434       } else if (isa<LoadInst>(I)) {
10435         unsigned AS = 
10436           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10437         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10438                                          PointerType::get(EI.getType(), AS),EI);
10439         GetElementPtrInst *GEP = 
10440           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10441         InsertNewInstBefore(GEP, EI);
10442         return new LoadInst(GEP);
10443       }
10444     }
10445     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10446       // Extracting the inserted element?
10447       if (IE->getOperand(2) == EI.getOperand(1))
10448         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10449       // If the inserted and extracted elements are constants, they must not
10450       // be the same value, extract from the pre-inserted value instead.
10451       if (isa<Constant>(IE->getOperand(2)) &&
10452           isa<Constant>(EI.getOperand(1))) {
10453         AddUsesToWorkList(EI);
10454         EI.setOperand(0, IE->getOperand(0));
10455         return &EI;
10456       }
10457     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10458       // If this is extracting an element from a shufflevector, figure out where
10459       // it came from and extract from the appropriate input element instead.
10460       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10461         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10462         Value *Src;
10463         if (SrcIdx < SVI->getType()->getNumElements())
10464           Src = SVI->getOperand(0);
10465         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10466           SrcIdx -= SVI->getType()->getNumElements();
10467           Src = SVI->getOperand(1);
10468         } else {
10469           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10470         }
10471         return new ExtractElementInst(Src, SrcIdx);
10472       }
10473     }
10474   }
10475   return 0;
10476 }
10477
10478 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10479 /// elements from either LHS or RHS, return the shuffle mask and true. 
10480 /// Otherwise, return false.
10481 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10482                                          std::vector<Constant*> &Mask) {
10483   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10484          "Invalid CollectSingleShuffleElements");
10485   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10486
10487   if (isa<UndefValue>(V)) {
10488     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10489     return true;
10490   } else if (V == LHS) {
10491     for (unsigned i = 0; i != NumElts; ++i)
10492       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10493     return true;
10494   } else if (V == RHS) {
10495     for (unsigned i = 0; i != NumElts; ++i)
10496       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10497     return true;
10498   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10499     // If this is an insert of an extract from some other vector, include it.
10500     Value *VecOp    = IEI->getOperand(0);
10501     Value *ScalarOp = IEI->getOperand(1);
10502     Value *IdxOp    = IEI->getOperand(2);
10503     
10504     if (!isa<ConstantInt>(IdxOp))
10505       return false;
10506     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10507     
10508     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10509       // Okay, we can handle this if the vector we are insertinting into is
10510       // transitively ok.
10511       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10512         // If so, update the mask to reflect the inserted undef.
10513         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10514         return true;
10515       }      
10516     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10517       if (isa<ConstantInt>(EI->getOperand(1)) &&
10518           EI->getOperand(0)->getType() == V->getType()) {
10519         unsigned ExtractedIdx =
10520           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10521         
10522         // This must be extracting from either LHS or RHS.
10523         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10524           // Okay, we can handle this if the vector we are insertinting into is
10525           // transitively ok.
10526           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10527             // If so, update the mask to reflect the inserted value.
10528             if (EI->getOperand(0) == LHS) {
10529               Mask[InsertedIdx & (NumElts-1)] = 
10530                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10531             } else {
10532               assert(EI->getOperand(0) == RHS);
10533               Mask[InsertedIdx & (NumElts-1)] = 
10534                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10535               
10536             }
10537             return true;
10538           }
10539         }
10540       }
10541     }
10542   }
10543   // TODO: Handle shufflevector here!
10544   
10545   return false;
10546 }
10547
10548 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10549 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10550 /// that computes V and the LHS value of the shuffle.
10551 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10552                                      Value *&RHS) {
10553   assert(isa<VectorType>(V->getType()) && 
10554          (RHS == 0 || V->getType() == RHS->getType()) &&
10555          "Invalid shuffle!");
10556   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10557
10558   if (isa<UndefValue>(V)) {
10559     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10560     return V;
10561   } else if (isa<ConstantAggregateZero>(V)) {
10562     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10563     return V;
10564   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10565     // If this is an insert of an extract from some other vector, include it.
10566     Value *VecOp    = IEI->getOperand(0);
10567     Value *ScalarOp = IEI->getOperand(1);
10568     Value *IdxOp    = IEI->getOperand(2);
10569     
10570     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10571       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10572           EI->getOperand(0)->getType() == V->getType()) {
10573         unsigned ExtractedIdx =
10574           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10575         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10576         
10577         // Either the extracted from or inserted into vector must be RHSVec,
10578         // otherwise we'd end up with a shuffle of three inputs.
10579         if (EI->getOperand(0) == RHS || RHS == 0) {
10580           RHS = EI->getOperand(0);
10581           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10582           Mask[InsertedIdx & (NumElts-1)] = 
10583             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10584           return V;
10585         }
10586         
10587         if (VecOp == RHS) {
10588           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10589           // Everything but the extracted element is replaced with the RHS.
10590           for (unsigned i = 0; i != NumElts; ++i) {
10591             if (i != InsertedIdx)
10592               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10593           }
10594           return V;
10595         }
10596         
10597         // If this insertelement is a chain that comes from exactly these two
10598         // vectors, return the vector and the effective shuffle.
10599         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10600           return EI->getOperand(0);
10601         
10602       }
10603     }
10604   }
10605   // TODO: Handle shufflevector here!
10606   
10607   // Otherwise, can't do anything fancy.  Return an identity vector.
10608   for (unsigned i = 0; i != NumElts; ++i)
10609     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10610   return V;
10611 }
10612
10613 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10614   Value *VecOp    = IE.getOperand(0);
10615   Value *ScalarOp = IE.getOperand(1);
10616   Value *IdxOp    = IE.getOperand(2);
10617   
10618   // Inserting an undef or into an undefined place, remove this.
10619   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10620     ReplaceInstUsesWith(IE, VecOp);
10621   
10622   // If the inserted element was extracted from some other vector, and if the 
10623   // indexes are constant, try to turn this into a shufflevector operation.
10624   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10625     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10626         EI->getOperand(0)->getType() == IE.getType()) {
10627       unsigned NumVectorElts = IE.getType()->getNumElements();
10628       unsigned ExtractedIdx =
10629         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10630       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10631       
10632       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10633         return ReplaceInstUsesWith(IE, VecOp);
10634       
10635       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10636         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10637       
10638       // If we are extracting a value from a vector, then inserting it right
10639       // back into the same place, just use the input vector.
10640       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10641         return ReplaceInstUsesWith(IE, VecOp);      
10642       
10643       // We could theoretically do this for ANY input.  However, doing so could
10644       // turn chains of insertelement instructions into a chain of shufflevector
10645       // instructions, and right now we do not merge shufflevectors.  As such,
10646       // only do this in a situation where it is clear that there is benefit.
10647       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10648         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10649         // the values of VecOp, except then one read from EIOp0.
10650         // Build a new shuffle mask.
10651         std::vector<Constant*> Mask;
10652         if (isa<UndefValue>(VecOp))
10653           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10654         else {
10655           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10656           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10657                                                        NumVectorElts));
10658         } 
10659         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10660         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10661                                      ConstantVector::get(Mask));
10662       }
10663       
10664       // If this insertelement isn't used by some other insertelement, turn it
10665       // (and any insertelements it points to), into one big shuffle.
10666       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10667         std::vector<Constant*> Mask;
10668         Value *RHS = 0;
10669         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10670         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10671         // We now have a shuffle of LHS, RHS, Mask.
10672         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10673       }
10674     }
10675   }
10676
10677   return 0;
10678 }
10679
10680
10681 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10682   Value *LHS = SVI.getOperand(0);
10683   Value *RHS = SVI.getOperand(1);
10684   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10685
10686   bool MadeChange = false;
10687   
10688   // Undefined shuffle mask -> undefined value.
10689   if (isa<UndefValue>(SVI.getOperand(2)))
10690     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10691   
10692   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10693   // the undef, change them to undefs.
10694   if (isa<UndefValue>(SVI.getOperand(1))) {
10695     // Scan to see if there are any references to the RHS.  If so, replace them
10696     // with undef element refs and set MadeChange to true.
10697     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10698       if (Mask[i] >= e && Mask[i] != 2*e) {
10699         Mask[i] = 2*e;
10700         MadeChange = true;
10701       }
10702     }
10703     
10704     if (MadeChange) {
10705       // Remap any references to RHS to use LHS.
10706       std::vector<Constant*> Elts;
10707       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10708         if (Mask[i] == 2*e)
10709           Elts.push_back(UndefValue::get(Type::Int32Ty));
10710         else
10711           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10712       }
10713       SVI.setOperand(2, ConstantVector::get(Elts));
10714     }
10715   }
10716   
10717   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10718   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10719   if (LHS == RHS || isa<UndefValue>(LHS)) {
10720     if (isa<UndefValue>(LHS) && LHS == RHS) {
10721       // shuffle(undef,undef,mask) -> undef.
10722       return ReplaceInstUsesWith(SVI, LHS);
10723     }
10724     
10725     // Remap any references to RHS to use LHS.
10726     std::vector<Constant*> Elts;
10727     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10728       if (Mask[i] >= 2*e)
10729         Elts.push_back(UndefValue::get(Type::Int32Ty));
10730       else {
10731         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10732             (Mask[i] <  e && isa<UndefValue>(LHS)))
10733           Mask[i] = 2*e;     // Turn into undef.
10734         else
10735           Mask[i] &= (e-1);  // Force to LHS.
10736         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10737       }
10738     }
10739     SVI.setOperand(0, SVI.getOperand(1));
10740     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10741     SVI.setOperand(2, ConstantVector::get(Elts));
10742     LHS = SVI.getOperand(0);
10743     RHS = SVI.getOperand(1);
10744     MadeChange = true;
10745   }
10746   
10747   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10748   bool isLHSID = true, isRHSID = true;
10749     
10750   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10751     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10752     // Is this an identity shuffle of the LHS value?
10753     isLHSID &= (Mask[i] == i);
10754       
10755     // Is this an identity shuffle of the RHS value?
10756     isRHSID &= (Mask[i]-e == i);
10757   }
10758
10759   // Eliminate identity shuffles.
10760   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10761   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10762   
10763   // If the LHS is a shufflevector itself, see if we can combine it with this
10764   // one without producing an unusual shuffle.  Here we are really conservative:
10765   // we are absolutely afraid of producing a shuffle mask not in the input
10766   // program, because the code gen may not be smart enough to turn a merged
10767   // shuffle into two specific shuffles: it may produce worse code.  As such,
10768   // we only merge two shuffles if the result is one of the two input shuffle
10769   // masks.  In this case, merging the shuffles just removes one instruction,
10770   // which we know is safe.  This is good for things like turning:
10771   // (splat(splat)) -> splat.
10772   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10773     if (isa<UndefValue>(RHS)) {
10774       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10775
10776       std::vector<unsigned> NewMask;
10777       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10778         if (Mask[i] >= 2*e)
10779           NewMask.push_back(2*e);
10780         else
10781           NewMask.push_back(LHSMask[Mask[i]]);
10782       
10783       // If the result mask is equal to the src shuffle or this shuffle mask, do
10784       // the replacement.
10785       if (NewMask == LHSMask || NewMask == Mask) {
10786         std::vector<Constant*> Elts;
10787         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10788           if (NewMask[i] >= e*2) {
10789             Elts.push_back(UndefValue::get(Type::Int32Ty));
10790           } else {
10791             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10792           }
10793         }
10794         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10795                                      LHSSVI->getOperand(1),
10796                                      ConstantVector::get(Elts));
10797       }
10798     }
10799   }
10800
10801   return MadeChange ? &SVI : 0;
10802 }
10803
10804
10805
10806
10807 /// TryToSinkInstruction - Try to move the specified instruction from its
10808 /// current block into the beginning of DestBlock, which can only happen if it's
10809 /// safe to move the instruction past all of the instructions between it and the
10810 /// end of its block.
10811 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10812   assert(I->hasOneUse() && "Invariants didn't hold!");
10813
10814   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10815   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10816
10817   // Do not sink alloca instructions out of the entry block.
10818   if (isa<AllocaInst>(I) && I->getParent() ==
10819         &DestBlock->getParent()->getEntryBlock())
10820     return false;
10821
10822   // We can only sink load instructions if there is nothing between the load and
10823   // the end of block that could change the value.
10824   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10825     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10826          Scan != E; ++Scan)
10827       if (Scan->mayWriteToMemory())
10828         return false;
10829   }
10830
10831   BasicBlock::iterator InsertPos = DestBlock->begin();
10832   while (isa<PHINode>(InsertPos)) ++InsertPos;
10833
10834   I->moveBefore(InsertPos);
10835   ++NumSunkInst;
10836   return true;
10837 }
10838
10839
10840 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10841 /// all reachable code to the worklist.
10842 ///
10843 /// This has a couple of tricks to make the code faster and more powerful.  In
10844 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10845 /// them to the worklist (this significantly speeds up instcombine on code where
10846 /// many instructions are dead or constant).  Additionally, if we find a branch
10847 /// whose condition is a known constant, we only visit the reachable successors.
10848 ///
10849 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10850                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10851                                        InstCombiner &IC,
10852                                        const TargetData *TD) {
10853   std::vector<BasicBlock*> Worklist;
10854   Worklist.push_back(BB);
10855
10856   while (!Worklist.empty()) {
10857     BB = Worklist.back();
10858     Worklist.pop_back();
10859     
10860     // We have now visited this block!  If we've already been here, ignore it.
10861     if (!Visited.insert(BB)) continue;
10862     
10863     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10864       Instruction *Inst = BBI++;
10865       
10866       // DCE instruction if trivially dead.
10867       if (isInstructionTriviallyDead(Inst)) {
10868         ++NumDeadInst;
10869         DOUT << "IC: DCE: " << *Inst;
10870         Inst->eraseFromParent();
10871         continue;
10872       }
10873       
10874       // ConstantProp instruction if trivially constant.
10875       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10876         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10877         Inst->replaceAllUsesWith(C);
10878         ++NumConstProp;
10879         Inst->eraseFromParent();
10880         continue;
10881       }
10882      
10883       IC.AddToWorkList(Inst);
10884     }
10885
10886     // Recursively visit successors.  If this is a branch or switch on a
10887     // constant, only visit the reachable successor.
10888     if (BB->getUnwindDest())
10889       Worklist.push_back(BB->getUnwindDest());
10890     TerminatorInst *TI = BB->getTerminator();
10891     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10892       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10893         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10894         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10895         if (ReachableBB != BB->getUnwindDest())
10896           Worklist.push_back(ReachableBB);
10897         continue;
10898       }
10899     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10900       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10901         // See if this is an explicit destination.
10902         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10903           if (SI->getCaseValue(i) == Cond) {
10904             BasicBlock *ReachableBB = SI->getSuccessor(i);
10905             if (ReachableBB != BB->getUnwindDest())
10906               Worklist.push_back(ReachableBB);
10907             continue;
10908           }
10909         
10910         // Otherwise it is the default destination.
10911         Worklist.push_back(SI->getSuccessor(0));
10912         continue;
10913       }
10914     }
10915     
10916     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10917       Worklist.push_back(TI->getSuccessor(i));
10918   }
10919 }
10920
10921 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10922   bool Changed = false;
10923   TD = &getAnalysis<TargetData>();
10924   
10925   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10926              << F.getNameStr() << "\n");
10927
10928   {
10929     // Do a depth-first traversal of the function, populate the worklist with
10930     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10931     // track of which blocks we visit.
10932     SmallPtrSet<BasicBlock*, 64> Visited;
10933     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10934
10935     // Do a quick scan over the function.  If we find any blocks that are
10936     // unreachable, remove any instructions inside of them.  This prevents
10937     // the instcombine code from having to deal with some bad special cases.
10938     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10939       if (!Visited.count(BB)) {
10940         Instruction *Term = BB->getTerminator();
10941         while (Term != BB->begin()) {   // Remove instrs bottom-up
10942           BasicBlock::iterator I = Term; --I;
10943
10944           DOUT << "IC: DCE: " << *I;
10945           ++NumDeadInst;
10946
10947           if (!I->use_empty())
10948             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10949           I->eraseFromParent();
10950         }
10951       }
10952   }
10953
10954   while (!Worklist.empty()) {
10955     Instruction *I = RemoveOneFromWorkList();
10956     if (I == 0) continue;  // skip null values.
10957
10958     // Check to see if we can DCE the instruction.
10959     if (isInstructionTriviallyDead(I)) {
10960       // Add operands to the worklist.
10961       if (I->getNumOperands() < 4)
10962         AddUsesToWorkList(*I);
10963       ++NumDeadInst;
10964
10965       DOUT << "IC: DCE: " << *I;
10966
10967       I->eraseFromParent();
10968       RemoveFromWorkList(I);
10969       continue;
10970     }
10971
10972     // Instruction isn't dead, see if we can constant propagate it.
10973     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10974       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10975
10976       // Add operands to the worklist.
10977       AddUsesToWorkList(*I);
10978       ReplaceInstUsesWith(*I, C);
10979
10980       ++NumConstProp;
10981       I->eraseFromParent();
10982       RemoveFromWorkList(I);
10983       continue;
10984     }
10985
10986     // See if we can trivially sink this instruction to a successor basic block.
10987     if (I->hasOneUse()) {
10988       BasicBlock *BB = I->getParent();
10989       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10990       if (UserParent != BB) {
10991         bool UserIsSuccessor = false;
10992         // See if the user is one of our successors.
10993         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10994           if (*SI == UserParent) {
10995             UserIsSuccessor = true;
10996             break;
10997           }
10998
10999         // If the user is one of our immediate successors, and if that successor
11000         // only has us as a predecessors (we'd have to split the critical edge
11001         // otherwise), we can keep going.
11002         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11003             next(pred_begin(UserParent)) == pred_end(UserParent))
11004           // Okay, the CFG is simple enough, try to sink this instruction.
11005           Changed |= TryToSinkInstruction(I, UserParent);
11006       }
11007     }
11008
11009     // Now that we have an instruction, try combining it to simplify it...
11010 #ifndef NDEBUG
11011     std::string OrigI;
11012 #endif
11013     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11014     if (Instruction *Result = visit(*I)) {
11015       ++NumCombined;
11016       // Should we replace the old instruction with a new one?
11017       if (Result != I) {
11018         DOUT << "IC: Old = " << *I
11019              << "    New = " << *Result;
11020
11021         // Everything uses the new instruction now.
11022         I->replaceAllUsesWith(Result);
11023
11024         // Push the new instruction and any users onto the worklist.
11025         AddToWorkList(Result);
11026         AddUsersToWorkList(*Result);
11027
11028         // Move the name to the new instruction first.
11029         Result->takeName(I);
11030
11031         // Insert the new instruction into the basic block...
11032         BasicBlock *InstParent = I->getParent();
11033         BasicBlock::iterator InsertPos = I;
11034
11035         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11036           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11037             ++InsertPos;
11038
11039         InstParent->getInstList().insert(InsertPos, Result);
11040
11041         // Make sure that we reprocess all operands now that we reduced their
11042         // use counts.
11043         AddUsesToWorkList(*I);
11044
11045         // Instructions can end up on the worklist more than once.  Make sure
11046         // we do not process an instruction that has been deleted.
11047         RemoveFromWorkList(I);
11048
11049         // Erase the old instruction.
11050         InstParent->getInstList().erase(I);
11051       } else {
11052 #ifndef NDEBUG
11053         DOUT << "IC: Mod = " << OrigI
11054              << "    New = " << *I;
11055 #endif
11056
11057         // If the instruction was modified, it's possible that it is now dead.
11058         // if so, remove it.
11059         if (isInstructionTriviallyDead(I)) {
11060           // Make sure we process all operands now that we are reducing their
11061           // use counts.
11062           AddUsesToWorkList(*I);
11063
11064           // Instructions may end up in the worklist more than once.  Erase all
11065           // occurrences of this instruction.
11066           RemoveFromWorkList(I);
11067           I->eraseFromParent();
11068         } else {
11069           AddToWorkList(I);
11070           AddUsersToWorkList(*I);
11071         }
11072       }
11073       Changed = true;
11074     }
11075   }
11076
11077   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11078     
11079   // Do an explicit clear, this shrinks the map if needed.
11080   WorklistMap.clear();
11081   return Changed;
11082 }
11083
11084
11085 bool InstCombiner::runOnFunction(Function &F) {
11086   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11087   
11088   bool EverMadeChange = false;
11089
11090   // Iterate while there is work to do.
11091   unsigned Iteration = 0;
11092   while (DoOneIteration(F, Iteration++)) 
11093     EverMadeChange = true;
11094   return EverMadeChange;
11095 }
11096
11097 FunctionPass *llvm::createInstructionCombiningPass() {
11098   return new InstCombiner();
11099 }
11100