simplify some code by adding a InsertBitCastBefore method,
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/ParameterAttributes.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include <algorithm>
60 #include <sstream>
61 using namespace llvm;
62 using namespace llvm::PatternMatch;
63
64 STATISTIC(NumCombined , "Number of insts combined");
65 STATISTIC(NumConstProp, "Number of constant folds");
66 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68 STATISTIC(NumSunkInst , "Number of instructions sunk");
69
70 namespace {
71   class VISIBILITY_HIDDEN InstCombiner
72     : public FunctionPass,
73       public InstVisitor<InstCombiner, Instruction*> {
74     // Worklist of all of the instructions that need to be simplified.
75     std::vector<Instruction*> Worklist;
76     DenseMap<Instruction*, unsigned> WorklistMap;
77     TargetData *TD;
78     bool MustPreserveLCSSA;
79   public:
80     static char ID; // Pass identification, replacement for typeid
81     InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
83     /// AddToWorkList - Add the specified instruction to the worklist if it
84     /// isn't already in it.
85     void AddToWorkList(Instruction *I) {
86       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87         Worklist.push_back(I);
88     }
89     
90     // RemoveFromWorkList - remove I from the worklist if it exists.
91     void RemoveFromWorkList(Instruction *I) {
92       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93       if (It == WorklistMap.end()) return; // Not in worklist.
94       
95       // Don't bother moving everything down, just null out the slot.
96       Worklist[It->second] = 0;
97       
98       WorklistMap.erase(It);
99     }
100     
101     Instruction *RemoveOneFromWorkList() {
102       Instruction *I = Worklist.back();
103       Worklist.pop_back();
104       WorklistMap.erase(I);
105       return I;
106     }
107
108     
109     /// AddUsersToWorkList - When an instruction is simplified, add all users of
110     /// the instruction to the work lists because they might get more simplified
111     /// now.
112     ///
113     void AddUsersToWorkList(Value &I) {
114       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
115            UI != UE; ++UI)
116         AddToWorkList(cast<Instruction>(*UI));
117     }
118
119     /// AddUsesToWorkList - When an instruction is simplified, add operands to
120     /// the work lists because they might get more simplified now.
121     ///
122     void AddUsesToWorkList(Instruction &I) {
123       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
125           AddToWorkList(Op);
126     }
127     
128     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129     /// dead.  Add all of its operands to the worklist, turning them into
130     /// undef's to reduce the number of uses of those instructions.
131     ///
132     /// Return the specified operand before it is turned into an undef.
133     ///
134     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135       Value *R = I.getOperand(op);
136       
137       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
139           AddToWorkList(Op);
140           // Set the operand to undef to drop the use.
141           I.setOperand(i, UndefValue::get(Op->getType()));
142         }
143       
144       return R;
145     }
146
147   public:
148     virtual bool runOnFunction(Function &F);
149     
150     bool DoOneIteration(Function &F, unsigned ItNum);
151
152     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153       AU.addRequired<TargetData>();
154       AU.addPreservedID(LCSSAID);
155       AU.setPreservesCFG();
156     }
157
158     TargetData &getTargetData() const { return *TD; }
159
160     // Visitation implementation - Implement instruction combining for different
161     // instruction types.  The semantics are as follows:
162     // Return Value:
163     //    null        - No change was made
164     //     I          - Change was made, I is still valid, I may be dead though
165     //   otherwise    - Change was made, replace I with returned instruction
166     //
167     Instruction *visitAdd(BinaryOperator &I);
168     Instruction *visitSub(BinaryOperator &I);
169     Instruction *visitMul(BinaryOperator &I);
170     Instruction *visitURem(BinaryOperator &I);
171     Instruction *visitSRem(BinaryOperator &I);
172     Instruction *visitFRem(BinaryOperator &I);
173     Instruction *commonRemTransforms(BinaryOperator &I);
174     Instruction *commonIRemTransforms(BinaryOperator &I);
175     Instruction *commonDivTransforms(BinaryOperator &I);
176     Instruction *commonIDivTransforms(BinaryOperator &I);
177     Instruction *visitUDiv(BinaryOperator &I);
178     Instruction *visitSDiv(BinaryOperator &I);
179     Instruction *visitFDiv(BinaryOperator &I);
180     Instruction *visitAnd(BinaryOperator &I);
181     Instruction *visitOr (BinaryOperator &I);
182     Instruction *visitXor(BinaryOperator &I);
183     Instruction *visitShl(BinaryOperator &I);
184     Instruction *visitAShr(BinaryOperator &I);
185     Instruction *visitLShr(BinaryOperator &I);
186     Instruction *commonShiftTransforms(BinaryOperator &I);
187     Instruction *visitFCmpInst(FCmpInst &I);
188     Instruction *visitICmpInst(ICmpInst &I);
189     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
190     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191                                                 Instruction *LHS,
192                                                 ConstantInt *RHS);
193     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194                                 ConstantInt *DivRHS);
195
196     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197                              ICmpInst::Predicate Cond, Instruction &I);
198     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
199                                      BinaryOperator &I);
200     Instruction *commonCastTransforms(CastInst &CI);
201     Instruction *commonIntCastTransforms(CastInst &CI);
202     Instruction *commonPointerCastTransforms(CastInst &CI);
203     Instruction *visitTrunc(TruncInst &CI);
204     Instruction *visitZExt(ZExtInst &CI);
205     Instruction *visitSExt(SExtInst &CI);
206     Instruction *visitFPTrunc(CastInst &CI);
207     Instruction *visitFPExt(CastInst &CI);
208     Instruction *visitFPToUI(CastInst &CI);
209     Instruction *visitFPToSI(CastInst &CI);
210     Instruction *visitUIToFP(CastInst &CI);
211     Instruction *visitSIToFP(CastInst &CI);
212     Instruction *visitPtrToInt(CastInst &CI);
213     Instruction *visitIntToPtr(IntToPtrInst &CI);
214     Instruction *visitBitCast(BitCastInst &CI);
215     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216                                 Instruction *FI);
217     Instruction *visitSelectInst(SelectInst &CI);
218     Instruction *visitCallInst(CallInst &CI);
219     Instruction *visitInvokeInst(InvokeInst &II);
220     Instruction *visitPHINode(PHINode &PN);
221     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
222     Instruction *visitAllocationInst(AllocationInst &AI);
223     Instruction *visitFreeInst(FreeInst &FI);
224     Instruction *visitLoadInst(LoadInst &LI);
225     Instruction *visitStoreInst(StoreInst &SI);
226     Instruction *visitBranchInst(BranchInst &BI);
227     Instruction *visitSwitchInst(SwitchInst &SI);
228     Instruction *visitInsertElementInst(InsertElementInst &IE);
229     Instruction *visitExtractElementInst(ExtractElementInst &EI);
230     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
231
232     // visitInstruction - Specify what to return for unhandled instructions...
233     Instruction *visitInstruction(Instruction &I) { return 0; }
234
235   private:
236     Instruction *visitCallSite(CallSite CS);
237     bool transformConstExprCastCall(CallSite CS);
238     Instruction *transformCallThroughTrampoline(CallSite CS);
239
240   public:
241     // InsertNewInstBefore - insert an instruction New before instruction Old
242     // in the program.  Add the new instruction to the worklist.
243     //
244     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
245       assert(New && New->getParent() == 0 &&
246              "New instruction already inserted into a basic block!");
247       BasicBlock *BB = Old.getParent();
248       BB->getInstList().insert(&Old, New);  // Insert inst
249       AddToWorkList(New);
250       return New;
251     }
252
253     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254     /// This also adds the cast to the worklist.  Finally, this returns the
255     /// cast.
256     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257                             Instruction &Pos) {
258       if (V->getType() == Ty) return V;
259
260       if (Constant *CV = dyn_cast<Constant>(V))
261         return ConstantExpr::getCast(opc, CV, Ty);
262       
263       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
264       AddToWorkList(C);
265       return C;
266     }
267         
268     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270     }
271
272
273     // ReplaceInstUsesWith - This method is to be used when an instruction is
274     // found to be dead, replacable with another preexisting expression.  Here
275     // we add all uses of I to the worklist, replace all uses of I with the new
276     // value, then return I, so that the inst combiner will know that I was
277     // modified.
278     //
279     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
280       AddUsersToWorkList(I);         // Add all modified instrs to worklist
281       if (&I != V) {
282         I.replaceAllUsesWith(V);
283         return &I;
284       } else {
285         // If we are replacing the instruction with itself, this must be in a
286         // segment of unreachable code, so just clobber the instruction.
287         I.replaceAllUsesWith(UndefValue::get(I.getType()));
288         return &I;
289       }
290     }
291
292     // UpdateValueUsesWith - This method is to be used when an value is
293     // found to be replacable with another preexisting expression or was
294     // updated.  Here we add all uses of I to the worklist, replace all uses of
295     // I with the new value (unless the instruction was just updated), then
296     // return true, so that the inst combiner will know that I was modified.
297     //
298     bool UpdateValueUsesWith(Value *Old, Value *New) {
299       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
300       if (Old != New)
301         Old->replaceAllUsesWith(New);
302       if (Instruction *I = dyn_cast<Instruction>(Old))
303         AddToWorkList(I);
304       if (Instruction *I = dyn_cast<Instruction>(New))
305         AddToWorkList(I);
306       return true;
307     }
308     
309     // EraseInstFromFunction - When dealing with an instruction that has side
310     // effects or produces a void value, we can't rely on DCE to delete the
311     // instruction.  Instead, visit methods should return the value returned by
312     // this function.
313     Instruction *EraseInstFromFunction(Instruction &I) {
314       assert(I.use_empty() && "Cannot erase instruction that is used!");
315       AddUsesToWorkList(I);
316       RemoveFromWorkList(&I);
317       I.eraseFromParent();
318       return 0;  // Don't do anything with FI
319     }
320
321   private:
322     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
324     /// casts that are known to not do anything...
325     ///
326     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327                                    Value *V, const Type *DestTy,
328                                    Instruction *InsertBefore);
329
330     /// SimplifyCommutative - This performs a few simplifications for 
331     /// commutative operators.
332     bool SimplifyCommutative(BinaryOperator &I);
333
334     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335     /// most-complex to least-complex order.
336     bool SimplifyCompare(CmpInst &I);
337
338     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339     /// on the demanded bits.
340     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
341                               APInt& KnownZero, APInt& KnownOne,
342                               unsigned Depth = 0);
343
344     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345                                       uint64_t &UndefElts, unsigned Depth = 0);
346       
347     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348     // PHI node as operand #0, see if we can fold the instruction into the PHI
349     // (which is only possible if all operands to the PHI are constants).
350     Instruction *FoldOpIntoPhi(Instruction &I);
351
352     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353     // operator and they all are only used by the PHI, PHI together their
354     // inputs, and do the operation once, to the result of the PHI.
355     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
356     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357     
358     
359     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
361     
362     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
363                               bool isSub, Instruction &I);
364     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
365                                  bool isSigned, bool Inside, Instruction &IB);
366     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
367     Instruction *MatchBSwap(BinaryOperator &I);
368     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
369
370     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
371   };
372
373   char InstCombiner::ID = 0;
374   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
375 }
376
377 // getComplexity:  Assign a complexity or rank value to LLVM Values...
378 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
379 static unsigned getComplexity(Value *V) {
380   if (isa<Instruction>(V)) {
381     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
382       return 3;
383     return 4;
384   }
385   if (isa<Argument>(V)) return 3;
386   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
387 }
388
389 // isOnlyUse - Return true if this instruction will be deleted if we stop using
390 // it.
391 static bool isOnlyUse(Value *V) {
392   return V->hasOneUse() || isa<Constant>(V);
393 }
394
395 // getPromotedType - Return the specified type promoted as it would be to pass
396 // though a va_arg area...
397 static const Type *getPromotedType(const Type *Ty) {
398   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
399     if (ITy->getBitWidth() < 32)
400       return Type::Int32Ty;
401   }
402   return Ty;
403 }
404
405 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
406 /// expression bitcast,  return the operand value, otherwise return null.
407 static Value *getBitCastOperand(Value *V) {
408   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
409     return I->getOperand(0);
410   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
411     if (CE->getOpcode() == Instruction::BitCast)
412       return CE->getOperand(0);
413   return 0;
414 }
415
416 /// This function is a wrapper around CastInst::isEliminableCastPair. It
417 /// simply extracts arguments and returns what that function returns.
418 static Instruction::CastOps 
419 isEliminableCastPair(
420   const CastInst *CI, ///< The first cast instruction
421   unsigned opcode,       ///< The opcode of the second cast instruction
422   const Type *DstTy,     ///< The target type for the second cast instruction
423   TargetData *TD         ///< The target data for pointer size
424 ) {
425   
426   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
427   const Type *MidTy = CI->getType();                  // B from above
428
429   // Get the opcodes of the two Cast instructions
430   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
431   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
432
433   return Instruction::CastOps(
434       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
435                                      DstTy, TD->getIntPtrType()));
436 }
437
438 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
439 /// in any code being generated.  It does not require codegen if V is simple
440 /// enough or if the cast can be folded into other casts.
441 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
442                               const Type *Ty, TargetData *TD) {
443   if (V->getType() == Ty || isa<Constant>(V)) return false;
444   
445   // If this is another cast that can be eliminated, it isn't codegen either.
446   if (const CastInst *CI = dyn_cast<CastInst>(V))
447     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
448       return false;
449   return true;
450 }
451
452 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
453 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
454 /// casts that are known to not do anything...
455 ///
456 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
457                                              Value *V, const Type *DestTy,
458                                              Instruction *InsertBefore) {
459   if (V->getType() == DestTy) return V;
460   if (Constant *C = dyn_cast<Constant>(V))
461     return ConstantExpr::getCast(opcode, C, DestTy);
462   
463   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
464 }
465
466 // SimplifyCommutative - This performs a few simplifications for commutative
467 // operators:
468 //
469 //  1. Order operands such that they are listed from right (least complex) to
470 //     left (most complex).  This puts constants before unary operators before
471 //     binary operators.
472 //
473 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
474 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
475 //
476 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
477   bool Changed = false;
478   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
479     Changed = !I.swapOperands();
480
481   if (!I.isAssociative()) return Changed;
482   Instruction::BinaryOps Opcode = I.getOpcode();
483   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
484     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
485       if (isa<Constant>(I.getOperand(1))) {
486         Constant *Folded = ConstantExpr::get(I.getOpcode(),
487                                              cast<Constant>(I.getOperand(1)),
488                                              cast<Constant>(Op->getOperand(1)));
489         I.setOperand(0, Op->getOperand(0));
490         I.setOperand(1, Folded);
491         return true;
492       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
493         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
494             isOnlyUse(Op) && isOnlyUse(Op1)) {
495           Constant *C1 = cast<Constant>(Op->getOperand(1));
496           Constant *C2 = cast<Constant>(Op1->getOperand(1));
497
498           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
499           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
500           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
501                                                     Op1->getOperand(0),
502                                                     Op1->getName(), &I);
503           AddToWorkList(New);
504           I.setOperand(0, New);
505           I.setOperand(1, Folded);
506           return true;
507         }
508     }
509   return Changed;
510 }
511
512 /// SimplifyCompare - For a CmpInst this function just orders the operands
513 /// so that theyare listed from right (least complex) to left (most complex).
514 /// This puts constants before unary operators before binary operators.
515 bool InstCombiner::SimplifyCompare(CmpInst &I) {
516   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
517     return false;
518   I.swapOperands();
519   // Compare instructions are not associative so there's nothing else we can do.
520   return true;
521 }
522
523 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
524 // if the LHS is a constant zero (which is the 'negate' form).
525 //
526 static inline Value *dyn_castNegVal(Value *V) {
527   if (BinaryOperator::isNeg(V))
528     return BinaryOperator::getNegArgument(V);
529
530   // Constants can be considered to be negated values if they can be folded.
531   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
532     return ConstantExpr::getNeg(C);
533   return 0;
534 }
535
536 static inline Value *dyn_castNotVal(Value *V) {
537   if (BinaryOperator::isNot(V))
538     return BinaryOperator::getNotArgument(V);
539
540   // Constants can be considered to be not'ed values...
541   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
542     return ConstantInt::get(~C->getValue());
543   return 0;
544 }
545
546 // dyn_castFoldableMul - If this value is a multiply that can be folded into
547 // other computations (because it has a constant operand), return the
548 // non-constant operand of the multiply, and set CST to point to the multiplier.
549 // Otherwise, return null.
550 //
551 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
552   if (V->hasOneUse() && V->getType()->isInteger())
553     if (Instruction *I = dyn_cast<Instruction>(V)) {
554       if (I->getOpcode() == Instruction::Mul)
555         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
556           return I->getOperand(0);
557       if (I->getOpcode() == Instruction::Shl)
558         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
559           // The multiplier is really 1 << CST.
560           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
561           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
562           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
563           return I->getOperand(0);
564         }
565     }
566   return 0;
567 }
568
569 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
570 /// expression, return it.
571 static User *dyn_castGetElementPtr(Value *V) {
572   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
573   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
574     if (CE->getOpcode() == Instruction::GetElementPtr)
575       return cast<User>(V);
576   return false;
577 }
578
579 /// AddOne - Add one to a ConstantInt
580 static ConstantInt *AddOne(ConstantInt *C) {
581   APInt Val(C->getValue());
582   return ConstantInt::get(++Val);
583 }
584 /// SubOne - Subtract one from a ConstantInt
585 static ConstantInt *SubOne(ConstantInt *C) {
586   APInt Val(C->getValue());
587   return ConstantInt::get(--Val);
588 }
589 /// Add - Add two ConstantInts together
590 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
591   return ConstantInt::get(C1->getValue() + C2->getValue());
592 }
593 /// And - Bitwise AND two ConstantInts together
594 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
595   return ConstantInt::get(C1->getValue() & C2->getValue());
596 }
597 /// Subtract - Subtract one ConstantInt from another
598 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
599   return ConstantInt::get(C1->getValue() - C2->getValue());
600 }
601 /// Multiply - Multiply two ConstantInts together
602 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
603   return ConstantInt::get(C1->getValue() * C2->getValue());
604 }
605
606 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
607 /// known to be either zero or one and return them in the KnownZero/KnownOne
608 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
609 /// processing.
610 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
611 /// we cannot optimize based on the assumption that it is zero without changing
612 /// it to be an explicit zero.  If we don't change it to zero, other code could
613 /// optimized based on the contradictory assumption that it is non-zero.
614 /// Because instcombine aggressively folds operations with undef args anyway,
615 /// this won't lose us code quality.
616 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
617                               APInt& KnownOne, unsigned Depth = 0) {
618   assert(V && "No Value?");
619   assert(Depth <= 6 && "Limit Search Depth");
620   uint32_t BitWidth = Mask.getBitWidth();
621   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
622          KnownZero.getBitWidth() == BitWidth && 
623          KnownOne.getBitWidth() == BitWidth &&
624          "V, Mask, KnownOne and KnownZero should have same BitWidth");
625   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
626     // We know all of the bits for a constant!
627     KnownOne = CI->getValue() & Mask;
628     KnownZero = ~KnownOne & Mask;
629     return;
630   }
631
632   if (Depth == 6 || Mask == 0)
633     return;  // Limit search depth.
634
635   Instruction *I = dyn_cast<Instruction>(V);
636   if (!I) return;
637
638   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
639   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
640   
641   switch (I->getOpcode()) {
642   case Instruction::And: {
643     // If either the LHS or the RHS are Zero, the result is zero.
644     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
645     APInt Mask2(Mask & ~KnownZero);
646     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
647     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
648     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
649     
650     // Output known-1 bits are only known if set in both the LHS & RHS.
651     KnownOne &= KnownOne2;
652     // Output known-0 are known to be clear if zero in either the LHS | RHS.
653     KnownZero |= KnownZero2;
654     return;
655   }
656   case Instruction::Or: {
657     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
658     APInt Mask2(Mask & ~KnownOne);
659     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
660     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
661     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
662     
663     // Output known-0 bits are only known if clear in both the LHS & RHS.
664     KnownZero &= KnownZero2;
665     // Output known-1 are known to be set if set in either the LHS | RHS.
666     KnownOne |= KnownOne2;
667     return;
668   }
669   case Instruction::Xor: {
670     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
671     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
672     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
673     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
674     
675     // Output known-0 bits are known if clear or set in both the LHS & RHS.
676     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
677     // Output known-1 are known to be set if set in only one of the LHS, RHS.
678     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
679     KnownZero = KnownZeroOut;
680     return;
681   }
682   case Instruction::Select:
683     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
684     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
685     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
686     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
687
688     // Only known if known in both the LHS and RHS.
689     KnownOne &= KnownOne2;
690     KnownZero &= KnownZero2;
691     return;
692   case Instruction::FPTrunc:
693   case Instruction::FPExt:
694   case Instruction::FPToUI:
695   case Instruction::FPToSI:
696   case Instruction::SIToFP:
697   case Instruction::PtrToInt:
698   case Instruction::UIToFP:
699   case Instruction::IntToPtr:
700     return; // Can't work with floating point or pointers
701   case Instruction::Trunc: {
702     // All these have integer operands
703     uint32_t SrcBitWidth = 
704       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
705     APInt MaskIn(Mask);
706     MaskIn.zext(SrcBitWidth);
707     KnownZero.zext(SrcBitWidth);
708     KnownOne.zext(SrcBitWidth);
709     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
710     KnownZero.trunc(BitWidth);
711     KnownOne.trunc(BitWidth);
712     return;
713   }
714   case Instruction::BitCast: {
715     const Type *SrcTy = I->getOperand(0)->getType();
716     if (SrcTy->isInteger()) {
717       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
718       return;
719     }
720     break;
721   }
722   case Instruction::ZExt:  {
723     // Compute the bits in the result that are not present in the input.
724     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
725     uint32_t SrcBitWidth = SrcTy->getBitWidth();
726       
727     APInt MaskIn(Mask);
728     MaskIn.trunc(SrcBitWidth);
729     KnownZero.trunc(SrcBitWidth);
730     KnownOne.trunc(SrcBitWidth);
731     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
732     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
733     // The top bits are known to be zero.
734     KnownZero.zext(BitWidth);
735     KnownOne.zext(BitWidth);
736     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
737     return;
738   }
739   case Instruction::SExt: {
740     // Compute the bits in the result that are not present in the input.
741     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
742     uint32_t SrcBitWidth = SrcTy->getBitWidth();
743       
744     APInt MaskIn(Mask); 
745     MaskIn.trunc(SrcBitWidth);
746     KnownZero.trunc(SrcBitWidth);
747     KnownOne.trunc(SrcBitWidth);
748     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
749     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
750     KnownZero.zext(BitWidth);
751     KnownOne.zext(BitWidth);
752
753     // If the sign bit of the input is known set or clear, then we know the
754     // top bits of the result.
755     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
756       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
757     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
758       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
759     return;
760   }
761   case Instruction::Shl:
762     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
763     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
764       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
765       APInt Mask2(Mask.lshr(ShiftAmt));
766       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
767       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
768       KnownZero <<= ShiftAmt;
769       KnownOne  <<= ShiftAmt;
770       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
771       return;
772     }
773     break;
774   case Instruction::LShr:
775     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
776     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
777       // Compute the new bits that are at the top now.
778       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
779       
780       // Unsigned shift right.
781       APInt Mask2(Mask.shl(ShiftAmt));
782       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
783       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
784       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
785       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
786       // high bits known zero.
787       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
788       return;
789     }
790     break;
791   case Instruction::AShr:
792     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
793     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
794       // Compute the new bits that are at the top now.
795       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
796       
797       // Signed shift right.
798       APInt Mask2(Mask.shl(ShiftAmt));
799       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
800       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
801       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
802       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
803         
804       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
805       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
806         KnownZero |= HighBits;
807       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
808         KnownOne |= HighBits;
809       return;
810     }
811     break;
812   }
813 }
814
815 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
816 /// this predicate to simplify operations downstream.  Mask is known to be zero
817 /// for bits that V cannot have.
818 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
819   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
820   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
821   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
822   return (KnownZero & Mask) == Mask;
823 }
824
825 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
826 /// specified instruction is a constant integer.  If so, check to see if there
827 /// are any bits set in the constant that are not demanded.  If so, shrink the
828 /// constant and return true.
829 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
830                                    APInt Demanded) {
831   assert(I && "No instruction?");
832   assert(OpNo < I->getNumOperands() && "Operand index too large");
833
834   // If the operand is not a constant integer, nothing to do.
835   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
836   if (!OpC) return false;
837
838   // If there are no bits set that aren't demanded, nothing to do.
839   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
840   if ((~Demanded & OpC->getValue()) == 0)
841     return false;
842
843   // This instruction is producing bits that are not demanded. Shrink the RHS.
844   Demanded &= OpC->getValue();
845   I->setOperand(OpNo, ConstantInt::get(Demanded));
846   return true;
847 }
848
849 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
850 // set of known zero and one bits, compute the maximum and minimum values that
851 // could have the specified known zero and known one bits, returning them in
852 // min/max.
853 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
854                                                    const APInt& KnownZero,
855                                                    const APInt& KnownOne,
856                                                    APInt& Min, APInt& Max) {
857   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
858   assert(KnownZero.getBitWidth() == BitWidth && 
859          KnownOne.getBitWidth() == BitWidth &&
860          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
861          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
862   APInt UnknownBits = ~(KnownZero|KnownOne);
863
864   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
865   // bit if it is unknown.
866   Min = KnownOne;
867   Max = KnownOne|UnknownBits;
868   
869   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
870     Min.set(BitWidth-1);
871     Max.clear(BitWidth-1);
872   }
873 }
874
875 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
876 // a set of known zero and one bits, compute the maximum and minimum values that
877 // could have the specified known zero and known one bits, returning them in
878 // min/max.
879 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
880                                                      const APInt &KnownZero,
881                                                      const APInt &KnownOne,
882                                                      APInt &Min, APInt &Max) {
883   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
884   assert(KnownZero.getBitWidth() == BitWidth && 
885          KnownOne.getBitWidth() == BitWidth &&
886          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
887          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
888   APInt UnknownBits = ~(KnownZero|KnownOne);
889   
890   // The minimum value is when the unknown bits are all zeros.
891   Min = KnownOne;
892   // The maximum value is when the unknown bits are all ones.
893   Max = KnownOne|UnknownBits;
894 }
895
896 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
897 /// value based on the demanded bits. When this function is called, it is known
898 /// that only the bits set in DemandedMask of the result of V are ever used
899 /// downstream. Consequently, depending on the mask and V, it may be possible
900 /// to replace V with a constant or one of its operands. In such cases, this
901 /// function does the replacement and returns true. In all other cases, it
902 /// returns false after analyzing the expression and setting KnownOne and known
903 /// to be one in the expression. KnownZero contains all the bits that are known
904 /// to be zero in the expression. These are provided to potentially allow the
905 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
906 /// the expression. KnownOne and KnownZero always follow the invariant that 
907 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
908 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
909 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
910 /// and KnownOne must all be the same.
911 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
912                                         APInt& KnownZero, APInt& KnownOne,
913                                         unsigned Depth) {
914   assert(V != 0 && "Null pointer of Value???");
915   assert(Depth <= 6 && "Limit Search Depth");
916   uint32_t BitWidth = DemandedMask.getBitWidth();
917   const IntegerType *VTy = cast<IntegerType>(V->getType());
918   assert(VTy->getBitWidth() == BitWidth && 
919          KnownZero.getBitWidth() == BitWidth && 
920          KnownOne.getBitWidth() == BitWidth &&
921          "Value *V, DemandedMask, KnownZero and KnownOne \
922           must have same BitWidth");
923   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
924     // We know all of the bits for a constant!
925     KnownOne = CI->getValue() & DemandedMask;
926     KnownZero = ~KnownOne & DemandedMask;
927     return false;
928   }
929   
930   KnownZero.clear(); 
931   KnownOne.clear();
932   if (!V->hasOneUse()) {    // Other users may use these bits.
933     if (Depth != 0) {       // Not at the root.
934       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
935       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
936       return false;
937     }
938     // If this is the root being simplified, allow it to have multiple uses,
939     // just set the DemandedMask to all bits.
940     DemandedMask = APInt::getAllOnesValue(BitWidth);
941   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
942     if (V != UndefValue::get(VTy))
943       return UpdateValueUsesWith(V, UndefValue::get(VTy));
944     return false;
945   } else if (Depth == 6) {        // Limit search depth.
946     return false;
947   }
948   
949   Instruction *I = dyn_cast<Instruction>(V);
950   if (!I) return false;        // Only analyze instructions.
951
952   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
953   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
954   switch (I->getOpcode()) {
955   default: break;
956   case Instruction::And:
957     // If either the LHS or the RHS are Zero, the result is zero.
958     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
959                              RHSKnownZero, RHSKnownOne, Depth+1))
960       return true;
961     assert((RHSKnownZero & RHSKnownOne) == 0 && 
962            "Bits known to be one AND zero?"); 
963
964     // If something is known zero on the RHS, the bits aren't demanded on the
965     // LHS.
966     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
967                              LHSKnownZero, LHSKnownOne, Depth+1))
968       return true;
969     assert((LHSKnownZero & LHSKnownOne) == 0 && 
970            "Bits known to be one AND zero?"); 
971
972     // If all of the demanded bits are known 1 on one side, return the other.
973     // These bits cannot contribute to the result of the 'and'.
974     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
975         (DemandedMask & ~LHSKnownZero))
976       return UpdateValueUsesWith(I, I->getOperand(0));
977     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
978         (DemandedMask & ~RHSKnownZero))
979       return UpdateValueUsesWith(I, I->getOperand(1));
980     
981     // If all of the demanded bits in the inputs are known zeros, return zero.
982     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
983       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
984       
985     // If the RHS is a constant, see if we can simplify it.
986     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
987       return UpdateValueUsesWith(I, I);
988       
989     // Output known-1 bits are only known if set in both the LHS & RHS.
990     RHSKnownOne &= LHSKnownOne;
991     // Output known-0 are known to be clear if zero in either the LHS | RHS.
992     RHSKnownZero |= LHSKnownZero;
993     break;
994   case Instruction::Or:
995     // If either the LHS or the RHS are One, the result is One.
996     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
997                              RHSKnownZero, RHSKnownOne, Depth+1))
998       return true;
999     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1000            "Bits known to be one AND zero?"); 
1001     // If something is known one on the RHS, the bits aren't demanded on the
1002     // LHS.
1003     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1004                              LHSKnownZero, LHSKnownOne, Depth+1))
1005       return true;
1006     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1007            "Bits known to be one AND zero?"); 
1008     
1009     // If all of the demanded bits are known zero on one side, return the other.
1010     // These bits cannot contribute to the result of the 'or'.
1011     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1012         (DemandedMask & ~LHSKnownOne))
1013       return UpdateValueUsesWith(I, I->getOperand(0));
1014     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1015         (DemandedMask & ~RHSKnownOne))
1016       return UpdateValueUsesWith(I, I->getOperand(1));
1017
1018     // If all of the potentially set bits on one side are known to be set on
1019     // the other side, just use the 'other' side.
1020     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1021         (DemandedMask & (~RHSKnownZero)))
1022       return UpdateValueUsesWith(I, I->getOperand(0));
1023     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1024         (DemandedMask & (~LHSKnownZero)))
1025       return UpdateValueUsesWith(I, I->getOperand(1));
1026         
1027     // If the RHS is a constant, see if we can simplify it.
1028     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1029       return UpdateValueUsesWith(I, I);
1030           
1031     // Output known-0 bits are only known if clear in both the LHS & RHS.
1032     RHSKnownZero &= LHSKnownZero;
1033     // Output known-1 are known to be set if set in either the LHS | RHS.
1034     RHSKnownOne |= LHSKnownOne;
1035     break;
1036   case Instruction::Xor: {
1037     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1038                              RHSKnownZero, RHSKnownOne, Depth+1))
1039       return true;
1040     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1041            "Bits known to be one AND zero?"); 
1042     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1043                              LHSKnownZero, LHSKnownOne, Depth+1))
1044       return true;
1045     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1046            "Bits known to be one AND zero?"); 
1047     
1048     // If all of the demanded bits are known zero on one side, return the other.
1049     // These bits cannot contribute to the result of the 'xor'.
1050     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1051       return UpdateValueUsesWith(I, I->getOperand(0));
1052     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1053       return UpdateValueUsesWith(I, I->getOperand(1));
1054     
1055     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1056     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1057                          (RHSKnownOne & LHSKnownOne);
1058     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1059     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1060                         (RHSKnownOne & LHSKnownZero);
1061     
1062     // If all of the demanded bits are known to be zero on one side or the
1063     // other, turn this into an *inclusive* or.
1064     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1065     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1066       Instruction *Or =
1067         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1068                                  I->getName());
1069       InsertNewInstBefore(Or, *I);
1070       return UpdateValueUsesWith(I, Or);
1071     }
1072     
1073     // If all of the demanded bits on one side are known, and all of the set
1074     // bits on that side are also known to be set on the other side, turn this
1075     // into an AND, as we know the bits will be cleared.
1076     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1077     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1078       // all known
1079       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1080         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1081         Instruction *And = 
1082           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1083         InsertNewInstBefore(And, *I);
1084         return UpdateValueUsesWith(I, And);
1085       }
1086     }
1087     
1088     // If the RHS is a constant, see if we can simplify it.
1089     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1090     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1091       return UpdateValueUsesWith(I, I);
1092     
1093     RHSKnownZero = KnownZeroOut;
1094     RHSKnownOne  = KnownOneOut;
1095     break;
1096   }
1097   case Instruction::Select:
1098     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1099                              RHSKnownZero, RHSKnownOne, Depth+1))
1100       return true;
1101     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1102                              LHSKnownZero, LHSKnownOne, Depth+1))
1103       return true;
1104     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1105            "Bits known to be one AND zero?"); 
1106     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1107            "Bits known to be one AND zero?"); 
1108     
1109     // If the operands are constants, see if we can simplify them.
1110     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1111       return UpdateValueUsesWith(I, I);
1112     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1113       return UpdateValueUsesWith(I, I);
1114     
1115     // Only known if known in both the LHS and RHS.
1116     RHSKnownOne &= LHSKnownOne;
1117     RHSKnownZero &= LHSKnownZero;
1118     break;
1119   case Instruction::Trunc: {
1120     uint32_t truncBf = 
1121       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1122     DemandedMask.zext(truncBf);
1123     RHSKnownZero.zext(truncBf);
1124     RHSKnownOne.zext(truncBf);
1125     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1126                              RHSKnownZero, RHSKnownOne, Depth+1))
1127       return true;
1128     DemandedMask.trunc(BitWidth);
1129     RHSKnownZero.trunc(BitWidth);
1130     RHSKnownOne.trunc(BitWidth);
1131     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1132            "Bits known to be one AND zero?"); 
1133     break;
1134   }
1135   case Instruction::BitCast:
1136     if (!I->getOperand(0)->getType()->isInteger())
1137       return false;
1138       
1139     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1140                              RHSKnownZero, RHSKnownOne, Depth+1))
1141       return true;
1142     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1143            "Bits known to be one AND zero?"); 
1144     break;
1145   case Instruction::ZExt: {
1146     // Compute the bits in the result that are not present in the input.
1147     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1148     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1149     
1150     DemandedMask.trunc(SrcBitWidth);
1151     RHSKnownZero.trunc(SrcBitWidth);
1152     RHSKnownOne.trunc(SrcBitWidth);
1153     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1154                              RHSKnownZero, RHSKnownOne, Depth+1))
1155       return true;
1156     DemandedMask.zext(BitWidth);
1157     RHSKnownZero.zext(BitWidth);
1158     RHSKnownOne.zext(BitWidth);
1159     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1160            "Bits known to be one AND zero?"); 
1161     // The top bits are known to be zero.
1162     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1163     break;
1164   }
1165   case Instruction::SExt: {
1166     // Compute the bits in the result that are not present in the input.
1167     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1168     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1169     
1170     APInt InputDemandedBits = DemandedMask & 
1171                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1172
1173     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1174     // If any of the sign extended bits are demanded, we know that the sign
1175     // bit is demanded.
1176     if ((NewBits & DemandedMask) != 0)
1177       InputDemandedBits.set(SrcBitWidth-1);
1178       
1179     InputDemandedBits.trunc(SrcBitWidth);
1180     RHSKnownZero.trunc(SrcBitWidth);
1181     RHSKnownOne.trunc(SrcBitWidth);
1182     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1183                              RHSKnownZero, RHSKnownOne, Depth+1))
1184       return true;
1185     InputDemandedBits.zext(BitWidth);
1186     RHSKnownZero.zext(BitWidth);
1187     RHSKnownOne.zext(BitWidth);
1188     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1189            "Bits known to be one AND zero?"); 
1190       
1191     // If the sign bit of the input is known set or clear, then we know the
1192     // top bits of the result.
1193
1194     // If the input sign bit is known zero, or if the NewBits are not demanded
1195     // convert this into a zero extension.
1196     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1197     {
1198       // Convert to ZExt cast
1199       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1200       return UpdateValueUsesWith(I, NewCast);
1201     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1202       RHSKnownOne |= NewBits;
1203     }
1204     break;
1205   }
1206   case Instruction::Add: {
1207     // Figure out what the input bits are.  If the top bits of the and result
1208     // are not demanded, then the add doesn't demand them from its input
1209     // either.
1210     uint32_t NLZ = DemandedMask.countLeadingZeros();
1211       
1212     // If there is a constant on the RHS, there are a variety of xformations
1213     // we can do.
1214     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215       // If null, this should be simplified elsewhere.  Some of the xforms here
1216       // won't work if the RHS is zero.
1217       if (RHS->isZero())
1218         break;
1219       
1220       // If the top bit of the output is demanded, demand everything from the
1221       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1222       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1223
1224       // Find information about known zero/one bits in the input.
1225       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1226                                LHSKnownZero, LHSKnownOne, Depth+1))
1227         return true;
1228
1229       // If the RHS of the add has bits set that can't affect the input, reduce
1230       // the constant.
1231       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1232         return UpdateValueUsesWith(I, I);
1233       
1234       // Avoid excess work.
1235       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1236         break;
1237       
1238       // Turn it into OR if input bits are zero.
1239       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1240         Instruction *Or =
1241           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1242                                    I->getName());
1243         InsertNewInstBefore(Or, *I);
1244         return UpdateValueUsesWith(I, Or);
1245       }
1246       
1247       // We can say something about the output known-zero and known-one bits,
1248       // depending on potential carries from the input constant and the
1249       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1250       // bits set and the RHS constant is 0x01001, then we know we have a known
1251       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1252       
1253       // To compute this, we first compute the potential carry bits.  These are
1254       // the bits which may be modified.  I'm not aware of a better way to do
1255       // this scan.
1256       const APInt& RHSVal = RHS->getValue();
1257       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1258       
1259       // Now that we know which bits have carries, compute the known-1/0 sets.
1260       
1261       // Bits are known one if they are known zero in one operand and one in the
1262       // other, and there is no input carry.
1263       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1264                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1265       
1266       // Bits are known zero if they are known zero in both operands and there
1267       // is no input carry.
1268       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1269     } else {
1270       // If the high-bits of this ADD are not demanded, then it does not demand
1271       // the high bits of its LHS or RHS.
1272       if (DemandedMask[BitWidth-1] == 0) {
1273         // Right fill the mask of bits for this ADD to demand the most
1274         // significant bit and all those below it.
1275         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1276         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1277                                  LHSKnownZero, LHSKnownOne, Depth+1))
1278           return true;
1279         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1280                                  LHSKnownZero, LHSKnownOne, Depth+1))
1281           return true;
1282       }
1283     }
1284     break;
1285   }
1286   case Instruction::Sub:
1287     // If the high-bits of this SUB are not demanded, then it does not demand
1288     // the high bits of its LHS or RHS.
1289     if (DemandedMask[BitWidth-1] == 0) {
1290       // Right fill the mask of bits for this SUB to demand the most
1291       // significant bit and all those below it.
1292       uint32_t NLZ = DemandedMask.countLeadingZeros();
1293       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1294       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1295                                LHSKnownZero, LHSKnownOne, Depth+1))
1296         return true;
1297       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1298                                LHSKnownZero, LHSKnownOne, Depth+1))
1299         return true;
1300     }
1301     break;
1302   case Instruction::Shl:
1303     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1304       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1305       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1306       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1307                                RHSKnownZero, RHSKnownOne, Depth+1))
1308         return true;
1309       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1310              "Bits known to be one AND zero?"); 
1311       RHSKnownZero <<= ShiftAmt;
1312       RHSKnownOne  <<= ShiftAmt;
1313       // low bits known zero.
1314       if (ShiftAmt)
1315         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1316     }
1317     break;
1318   case Instruction::LShr:
1319     // For a logical shift right
1320     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1321       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1322       
1323       // Unsigned shift right.
1324       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1325       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1326                                RHSKnownZero, RHSKnownOne, Depth+1))
1327         return true;
1328       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1329              "Bits known to be one AND zero?"); 
1330       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1331       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1332       if (ShiftAmt) {
1333         // Compute the new bits that are at the top now.
1334         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1335         RHSKnownZero |= HighBits;  // high bits known zero.
1336       }
1337     }
1338     break;
1339   case Instruction::AShr:
1340     // If this is an arithmetic shift right and only the low-bit is set, we can
1341     // always convert this into a logical shr, even if the shift amount is
1342     // variable.  The low bit of the shift cannot be an input sign bit unless
1343     // the shift amount is >= the size of the datatype, which is undefined.
1344     if (DemandedMask == 1) {
1345       // Perform the logical shift right.
1346       Value *NewVal = BinaryOperator::createLShr(
1347                         I->getOperand(0), I->getOperand(1), I->getName());
1348       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1349       return UpdateValueUsesWith(I, NewVal);
1350     }    
1351
1352     // If the sign bit is the only bit demanded by this ashr, then there is no
1353     // need to do it, the shift doesn't change the high bit.
1354     if (DemandedMask.isSignBit())
1355       return UpdateValueUsesWith(I, I->getOperand(0));
1356     
1357     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1359       
1360       // Signed shift right.
1361       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1362       // If any of the "high bits" are demanded, we should set the sign bit as
1363       // demanded.
1364       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1365         DemandedMaskIn.set(BitWidth-1);
1366       if (SimplifyDemandedBits(I->getOperand(0),
1367                                DemandedMaskIn,
1368                                RHSKnownZero, RHSKnownOne, Depth+1))
1369         return true;
1370       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1371              "Bits known to be one AND zero?"); 
1372       // Compute the new bits that are at the top now.
1373       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1374       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1375       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1376         
1377       // Handle the sign bits.
1378       APInt SignBit(APInt::getSignBit(BitWidth));
1379       // Adjust to where it is now in the mask.
1380       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1381         
1382       // If the input sign bit is known to be zero, or if none of the top bits
1383       // are demanded, turn this into an unsigned shift right.
1384       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1385           (HighBits & ~DemandedMask) == HighBits) {
1386         // Perform the logical shift right.
1387         Value *NewVal = BinaryOperator::createLShr(
1388                           I->getOperand(0), SA, I->getName());
1389         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1390         return UpdateValueUsesWith(I, NewVal);
1391       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1392         RHSKnownOne |= HighBits;
1393       }
1394     }
1395     break;
1396   }
1397   
1398   // If the client is only demanding bits that we know, return the known
1399   // constant.
1400   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1401     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1402   return false;
1403 }
1404
1405
1406 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1407 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1408 /// actually used by the caller.  This method analyzes which elements of the
1409 /// operand are undef and returns that information in UndefElts.
1410 ///
1411 /// If the information about demanded elements can be used to simplify the
1412 /// operation, the operation is simplified, then the resultant value is
1413 /// returned.  This returns null if no change was made.
1414 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1415                                                 uint64_t &UndefElts,
1416                                                 unsigned Depth) {
1417   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1418   assert(VWidth <= 64 && "Vector too wide to analyze!");
1419   uint64_t EltMask = ~0ULL >> (64-VWidth);
1420   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1421          "Invalid DemandedElts!");
1422
1423   if (isa<UndefValue>(V)) {
1424     // If the entire vector is undefined, just return this info.
1425     UndefElts = EltMask;
1426     return 0;
1427   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1428     UndefElts = EltMask;
1429     return UndefValue::get(V->getType());
1430   }
1431   
1432   UndefElts = 0;
1433   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1434     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1435     Constant *Undef = UndefValue::get(EltTy);
1436
1437     std::vector<Constant*> Elts;
1438     for (unsigned i = 0; i != VWidth; ++i)
1439       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1440         Elts.push_back(Undef);
1441         UndefElts |= (1ULL << i);
1442       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1443         Elts.push_back(Undef);
1444         UndefElts |= (1ULL << i);
1445       } else {                               // Otherwise, defined.
1446         Elts.push_back(CP->getOperand(i));
1447       }
1448         
1449     // If we changed the constant, return it.
1450     Constant *NewCP = ConstantVector::get(Elts);
1451     return NewCP != CP ? NewCP : 0;
1452   } else if (isa<ConstantAggregateZero>(V)) {
1453     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1454     // set to undef.
1455     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1456     Constant *Zero = Constant::getNullValue(EltTy);
1457     Constant *Undef = UndefValue::get(EltTy);
1458     std::vector<Constant*> Elts;
1459     for (unsigned i = 0; i != VWidth; ++i)
1460       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1461     UndefElts = DemandedElts ^ EltMask;
1462     return ConstantVector::get(Elts);
1463   }
1464   
1465   if (!V->hasOneUse()) {    // Other users may use these bits.
1466     if (Depth != 0) {       // Not at the root.
1467       // TODO: Just compute the UndefElts information recursively.
1468       return false;
1469     }
1470     return false;
1471   } else if (Depth == 10) {        // Limit search depth.
1472     return false;
1473   }
1474   
1475   Instruction *I = dyn_cast<Instruction>(V);
1476   if (!I) return false;        // Only analyze instructions.
1477   
1478   bool MadeChange = false;
1479   uint64_t UndefElts2;
1480   Value *TmpV;
1481   switch (I->getOpcode()) {
1482   default: break;
1483     
1484   case Instruction::InsertElement: {
1485     // If this is a variable index, we don't know which element it overwrites.
1486     // demand exactly the same input as we produce.
1487     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1488     if (Idx == 0) {
1489       // Note that we can't propagate undef elt info, because we don't know
1490       // which elt is getting updated.
1491       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1492                                         UndefElts2, Depth+1);
1493       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1494       break;
1495     }
1496     
1497     // If this is inserting an element that isn't demanded, remove this
1498     // insertelement.
1499     unsigned IdxNo = Idx->getZExtValue();
1500     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1501       return AddSoonDeadInstToWorklist(*I, 0);
1502     
1503     // Otherwise, the element inserted overwrites whatever was there, so the
1504     // input demanded set is simpler than the output set.
1505     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1506                                       DemandedElts & ~(1ULL << IdxNo),
1507                                       UndefElts, Depth+1);
1508     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1509
1510     // The inserted element is defined.
1511     UndefElts |= 1ULL << IdxNo;
1512     break;
1513   }
1514   case Instruction::BitCast: {
1515     // Vector->vector casts only.
1516     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1517     if (!VTy) break;
1518     unsigned InVWidth = VTy->getNumElements();
1519     uint64_t InputDemandedElts = 0;
1520     unsigned Ratio;
1521
1522     if (VWidth == InVWidth) {
1523       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1524       // elements as are demanded of us.
1525       Ratio = 1;
1526       InputDemandedElts = DemandedElts;
1527     } else if (VWidth > InVWidth) {
1528       // Untested so far.
1529       break;
1530       
1531       // If there are more elements in the result than there are in the source,
1532       // then an input element is live if any of the corresponding output
1533       // elements are live.
1534       Ratio = VWidth/InVWidth;
1535       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1536         if (DemandedElts & (1ULL << OutIdx))
1537           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1538       }
1539     } else {
1540       // Untested so far.
1541       break;
1542       
1543       // If there are more elements in the source than there are in the result,
1544       // then an input element is live if the corresponding output element is
1545       // live.
1546       Ratio = InVWidth/VWidth;
1547       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1548         if (DemandedElts & (1ULL << InIdx/Ratio))
1549           InputDemandedElts |= 1ULL << InIdx;
1550     }
1551     
1552     // div/rem demand all inputs, because they don't want divide by zero.
1553     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1554                                       UndefElts2, Depth+1);
1555     if (TmpV) {
1556       I->setOperand(0, TmpV);
1557       MadeChange = true;
1558     }
1559     
1560     UndefElts = UndefElts2;
1561     if (VWidth > InVWidth) {
1562       assert(0 && "Unimp");
1563       // If there are more elements in the result than there are in the source,
1564       // then an output element is undef if the corresponding input element is
1565       // undef.
1566       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1567         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1568           UndefElts |= 1ULL << OutIdx;
1569     } else if (VWidth < InVWidth) {
1570       assert(0 && "Unimp");
1571       // If there are more elements in the source than there are in the result,
1572       // then a result element is undef if all of the corresponding input
1573       // elements are undef.
1574       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1575       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1576         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1577           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1578     }
1579     break;
1580   }
1581   case Instruction::And:
1582   case Instruction::Or:
1583   case Instruction::Xor:
1584   case Instruction::Add:
1585   case Instruction::Sub:
1586   case Instruction::Mul:
1587     // div/rem demand all inputs, because they don't want divide by zero.
1588     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1589                                       UndefElts, Depth+1);
1590     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1591     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1592                                       UndefElts2, Depth+1);
1593     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1594       
1595     // Output elements are undefined if both are undefined.  Consider things
1596     // like undef&0.  The result is known zero, not undef.
1597     UndefElts &= UndefElts2;
1598     break;
1599     
1600   case Instruction::Call: {
1601     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1602     if (!II) break;
1603     switch (II->getIntrinsicID()) {
1604     default: break;
1605       
1606     // Binary vector operations that work column-wise.  A dest element is a
1607     // function of the corresponding input elements from the two inputs.
1608     case Intrinsic::x86_sse_sub_ss:
1609     case Intrinsic::x86_sse_mul_ss:
1610     case Intrinsic::x86_sse_min_ss:
1611     case Intrinsic::x86_sse_max_ss:
1612     case Intrinsic::x86_sse2_sub_sd:
1613     case Intrinsic::x86_sse2_mul_sd:
1614     case Intrinsic::x86_sse2_min_sd:
1615     case Intrinsic::x86_sse2_max_sd:
1616       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1617                                         UndefElts, Depth+1);
1618       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1619       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1620                                         UndefElts2, Depth+1);
1621       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1622
1623       // If only the low elt is demanded and this is a scalarizable intrinsic,
1624       // scalarize it now.
1625       if (DemandedElts == 1) {
1626         switch (II->getIntrinsicID()) {
1627         default: break;
1628         case Intrinsic::x86_sse_sub_ss:
1629         case Intrinsic::x86_sse_mul_ss:
1630         case Intrinsic::x86_sse2_sub_sd:
1631         case Intrinsic::x86_sse2_mul_sd:
1632           // TODO: Lower MIN/MAX/ABS/etc
1633           Value *LHS = II->getOperand(1);
1634           Value *RHS = II->getOperand(2);
1635           // Extract the element as scalars.
1636           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1637           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1638           
1639           switch (II->getIntrinsicID()) {
1640           default: assert(0 && "Case stmts out of sync!");
1641           case Intrinsic::x86_sse_sub_ss:
1642           case Intrinsic::x86_sse2_sub_sd:
1643             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1644                                                         II->getName()), *II);
1645             break;
1646           case Intrinsic::x86_sse_mul_ss:
1647           case Intrinsic::x86_sse2_mul_sd:
1648             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1649                                                          II->getName()), *II);
1650             break;
1651           }
1652           
1653           Instruction *New =
1654             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1655                                   II->getName());
1656           InsertNewInstBefore(New, *II);
1657           AddSoonDeadInstToWorklist(*II, 0);
1658           return New;
1659         }            
1660       }
1661         
1662       // Output elements are undefined if both are undefined.  Consider things
1663       // like undef&0.  The result is known zero, not undef.
1664       UndefElts &= UndefElts2;
1665       break;
1666     }
1667     break;
1668   }
1669   }
1670   return MadeChange ? I : 0;
1671 }
1672
1673 /// @returns true if the specified compare predicate is
1674 /// true when both operands are equal...
1675 /// @brief Determine if the icmp Predicate is true when both operands are equal
1676 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1677   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1678          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1679          pred == ICmpInst::ICMP_SLE;
1680 }
1681
1682 /// @returns true if the specified compare instruction is
1683 /// true when both operands are equal...
1684 /// @brief Determine if the ICmpInst returns true when both operands are equal
1685 static bool isTrueWhenEqual(ICmpInst &ICI) {
1686   return isTrueWhenEqual(ICI.getPredicate());
1687 }
1688
1689 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1690 /// function is designed to check a chain of associative operators for a
1691 /// potential to apply a certain optimization.  Since the optimization may be
1692 /// applicable if the expression was reassociated, this checks the chain, then
1693 /// reassociates the expression as necessary to expose the optimization
1694 /// opportunity.  This makes use of a special Functor, which must define
1695 /// 'shouldApply' and 'apply' methods.
1696 ///
1697 template<typename Functor>
1698 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1699   unsigned Opcode = Root.getOpcode();
1700   Value *LHS = Root.getOperand(0);
1701
1702   // Quick check, see if the immediate LHS matches...
1703   if (F.shouldApply(LHS))
1704     return F.apply(Root);
1705
1706   // Otherwise, if the LHS is not of the same opcode as the root, return.
1707   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1708   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1709     // Should we apply this transform to the RHS?
1710     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1711
1712     // If not to the RHS, check to see if we should apply to the LHS...
1713     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1714       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1715       ShouldApply = true;
1716     }
1717
1718     // If the functor wants to apply the optimization to the RHS of LHSI,
1719     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1720     if (ShouldApply) {
1721       BasicBlock *BB = Root.getParent();
1722
1723       // Now all of the instructions are in the current basic block, go ahead
1724       // and perform the reassociation.
1725       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1726
1727       // First move the selected RHS to the LHS of the root...
1728       Root.setOperand(0, LHSI->getOperand(1));
1729
1730       // Make what used to be the LHS of the root be the user of the root...
1731       Value *ExtraOperand = TmpLHSI->getOperand(1);
1732       if (&Root == TmpLHSI) {
1733         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1734         return 0;
1735       }
1736       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1737       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1738       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1739       BasicBlock::iterator ARI = &Root; ++ARI;
1740       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1741       ARI = Root;
1742
1743       // Now propagate the ExtraOperand down the chain of instructions until we
1744       // get to LHSI.
1745       while (TmpLHSI != LHSI) {
1746         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1747         // Move the instruction to immediately before the chain we are
1748         // constructing to avoid breaking dominance properties.
1749         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1750         BB->getInstList().insert(ARI, NextLHSI);
1751         ARI = NextLHSI;
1752
1753         Value *NextOp = NextLHSI->getOperand(1);
1754         NextLHSI->setOperand(1, ExtraOperand);
1755         TmpLHSI = NextLHSI;
1756         ExtraOperand = NextOp;
1757       }
1758
1759       // Now that the instructions are reassociated, have the functor perform
1760       // the transformation...
1761       return F.apply(Root);
1762     }
1763
1764     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1765   }
1766   return 0;
1767 }
1768
1769
1770 // AddRHS - Implements: X + X --> X << 1
1771 struct AddRHS {
1772   Value *RHS;
1773   AddRHS(Value *rhs) : RHS(rhs) {}
1774   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1775   Instruction *apply(BinaryOperator &Add) const {
1776     return BinaryOperator::createShl(Add.getOperand(0),
1777                                   ConstantInt::get(Add.getType(), 1));
1778   }
1779 };
1780
1781 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1782 //                 iff C1&C2 == 0
1783 struct AddMaskingAnd {
1784   Constant *C2;
1785   AddMaskingAnd(Constant *c) : C2(c) {}
1786   bool shouldApply(Value *LHS) const {
1787     ConstantInt *C1;
1788     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1789            ConstantExpr::getAnd(C1, C2)->isNullValue();
1790   }
1791   Instruction *apply(BinaryOperator &Add) const {
1792     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1793   }
1794 };
1795
1796 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1797                                              InstCombiner *IC) {
1798   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1799     if (Constant *SOC = dyn_cast<Constant>(SO))
1800       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1801
1802     return IC->InsertNewInstBefore(CastInst::create(
1803           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1804   }
1805
1806   // Figure out if the constant is the left or the right argument.
1807   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1808   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1809
1810   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1811     if (ConstIsRHS)
1812       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1813     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1814   }
1815
1816   Value *Op0 = SO, *Op1 = ConstOperand;
1817   if (!ConstIsRHS)
1818     std::swap(Op0, Op1);
1819   Instruction *New;
1820   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1821     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1822   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1823     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1824                           SO->getName()+".cmp");
1825   else {
1826     assert(0 && "Unknown binary instruction type!");
1827     abort();
1828   }
1829   return IC->InsertNewInstBefore(New, I);
1830 }
1831
1832 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1833 // constant as the other operand, try to fold the binary operator into the
1834 // select arguments.  This also works for Cast instructions, which obviously do
1835 // not have a second operand.
1836 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1837                                      InstCombiner *IC) {
1838   // Don't modify shared select instructions
1839   if (!SI->hasOneUse()) return 0;
1840   Value *TV = SI->getOperand(1);
1841   Value *FV = SI->getOperand(2);
1842
1843   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1844     // Bool selects with constant operands can be folded to logical ops.
1845     if (SI->getType() == Type::Int1Ty) return 0;
1846
1847     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1848     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1849
1850     return new SelectInst(SI->getCondition(), SelectTrueVal,
1851                           SelectFalseVal);
1852   }
1853   return 0;
1854 }
1855
1856
1857 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1858 /// node as operand #0, see if we can fold the instruction into the PHI (which
1859 /// is only possible if all operands to the PHI are constants).
1860 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1861   PHINode *PN = cast<PHINode>(I.getOperand(0));
1862   unsigned NumPHIValues = PN->getNumIncomingValues();
1863   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1864
1865   // Check to see if all of the operands of the PHI are constants.  If there is
1866   // one non-constant value, remember the BB it is.  If there is more than one
1867   // or if *it* is a PHI, bail out.
1868   BasicBlock *NonConstBB = 0;
1869   for (unsigned i = 0; i != NumPHIValues; ++i)
1870     if (!isa<Constant>(PN->getIncomingValue(i))) {
1871       if (NonConstBB) return 0;  // More than one non-const value.
1872       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1873       NonConstBB = PN->getIncomingBlock(i);
1874       
1875       // If the incoming non-constant value is in I's block, we have an infinite
1876       // loop.
1877       if (NonConstBB == I.getParent())
1878         return 0;
1879     }
1880   
1881   // If there is exactly one non-constant value, we can insert a copy of the
1882   // operation in that block.  However, if this is a critical edge, we would be
1883   // inserting the computation one some other paths (e.g. inside a loop).  Only
1884   // do this if the pred block is unconditionally branching into the phi block.
1885   if (NonConstBB) {
1886     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1887     if (!BI || !BI->isUnconditional()) return 0;
1888   }
1889
1890   // Okay, we can do the transformation: create the new PHI node.
1891   PHINode *NewPN = new PHINode(I.getType(), "");
1892   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1893   InsertNewInstBefore(NewPN, *PN);
1894   NewPN->takeName(PN);
1895
1896   // Next, add all of the operands to the PHI.
1897   if (I.getNumOperands() == 2) {
1898     Constant *C = cast<Constant>(I.getOperand(1));
1899     for (unsigned i = 0; i != NumPHIValues; ++i) {
1900       Value *InV = 0;
1901       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1902         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1903           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1904         else
1905           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1906       } else {
1907         assert(PN->getIncomingBlock(i) == NonConstBB);
1908         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1909           InV = BinaryOperator::create(BO->getOpcode(),
1910                                        PN->getIncomingValue(i), C, "phitmp",
1911                                        NonConstBB->getTerminator());
1912         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1913           InV = CmpInst::create(CI->getOpcode(), 
1914                                 CI->getPredicate(),
1915                                 PN->getIncomingValue(i), C, "phitmp",
1916                                 NonConstBB->getTerminator());
1917         else
1918           assert(0 && "Unknown binop!");
1919         
1920         AddToWorkList(cast<Instruction>(InV));
1921       }
1922       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1923     }
1924   } else { 
1925     CastInst *CI = cast<CastInst>(&I);
1926     const Type *RetTy = CI->getType();
1927     for (unsigned i = 0; i != NumPHIValues; ++i) {
1928       Value *InV;
1929       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1930         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1931       } else {
1932         assert(PN->getIncomingBlock(i) == NonConstBB);
1933         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1934                                I.getType(), "phitmp", 
1935                                NonConstBB->getTerminator());
1936         AddToWorkList(cast<Instruction>(InV));
1937       }
1938       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1939     }
1940   }
1941   return ReplaceInstUsesWith(I, NewPN);
1942 }
1943
1944 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1945   bool Changed = SimplifyCommutative(I);
1946   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1947
1948   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1949     // X + undef -> undef
1950     if (isa<UndefValue>(RHS))
1951       return ReplaceInstUsesWith(I, RHS);
1952
1953     // X + 0 --> X
1954     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1955       if (RHSC->isNullValue())
1956         return ReplaceInstUsesWith(I, LHS);
1957     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1958       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1959                               (I.getType())->getValueAPF()))
1960         return ReplaceInstUsesWith(I, LHS);
1961     }
1962
1963     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1964       // X + (signbit) --> X ^ signbit
1965       const APInt& Val = CI->getValue();
1966       uint32_t BitWidth = Val.getBitWidth();
1967       if (Val == APInt::getSignBit(BitWidth))
1968         return BinaryOperator::createXor(LHS, RHS);
1969       
1970       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1971       // (X & 254)+1 -> (X&254)|1
1972       if (!isa<VectorType>(I.getType())) {
1973         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1974         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1975                                  KnownZero, KnownOne))
1976           return &I;
1977       }
1978     }
1979
1980     if (isa<PHINode>(LHS))
1981       if (Instruction *NV = FoldOpIntoPhi(I))
1982         return NV;
1983     
1984     ConstantInt *XorRHS = 0;
1985     Value *XorLHS = 0;
1986     if (isa<ConstantInt>(RHSC) &&
1987         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1988       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1989       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1990       
1991       uint32_t Size = TySizeBits / 2;
1992       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1993       APInt CFF80Val(-C0080Val);
1994       do {
1995         if (TySizeBits > Size) {
1996           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1997           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1998           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1999               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2000             // This is a sign extend if the top bits are known zero.
2001             if (!MaskedValueIsZero(XorLHS, 
2002                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2003               Size = 0;  // Not a sign ext, but can't be any others either.
2004             break;
2005           }
2006         }
2007         Size >>= 1;
2008         C0080Val = APIntOps::lshr(C0080Val, Size);
2009         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2010       } while (Size >= 1);
2011       
2012       // FIXME: This shouldn't be necessary. When the backends can handle types
2013       // with funny bit widths then this whole cascade of if statements should
2014       // be removed. It is just here to get the size of the "middle" type back
2015       // up to something that the back ends can handle.
2016       const Type *MiddleType = 0;
2017       switch (Size) {
2018         default: break;
2019         case 32: MiddleType = Type::Int32Ty; break;
2020         case 16: MiddleType = Type::Int16Ty; break;
2021         case  8: MiddleType = Type::Int8Ty; break;
2022       }
2023       if (MiddleType) {
2024         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2025         InsertNewInstBefore(NewTrunc, I);
2026         return new SExtInst(NewTrunc, I.getType(), I.getName());
2027       }
2028     }
2029   }
2030
2031   // X + X --> X << 1
2032   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2033     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2034
2035     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2036       if (RHSI->getOpcode() == Instruction::Sub)
2037         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2038           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2039     }
2040     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2041       if (LHSI->getOpcode() == Instruction::Sub)
2042         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2043           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2044     }
2045   }
2046
2047   // -A + B  -->  B - A
2048   if (Value *V = dyn_castNegVal(LHS))
2049     return BinaryOperator::createSub(RHS, V);
2050
2051   // A + -B  -->  A - B
2052   if (!isa<Constant>(RHS))
2053     if (Value *V = dyn_castNegVal(RHS))
2054       return BinaryOperator::createSub(LHS, V);
2055
2056
2057   ConstantInt *C2;
2058   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2059     if (X == RHS)   // X*C + X --> X * (C+1)
2060       return BinaryOperator::createMul(RHS, AddOne(C2));
2061
2062     // X*C1 + X*C2 --> X * (C1+C2)
2063     ConstantInt *C1;
2064     if (X == dyn_castFoldableMul(RHS, C1))
2065       return BinaryOperator::createMul(X, Add(C1, C2));
2066   }
2067
2068   // X + X*C --> X * (C+1)
2069   if (dyn_castFoldableMul(RHS, C2) == LHS)
2070     return BinaryOperator::createMul(LHS, AddOne(C2));
2071
2072   // X + ~X --> -1   since   ~X = -X-1
2073   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2074     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2075   
2076
2077   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2078   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2079     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2080       return R;
2081
2082   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2083     Value *X = 0;
2084     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2085       return BinaryOperator::createSub(SubOne(CRHS), X);
2086
2087     // (X & FF00) + xx00  -> (X+xx00) & FF00
2088     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2089       Constant *Anded = And(CRHS, C2);
2090       if (Anded == CRHS) {
2091         // See if all bits from the first bit set in the Add RHS up are included
2092         // in the mask.  First, get the rightmost bit.
2093         const APInt& AddRHSV = CRHS->getValue();
2094
2095         // Form a mask of all bits from the lowest bit added through the top.
2096         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2097
2098         // See if the and mask includes all of these bits.
2099         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2100
2101         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2102           // Okay, the xform is safe.  Insert the new add pronto.
2103           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2104                                                             LHS->getName()), I);
2105           return BinaryOperator::createAnd(NewAdd, C2);
2106         }
2107       }
2108     }
2109
2110     // Try to fold constant add into select arguments.
2111     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2112       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2113         return R;
2114   }
2115
2116   // add (cast *A to intptrtype) B -> 
2117   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2118   {
2119     CastInst *CI = dyn_cast<CastInst>(LHS);
2120     Value *Other = RHS;
2121     if (!CI) {
2122       CI = dyn_cast<CastInst>(RHS);
2123       Other = LHS;
2124     }
2125     if (CI && CI->getType()->isSized() && 
2126         (CI->getType()->getPrimitiveSizeInBits() == 
2127          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2128         && isa<PointerType>(CI->getOperand(0)->getType())) {
2129       unsigned AS =
2130         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2131       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2132                                       PointerType::get(Type::Int8Ty, AS), I);
2133       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2134       return new PtrToIntInst(I2, CI->getType());
2135     }
2136   }
2137   
2138   // add (select X 0 (sub n A)) A  -->  select X A n
2139   {
2140     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2141     Value *Other = RHS;
2142     if (!SI) {
2143       SI = dyn_cast<SelectInst>(RHS);
2144       Other = LHS;
2145     }
2146     if (SI && SI->hasOneUse()) {
2147       Value *TV = SI->getTrueValue();
2148       Value *FV = SI->getFalseValue();
2149       Value *A, *N;
2150
2151       // Can we fold the add into the argument of the select?
2152       // We check both true and false select arguments for a matching subtract.
2153       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2154           A == Other)  // Fold the add into the true select value.
2155         return new SelectInst(SI->getCondition(), N, A);
2156       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2157           A == Other)  // Fold the add into the false select value.
2158         return new SelectInst(SI->getCondition(), A, N);
2159     }
2160   }
2161
2162   return Changed ? &I : 0;
2163 }
2164
2165 // isSignBit - Return true if the value represented by the constant only has the
2166 // highest order bit set.
2167 static bool isSignBit(ConstantInt *CI) {
2168   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2169   return CI->getValue() == APInt::getSignBit(NumBits);
2170 }
2171
2172 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2173   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2174
2175   if (Op0 == Op1)         // sub X, X  -> 0
2176     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2177
2178   // If this is a 'B = x-(-A)', change to B = x+A...
2179   if (Value *V = dyn_castNegVal(Op1))
2180     return BinaryOperator::createAdd(Op0, V);
2181
2182   if (isa<UndefValue>(Op0))
2183     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2184   if (isa<UndefValue>(Op1))
2185     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2186
2187   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2188     // Replace (-1 - A) with (~A)...
2189     if (C->isAllOnesValue())
2190       return BinaryOperator::createNot(Op1);
2191
2192     // C - ~X == X + (1+C)
2193     Value *X = 0;
2194     if (match(Op1, m_Not(m_Value(X))))
2195       return BinaryOperator::createAdd(X, AddOne(C));
2196
2197     // -(X >>u 31) -> (X >>s 31)
2198     // -(X >>s 31) -> (X >>u 31)
2199     if (C->isZero()) {
2200       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2201         if (SI->getOpcode() == Instruction::LShr) {
2202           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2203             // Check to see if we are shifting out everything but the sign bit.
2204             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2205                 SI->getType()->getPrimitiveSizeInBits()-1) {
2206               // Ok, the transformation is safe.  Insert AShr.
2207               return BinaryOperator::create(Instruction::AShr, 
2208                                           SI->getOperand(0), CU, SI->getName());
2209             }
2210           }
2211         }
2212         else if (SI->getOpcode() == Instruction::AShr) {
2213           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2214             // Check to see if we are shifting out everything but the sign bit.
2215             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2216                 SI->getType()->getPrimitiveSizeInBits()-1) {
2217               // Ok, the transformation is safe.  Insert LShr. 
2218               return BinaryOperator::createLShr(
2219                                           SI->getOperand(0), CU, SI->getName());
2220             }
2221           }
2222         } 
2223     }
2224
2225     // Try to fold constant sub into select arguments.
2226     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2227       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2228         return R;
2229
2230     if (isa<PHINode>(Op0))
2231       if (Instruction *NV = FoldOpIntoPhi(I))
2232         return NV;
2233   }
2234
2235   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2236     if (Op1I->getOpcode() == Instruction::Add &&
2237         !Op0->getType()->isFPOrFPVector()) {
2238       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2239         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2240       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2241         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2242       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2243         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2244           // C1-(X+C2) --> (C1-C2)-X
2245           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2246                                            Op1I->getOperand(0));
2247       }
2248     }
2249
2250     if (Op1I->hasOneUse()) {
2251       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2252       // is not used by anyone else...
2253       //
2254       if (Op1I->getOpcode() == Instruction::Sub &&
2255           !Op1I->getType()->isFPOrFPVector()) {
2256         // Swap the two operands of the subexpr...
2257         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2258         Op1I->setOperand(0, IIOp1);
2259         Op1I->setOperand(1, IIOp0);
2260
2261         // Create the new top level add instruction...
2262         return BinaryOperator::createAdd(Op0, Op1);
2263       }
2264
2265       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2266       //
2267       if (Op1I->getOpcode() == Instruction::And &&
2268           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2269         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2270
2271         Value *NewNot =
2272           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2273         return BinaryOperator::createAnd(Op0, NewNot);
2274       }
2275
2276       // 0 - (X sdiv C)  -> (X sdiv -C)
2277       if (Op1I->getOpcode() == Instruction::SDiv)
2278         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2279           if (CSI->isZero())
2280             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2281               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2282                                                ConstantExpr::getNeg(DivRHS));
2283
2284       // X - X*C --> X * (1-C)
2285       ConstantInt *C2 = 0;
2286       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2287         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2288         return BinaryOperator::createMul(Op0, CP1);
2289       }
2290
2291       // X - ((X / Y) * Y) --> X % Y
2292       if (Op1I->getOpcode() == Instruction::Mul)
2293         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2294           if (Op0 == I->getOperand(0) &&
2295               Op1I->getOperand(1) == I->getOperand(1)) {
2296             if (I->getOpcode() == Instruction::SDiv)
2297               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2298             if (I->getOpcode() == Instruction::UDiv)
2299               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2300           }
2301     }
2302   }
2303
2304   if (!Op0->getType()->isFPOrFPVector())
2305     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2306       if (Op0I->getOpcode() == Instruction::Add) {
2307         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2308           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2309         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2310           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2311       } else if (Op0I->getOpcode() == Instruction::Sub) {
2312         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2313           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2314       }
2315
2316   ConstantInt *C1;
2317   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2318     if (X == Op1)  // X*C - X --> X * (C-1)
2319       return BinaryOperator::createMul(Op1, SubOne(C1));
2320
2321     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2322     if (X == dyn_castFoldableMul(Op1, C2))
2323       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2324   }
2325   return 0;
2326 }
2327
2328 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2329 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2330 /// TrueIfSigned if the result of the comparison is true when the input value is
2331 /// signed.
2332 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2333                            bool &TrueIfSigned) {
2334   switch (pred) {
2335   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2336     TrueIfSigned = true;
2337     return RHS->isZero();
2338   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2339     TrueIfSigned = true;
2340     return RHS->isAllOnesValue();
2341   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2342     TrueIfSigned = false;
2343     return RHS->isAllOnesValue();
2344   case ICmpInst::ICMP_UGT:
2345     // True if LHS u> RHS and RHS == high-bit-mask - 1
2346     TrueIfSigned = true;
2347     return RHS->getValue() ==
2348       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2349   case ICmpInst::ICMP_UGE: 
2350     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2351     TrueIfSigned = true;
2352     return RHS->getValue() == 
2353       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2354   default:
2355     return false;
2356   }
2357 }
2358
2359 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2360   bool Changed = SimplifyCommutative(I);
2361   Value *Op0 = I.getOperand(0);
2362
2363   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2364     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2365
2366   // Simplify mul instructions with a constant RHS...
2367   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2368     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2369
2370       // ((X << C1)*C2) == (X * (C2 << C1))
2371       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2372         if (SI->getOpcode() == Instruction::Shl)
2373           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2374             return BinaryOperator::createMul(SI->getOperand(0),
2375                                              ConstantExpr::getShl(CI, ShOp));
2376
2377       if (CI->isZero())
2378         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2379       if (CI->equalsInt(1))                  // X * 1  == X
2380         return ReplaceInstUsesWith(I, Op0);
2381       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2382         return BinaryOperator::createNeg(Op0, I.getName());
2383
2384       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2385       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2386         return BinaryOperator::createShl(Op0,
2387                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2388       }
2389     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2390       if (Op1F->isNullValue())
2391         return ReplaceInstUsesWith(I, Op1);
2392
2393       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2394       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2395       // We need a better interface for long double here.
2396       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2397         if (Op1F->isExactlyValue(1.0))
2398           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2399     }
2400     
2401     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2402       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2403           isa<ConstantInt>(Op0I->getOperand(1))) {
2404         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2405         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2406                                                      Op1, "tmp");
2407         InsertNewInstBefore(Add, I);
2408         Value *C1C2 = ConstantExpr::getMul(Op1, 
2409                                            cast<Constant>(Op0I->getOperand(1)));
2410         return BinaryOperator::createAdd(Add, C1C2);
2411         
2412       }
2413
2414     // Try to fold constant mul into select arguments.
2415     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2416       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2417         return R;
2418
2419     if (isa<PHINode>(Op0))
2420       if (Instruction *NV = FoldOpIntoPhi(I))
2421         return NV;
2422   }
2423
2424   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2425     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2426       return BinaryOperator::createMul(Op0v, Op1v);
2427
2428   // If one of the operands of the multiply is a cast from a boolean value, then
2429   // we know the bool is either zero or one, so this is a 'masking' multiply.
2430   // See if we can simplify things based on how the boolean was originally
2431   // formed.
2432   CastInst *BoolCast = 0;
2433   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2434     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2435       BoolCast = CI;
2436   if (!BoolCast)
2437     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2438       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2439         BoolCast = CI;
2440   if (BoolCast) {
2441     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2442       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2443       const Type *SCOpTy = SCIOp0->getType();
2444       bool TIS = false;
2445       
2446       // If the icmp is true iff the sign bit of X is set, then convert this
2447       // multiply into a shift/and combination.
2448       if (isa<ConstantInt>(SCIOp1) &&
2449           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2450           TIS) {
2451         // Shift the X value right to turn it into "all signbits".
2452         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2453                                           SCOpTy->getPrimitiveSizeInBits()-1);
2454         Value *V =
2455           InsertNewInstBefore(
2456             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2457                                             BoolCast->getOperand(0)->getName()+
2458                                             ".mask"), I);
2459
2460         // If the multiply type is not the same as the source type, sign extend
2461         // or truncate to the multiply type.
2462         if (I.getType() != V->getType()) {
2463           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2464           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2465           Instruction::CastOps opcode = 
2466             (SrcBits == DstBits ? Instruction::BitCast : 
2467              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2468           V = InsertCastBefore(opcode, V, I.getType(), I);
2469         }
2470
2471         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2472         return BinaryOperator::createAnd(V, OtherOp);
2473       }
2474     }
2475   }
2476
2477   return Changed ? &I : 0;
2478 }
2479
2480 /// This function implements the transforms on div instructions that work
2481 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2482 /// used by the visitors to those instructions.
2483 /// @brief Transforms common to all three div instructions
2484 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2485   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2486
2487   // undef / X -> 0
2488   if (isa<UndefValue>(Op0))
2489     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2490
2491   // X / undef -> undef
2492   if (isa<UndefValue>(Op1))
2493     return ReplaceInstUsesWith(I, Op1);
2494
2495   // Handle cases involving: div X, (select Cond, Y, Z)
2496   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2497     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2498     // same basic block, then we replace the select with Y, and the condition 
2499     // of the select with false (if the cond value is in the same BB).  If the
2500     // select has uses other than the div, this allows them to be simplified
2501     // also. Note that div X, Y is just as good as div X, 0 (undef)
2502     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2503       if (ST->isNullValue()) {
2504         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2505         if (CondI && CondI->getParent() == I.getParent())
2506           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2507         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2508           I.setOperand(1, SI->getOperand(2));
2509         else
2510           UpdateValueUsesWith(SI, SI->getOperand(2));
2511         return &I;
2512       }
2513
2514     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2515     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2516       if (ST->isNullValue()) {
2517         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2518         if (CondI && CondI->getParent() == I.getParent())
2519           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2520         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2521           I.setOperand(1, SI->getOperand(1));
2522         else
2523           UpdateValueUsesWith(SI, SI->getOperand(1));
2524         return &I;
2525       }
2526   }
2527
2528   return 0;
2529 }
2530
2531 /// This function implements the transforms common to both integer division
2532 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2533 /// division instructions.
2534 /// @brief Common integer divide transforms
2535 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2536   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2537
2538   if (Instruction *Common = commonDivTransforms(I))
2539     return Common;
2540
2541   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2542     // div X, 1 == X
2543     if (RHS->equalsInt(1))
2544       return ReplaceInstUsesWith(I, Op0);
2545
2546     // (X / C1) / C2  -> X / (C1*C2)
2547     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2548       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2549         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2550           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2551                                         Multiply(RHS, LHSRHS));
2552         }
2553
2554     if (!RHS->isZero()) { // avoid X udiv 0
2555       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2556         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2557           return R;
2558       if (isa<PHINode>(Op0))
2559         if (Instruction *NV = FoldOpIntoPhi(I))
2560           return NV;
2561     }
2562   }
2563
2564   // 0 / X == 0, we don't need to preserve faults!
2565   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2566     if (LHS->equalsInt(0))
2567       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2568
2569   return 0;
2570 }
2571
2572 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2573   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2574
2575   // Handle the integer div common cases
2576   if (Instruction *Common = commonIDivTransforms(I))
2577     return Common;
2578
2579   // X udiv C^2 -> X >> C
2580   // Check to see if this is an unsigned division with an exact power of 2,
2581   // if so, convert to a right shift.
2582   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2583     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2584       return BinaryOperator::createLShr(Op0, 
2585                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2586   }
2587
2588   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2589   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2590     if (RHSI->getOpcode() == Instruction::Shl &&
2591         isa<ConstantInt>(RHSI->getOperand(0))) {
2592       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2593       if (C1.isPowerOf2()) {
2594         Value *N = RHSI->getOperand(1);
2595         const Type *NTy = N->getType();
2596         if (uint32_t C2 = C1.logBase2()) {
2597           Constant *C2V = ConstantInt::get(NTy, C2);
2598           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2599         }
2600         return BinaryOperator::createLShr(Op0, N);
2601       }
2602     }
2603   }
2604   
2605   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2606   // where C1&C2 are powers of two.
2607   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2608     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2609       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2610         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2611         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2612           // Compute the shift amounts
2613           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2614           // Construct the "on true" case of the select
2615           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2616           Instruction *TSI = BinaryOperator::createLShr(
2617                                                  Op0, TC, SI->getName()+".t");
2618           TSI = InsertNewInstBefore(TSI, I);
2619   
2620           // Construct the "on false" case of the select
2621           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2622           Instruction *FSI = BinaryOperator::createLShr(
2623                                                  Op0, FC, SI->getName()+".f");
2624           FSI = InsertNewInstBefore(FSI, I);
2625
2626           // construct the select instruction and return it.
2627           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2628         }
2629       }
2630   return 0;
2631 }
2632
2633 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2634   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2635
2636   // Handle the integer div common cases
2637   if (Instruction *Common = commonIDivTransforms(I))
2638     return Common;
2639
2640   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2641     // sdiv X, -1 == -X
2642     if (RHS->isAllOnesValue())
2643       return BinaryOperator::createNeg(Op0);
2644
2645     // -X/C -> X/-C
2646     if (Value *LHSNeg = dyn_castNegVal(Op0))
2647       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2648   }
2649
2650   // If the sign bits of both operands are zero (i.e. we can prove they are
2651   // unsigned inputs), turn this into a udiv.
2652   if (I.getType()->isInteger()) {
2653     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2654     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2655       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2656       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2657     }
2658   }      
2659   
2660   return 0;
2661 }
2662
2663 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2664   return commonDivTransforms(I);
2665 }
2666
2667 /// GetFactor - If we can prove that the specified value is at least a multiple
2668 /// of some factor, return that factor.
2669 static Constant *GetFactor(Value *V) {
2670   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2671     return CI;
2672   
2673   // Unless we can be tricky, we know this is a multiple of 1.
2674   Constant *Result = ConstantInt::get(V->getType(), 1);
2675   
2676   Instruction *I = dyn_cast<Instruction>(V);
2677   if (!I) return Result;
2678   
2679   if (I->getOpcode() == Instruction::Mul) {
2680     // Handle multiplies by a constant, etc.
2681     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2682                                 GetFactor(I->getOperand(1)));
2683   } else if (I->getOpcode() == Instruction::Shl) {
2684     // (X<<C) -> X * (1 << C)
2685     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2686       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2687       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2688     }
2689   } else if (I->getOpcode() == Instruction::And) {
2690     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2691       // X & 0xFFF0 is known to be a multiple of 16.
2692       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2693       if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
2694         return ConstantExpr::getShl(Result, 
2695                                     ConstantInt::get(Result->getType(), Zeros));
2696     }
2697   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2698     // Only handle int->int casts.
2699     if (!CI->isIntegerCast())
2700       return Result;
2701     Value *Op = CI->getOperand(0);
2702     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2703   }    
2704   return Result;
2705 }
2706
2707 /// This function implements the transforms on rem instructions that work
2708 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2709 /// is used by the visitors to those instructions.
2710 /// @brief Transforms common to all three rem instructions
2711 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2712   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2713
2714   // 0 % X == 0, we don't need to preserve faults!
2715   if (Constant *LHS = dyn_cast<Constant>(Op0))
2716     if (LHS->isNullValue())
2717       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2718
2719   if (isa<UndefValue>(Op0))              // undef % X -> 0
2720     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2721   if (isa<UndefValue>(Op1))
2722     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2723
2724   // Handle cases involving: rem X, (select Cond, Y, Z)
2725   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2726     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2727     // the same basic block, then we replace the select with Y, and the
2728     // condition of the select with false (if the cond value is in the same
2729     // BB).  If the select has uses other than the div, this allows them to be
2730     // simplified also.
2731     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2732       if (ST->isNullValue()) {
2733         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2734         if (CondI && CondI->getParent() == I.getParent())
2735           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2736         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2737           I.setOperand(1, SI->getOperand(2));
2738         else
2739           UpdateValueUsesWith(SI, SI->getOperand(2));
2740         return &I;
2741       }
2742     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2743     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2744       if (ST->isNullValue()) {
2745         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2746         if (CondI && CondI->getParent() == I.getParent())
2747           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2748         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2749           I.setOperand(1, SI->getOperand(1));
2750         else
2751           UpdateValueUsesWith(SI, SI->getOperand(1));
2752         return &I;
2753       }
2754   }
2755
2756   return 0;
2757 }
2758
2759 /// This function implements the transforms common to both integer remainder
2760 /// instructions (urem and srem). It is called by the visitors to those integer
2761 /// remainder instructions.
2762 /// @brief Common integer remainder transforms
2763 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2764   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2765
2766   if (Instruction *common = commonRemTransforms(I))
2767     return common;
2768
2769   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2770     // X % 0 == undef, we don't need to preserve faults!
2771     if (RHS->equalsInt(0))
2772       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2773     
2774     if (RHS->equalsInt(1))  // X % 1 == 0
2775       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2776
2777     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2778       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2779         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2780           return R;
2781       } else if (isa<PHINode>(Op0I)) {
2782         if (Instruction *NV = FoldOpIntoPhi(I))
2783           return NV;
2784       }
2785       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2786       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2787         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2788     }
2789   }
2790
2791   return 0;
2792 }
2793
2794 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2795   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2796
2797   if (Instruction *common = commonIRemTransforms(I))
2798     return common;
2799   
2800   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2801     // X urem C^2 -> X and C
2802     // Check to see if this is an unsigned remainder with an exact power of 2,
2803     // if so, convert to a bitwise and.
2804     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2805       if (C->getValue().isPowerOf2())
2806         return BinaryOperator::createAnd(Op0, SubOne(C));
2807   }
2808
2809   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2810     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2811     if (RHSI->getOpcode() == Instruction::Shl &&
2812         isa<ConstantInt>(RHSI->getOperand(0))) {
2813       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2814         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2815         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2816                                                                    "tmp"), I);
2817         return BinaryOperator::createAnd(Op0, Add);
2818       }
2819     }
2820   }
2821
2822   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2823   // where C1&C2 are powers of two.
2824   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2825     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2826       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2827         // STO == 0 and SFO == 0 handled above.
2828         if ((STO->getValue().isPowerOf2()) && 
2829             (SFO->getValue().isPowerOf2())) {
2830           Value *TrueAnd = InsertNewInstBefore(
2831             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2832           Value *FalseAnd = InsertNewInstBefore(
2833             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2834           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2835         }
2836       }
2837   }
2838   
2839   return 0;
2840 }
2841
2842 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2843   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2844
2845   // Handle the integer rem common cases
2846   if (Instruction *common = commonIRemTransforms(I))
2847     return common;
2848   
2849   if (Value *RHSNeg = dyn_castNegVal(Op1))
2850     if (!isa<ConstantInt>(RHSNeg) || 
2851         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2852       // X % -Y -> X % Y
2853       AddUsesToWorkList(I);
2854       I.setOperand(1, RHSNeg);
2855       return &I;
2856     }
2857  
2858   // If the sign bits of both operands are zero (i.e. we can prove they are
2859   // unsigned inputs), turn this into a urem.
2860   if (I.getType()->isInteger()) {
2861     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2862     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2863       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2864       return BinaryOperator::createURem(Op0, Op1, I.getName());
2865     }
2866   }
2867
2868   return 0;
2869 }
2870
2871 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2872   return commonRemTransforms(I);
2873 }
2874
2875 // isMaxValueMinusOne - return true if this is Max-1
2876 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2877   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2878   if (!isSigned)
2879     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2880   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2881 }
2882
2883 // isMinValuePlusOne - return true if this is Min+1
2884 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2885   if (!isSigned)
2886     return C->getValue() == 1; // unsigned
2887     
2888   // Calculate 1111111111000000000000
2889   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2890   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2891 }
2892
2893 // isOneBitSet - Return true if there is exactly one bit set in the specified
2894 // constant.
2895 static bool isOneBitSet(const ConstantInt *CI) {
2896   return CI->getValue().isPowerOf2();
2897 }
2898
2899 // isHighOnes - Return true if the constant is of the form 1+0+.
2900 // This is the same as lowones(~X).
2901 static bool isHighOnes(const ConstantInt *CI) {
2902   return (~CI->getValue() + 1).isPowerOf2();
2903 }
2904
2905 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2906 /// are carefully arranged to allow folding of expressions such as:
2907 ///
2908 ///      (A < B) | (A > B) --> (A != B)
2909 ///
2910 /// Note that this is only valid if the first and second predicates have the
2911 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2912 ///
2913 /// Three bits are used to represent the condition, as follows:
2914 ///   0  A > B
2915 ///   1  A == B
2916 ///   2  A < B
2917 ///
2918 /// <=>  Value  Definition
2919 /// 000     0   Always false
2920 /// 001     1   A >  B
2921 /// 010     2   A == B
2922 /// 011     3   A >= B
2923 /// 100     4   A <  B
2924 /// 101     5   A != B
2925 /// 110     6   A <= B
2926 /// 111     7   Always true
2927 ///  
2928 static unsigned getICmpCode(const ICmpInst *ICI) {
2929   switch (ICI->getPredicate()) {
2930     // False -> 0
2931   case ICmpInst::ICMP_UGT: return 1;  // 001
2932   case ICmpInst::ICMP_SGT: return 1;  // 001
2933   case ICmpInst::ICMP_EQ:  return 2;  // 010
2934   case ICmpInst::ICMP_UGE: return 3;  // 011
2935   case ICmpInst::ICMP_SGE: return 3;  // 011
2936   case ICmpInst::ICMP_ULT: return 4;  // 100
2937   case ICmpInst::ICMP_SLT: return 4;  // 100
2938   case ICmpInst::ICMP_NE:  return 5;  // 101
2939   case ICmpInst::ICMP_ULE: return 6;  // 110
2940   case ICmpInst::ICMP_SLE: return 6;  // 110
2941     // True -> 7
2942   default:
2943     assert(0 && "Invalid ICmp predicate!");
2944     return 0;
2945   }
2946 }
2947
2948 /// getICmpValue - This is the complement of getICmpCode, which turns an
2949 /// opcode and two operands into either a constant true or false, or a brand 
2950 /// new ICmp instruction. The sign is passed in to determine which kind
2951 /// of predicate to use in new icmp instructions.
2952 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2953   switch (code) {
2954   default: assert(0 && "Illegal ICmp code!");
2955   case  0: return ConstantInt::getFalse();
2956   case  1: 
2957     if (sign)
2958       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2959     else
2960       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2961   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2962   case  3: 
2963     if (sign)
2964       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2965     else
2966       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2967   case  4: 
2968     if (sign)
2969       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2970     else
2971       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2972   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2973   case  6: 
2974     if (sign)
2975       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2976     else
2977       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2978   case  7: return ConstantInt::getTrue();
2979   }
2980 }
2981
2982 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2983   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2984     (ICmpInst::isSignedPredicate(p1) && 
2985      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2986     (ICmpInst::isSignedPredicate(p2) && 
2987      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2988 }
2989
2990 namespace { 
2991 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2992 struct FoldICmpLogical {
2993   InstCombiner &IC;
2994   Value *LHS, *RHS;
2995   ICmpInst::Predicate pred;
2996   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2997     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2998       pred(ICI->getPredicate()) {}
2999   bool shouldApply(Value *V) const {
3000     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3001       if (PredicatesFoldable(pred, ICI->getPredicate()))
3002         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3003                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3004     return false;
3005   }
3006   Instruction *apply(Instruction &Log) const {
3007     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3008     if (ICI->getOperand(0) != LHS) {
3009       assert(ICI->getOperand(1) == LHS);
3010       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3011     }
3012
3013     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3014     unsigned LHSCode = getICmpCode(ICI);
3015     unsigned RHSCode = getICmpCode(RHSICI);
3016     unsigned Code;
3017     switch (Log.getOpcode()) {
3018     case Instruction::And: Code = LHSCode & RHSCode; break;
3019     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3020     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3021     default: assert(0 && "Illegal logical opcode!"); return 0;
3022     }
3023
3024     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3025                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3026       
3027     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3028     if (Instruction *I = dyn_cast<Instruction>(RV))
3029       return I;
3030     // Otherwise, it's a constant boolean value...
3031     return IC.ReplaceInstUsesWith(Log, RV);
3032   }
3033 };
3034 } // end anonymous namespace
3035
3036 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3037 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3038 // guaranteed to be a binary operator.
3039 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3040                                     ConstantInt *OpRHS,
3041                                     ConstantInt *AndRHS,
3042                                     BinaryOperator &TheAnd) {
3043   Value *X = Op->getOperand(0);
3044   Constant *Together = 0;
3045   if (!Op->isShift())
3046     Together = And(AndRHS, OpRHS);
3047
3048   switch (Op->getOpcode()) {
3049   case Instruction::Xor:
3050     if (Op->hasOneUse()) {
3051       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3052       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3053       InsertNewInstBefore(And, TheAnd);
3054       And->takeName(Op);
3055       return BinaryOperator::createXor(And, Together);
3056     }
3057     break;
3058   case Instruction::Or:
3059     if (Together == AndRHS) // (X | C) & C --> C
3060       return ReplaceInstUsesWith(TheAnd, AndRHS);
3061
3062     if (Op->hasOneUse() && Together != OpRHS) {
3063       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3064       Instruction *Or = BinaryOperator::createOr(X, Together);
3065       InsertNewInstBefore(Or, TheAnd);
3066       Or->takeName(Op);
3067       return BinaryOperator::createAnd(Or, AndRHS);
3068     }
3069     break;
3070   case Instruction::Add:
3071     if (Op->hasOneUse()) {
3072       // Adding a one to a single bit bit-field should be turned into an XOR
3073       // of the bit.  First thing to check is to see if this AND is with a
3074       // single bit constant.
3075       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3076
3077       // If there is only one bit set...
3078       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3079         // Ok, at this point, we know that we are masking the result of the
3080         // ADD down to exactly one bit.  If the constant we are adding has
3081         // no bits set below this bit, then we can eliminate the ADD.
3082         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3083
3084         // Check to see if any bits below the one bit set in AndRHSV are set.
3085         if ((AddRHS & (AndRHSV-1)) == 0) {
3086           // If not, the only thing that can effect the output of the AND is
3087           // the bit specified by AndRHSV.  If that bit is set, the effect of
3088           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3089           // no effect.
3090           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3091             TheAnd.setOperand(0, X);
3092             return &TheAnd;
3093           } else {
3094             // Pull the XOR out of the AND.
3095             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3096             InsertNewInstBefore(NewAnd, TheAnd);
3097             NewAnd->takeName(Op);
3098             return BinaryOperator::createXor(NewAnd, AndRHS);
3099           }
3100         }
3101       }
3102     }
3103     break;
3104
3105   case Instruction::Shl: {
3106     // We know that the AND will not produce any of the bits shifted in, so if
3107     // the anded constant includes them, clear them now!
3108     //
3109     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3110     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3111     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3112     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3113
3114     if (CI->getValue() == ShlMask) { 
3115     // Masking out bits that the shift already masks
3116       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3117     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3118       TheAnd.setOperand(1, CI);
3119       return &TheAnd;
3120     }
3121     break;
3122   }
3123   case Instruction::LShr:
3124   {
3125     // We know that the AND will not produce any of the bits shifted in, so if
3126     // the anded constant includes them, clear them now!  This only applies to
3127     // unsigned shifts, because a signed shr may bring in set bits!
3128     //
3129     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3130     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3131     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3132     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3133
3134     if (CI->getValue() == ShrMask) {   
3135     // Masking out bits that the shift already masks.
3136       return ReplaceInstUsesWith(TheAnd, Op);
3137     } else if (CI != AndRHS) {
3138       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3139       return &TheAnd;
3140     }
3141     break;
3142   }
3143   case Instruction::AShr:
3144     // Signed shr.
3145     // See if this is shifting in some sign extension, then masking it out
3146     // with an and.
3147     if (Op->hasOneUse()) {
3148       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3149       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3150       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3151       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3152       if (C == AndRHS) {          // Masking out bits shifted in.
3153         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3154         // Make the argument unsigned.
3155         Value *ShVal = Op->getOperand(0);
3156         ShVal = InsertNewInstBefore(
3157             BinaryOperator::createLShr(ShVal, OpRHS, 
3158                                    Op->getName()), TheAnd);
3159         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3160       }
3161     }
3162     break;
3163   }
3164   return 0;
3165 }
3166
3167
3168 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3169 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3170 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3171 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3172 /// insert new instructions.
3173 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3174                                            bool isSigned, bool Inside, 
3175                                            Instruction &IB) {
3176   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3177             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3178          "Lo is not <= Hi in range emission code!");
3179     
3180   if (Inside) {
3181     if (Lo == Hi)  // Trivially false.
3182       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3183
3184     // V >= Min && V < Hi --> V < Hi
3185     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3186       ICmpInst::Predicate pred = (isSigned ? 
3187         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3188       return new ICmpInst(pred, V, Hi);
3189     }
3190
3191     // Emit V-Lo <u Hi-Lo
3192     Constant *NegLo = ConstantExpr::getNeg(Lo);
3193     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3194     InsertNewInstBefore(Add, IB);
3195     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3196     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3197   }
3198
3199   if (Lo == Hi)  // Trivially true.
3200     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3201
3202   // V < Min || V >= Hi -> V > Hi-1
3203   Hi = SubOne(cast<ConstantInt>(Hi));
3204   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3205     ICmpInst::Predicate pred = (isSigned ? 
3206         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3207     return new ICmpInst(pred, V, Hi);
3208   }
3209
3210   // Emit V-Lo >u Hi-1-Lo
3211   // Note that Hi has already had one subtracted from it, above.
3212   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3213   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3214   InsertNewInstBefore(Add, IB);
3215   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3216   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3217 }
3218
3219 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3220 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3221 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3222 // not, since all 1s are not contiguous.
3223 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3224   const APInt& V = Val->getValue();
3225   uint32_t BitWidth = Val->getType()->getBitWidth();
3226   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3227
3228   // look for the first zero bit after the run of ones
3229   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3230   // look for the first non-zero bit
3231   ME = V.getActiveBits(); 
3232   return true;
3233 }
3234
3235 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3236 /// where isSub determines whether the operator is a sub.  If we can fold one of
3237 /// the following xforms:
3238 /// 
3239 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3240 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3241 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3242 ///
3243 /// return (A +/- B).
3244 ///
3245 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3246                                         ConstantInt *Mask, bool isSub,
3247                                         Instruction &I) {
3248   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3249   if (!LHSI || LHSI->getNumOperands() != 2 ||
3250       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3251
3252   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3253
3254   switch (LHSI->getOpcode()) {
3255   default: return 0;
3256   case Instruction::And:
3257     if (And(N, Mask) == Mask) {
3258       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3259       if ((Mask->getValue().countLeadingZeros() + 
3260            Mask->getValue().countPopulation()) == 
3261           Mask->getValue().getBitWidth())
3262         break;
3263
3264       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3265       // part, we don't need any explicit masks to take them out of A.  If that
3266       // is all N is, ignore it.
3267       uint32_t MB = 0, ME = 0;
3268       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3269         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3270         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3271         if (MaskedValueIsZero(RHS, Mask))
3272           break;
3273       }
3274     }
3275     return 0;
3276   case Instruction::Or:
3277   case Instruction::Xor:
3278     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3279     if ((Mask->getValue().countLeadingZeros() + 
3280          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3281         && And(N, Mask)->isZero())
3282       break;
3283     return 0;
3284   }
3285   
3286   Instruction *New;
3287   if (isSub)
3288     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3289   else
3290     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3291   return InsertNewInstBefore(New, I);
3292 }
3293
3294 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3295   bool Changed = SimplifyCommutative(I);
3296   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3297
3298   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3299     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3300
3301   // and X, X = X
3302   if (Op0 == Op1)
3303     return ReplaceInstUsesWith(I, Op1);
3304
3305   // See if we can simplify any instructions used by the instruction whose sole 
3306   // purpose is to compute bits we don't care about.
3307   if (!isa<VectorType>(I.getType())) {
3308     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3309     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3310     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3311                              KnownZero, KnownOne))
3312       return &I;
3313   } else {
3314     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3315       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3316         return ReplaceInstUsesWith(I, I.getOperand(0));
3317     } else if (isa<ConstantAggregateZero>(Op1)) {
3318       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3319     }
3320   }
3321   
3322   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3323     const APInt& AndRHSMask = AndRHS->getValue();
3324     APInt NotAndRHS(~AndRHSMask);
3325
3326     // Optimize a variety of ((val OP C1) & C2) combinations...
3327     if (isa<BinaryOperator>(Op0)) {
3328       Instruction *Op0I = cast<Instruction>(Op0);
3329       Value *Op0LHS = Op0I->getOperand(0);
3330       Value *Op0RHS = Op0I->getOperand(1);
3331       switch (Op0I->getOpcode()) {
3332       case Instruction::Xor:
3333       case Instruction::Or:
3334         // If the mask is only needed on one incoming arm, push it up.
3335         if (Op0I->hasOneUse()) {
3336           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3337             // Not masking anything out for the LHS, move to RHS.
3338             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3339                                                    Op0RHS->getName()+".masked");
3340             InsertNewInstBefore(NewRHS, I);
3341             return BinaryOperator::create(
3342                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3343           }
3344           if (!isa<Constant>(Op0RHS) &&
3345               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3346             // Not masking anything out for the RHS, move to LHS.
3347             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3348                                                    Op0LHS->getName()+".masked");
3349             InsertNewInstBefore(NewLHS, I);
3350             return BinaryOperator::create(
3351                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3352           }
3353         }
3354
3355         break;
3356       case Instruction::Add:
3357         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3358         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3359         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3360         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3361           return BinaryOperator::createAnd(V, AndRHS);
3362         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3363           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3364         break;
3365
3366       case Instruction::Sub:
3367         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3368         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3369         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3370         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3371           return BinaryOperator::createAnd(V, AndRHS);
3372         break;
3373       }
3374
3375       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3376         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3377           return Res;
3378     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3379       // If this is an integer truncation or change from signed-to-unsigned, and
3380       // if the source is an and/or with immediate, transform it.  This
3381       // frequently occurs for bitfield accesses.
3382       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3383         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3384             CastOp->getNumOperands() == 2)
3385           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3386             if (CastOp->getOpcode() == Instruction::And) {
3387               // Change: and (cast (and X, C1) to T), C2
3388               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3389               // This will fold the two constants together, which may allow 
3390               // other simplifications.
3391               Instruction *NewCast = CastInst::createTruncOrBitCast(
3392                 CastOp->getOperand(0), I.getType(), 
3393                 CastOp->getName()+".shrunk");
3394               NewCast = InsertNewInstBefore(NewCast, I);
3395               // trunc_or_bitcast(C1)&C2
3396               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3397               C3 = ConstantExpr::getAnd(C3, AndRHS);
3398               return BinaryOperator::createAnd(NewCast, C3);
3399             } else if (CastOp->getOpcode() == Instruction::Or) {
3400               // Change: and (cast (or X, C1) to T), C2
3401               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3402               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3403               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3404                 return ReplaceInstUsesWith(I, AndRHS);
3405             }
3406       }
3407     }
3408
3409     // Try to fold constant and into select arguments.
3410     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3411       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3412         return R;
3413     if (isa<PHINode>(Op0))
3414       if (Instruction *NV = FoldOpIntoPhi(I))
3415         return NV;
3416   }
3417
3418   Value *Op0NotVal = dyn_castNotVal(Op0);
3419   Value *Op1NotVal = dyn_castNotVal(Op1);
3420
3421   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3422     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3423
3424   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3425   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3426     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3427                                                I.getName()+".demorgan");
3428     InsertNewInstBefore(Or, I);
3429     return BinaryOperator::createNot(Or);
3430   }
3431   
3432   {
3433     Value *A = 0, *B = 0, *C = 0, *D = 0;
3434     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3435       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3436         return ReplaceInstUsesWith(I, Op1);
3437     
3438       // (A|B) & ~(A&B) -> A^B
3439       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3440         if ((A == C && B == D) || (A == D && B == C))
3441           return BinaryOperator::createXor(A, B);
3442       }
3443     }
3444     
3445     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3446       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3447         return ReplaceInstUsesWith(I, Op0);
3448
3449       // ~(A&B) & (A|B) -> A^B
3450       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3451         if ((A == C && B == D) || (A == D && B == C))
3452           return BinaryOperator::createXor(A, B);
3453       }
3454     }
3455     
3456     if (Op0->hasOneUse() &&
3457         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3458       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3459         I.swapOperands();     // Simplify below
3460         std::swap(Op0, Op1);
3461       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3462         cast<BinaryOperator>(Op0)->swapOperands();
3463         I.swapOperands();     // Simplify below
3464         std::swap(Op0, Op1);
3465       }
3466     }
3467     if (Op1->hasOneUse() &&
3468         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3469       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3470         cast<BinaryOperator>(Op1)->swapOperands();
3471         std::swap(A, B);
3472       }
3473       if (A == Op0) {                                // A&(A^B) -> A & ~B
3474         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3475         InsertNewInstBefore(NotB, I);
3476         return BinaryOperator::createAnd(A, NotB);
3477       }
3478     }
3479   }
3480   
3481   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3482     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3483     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3484       return R;
3485
3486     Value *LHSVal, *RHSVal;
3487     ConstantInt *LHSCst, *RHSCst;
3488     ICmpInst::Predicate LHSCC, RHSCC;
3489     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3490       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3491         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3492             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3493             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3494             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3495             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3496             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3497             
3498             // Don't try to fold ICMP_SLT + ICMP_ULT.
3499             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3500              ICmpInst::isSignedPredicate(LHSCC) == 
3501                  ICmpInst::isSignedPredicate(RHSCC))) {
3502           // Ensure that the larger constant is on the RHS.
3503           ICmpInst::Predicate GT;
3504           if (ICmpInst::isSignedPredicate(LHSCC) ||
3505               (ICmpInst::isEquality(LHSCC) && 
3506                ICmpInst::isSignedPredicate(RHSCC)))
3507             GT = ICmpInst::ICMP_SGT;
3508           else
3509             GT = ICmpInst::ICMP_UGT;
3510           
3511           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3512           ICmpInst *LHS = cast<ICmpInst>(Op0);
3513           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3514             std::swap(LHS, RHS);
3515             std::swap(LHSCst, RHSCst);
3516             std::swap(LHSCC, RHSCC);
3517           }
3518
3519           // At this point, we know we have have two icmp instructions
3520           // comparing a value against two constants and and'ing the result
3521           // together.  Because of the above check, we know that we only have
3522           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3523           // (from the FoldICmpLogical check above), that the two constants 
3524           // are not equal and that the larger constant is on the RHS
3525           assert(LHSCst != RHSCst && "Compares not folded above?");
3526
3527           switch (LHSCC) {
3528           default: assert(0 && "Unknown integer condition code!");
3529           case ICmpInst::ICMP_EQ:
3530             switch (RHSCC) {
3531             default: assert(0 && "Unknown integer condition code!");
3532             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3533             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3534             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3535               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3536             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3537             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3538             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3539               return ReplaceInstUsesWith(I, LHS);
3540             }
3541           case ICmpInst::ICMP_NE:
3542             switch (RHSCC) {
3543             default: assert(0 && "Unknown integer condition code!");
3544             case ICmpInst::ICMP_ULT:
3545               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3546                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3547               break;                        // (X != 13 & X u< 15) -> no change
3548             case ICmpInst::ICMP_SLT:
3549               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3550                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3551               break;                        // (X != 13 & X s< 15) -> no change
3552             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3553             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3554             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3555               return ReplaceInstUsesWith(I, RHS);
3556             case ICmpInst::ICMP_NE:
3557               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3558                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3559                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3560                                                       LHSVal->getName()+".off");
3561                 InsertNewInstBefore(Add, I);
3562                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3563                                     ConstantInt::get(Add->getType(), 1));
3564               }
3565               break;                        // (X != 13 & X != 15) -> no change
3566             }
3567             break;
3568           case ICmpInst::ICMP_ULT:
3569             switch (RHSCC) {
3570             default: assert(0 && "Unknown integer condition code!");
3571             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3572             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3573               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3574             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3575               break;
3576             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3577             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3578               return ReplaceInstUsesWith(I, LHS);
3579             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3580               break;
3581             }
3582             break;
3583           case ICmpInst::ICMP_SLT:
3584             switch (RHSCC) {
3585             default: assert(0 && "Unknown integer condition code!");
3586             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3587             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3588               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3589             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3590               break;
3591             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3592             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3593               return ReplaceInstUsesWith(I, LHS);
3594             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3595               break;
3596             }
3597             break;
3598           case ICmpInst::ICMP_UGT:
3599             switch (RHSCC) {
3600             default: assert(0 && "Unknown integer condition code!");
3601             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3602               return ReplaceInstUsesWith(I, LHS);
3603             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3604               return ReplaceInstUsesWith(I, RHS);
3605             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3606               break;
3607             case ICmpInst::ICMP_NE:
3608               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3609                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3610               break;                        // (X u> 13 & X != 15) -> no change
3611             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3612               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3613                                      true, I);
3614             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3615               break;
3616             }
3617             break;
3618           case ICmpInst::ICMP_SGT:
3619             switch (RHSCC) {
3620             default: assert(0 && "Unknown integer condition code!");
3621             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3622             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3623               return ReplaceInstUsesWith(I, RHS);
3624             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3625               break;
3626             case ICmpInst::ICMP_NE:
3627               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3628                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3629               break;                        // (X s> 13 & X != 15) -> no change
3630             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3631               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3632                                      true, I);
3633             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3634               break;
3635             }
3636             break;
3637           }
3638         }
3639   }
3640
3641   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3642   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3643     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3644       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3645         const Type *SrcTy = Op0C->getOperand(0)->getType();
3646         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3647             // Only do this if the casts both really cause code to be generated.
3648             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3649                               I.getType(), TD) &&
3650             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3651                               I.getType(), TD)) {
3652           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3653                                                          Op1C->getOperand(0),
3654                                                          I.getName());
3655           InsertNewInstBefore(NewOp, I);
3656           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3657         }
3658       }
3659     
3660   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3661   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3662     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3663       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3664           SI0->getOperand(1) == SI1->getOperand(1) &&
3665           (SI0->hasOneUse() || SI1->hasOneUse())) {
3666         Instruction *NewOp =
3667           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3668                                                         SI1->getOperand(0),
3669                                                         SI0->getName()), I);
3670         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3671                                       SI1->getOperand(1));
3672       }
3673   }
3674
3675   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3676   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3677     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3678       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3679           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3680         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3681           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3682             // If either of the constants are nans, then the whole thing returns
3683             // false.
3684             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3685               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3686             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3687                                 RHS->getOperand(0));
3688           }
3689     }
3690   }
3691       
3692   return Changed ? &I : 0;
3693 }
3694
3695 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3696 /// in the result.  If it does, and if the specified byte hasn't been filled in
3697 /// yet, fill it in and return false.
3698 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3699   Instruction *I = dyn_cast<Instruction>(V);
3700   if (I == 0) return true;
3701
3702   // If this is an or instruction, it is an inner node of the bswap.
3703   if (I->getOpcode() == Instruction::Or)
3704     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3705            CollectBSwapParts(I->getOperand(1), ByteValues);
3706   
3707   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3708   // If this is a shift by a constant int, and it is "24", then its operand
3709   // defines a byte.  We only handle unsigned types here.
3710   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3711     // Not shifting the entire input by N-1 bytes?
3712     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3713         8*(ByteValues.size()-1))
3714       return true;
3715     
3716     unsigned DestNo;
3717     if (I->getOpcode() == Instruction::Shl) {
3718       // X << 24 defines the top byte with the lowest of the input bytes.
3719       DestNo = ByteValues.size()-1;
3720     } else {
3721       // X >>u 24 defines the low byte with the highest of the input bytes.
3722       DestNo = 0;
3723     }
3724     
3725     // If the destination byte value is already defined, the values are or'd
3726     // together, which isn't a bswap (unless it's an or of the same bits).
3727     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3728       return true;
3729     ByteValues[DestNo] = I->getOperand(0);
3730     return false;
3731   }
3732   
3733   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3734   // don't have this.
3735   Value *Shift = 0, *ShiftLHS = 0;
3736   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3737   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3738       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3739     return true;
3740   Instruction *SI = cast<Instruction>(Shift);
3741
3742   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3743   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3744       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3745     return true;
3746   
3747   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3748   unsigned DestByte;
3749   if (AndAmt->getValue().getActiveBits() > 64)
3750     return true;
3751   uint64_t AndAmtVal = AndAmt->getZExtValue();
3752   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3753     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3754       break;
3755   // Unknown mask for bswap.
3756   if (DestByte == ByteValues.size()) return true;
3757   
3758   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3759   unsigned SrcByte;
3760   if (SI->getOpcode() == Instruction::Shl)
3761     SrcByte = DestByte - ShiftBytes;
3762   else
3763     SrcByte = DestByte + ShiftBytes;
3764   
3765   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3766   if (SrcByte != ByteValues.size()-DestByte-1)
3767     return true;
3768   
3769   // If the destination byte value is already defined, the values are or'd
3770   // together, which isn't a bswap (unless it's an or of the same bits).
3771   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3772     return true;
3773   ByteValues[DestByte] = SI->getOperand(0);
3774   return false;
3775 }
3776
3777 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3778 /// If so, insert the new bswap intrinsic and return it.
3779 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3780   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3781   if (!ITy || ITy->getBitWidth() % 16) 
3782     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3783   
3784   /// ByteValues - For each byte of the result, we keep track of which value
3785   /// defines each byte.
3786   SmallVector<Value*, 8> ByteValues;
3787   ByteValues.resize(ITy->getBitWidth()/8);
3788     
3789   // Try to find all the pieces corresponding to the bswap.
3790   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3791       CollectBSwapParts(I.getOperand(1), ByteValues))
3792     return 0;
3793   
3794   // Check to see if all of the bytes come from the same value.
3795   Value *V = ByteValues[0];
3796   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3797   
3798   // Check to make sure that all of the bytes come from the same value.
3799   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3800     if (ByteValues[i] != V)
3801       return 0;
3802   const Type *Tys[] = { ITy };
3803   Module *M = I.getParent()->getParent()->getParent();
3804   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3805   return new CallInst(F, V);
3806 }
3807
3808
3809 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3810   bool Changed = SimplifyCommutative(I);
3811   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3812
3813   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3814     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3815
3816   // or X, X = X
3817   if (Op0 == Op1)
3818     return ReplaceInstUsesWith(I, Op0);
3819
3820   // See if we can simplify any instructions used by the instruction whose sole 
3821   // purpose is to compute bits we don't care about.
3822   if (!isa<VectorType>(I.getType())) {
3823     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3824     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3825     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3826                              KnownZero, KnownOne))
3827       return &I;
3828   } else if (isa<ConstantAggregateZero>(Op1)) {
3829     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3830   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3831     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3832       return ReplaceInstUsesWith(I, I.getOperand(1));
3833   }
3834     
3835
3836   
3837   // or X, -1 == -1
3838   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3839     ConstantInt *C1 = 0; Value *X = 0;
3840     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3841     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3842       Instruction *Or = BinaryOperator::createOr(X, RHS);
3843       InsertNewInstBefore(Or, I);
3844       Or->takeName(Op0);
3845       return BinaryOperator::createAnd(Or, 
3846                ConstantInt::get(RHS->getValue() | C1->getValue()));
3847     }
3848
3849     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3850     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3851       Instruction *Or = BinaryOperator::createOr(X, RHS);
3852       InsertNewInstBefore(Or, I);
3853       Or->takeName(Op0);
3854       return BinaryOperator::createXor(Or,
3855                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3856     }
3857
3858     // Try to fold constant and into select arguments.
3859     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3860       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3861         return R;
3862     if (isa<PHINode>(Op0))
3863       if (Instruction *NV = FoldOpIntoPhi(I))
3864         return NV;
3865   }
3866
3867   Value *A = 0, *B = 0;
3868   ConstantInt *C1 = 0, *C2 = 0;
3869
3870   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3871     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3872       return ReplaceInstUsesWith(I, Op1);
3873   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3874     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3875       return ReplaceInstUsesWith(I, Op0);
3876
3877   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3878   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3879   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3880       match(Op1, m_Or(m_Value(), m_Value())) ||
3881       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3882        match(Op1, m_Shift(m_Value(), m_Value())))) {
3883     if (Instruction *BSwap = MatchBSwap(I))
3884       return BSwap;
3885   }
3886   
3887   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3888   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3889       MaskedValueIsZero(Op1, C1->getValue())) {
3890     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3891     InsertNewInstBefore(NOr, I);
3892     NOr->takeName(Op0);
3893     return BinaryOperator::createXor(NOr, C1);
3894   }
3895
3896   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3897   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3898       MaskedValueIsZero(Op0, C1->getValue())) {
3899     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3900     InsertNewInstBefore(NOr, I);
3901     NOr->takeName(Op0);
3902     return BinaryOperator::createXor(NOr, C1);
3903   }
3904
3905   // (A & C)|(B & D)
3906   Value *C = 0, *D = 0;
3907   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3908       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3909     Value *V1 = 0, *V2 = 0, *V3 = 0;
3910     C1 = dyn_cast<ConstantInt>(C);
3911     C2 = dyn_cast<ConstantInt>(D);
3912     if (C1 && C2) {  // (A & C1)|(B & C2)
3913       // If we have: ((V + N) & C1) | (V & C2)
3914       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3915       // replace with V+N.
3916       if (C1->getValue() == ~C2->getValue()) {
3917         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3918             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3919           // Add commutes, try both ways.
3920           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3921             return ReplaceInstUsesWith(I, A);
3922           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3923             return ReplaceInstUsesWith(I, A);
3924         }
3925         // Or commutes, try both ways.
3926         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3927             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3928           // Add commutes, try both ways.
3929           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3930             return ReplaceInstUsesWith(I, B);
3931           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3932             return ReplaceInstUsesWith(I, B);
3933         }
3934       }
3935       V1 = 0; V2 = 0; V3 = 0;
3936     }
3937     
3938     // Check to see if we have any common things being and'ed.  If so, find the
3939     // terms for V1 & (V2|V3).
3940     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3941       if (A == B)      // (A & C)|(A & D) == A & (C|D)
3942         V1 = A, V2 = C, V3 = D;
3943       else if (A == D) // (A & C)|(B & A) == A & (B|C)
3944         V1 = A, V2 = B, V3 = C;
3945       else if (C == B) // (A & C)|(C & D) == C & (A|D)
3946         V1 = C, V2 = A, V3 = D;
3947       else if (C == D) // (A & C)|(B & C) == C & (A|B)
3948         V1 = C, V2 = A, V3 = B;
3949       
3950       if (V1) {
3951         Value *Or =
3952           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3953         return BinaryOperator::createAnd(V1, Or);
3954       }
3955     }
3956   }
3957   
3958   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3959   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3960     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3961       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3962           SI0->getOperand(1) == SI1->getOperand(1) &&
3963           (SI0->hasOneUse() || SI1->hasOneUse())) {
3964         Instruction *NewOp =
3965         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3966                                                      SI1->getOperand(0),
3967                                                      SI0->getName()), I);
3968         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3969                                       SI1->getOperand(1));
3970       }
3971   }
3972
3973   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3974     if (A == Op1)   // ~A | A == -1
3975       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3976   } else {
3977     A = 0;
3978   }
3979   // Note, A is still live here!
3980   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3981     if (Op0 == B)
3982       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3983
3984     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3985     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3986       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3987                                               I.getName()+".demorgan"), I);
3988       return BinaryOperator::createNot(And);
3989     }
3990   }
3991
3992   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3993   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3994     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3995       return R;
3996
3997     Value *LHSVal, *RHSVal;
3998     ConstantInt *LHSCst, *RHSCst;
3999     ICmpInst::Predicate LHSCC, RHSCC;
4000     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4001       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4002         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4003             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4004             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4005             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4006             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4007             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4008             // We can't fold (ugt x, C) | (sgt x, C2).
4009             PredicatesFoldable(LHSCC, RHSCC)) {
4010           // Ensure that the larger constant is on the RHS.
4011           ICmpInst *LHS = cast<ICmpInst>(Op0);
4012           bool NeedsSwap;
4013           if (ICmpInst::isSignedPredicate(LHSCC))
4014             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4015           else
4016             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4017             
4018           if (NeedsSwap) {
4019             std::swap(LHS, RHS);
4020             std::swap(LHSCst, RHSCst);
4021             std::swap(LHSCC, RHSCC);
4022           }
4023
4024           // At this point, we know we have have two icmp instructions
4025           // comparing a value against two constants and or'ing the result
4026           // together.  Because of the above check, we know that we only have
4027           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4028           // FoldICmpLogical check above), that the two constants are not
4029           // equal.
4030           assert(LHSCst != RHSCst && "Compares not folded above?");
4031
4032           switch (LHSCC) {
4033           default: assert(0 && "Unknown integer condition code!");
4034           case ICmpInst::ICMP_EQ:
4035             switch (RHSCC) {
4036             default: assert(0 && "Unknown integer condition code!");
4037             case ICmpInst::ICMP_EQ:
4038               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4039                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4040                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4041                                                       LHSVal->getName()+".off");
4042                 InsertNewInstBefore(Add, I);
4043                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4044                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4045               }
4046               break;                         // (X == 13 | X == 15) -> no change
4047             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4048             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4049               break;
4050             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4051             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4052             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4053               return ReplaceInstUsesWith(I, RHS);
4054             }
4055             break;
4056           case ICmpInst::ICMP_NE:
4057             switch (RHSCC) {
4058             default: assert(0 && "Unknown integer condition code!");
4059             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4060             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4061             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4062               return ReplaceInstUsesWith(I, LHS);
4063             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4064             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4065             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4066               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4067             }
4068             break;
4069           case ICmpInst::ICMP_ULT:
4070             switch (RHSCC) {
4071             default: assert(0 && "Unknown integer condition code!");
4072             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4073               break;
4074             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4075               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4076               // this can cause overflow.
4077               if (RHSCst->isMaxValue(false))
4078                 return ReplaceInstUsesWith(I, LHS);
4079               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4080                                      false, I);
4081             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4082               break;
4083             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4084             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4085               return ReplaceInstUsesWith(I, RHS);
4086             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4087               break;
4088             }
4089             break;
4090           case ICmpInst::ICMP_SLT:
4091             switch (RHSCC) {
4092             default: assert(0 && "Unknown integer condition code!");
4093             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4094               break;
4095             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4096               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4097               // this can cause overflow.
4098               if (RHSCst->isMaxValue(true))
4099                 return ReplaceInstUsesWith(I, LHS);
4100               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4101                                      false, I);
4102             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4103               break;
4104             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4105             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4106               return ReplaceInstUsesWith(I, RHS);
4107             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4108               break;
4109             }
4110             break;
4111           case ICmpInst::ICMP_UGT:
4112             switch (RHSCC) {
4113             default: assert(0 && "Unknown integer condition code!");
4114             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4115             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4116               return ReplaceInstUsesWith(I, LHS);
4117             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4118               break;
4119             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4120             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4121               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4122             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4123               break;
4124             }
4125             break;
4126           case ICmpInst::ICMP_SGT:
4127             switch (RHSCC) {
4128             default: assert(0 && "Unknown integer condition code!");
4129             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4130             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4131               return ReplaceInstUsesWith(I, LHS);
4132             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4133               break;
4134             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4135             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4136               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4137             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4138               break;
4139             }
4140             break;
4141           }
4142         }
4143   }
4144     
4145   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4146   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4147     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4148       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4149         const Type *SrcTy = Op0C->getOperand(0)->getType();
4150         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4151             // Only do this if the casts both really cause code to be generated.
4152             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4153                               I.getType(), TD) &&
4154             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4155                               I.getType(), TD)) {
4156           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4157                                                         Op1C->getOperand(0),
4158                                                         I.getName());
4159           InsertNewInstBefore(NewOp, I);
4160           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4161         }
4162       }
4163   }
4164   
4165     
4166   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4167   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4168     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4169       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4170           RHS->getPredicate() == FCmpInst::FCMP_UNO)
4171         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4172           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4173             // If either of the constants are nans, then the whole thing returns
4174             // true.
4175             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4176               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4177             
4178             // Otherwise, no need to compare the two constants, compare the
4179             // rest.
4180             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4181                                 RHS->getOperand(0));
4182           }
4183     }
4184   }
4185
4186   return Changed ? &I : 0;
4187 }
4188
4189 // XorSelf - Implements: X ^ X --> 0
4190 struct XorSelf {
4191   Value *RHS;
4192   XorSelf(Value *rhs) : RHS(rhs) {}
4193   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4194   Instruction *apply(BinaryOperator &Xor) const {
4195     return &Xor;
4196   }
4197 };
4198
4199
4200 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4201   bool Changed = SimplifyCommutative(I);
4202   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4203
4204   if (isa<UndefValue>(Op1))
4205     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4206
4207   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4208   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4209     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4210     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4211   }
4212   
4213   // See if we can simplify any instructions used by the instruction whose sole 
4214   // purpose is to compute bits we don't care about.
4215   if (!isa<VectorType>(I.getType())) {
4216     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4217     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4218     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4219                              KnownZero, KnownOne))
4220       return &I;
4221   } else if (isa<ConstantAggregateZero>(Op1)) {
4222     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4223   }
4224
4225   // Is this a ~ operation?
4226   if (Value *NotOp = dyn_castNotVal(&I)) {
4227     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4228     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4229     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4230       if (Op0I->getOpcode() == Instruction::And || 
4231           Op0I->getOpcode() == Instruction::Or) {
4232         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4233         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4234           Instruction *NotY =
4235             BinaryOperator::createNot(Op0I->getOperand(1),
4236                                       Op0I->getOperand(1)->getName()+".not");
4237           InsertNewInstBefore(NotY, I);
4238           if (Op0I->getOpcode() == Instruction::And)
4239             return BinaryOperator::createOr(Op0NotVal, NotY);
4240           else
4241             return BinaryOperator::createAnd(Op0NotVal, NotY);
4242         }
4243       }
4244     }
4245   }
4246   
4247   
4248   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4249     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4250     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4251       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4252         return new ICmpInst(ICI->getInversePredicate(),
4253                             ICI->getOperand(0), ICI->getOperand(1));
4254
4255       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4256         return new FCmpInst(FCI->getInversePredicate(),
4257                             FCI->getOperand(0), FCI->getOperand(1));
4258     }
4259
4260     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4261       // ~(c-X) == X-c-1 == X+(-c-1)
4262       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4263         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4264           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4265           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4266                                               ConstantInt::get(I.getType(), 1));
4267           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4268         }
4269           
4270       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4271         if (Op0I->getOpcode() == Instruction::Add) {
4272           // ~(X-c) --> (-c-1)-X
4273           if (RHS->isAllOnesValue()) {
4274             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4275             return BinaryOperator::createSub(
4276                            ConstantExpr::getSub(NegOp0CI,
4277                                              ConstantInt::get(I.getType(), 1)),
4278                                           Op0I->getOperand(0));
4279           } else if (RHS->getValue().isSignBit()) {
4280             // (X + C) ^ signbit -> (X + C + signbit)
4281             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4282             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4283
4284           }
4285         } else if (Op0I->getOpcode() == Instruction::Or) {
4286           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4287           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4288             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4289             // Anything in both C1 and C2 is known to be zero, remove it from
4290             // NewRHS.
4291             Constant *CommonBits = And(Op0CI, RHS);
4292             NewRHS = ConstantExpr::getAnd(NewRHS, 
4293                                           ConstantExpr::getNot(CommonBits));
4294             AddToWorkList(Op0I);
4295             I.setOperand(0, Op0I->getOperand(0));
4296             I.setOperand(1, NewRHS);
4297             return &I;
4298           }
4299         }
4300     }
4301
4302     // Try to fold constant and into select arguments.
4303     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4304       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4305         return R;
4306     if (isa<PHINode>(Op0))
4307       if (Instruction *NV = FoldOpIntoPhi(I))
4308         return NV;
4309   }
4310
4311   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4312     if (X == Op1)
4313       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4314
4315   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4316     if (X == Op0)
4317       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4318
4319   
4320   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4321   if (Op1I) {
4322     Value *A, *B;
4323     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4324       if (A == Op0) {              // B^(B|A) == (A|B)^B
4325         Op1I->swapOperands();
4326         I.swapOperands();
4327         std::swap(Op0, Op1);
4328       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4329         I.swapOperands();     // Simplified below.
4330         std::swap(Op0, Op1);
4331       }
4332     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4333       if (Op0 == A)                                          // A^(A^B) == B
4334         return ReplaceInstUsesWith(I, B);
4335       else if (Op0 == B)                                     // A^(B^A) == B
4336         return ReplaceInstUsesWith(I, A);
4337     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4338       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4339         Op1I->swapOperands();
4340         std::swap(A, B);
4341       }
4342       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4343         I.swapOperands();     // Simplified below.
4344         std::swap(Op0, Op1);
4345       }
4346     }
4347   }
4348   
4349   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4350   if (Op0I) {
4351     Value *A, *B;
4352     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4353       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4354         std::swap(A, B);
4355       if (B == Op1) {                                // (A|B)^B == A & ~B
4356         Instruction *NotB =
4357           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4358         return BinaryOperator::createAnd(A, NotB);
4359       }
4360     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4361       if (Op1 == A)                                          // (A^B)^A == B
4362         return ReplaceInstUsesWith(I, B);
4363       else if (Op1 == B)                                     // (B^A)^A == B
4364         return ReplaceInstUsesWith(I, A);
4365     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4366       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4367         std::swap(A, B);
4368       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4369           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4370         Instruction *N =
4371           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4372         return BinaryOperator::createAnd(N, Op1);
4373       }
4374     }
4375   }
4376   
4377   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4378   if (Op0I && Op1I && Op0I->isShift() && 
4379       Op0I->getOpcode() == Op1I->getOpcode() && 
4380       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4381       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4382     Instruction *NewOp =
4383       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4384                                                     Op1I->getOperand(0),
4385                                                     Op0I->getName()), I);
4386     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4387                                   Op1I->getOperand(1));
4388   }
4389     
4390   if (Op0I && Op1I) {
4391     Value *A, *B, *C, *D;
4392     // (A & B)^(A | B) -> A ^ B
4393     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4394         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4395       if ((A == C && B == D) || (A == D && B == C)) 
4396         return BinaryOperator::createXor(A, B);
4397     }
4398     // (A | B)^(A & B) -> A ^ B
4399     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4400         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4401       if ((A == C && B == D) || (A == D && B == C)) 
4402         return BinaryOperator::createXor(A, B);
4403     }
4404     
4405     // (A & B)^(C & D)
4406     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4407         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4408         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4409       // (X & Y)^(X & Y) -> (Y^Z) & X
4410       Value *X = 0, *Y = 0, *Z = 0;
4411       if (A == C)
4412         X = A, Y = B, Z = D;
4413       else if (A == D)
4414         X = A, Y = B, Z = C;
4415       else if (B == C)
4416         X = B, Y = A, Z = D;
4417       else if (B == D)
4418         X = B, Y = A, Z = C;
4419       
4420       if (X) {
4421         Instruction *NewOp =
4422         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4423         return BinaryOperator::createAnd(NewOp, X);
4424       }
4425     }
4426   }
4427     
4428   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4429   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4430     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4431       return R;
4432
4433   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4434   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4435     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4436       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4437         const Type *SrcTy = Op0C->getOperand(0)->getType();
4438         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4439             // Only do this if the casts both really cause code to be generated.
4440             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4441                               I.getType(), TD) &&
4442             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4443                               I.getType(), TD)) {
4444           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4445                                                          Op1C->getOperand(0),
4446                                                          I.getName());
4447           InsertNewInstBefore(NewOp, I);
4448           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4449         }
4450       }
4451   }
4452   return Changed ? &I : 0;
4453 }
4454
4455 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4456 /// overflowed for this type.
4457 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4458                             ConstantInt *In2, bool IsSigned = false) {
4459   Result = cast<ConstantInt>(Add(In1, In2));
4460
4461   if (IsSigned)
4462     if (In2->getValue().isNegative())
4463       return Result->getValue().sgt(In1->getValue());
4464     else
4465       return Result->getValue().slt(In1->getValue());
4466   else
4467     return Result->getValue().ult(In1->getValue());
4468 }
4469
4470 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4471 /// code necessary to compute the offset from the base pointer (without adding
4472 /// in the base pointer).  Return the result as a signed integer of intptr size.
4473 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4474   TargetData &TD = IC.getTargetData();
4475   gep_type_iterator GTI = gep_type_begin(GEP);
4476   const Type *IntPtrTy = TD.getIntPtrType();
4477   Value *Result = Constant::getNullValue(IntPtrTy);
4478
4479   // Build a mask for high order bits.
4480   unsigned IntPtrWidth = TD.getPointerSize()*8;
4481   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4482
4483   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4484     Value *Op = GEP->getOperand(i);
4485     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4486     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4487       if (OpC->isZero()) continue;
4488       
4489       // Handle a struct index, which adds its field offset to the pointer.
4490       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4491         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4492         
4493         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4494           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4495         else
4496           Result = IC.InsertNewInstBefore(
4497                    BinaryOperator::createAdd(Result,
4498                                              ConstantInt::get(IntPtrTy, Size),
4499                                              GEP->getName()+".offs"), I);
4500         continue;
4501       }
4502       
4503       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4504       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4505       Scale = ConstantExpr::getMul(OC, Scale);
4506       if (Constant *RC = dyn_cast<Constant>(Result))
4507         Result = ConstantExpr::getAdd(RC, Scale);
4508       else {
4509         // Emit an add instruction.
4510         Result = IC.InsertNewInstBefore(
4511            BinaryOperator::createAdd(Result, Scale,
4512                                      GEP->getName()+".offs"), I);
4513       }
4514       continue;
4515     }
4516     // Convert to correct type.
4517     if (Op->getType() != IntPtrTy) {
4518       if (Constant *OpC = dyn_cast<Constant>(Op))
4519         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4520       else
4521         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4522                                                  Op->getName()+".c"), I);
4523     }
4524     if (Size != 1) {
4525       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4526       if (Constant *OpC = dyn_cast<Constant>(Op))
4527         Op = ConstantExpr::getMul(OpC, Scale);
4528       else    // We'll let instcombine(mul) convert this to a shl if possible.
4529         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4530                                                   GEP->getName()+".idx"), I);
4531     }
4532
4533     // Emit an add instruction.
4534     if (isa<Constant>(Op) && isa<Constant>(Result))
4535       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4536                                     cast<Constant>(Result));
4537     else
4538       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4539                                                   GEP->getName()+".offs"), I);
4540   }
4541   return Result;
4542 }
4543
4544 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4545 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4546 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4547                                        ICmpInst::Predicate Cond,
4548                                        Instruction &I) {
4549   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4550
4551   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4552     if (isa<PointerType>(CI->getOperand(0)->getType()))
4553       RHS = CI->getOperand(0);
4554
4555   Value *PtrBase = GEPLHS->getOperand(0);
4556   if (PtrBase == RHS) {
4557     // As an optimization, we don't actually have to compute the actual value of
4558     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4559     // each index is zero or not.
4560     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4561       Instruction *InVal = 0;
4562       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4563       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4564         bool EmitIt = true;
4565         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4566           if (isa<UndefValue>(C))  // undef index -> undef.
4567             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4568           if (C->isNullValue())
4569             EmitIt = false;
4570           else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
4571             EmitIt = false;  // This is indexing into a zero sized array?
4572           } else if (isa<ConstantInt>(C))
4573             return ReplaceInstUsesWith(I, // No comparison is needed here.
4574                                  ConstantInt::get(Type::Int1Ty, 
4575                                                   Cond == ICmpInst::ICMP_NE));
4576         }
4577
4578         if (EmitIt) {
4579           Instruction *Comp =
4580             new ICmpInst(Cond, GEPLHS->getOperand(i),
4581                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4582           if (InVal == 0)
4583             InVal = Comp;
4584           else {
4585             InVal = InsertNewInstBefore(InVal, I);
4586             InsertNewInstBefore(Comp, I);
4587             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4588               InVal = BinaryOperator::createOr(InVal, Comp);
4589             else                              // True if all are equal
4590               InVal = BinaryOperator::createAnd(InVal, Comp);
4591           }
4592         }
4593       }
4594
4595       if (InVal)
4596         return InVal;
4597       else
4598         // No comparison is needed here, all indexes = 0
4599         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4600                                                 Cond == ICmpInst::ICMP_EQ));
4601     }
4602
4603     // Only lower this if the icmp is the only user of the GEP or if we expect
4604     // the result to fold to a constant!
4605     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4606       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4607       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4608       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4609                           Constant::getNullValue(Offset->getType()));
4610     }
4611   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4612     // If the base pointers are different, but the indices are the same, just
4613     // compare the base pointer.
4614     if (PtrBase != GEPRHS->getOperand(0)) {
4615       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4616       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4617                         GEPRHS->getOperand(0)->getType();
4618       if (IndicesTheSame)
4619         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4620           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4621             IndicesTheSame = false;
4622             break;
4623           }
4624
4625       // If all indices are the same, just compare the base pointers.
4626       if (IndicesTheSame)
4627         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4628                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4629
4630       // Otherwise, the base pointers are different and the indices are
4631       // different, bail out.
4632       return 0;
4633     }
4634
4635     // If one of the GEPs has all zero indices, recurse.
4636     bool AllZeros = true;
4637     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4638       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4639           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4640         AllZeros = false;
4641         break;
4642       }
4643     if (AllZeros)
4644       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4645                           ICmpInst::getSwappedPredicate(Cond), I);
4646
4647     // If the other GEP has all zero indices, recurse.
4648     AllZeros = true;
4649     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4650       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4651           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4652         AllZeros = false;
4653         break;
4654       }
4655     if (AllZeros)
4656       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4657
4658     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4659       // If the GEPs only differ by one index, compare it.
4660       unsigned NumDifferences = 0;  // Keep track of # differences.
4661       unsigned DiffOperand = 0;     // The operand that differs.
4662       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4663         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4664           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4665                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4666             // Irreconcilable differences.
4667             NumDifferences = 2;
4668             break;
4669           } else {
4670             if (NumDifferences++) break;
4671             DiffOperand = i;
4672           }
4673         }
4674
4675       if (NumDifferences == 0)   // SAME GEP?
4676         return ReplaceInstUsesWith(I, // No comparison is needed here.
4677                                    ConstantInt::get(Type::Int1Ty,
4678                                                     isTrueWhenEqual(Cond)));
4679
4680       else if (NumDifferences == 1) {
4681         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4682         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4683         // Make sure we do a signed comparison here.
4684         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4685       }
4686     }
4687
4688     // Only lower this if the icmp is the only user of the GEP or if we expect
4689     // the result to fold to a constant!
4690     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4691         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4692       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4693       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4694       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4695       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4696     }
4697   }
4698   return 0;
4699 }
4700
4701 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4702   bool Changed = SimplifyCompare(I);
4703   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4704
4705   // Fold trivial predicates.
4706   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4707     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4708   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4709     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4710   
4711   // Simplify 'fcmp pred X, X'
4712   if (Op0 == Op1) {
4713     switch (I.getPredicate()) {
4714     default: assert(0 && "Unknown predicate!");
4715     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4716     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4717     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4718       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4719     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4720     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4721     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4722       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4723       
4724     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4725     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4726     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4727     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4728       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4729       I.setPredicate(FCmpInst::FCMP_UNO);
4730       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4731       return &I;
4732       
4733     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4734     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4735     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4736     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4737       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4738       I.setPredicate(FCmpInst::FCMP_ORD);
4739       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4740       return &I;
4741     }
4742   }
4743     
4744   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4745     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4746
4747   // Handle fcmp with constant RHS
4748   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4749     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4750       switch (LHSI->getOpcode()) {
4751       case Instruction::PHI:
4752         if (Instruction *NV = FoldOpIntoPhi(I))
4753           return NV;
4754         break;
4755       case Instruction::Select:
4756         // If either operand of the select is a constant, we can fold the
4757         // comparison into the select arms, which will cause one to be
4758         // constant folded and the select turned into a bitwise or.
4759         Value *Op1 = 0, *Op2 = 0;
4760         if (LHSI->hasOneUse()) {
4761           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4762             // Fold the known value into the constant operand.
4763             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4764             // Insert a new FCmp of the other select operand.
4765             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4766                                                       LHSI->getOperand(2), RHSC,
4767                                                       I.getName()), I);
4768           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4769             // Fold the known value into the constant operand.
4770             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4771             // Insert a new FCmp of the other select operand.
4772             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4773                                                       LHSI->getOperand(1), RHSC,
4774                                                       I.getName()), I);
4775           }
4776         }
4777
4778         if (Op1)
4779           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4780         break;
4781       }
4782   }
4783
4784   return Changed ? &I : 0;
4785 }
4786
4787 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4788   bool Changed = SimplifyCompare(I);
4789   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4790   const Type *Ty = Op0->getType();
4791
4792   // icmp X, X
4793   if (Op0 == Op1)
4794     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4795                                                    isTrueWhenEqual(I)));
4796
4797   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4798     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4799   
4800   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4801   // addresses never equal each other!  We already know that Op0 != Op1.
4802   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4803        isa<ConstantPointerNull>(Op0)) &&
4804       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4805        isa<ConstantPointerNull>(Op1)))
4806     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4807                                                    !isTrueWhenEqual(I)));
4808
4809   // icmp's with boolean values can always be turned into bitwise operations
4810   if (Ty == Type::Int1Ty) {
4811     switch (I.getPredicate()) {
4812     default: assert(0 && "Invalid icmp instruction!");
4813     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4814       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4815       InsertNewInstBefore(Xor, I);
4816       return BinaryOperator::createNot(Xor);
4817     }
4818     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4819       return BinaryOperator::createXor(Op0, Op1);
4820
4821     case ICmpInst::ICMP_UGT:
4822     case ICmpInst::ICMP_SGT:
4823       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4824       // FALL THROUGH
4825     case ICmpInst::ICMP_ULT:
4826     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4827       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4828       InsertNewInstBefore(Not, I);
4829       return BinaryOperator::createAnd(Not, Op1);
4830     }
4831     case ICmpInst::ICMP_UGE:
4832     case ICmpInst::ICMP_SGE:
4833       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4834       // FALL THROUGH
4835     case ICmpInst::ICMP_ULE:
4836     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4837       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4838       InsertNewInstBefore(Not, I);
4839       return BinaryOperator::createOr(Not, Op1);
4840     }
4841     }
4842   }
4843
4844   // See if we are doing a comparison between a constant and an instruction that
4845   // can be folded into the comparison.
4846   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4847       Value *A, *B;
4848     
4849     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4850     if (I.isEquality() && CI->isNullValue() &&
4851         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4852       // (icmp cond A B) if cond is equality
4853       return new ICmpInst(I.getPredicate(), A, B);
4854     }
4855     
4856     switch (I.getPredicate()) {
4857     default: break;
4858     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4859       if (CI->isMinValue(false))
4860         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4861       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4862         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4863       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4864         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4865       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4866       if (CI->isMinValue(true))
4867         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4868                             ConstantInt::getAllOnesValue(Op0->getType()));
4869           
4870       break;
4871
4872     case ICmpInst::ICMP_SLT:
4873       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4874         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4875       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4876         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4877       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4878         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4879       break;
4880
4881     case ICmpInst::ICMP_UGT:
4882       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4883         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4884       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4885         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4886       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4887         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4888         
4889       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4890       if (CI->isMaxValue(true))
4891         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4892                             ConstantInt::getNullValue(Op0->getType()));
4893       break;
4894
4895     case ICmpInst::ICMP_SGT:
4896       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4897         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4898       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4899         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4900       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4901         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4902       break;
4903
4904     case ICmpInst::ICMP_ULE:
4905       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4906         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4907       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4908         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4909       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4910         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4911       break;
4912
4913     case ICmpInst::ICMP_SLE:
4914       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4915         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4916       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4917         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4918       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4919         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4920       break;
4921
4922     case ICmpInst::ICMP_UGE:
4923       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4924         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4925       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4926         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4927       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4928         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4929       break;
4930
4931     case ICmpInst::ICMP_SGE:
4932       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4933         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4934       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4935         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4936       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4937         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4938       break;
4939     }
4940
4941     // If we still have a icmp le or icmp ge instruction, turn it into the
4942     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4943     // already been handled above, this requires little checking.
4944     //
4945     switch (I.getPredicate()) {
4946     default: break;
4947     case ICmpInst::ICMP_ULE: 
4948       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4949     case ICmpInst::ICMP_SLE:
4950       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4951     case ICmpInst::ICMP_UGE:
4952       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4953     case ICmpInst::ICMP_SGE:
4954       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4955     }
4956     
4957     // See if we can fold the comparison based on bits known to be zero or one
4958     // in the input.  If this comparison is a normal comparison, it demands all
4959     // bits, if it is a sign bit comparison, it only demands the sign bit.
4960     
4961     bool UnusedBit;
4962     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4963     
4964     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4965     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4966     if (SimplifyDemandedBits(Op0, 
4967                              isSignBit ? APInt::getSignBit(BitWidth)
4968                                        : APInt::getAllOnesValue(BitWidth),
4969                              KnownZero, KnownOne, 0))
4970       return &I;
4971         
4972     // Given the known and unknown bits, compute a range that the LHS could be
4973     // in.
4974     if ((KnownOne | KnownZero) != 0) {
4975       // Compute the Min, Max and RHS values based on the known bits. For the
4976       // EQ and NE we use unsigned values.
4977       APInt Min(BitWidth, 0), Max(BitWidth, 0);
4978       const APInt& RHSVal = CI->getValue();
4979       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4980         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4981                                                Max);
4982       } else {
4983         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4984                                                  Max);
4985       }
4986       switch (I.getPredicate()) {  // LE/GE have been folded already.
4987       default: assert(0 && "Unknown icmp opcode!");
4988       case ICmpInst::ICMP_EQ:
4989         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4990           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4991         break;
4992       case ICmpInst::ICMP_NE:
4993         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4994           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4995         break;
4996       case ICmpInst::ICMP_ULT:
4997         if (Max.ult(RHSVal))
4998           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4999         if (Min.uge(RHSVal))
5000           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5001         break;
5002       case ICmpInst::ICMP_UGT:
5003         if (Min.ugt(RHSVal))
5004           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5005         if (Max.ule(RHSVal))
5006           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5007         break;
5008       case ICmpInst::ICMP_SLT:
5009         if (Max.slt(RHSVal))
5010           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5011         if (Min.sgt(RHSVal))
5012           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5013         break;
5014       case ICmpInst::ICMP_SGT: 
5015         if (Min.sgt(RHSVal))
5016           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5017         if (Max.sle(RHSVal))
5018           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5019         break;
5020       }
5021     }
5022           
5023     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5024     // instruction, see if that instruction also has constants so that the 
5025     // instruction can be folded into the icmp 
5026     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5027       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5028         return Res;
5029   }
5030
5031   // Handle icmp with constant (but not simple integer constant) RHS
5032   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5033     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5034       switch (LHSI->getOpcode()) {
5035       case Instruction::GetElementPtr:
5036         if (RHSC->isNullValue()) {
5037           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5038           bool isAllZeros = true;
5039           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5040             if (!isa<Constant>(LHSI->getOperand(i)) ||
5041                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5042               isAllZeros = false;
5043               break;
5044             }
5045           if (isAllZeros)
5046             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5047                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5048         }
5049         break;
5050
5051       case Instruction::PHI:
5052         if (Instruction *NV = FoldOpIntoPhi(I))
5053           return NV;
5054         break;
5055       case Instruction::Select: {
5056         // If either operand of the select is a constant, we can fold the
5057         // comparison into the select arms, which will cause one to be
5058         // constant folded and the select turned into a bitwise or.
5059         Value *Op1 = 0, *Op2 = 0;
5060         if (LHSI->hasOneUse()) {
5061           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5062             // Fold the known value into the constant operand.
5063             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5064             // Insert a new ICmp of the other select operand.
5065             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5066                                                    LHSI->getOperand(2), RHSC,
5067                                                    I.getName()), I);
5068           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5069             // Fold the known value into the constant operand.
5070             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5071             // Insert a new ICmp of the other select operand.
5072             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5073                                                    LHSI->getOperand(1), RHSC,
5074                                                    I.getName()), I);
5075           }
5076         }
5077
5078         if (Op1)
5079           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5080         break;
5081       }
5082       case Instruction::Malloc:
5083         // If we have (malloc != null), and if the malloc has a single use, we
5084         // can assume it is successful and remove the malloc.
5085         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5086           AddToWorkList(LHSI);
5087           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5088                                                          !isTrueWhenEqual(I)));
5089         }
5090         break;
5091       }
5092   }
5093
5094   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5095   if (User *GEP = dyn_castGetElementPtr(Op0))
5096     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5097       return NI;
5098   if (User *GEP = dyn_castGetElementPtr(Op1))
5099     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5100                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5101       return NI;
5102
5103   // Test to see if the operands of the icmp are casted versions of other
5104   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5105   // now.
5106   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5107     if (isa<PointerType>(Op0->getType()) && 
5108         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5109       // We keep moving the cast from the left operand over to the right
5110       // operand, where it can often be eliminated completely.
5111       Op0 = CI->getOperand(0);
5112
5113       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5114       // so eliminate it as well.
5115       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5116         Op1 = CI2->getOperand(0);
5117
5118       // If Op1 is a constant, we can fold the cast into the constant.
5119       if (Op0->getType() != Op1->getType())
5120         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5121           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5122         } else {
5123           // Otherwise, cast the RHS right before the icmp
5124           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5125         }
5126       return new ICmpInst(I.getPredicate(), Op0, Op1);
5127     }
5128   }
5129   
5130   if (isa<CastInst>(Op0)) {
5131     // Handle the special case of: icmp (cast bool to X), <cst>
5132     // This comes up when you have code like
5133     //   int X = A < B;
5134     //   if (X) ...
5135     // For generality, we handle any zero-extension of any operand comparison
5136     // with a constant or another cast from the same type.
5137     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5138       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5139         return R;
5140   }
5141   
5142   if (I.isEquality()) {
5143     Value *A, *B, *C, *D;
5144     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5145       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5146         Value *OtherVal = A == Op1 ? B : A;
5147         return new ICmpInst(I.getPredicate(), OtherVal,
5148                             Constant::getNullValue(A->getType()));
5149       }
5150
5151       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5152         // A^c1 == C^c2 --> A == C^(c1^c2)
5153         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5154           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5155             if (Op1->hasOneUse()) {
5156               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5157               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5158               return new ICmpInst(I.getPredicate(), A,
5159                                   InsertNewInstBefore(Xor, I));
5160             }
5161         
5162         // A^B == A^D -> B == D
5163         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5164         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5165         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5166         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5167       }
5168     }
5169     
5170     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5171         (A == Op0 || B == Op0)) {
5172       // A == (A^B)  ->  B == 0
5173       Value *OtherVal = A == Op0 ? B : A;
5174       return new ICmpInst(I.getPredicate(), OtherVal,
5175                           Constant::getNullValue(A->getType()));
5176     }
5177     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5178       // (A-B) == A  ->  B == 0
5179       return new ICmpInst(I.getPredicate(), B,
5180                           Constant::getNullValue(B->getType()));
5181     }
5182     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5183       // A == (A-B)  ->  B == 0
5184       return new ICmpInst(I.getPredicate(), B,
5185                           Constant::getNullValue(B->getType()));
5186     }
5187     
5188     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5189     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5190         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5191         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5192       Value *X = 0, *Y = 0, *Z = 0;
5193       
5194       if (A == C) {
5195         X = B; Y = D; Z = A;
5196       } else if (A == D) {
5197         X = B; Y = C; Z = A;
5198       } else if (B == C) {
5199         X = A; Y = D; Z = B;
5200       } else if (B == D) {
5201         X = A; Y = C; Z = B;
5202       }
5203       
5204       if (X) {   // Build (X^Y) & Z
5205         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5206         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5207         I.setOperand(0, Op1);
5208         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5209         return &I;
5210       }
5211     }
5212   }
5213   return Changed ? &I : 0;
5214 }
5215
5216
5217 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5218 /// and CmpRHS are both known to be integer constants.
5219 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5220                                           ConstantInt *DivRHS) {
5221   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5222   const APInt &CmpRHSV = CmpRHS->getValue();
5223   
5224   // FIXME: If the operand types don't match the type of the divide 
5225   // then don't attempt this transform. The code below doesn't have the
5226   // logic to deal with a signed divide and an unsigned compare (and
5227   // vice versa). This is because (x /s C1) <s C2  produces different 
5228   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5229   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5230   // work. :(  The if statement below tests that condition and bails 
5231   // if it finds it. 
5232   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5233   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5234     return 0;
5235   if (DivRHS->isZero())
5236     return 0; // The ProdOV computation fails on divide by zero.
5237
5238   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5239   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5240   // C2 (CI). By solving for X we can turn this into a range check 
5241   // instead of computing a divide. 
5242   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5243
5244   // Determine if the product overflows by seeing if the product is
5245   // not equal to the divide. Make sure we do the same kind of divide
5246   // as in the LHS instruction that we're folding. 
5247   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5248                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5249
5250   // Get the ICmp opcode
5251   ICmpInst::Predicate Pred = ICI.getPredicate();
5252
5253   // Figure out the interval that is being checked.  For example, a comparison
5254   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5255   // Compute this interval based on the constants involved and the signedness of
5256   // the compare/divide.  This computes a half-open interval, keeping track of
5257   // whether either value in the interval overflows.  After analysis each
5258   // overflow variable is set to 0 if it's corresponding bound variable is valid
5259   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5260   int LoOverflow = 0, HiOverflow = 0;
5261   ConstantInt *LoBound = 0, *HiBound = 0;
5262   
5263   
5264   if (!DivIsSigned) {  // udiv
5265     // e.g. X/5 op 3  --> [15, 20)
5266     LoBound = Prod;
5267     HiOverflow = LoOverflow = ProdOV;
5268     if (!HiOverflow)
5269       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5270   } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5271     if (CmpRHSV == 0) {       // (X / pos) op 0
5272       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5273       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5274       HiBound = DivRHS;
5275     } else if (CmpRHSV.isPositive()) {   // (X / pos) op pos
5276       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5277       HiOverflow = LoOverflow = ProdOV;
5278       if (!HiOverflow)
5279         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5280     } else {                       // (X / pos) op neg
5281       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5282       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5283       LoOverflow = AddWithOverflow(LoBound, Prod,
5284                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5285       HiBound = AddOne(Prod);
5286       HiOverflow = ProdOV ? -1 : 0;
5287     }
5288   } else {                         // Divisor is < 0.
5289     if (CmpRHSV == 0) {       // (X / neg) op 0
5290       // e.g. X/-5 op 0  --> [-4, 5)
5291       LoBound = AddOne(DivRHS);
5292       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5293       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5294         HiOverflow = 1;            // [INTMIN+1, overflow)
5295         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5296       }
5297     } else if (CmpRHSV.isPositive()) {   // (X / neg) op pos
5298       // e.g. X/-5 op 3  --> [-19, -14)
5299       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5300       if (!LoOverflow)
5301         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5302       HiBound = AddOne(Prod);
5303     } else {                       // (X / neg) op neg
5304       // e.g. X/-5 op -3  --> [15, 20)
5305       LoBound = Prod;
5306       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5307       HiBound = Subtract(Prod, DivRHS);
5308     }
5309     
5310     // Dividing by a negative swaps the condition.  LT <-> GT
5311     Pred = ICmpInst::getSwappedPredicate(Pred);
5312   }
5313
5314   Value *X = DivI->getOperand(0);
5315   switch (Pred) {
5316   default: assert(0 && "Unhandled icmp opcode!");
5317   case ICmpInst::ICMP_EQ:
5318     if (LoOverflow && HiOverflow)
5319       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5320     else if (HiOverflow)
5321       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5322                           ICmpInst::ICMP_UGE, X, LoBound);
5323     else if (LoOverflow)
5324       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5325                           ICmpInst::ICMP_ULT, X, HiBound);
5326     else
5327       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5328   case ICmpInst::ICMP_NE:
5329     if (LoOverflow && HiOverflow)
5330       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5331     else if (HiOverflow)
5332       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5333                           ICmpInst::ICMP_ULT, X, LoBound);
5334     else if (LoOverflow)
5335       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5336                           ICmpInst::ICMP_UGE, X, HiBound);
5337     else
5338       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5339   case ICmpInst::ICMP_ULT:
5340   case ICmpInst::ICMP_SLT:
5341     if (LoOverflow == +1)   // Low bound is greater than input range.
5342       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5343     if (LoOverflow == -1)   // Low bound is less than input range.
5344       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5345     return new ICmpInst(Pred, X, LoBound);
5346   case ICmpInst::ICMP_UGT:
5347   case ICmpInst::ICMP_SGT:
5348     if (HiOverflow == +1)       // High bound greater than input range.
5349       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5350     else if (HiOverflow == -1)  // High bound less than input range.
5351       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5352     if (Pred == ICmpInst::ICMP_UGT)
5353       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5354     else
5355       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5356   }
5357 }
5358
5359
5360 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5361 ///
5362 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5363                                                           Instruction *LHSI,
5364                                                           ConstantInt *RHS) {
5365   const APInt &RHSV = RHS->getValue();
5366   
5367   switch (LHSI->getOpcode()) {
5368   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5369     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5370       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5371       // fold the xor.
5372       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5373           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5374         Value *CompareVal = LHSI->getOperand(0);
5375         
5376         // If the sign bit of the XorCST is not set, there is no change to
5377         // the operation, just stop using the Xor.
5378         if (!XorCST->getValue().isNegative()) {
5379           ICI.setOperand(0, CompareVal);
5380           AddToWorkList(LHSI);
5381           return &ICI;
5382         }
5383         
5384         // Was the old condition true if the operand is positive?
5385         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5386         
5387         // If so, the new one isn't.
5388         isTrueIfPositive ^= true;
5389         
5390         if (isTrueIfPositive)
5391           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5392         else
5393           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5394       }
5395     }
5396     break;
5397   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5398     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5399         LHSI->getOperand(0)->hasOneUse()) {
5400       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5401       
5402       // If the LHS is an AND of a truncating cast, we can widen the
5403       // and/compare to be the input width without changing the value
5404       // produced, eliminating a cast.
5405       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5406         // We can do this transformation if either the AND constant does not
5407         // have its sign bit set or if it is an equality comparison. 
5408         // Extending a relational comparison when we're checking the sign
5409         // bit would not work.
5410         if (Cast->hasOneUse() &&
5411             (ICI.isEquality() || AndCST->getValue().isPositive() && 
5412              RHSV.isPositive())) {
5413           uint32_t BitWidth = 
5414             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5415           APInt NewCST = AndCST->getValue();
5416           NewCST.zext(BitWidth);
5417           APInt NewCI = RHSV;
5418           NewCI.zext(BitWidth);
5419           Instruction *NewAnd = 
5420             BinaryOperator::createAnd(Cast->getOperand(0),
5421                                       ConstantInt::get(NewCST),LHSI->getName());
5422           InsertNewInstBefore(NewAnd, ICI);
5423           return new ICmpInst(ICI.getPredicate(), NewAnd,
5424                               ConstantInt::get(NewCI));
5425         }
5426       }
5427       
5428       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5429       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5430       // happens a LOT in code produced by the C front-end, for bitfield
5431       // access.
5432       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5433       if (Shift && !Shift->isShift())
5434         Shift = 0;
5435       
5436       ConstantInt *ShAmt;
5437       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5438       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5439       const Type *AndTy = AndCST->getType();          // Type of the and.
5440       
5441       // We can fold this as long as we can't shift unknown bits
5442       // into the mask.  This can only happen with signed shift
5443       // rights, as they sign-extend.
5444       if (ShAmt) {
5445         bool CanFold = Shift->isLogicalShift();
5446         if (!CanFold) {
5447           // To test for the bad case of the signed shr, see if any
5448           // of the bits shifted in could be tested after the mask.
5449           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5450           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5451           
5452           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5453           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5454                AndCST->getValue()) == 0)
5455             CanFold = true;
5456         }
5457         
5458         if (CanFold) {
5459           Constant *NewCst;
5460           if (Shift->getOpcode() == Instruction::Shl)
5461             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5462           else
5463             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5464           
5465           // Check to see if we are shifting out any of the bits being
5466           // compared.
5467           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5468             // If we shifted bits out, the fold is not going to work out.
5469             // As a special case, check to see if this means that the
5470             // result is always true or false now.
5471             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5472               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5473             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5474               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5475           } else {
5476             ICI.setOperand(1, NewCst);
5477             Constant *NewAndCST;
5478             if (Shift->getOpcode() == Instruction::Shl)
5479               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5480             else
5481               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5482             LHSI->setOperand(1, NewAndCST);
5483             LHSI->setOperand(0, Shift->getOperand(0));
5484             AddToWorkList(Shift); // Shift is dead.
5485             AddUsesToWorkList(ICI);
5486             return &ICI;
5487           }
5488         }
5489       }
5490       
5491       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5492       // preferable because it allows the C<<Y expression to be hoisted out
5493       // of a loop if Y is invariant and X is not.
5494       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5495           ICI.isEquality() && !Shift->isArithmeticShift() &&
5496           isa<Instruction>(Shift->getOperand(0))) {
5497         // Compute C << Y.
5498         Value *NS;
5499         if (Shift->getOpcode() == Instruction::LShr) {
5500           NS = BinaryOperator::createShl(AndCST, 
5501                                          Shift->getOperand(1), "tmp");
5502         } else {
5503           // Insert a logical shift.
5504           NS = BinaryOperator::createLShr(AndCST,
5505                                           Shift->getOperand(1), "tmp");
5506         }
5507         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5508         
5509         // Compute X & (C << Y).
5510         Instruction *NewAnd = 
5511           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5512         InsertNewInstBefore(NewAnd, ICI);
5513         
5514         ICI.setOperand(0, NewAnd);
5515         return &ICI;
5516       }
5517     }
5518     break;
5519     
5520   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5521     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5522     if (!ShAmt) break;
5523     
5524     uint32_t TypeBits = RHSV.getBitWidth();
5525     
5526     // Check that the shift amount is in range.  If not, don't perform
5527     // undefined shifts.  When the shift is visited it will be
5528     // simplified.
5529     if (ShAmt->uge(TypeBits))
5530       break;
5531     
5532     if (ICI.isEquality()) {
5533       // If we are comparing against bits always shifted out, the
5534       // comparison cannot succeed.
5535       Constant *Comp =
5536         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5537       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5538         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5539         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5540         return ReplaceInstUsesWith(ICI, Cst);
5541       }
5542       
5543       if (LHSI->hasOneUse()) {
5544         // Otherwise strength reduce the shift into an and.
5545         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5546         Constant *Mask =
5547           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5548         
5549         Instruction *AndI =
5550           BinaryOperator::createAnd(LHSI->getOperand(0),
5551                                     Mask, LHSI->getName()+".mask");
5552         Value *And = InsertNewInstBefore(AndI, ICI);
5553         return new ICmpInst(ICI.getPredicate(), And,
5554                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5555       }
5556     }
5557     
5558     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5559     bool TrueIfSigned = false;
5560     if (LHSI->hasOneUse() &&
5561         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5562       // (X << 31) <s 0  --> (X&1) != 0
5563       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5564                                            (TypeBits-ShAmt->getZExtValue()-1));
5565       Instruction *AndI =
5566         BinaryOperator::createAnd(LHSI->getOperand(0),
5567                                   Mask, LHSI->getName()+".mask");
5568       Value *And = InsertNewInstBefore(AndI, ICI);
5569       
5570       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5571                           And, Constant::getNullValue(And->getType()));
5572     }
5573     break;
5574   }
5575     
5576   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5577   case Instruction::AShr: {
5578     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5579     if (!ShAmt) break;
5580
5581     if (ICI.isEquality()) {
5582       // Check that the shift amount is in range.  If not, don't perform
5583       // undefined shifts.  When the shift is visited it will be
5584       // simplified.
5585       uint32_t TypeBits = RHSV.getBitWidth();
5586       if (ShAmt->uge(TypeBits))
5587         break;
5588       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5589       
5590       // If we are comparing against bits always shifted out, the
5591       // comparison cannot succeed.
5592       APInt Comp = RHSV << ShAmtVal;
5593       if (LHSI->getOpcode() == Instruction::LShr)
5594         Comp = Comp.lshr(ShAmtVal);
5595       else
5596         Comp = Comp.ashr(ShAmtVal);
5597       
5598       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5599         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5600         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5601         return ReplaceInstUsesWith(ICI, Cst);
5602       }
5603       
5604       if (LHSI->hasOneUse() || RHSV == 0) {
5605         // Otherwise strength reduce the shift into an and.
5606         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5607         Constant *Mask = ConstantInt::get(Val);
5608         
5609         Instruction *AndI =
5610           BinaryOperator::createAnd(LHSI->getOperand(0),
5611                                     Mask, LHSI->getName()+".mask");
5612         Value *And = InsertNewInstBefore(AndI, ICI);
5613         return new ICmpInst(ICI.getPredicate(), And,
5614                             ConstantExpr::getShl(RHS, ShAmt));
5615       }
5616     }
5617     break;
5618   }
5619     
5620   case Instruction::SDiv:
5621   case Instruction::UDiv:
5622     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5623     // Fold this div into the comparison, producing a range check. 
5624     // Determine, based on the divide type, what the range is being 
5625     // checked.  If there is an overflow on the low or high side, remember 
5626     // it, otherwise compute the range [low, hi) bounding the new value.
5627     // See: InsertRangeTest above for the kinds of replacements possible.
5628     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5629       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5630                                           DivRHS))
5631         return R;
5632     break;
5633   }
5634   
5635   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5636   if (ICI.isEquality()) {
5637     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5638     
5639     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5640     // the second operand is a constant, simplify a bit.
5641     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5642       switch (BO->getOpcode()) {
5643       case Instruction::SRem:
5644         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5645         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5646           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5647           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5648             Instruction *NewRem =
5649               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5650                                          BO->getName());
5651             InsertNewInstBefore(NewRem, ICI);
5652             return new ICmpInst(ICI.getPredicate(), NewRem, 
5653                                 Constant::getNullValue(BO->getType()));
5654           }
5655         }
5656         break;
5657       case Instruction::Add:
5658         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5659         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5660           if (BO->hasOneUse())
5661             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5662                                 Subtract(RHS, BOp1C));
5663         } else if (RHSV == 0) {
5664           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5665           // efficiently invertible, or if the add has just this one use.
5666           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5667           
5668           if (Value *NegVal = dyn_castNegVal(BOp1))
5669             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5670           else if (Value *NegVal = dyn_castNegVal(BOp0))
5671             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5672           else if (BO->hasOneUse()) {
5673             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5674             InsertNewInstBefore(Neg, ICI);
5675             Neg->takeName(BO);
5676             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5677           }
5678         }
5679         break;
5680       case Instruction::Xor:
5681         // For the xor case, we can xor two constants together, eliminating
5682         // the explicit xor.
5683         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5684           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5685                               ConstantExpr::getXor(RHS, BOC));
5686         
5687         // FALLTHROUGH
5688       case Instruction::Sub:
5689         // Replace (([sub|xor] A, B) != 0) with (A != B)
5690         if (RHSV == 0)
5691           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5692                               BO->getOperand(1));
5693         break;
5694         
5695       case Instruction::Or:
5696         // If bits are being or'd in that are not present in the constant we
5697         // are comparing against, then the comparison could never succeed!
5698         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5699           Constant *NotCI = ConstantExpr::getNot(RHS);
5700           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5701             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5702                                                              isICMP_NE));
5703         }
5704         break;
5705         
5706       case Instruction::And:
5707         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5708           // If bits are being compared against that are and'd out, then the
5709           // comparison can never succeed!
5710           if ((RHSV & ~BOC->getValue()) != 0)
5711             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5712                                                              isICMP_NE));
5713           
5714           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5715           if (RHS == BOC && RHSV.isPowerOf2())
5716             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5717                                 ICmpInst::ICMP_NE, LHSI,
5718                                 Constant::getNullValue(RHS->getType()));
5719           
5720           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5721           if (isSignBit(BOC)) {
5722             Value *X = BO->getOperand(0);
5723             Constant *Zero = Constant::getNullValue(X->getType());
5724             ICmpInst::Predicate pred = isICMP_NE ? 
5725               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5726             return new ICmpInst(pred, X, Zero);
5727           }
5728           
5729           // ((X & ~7) == 0) --> X < 8
5730           if (RHSV == 0 && isHighOnes(BOC)) {
5731             Value *X = BO->getOperand(0);
5732             Constant *NegX = ConstantExpr::getNeg(BOC);
5733             ICmpInst::Predicate pred = isICMP_NE ? 
5734               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5735             return new ICmpInst(pred, X, NegX);
5736           }
5737         }
5738       default: break;
5739       }
5740     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5741       // Handle icmp {eq|ne} <intrinsic>, intcst.
5742       if (II->getIntrinsicID() == Intrinsic::bswap) {
5743         AddToWorkList(II);
5744         ICI.setOperand(0, II->getOperand(1));
5745         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5746         return &ICI;
5747       }
5748     }
5749   } else {  // Not a ICMP_EQ/ICMP_NE
5750             // If the LHS is a cast from an integral value of the same size, 
5751             // then since we know the RHS is a constant, try to simlify.
5752     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5753       Value *CastOp = Cast->getOperand(0);
5754       const Type *SrcTy = CastOp->getType();
5755       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5756       if (SrcTy->isInteger() && 
5757           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5758         // If this is an unsigned comparison, try to make the comparison use
5759         // smaller constant values.
5760         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5761           // X u< 128 => X s> -1
5762           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5763                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5764         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5765                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5766           // X u> 127 => X s< 0
5767           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5768                               Constant::getNullValue(SrcTy));
5769         }
5770       }
5771     }
5772   }
5773   return 0;
5774 }
5775
5776 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5777 /// We only handle extending casts so far.
5778 ///
5779 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5780   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5781   Value *LHSCIOp        = LHSCI->getOperand(0);
5782   const Type *SrcTy     = LHSCIOp->getType();
5783   const Type *DestTy    = LHSCI->getType();
5784   Value *RHSCIOp;
5785
5786   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5787   // integer type is the same size as the pointer type.
5788   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5789       getTargetData().getPointerSizeInBits() == 
5790          cast<IntegerType>(DestTy)->getBitWidth()) {
5791     Value *RHSOp = 0;
5792     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5793       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5794     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5795       RHSOp = RHSC->getOperand(0);
5796       // If the pointer types don't match, insert a bitcast.
5797       if (LHSCIOp->getType() != RHSOp->getType())
5798         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
5799     }
5800
5801     if (RHSOp)
5802       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5803   }
5804   
5805   // The code below only handles extension cast instructions, so far.
5806   // Enforce this.
5807   if (LHSCI->getOpcode() != Instruction::ZExt &&
5808       LHSCI->getOpcode() != Instruction::SExt)
5809     return 0;
5810
5811   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5812   bool isSignedCmp = ICI.isSignedPredicate();
5813
5814   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5815     // Not an extension from the same type?
5816     RHSCIOp = CI->getOperand(0);
5817     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5818       return 0;
5819     
5820     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5821     // and the other is a zext), then we can't handle this.
5822     if (CI->getOpcode() != LHSCI->getOpcode())
5823       return 0;
5824
5825     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5826     // then we can't handle this.
5827     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5828       return 0;
5829     
5830     // Okay, just insert a compare of the reduced operands now!
5831     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5832   }
5833
5834   // If we aren't dealing with a constant on the RHS, exit early
5835   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5836   if (!CI)
5837     return 0;
5838
5839   // Compute the constant that would happen if we truncated to SrcTy then
5840   // reextended to DestTy.
5841   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5842   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5843
5844   // If the re-extended constant didn't change...
5845   if (Res2 == CI) {
5846     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5847     // For example, we might have:
5848     //    %A = sext short %X to uint
5849     //    %B = icmp ugt uint %A, 1330
5850     // It is incorrect to transform this into 
5851     //    %B = icmp ugt short %X, 1330 
5852     // because %A may have negative value. 
5853     //
5854     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5855     // OR operation is EQ/NE.
5856     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5857       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5858     else
5859       return 0;
5860   }
5861
5862   // The re-extended constant changed so the constant cannot be represented 
5863   // in the shorter type. Consequently, we cannot emit a simple comparison.
5864
5865   // First, handle some easy cases. We know the result cannot be equal at this
5866   // point so handle the ICI.isEquality() cases
5867   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5868     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5869   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5870     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5871
5872   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5873   // should have been folded away previously and not enter in here.
5874   Value *Result;
5875   if (isSignedCmp) {
5876     // We're performing a signed comparison.
5877     if (cast<ConstantInt>(CI)->getValue().isNegative())
5878       Result = ConstantInt::getFalse();          // X < (small) --> false
5879     else
5880       Result = ConstantInt::getTrue();           // X < (large) --> true
5881   } else {
5882     // We're performing an unsigned comparison.
5883     if (isSignedExt) {
5884       // We're performing an unsigned comp with a sign extended value.
5885       // This is true if the input is >= 0. [aka >s -1]
5886       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5887       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5888                                    NegOne, ICI.getName()), ICI);
5889     } else {
5890       // Unsigned extend & unsigned compare -> always true.
5891       Result = ConstantInt::getTrue();
5892     }
5893   }
5894
5895   // Finally, return the value computed.
5896   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5897       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5898     return ReplaceInstUsesWith(ICI, Result);
5899   } else {
5900     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5901             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5902            "ICmp should be folded!");
5903     if (Constant *CI = dyn_cast<Constant>(Result))
5904       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5905     else
5906       return BinaryOperator::createNot(Result);
5907   }
5908 }
5909
5910 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5911   return commonShiftTransforms(I);
5912 }
5913
5914 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5915   return commonShiftTransforms(I);
5916 }
5917
5918 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5919   if (Instruction *R = commonShiftTransforms(I))
5920     return R;
5921   
5922   Value *Op0 = I.getOperand(0);
5923   
5924   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5925   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5926     if (CSI->isAllOnesValue())
5927       return ReplaceInstUsesWith(I, CSI);
5928   
5929   // See if we can turn a signed shr into an unsigned shr.
5930   if (MaskedValueIsZero(Op0, 
5931                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5932     return BinaryOperator::createLShr(Op0, I.getOperand(1));
5933   
5934   return 0;
5935 }
5936
5937 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5938   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5939   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5940
5941   // shl X, 0 == X and shr X, 0 == X
5942   // shl 0, X == 0 and shr 0, X == 0
5943   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5944       Op0 == Constant::getNullValue(Op0->getType()))
5945     return ReplaceInstUsesWith(I, Op0);
5946   
5947   if (isa<UndefValue>(Op0)) {            
5948     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5949       return ReplaceInstUsesWith(I, Op0);
5950     else                                    // undef << X -> 0, undef >>u X -> 0
5951       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5952   }
5953   if (isa<UndefValue>(Op1)) {
5954     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5955       return ReplaceInstUsesWith(I, Op0);          
5956     else                                     // X << undef, X >>u undef -> 0
5957       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5958   }
5959
5960   // Try to fold constant and into select arguments.
5961   if (isa<Constant>(Op0))
5962     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5963       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5964         return R;
5965
5966   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5967     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5968       return Res;
5969   return 0;
5970 }
5971
5972 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5973                                                BinaryOperator &I) {
5974   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5975
5976   // See if we can simplify any instructions used by the instruction whose sole 
5977   // purpose is to compute bits we don't care about.
5978   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5979   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5980   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5981                            KnownZero, KnownOne))
5982     return &I;
5983   
5984   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5985   // of a signed value.
5986   //
5987   if (Op1->uge(TypeBits)) {
5988     if (I.getOpcode() != Instruction::AShr)
5989       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5990     else {
5991       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5992       return &I;
5993     }
5994   }
5995   
5996   // ((X*C1) << C2) == (X * (C1 << C2))
5997   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5998     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5999       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6000         return BinaryOperator::createMul(BO->getOperand(0),
6001                                          ConstantExpr::getShl(BOOp, Op1));
6002   
6003   // Try to fold constant and into select arguments.
6004   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6005     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6006       return R;
6007   if (isa<PHINode>(Op0))
6008     if (Instruction *NV = FoldOpIntoPhi(I))
6009       return NV;
6010   
6011   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6012   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6013     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6014     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6015     // place.  Don't try to do this transformation in this case.  Also, we
6016     // require that the input operand is a shift-by-constant so that we have
6017     // confidence that the shifts will get folded together.  We could do this
6018     // xform in more cases, but it is unlikely to be profitable.
6019     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6020         isa<ConstantInt>(TrOp->getOperand(1))) {
6021       // Okay, we'll do this xform.  Make the shift of shift.
6022       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6023       Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6024                                                 I.getName());
6025       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6026
6027       // For logical shifts, the truncation has the effect of making the high
6028       // part of the register be zeros.  Emulate this by inserting an AND to
6029       // clear the top bits as needed.  This 'and' will usually be zapped by
6030       // other xforms later if dead.
6031       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6032       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6033       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6034       
6035       // The mask we constructed says what the trunc would do if occurring
6036       // between the shifts.  We want to know the effect *after* the second
6037       // shift.  We know that it is a logical shift by a constant, so adjust the
6038       // mask as appropriate.
6039       if (I.getOpcode() == Instruction::Shl)
6040         MaskV <<= Op1->getZExtValue();
6041       else {
6042         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6043         MaskV = MaskV.lshr(Op1->getZExtValue());
6044       }
6045
6046       Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6047                                                    TI->getName());
6048       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6049
6050       // Return the value truncated to the interesting size.
6051       return new TruncInst(And, I.getType());
6052     }
6053   }
6054   
6055   if (Op0->hasOneUse()) {
6056     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6057       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6058       Value *V1, *V2;
6059       ConstantInt *CC;
6060       switch (Op0BO->getOpcode()) {
6061         default: break;
6062         case Instruction::Add:
6063         case Instruction::And:
6064         case Instruction::Or:
6065         case Instruction::Xor: {
6066           // These operators commute.
6067           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6068           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6069               match(Op0BO->getOperand(1),
6070                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6071             Instruction *YS = BinaryOperator::createShl(
6072                                             Op0BO->getOperand(0), Op1,
6073                                             Op0BO->getName());
6074             InsertNewInstBefore(YS, I); // (Y << C)
6075             Instruction *X = 
6076               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6077                                      Op0BO->getOperand(1)->getName());
6078             InsertNewInstBefore(X, I);  // (X + (Y << C))
6079             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6080             return BinaryOperator::createAnd(X, ConstantInt::get(
6081                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6082           }
6083           
6084           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6085           Value *Op0BOOp1 = Op0BO->getOperand(1);
6086           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6087               match(Op0BOOp1, 
6088                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6089               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6090               V2 == Op1) {
6091             Instruction *YS = BinaryOperator::createShl(
6092                                                      Op0BO->getOperand(0), Op1,
6093                                                      Op0BO->getName());
6094             InsertNewInstBefore(YS, I); // (Y << C)
6095             Instruction *XM =
6096               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6097                                         V1->getName()+".mask");
6098             InsertNewInstBefore(XM, I); // X & (CC << C)
6099             
6100             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6101           }
6102         }
6103           
6104         // FALL THROUGH.
6105         case Instruction::Sub: {
6106           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6107           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6108               match(Op0BO->getOperand(0),
6109                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6110             Instruction *YS = BinaryOperator::createShl(
6111                                                      Op0BO->getOperand(1), Op1,
6112                                                      Op0BO->getName());
6113             InsertNewInstBefore(YS, I); // (Y << C)
6114             Instruction *X =
6115               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6116                                      Op0BO->getOperand(0)->getName());
6117             InsertNewInstBefore(X, I);  // (X + (Y << C))
6118             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6119             return BinaryOperator::createAnd(X, ConstantInt::get(
6120                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6121           }
6122           
6123           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6124           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6125               match(Op0BO->getOperand(0),
6126                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6127                           m_ConstantInt(CC))) && V2 == Op1 &&
6128               cast<BinaryOperator>(Op0BO->getOperand(0))
6129                   ->getOperand(0)->hasOneUse()) {
6130             Instruction *YS = BinaryOperator::createShl(
6131                                                      Op0BO->getOperand(1), Op1,
6132                                                      Op0BO->getName());
6133             InsertNewInstBefore(YS, I); // (Y << C)
6134             Instruction *XM =
6135               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6136                                         V1->getName()+".mask");
6137             InsertNewInstBefore(XM, I); // X & (CC << C)
6138             
6139             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6140           }
6141           
6142           break;
6143         }
6144       }
6145       
6146       
6147       // If the operand is an bitwise operator with a constant RHS, and the
6148       // shift is the only use, we can pull it out of the shift.
6149       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6150         bool isValid = true;     // Valid only for And, Or, Xor
6151         bool highBitSet = false; // Transform if high bit of constant set?
6152         
6153         switch (Op0BO->getOpcode()) {
6154           default: isValid = false; break;   // Do not perform transform!
6155           case Instruction::Add:
6156             isValid = isLeftShift;
6157             break;
6158           case Instruction::Or:
6159           case Instruction::Xor:
6160             highBitSet = false;
6161             break;
6162           case Instruction::And:
6163             highBitSet = true;
6164             break;
6165         }
6166         
6167         // If this is a signed shift right, and the high bit is modified
6168         // by the logical operation, do not perform the transformation.
6169         // The highBitSet boolean indicates the value of the high bit of
6170         // the constant which would cause it to be modified for this
6171         // operation.
6172         //
6173         if (isValid && I.getOpcode() == Instruction::AShr)
6174           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6175         
6176         if (isValid) {
6177           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6178           
6179           Instruction *NewShift =
6180             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6181           InsertNewInstBefore(NewShift, I);
6182           NewShift->takeName(Op0BO);
6183           
6184           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6185                                         NewRHS);
6186         }
6187       }
6188     }
6189   }
6190   
6191   // Find out if this is a shift of a shift by a constant.
6192   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6193   if (ShiftOp && !ShiftOp->isShift())
6194     ShiftOp = 0;
6195   
6196   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6197     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6198     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6199     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6200     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6201     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6202     Value *X = ShiftOp->getOperand(0);
6203     
6204     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6205     if (AmtSum > TypeBits)
6206       AmtSum = TypeBits;
6207     
6208     const IntegerType *Ty = cast<IntegerType>(I.getType());
6209     
6210     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6211     if (I.getOpcode() == ShiftOp->getOpcode()) {
6212       return BinaryOperator::create(I.getOpcode(), X,
6213                                     ConstantInt::get(Ty, AmtSum));
6214     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6215                I.getOpcode() == Instruction::AShr) {
6216       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6217       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6218     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6219                I.getOpcode() == Instruction::LShr) {
6220       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6221       Instruction *Shift =
6222         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6223       InsertNewInstBefore(Shift, I);
6224
6225       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6226       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6227     }
6228     
6229     // Okay, if we get here, one shift must be left, and the other shift must be
6230     // right.  See if the amounts are equal.
6231     if (ShiftAmt1 == ShiftAmt2) {
6232       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6233       if (I.getOpcode() == Instruction::Shl) {
6234         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6235         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6236       }
6237       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6238       if (I.getOpcode() == Instruction::LShr) {
6239         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6240         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6241       }
6242       // We can simplify ((X << C) >>s C) into a trunc + sext.
6243       // NOTE: we could do this for any C, but that would make 'unusual' integer
6244       // types.  For now, just stick to ones well-supported by the code
6245       // generators.
6246       const Type *SExtType = 0;
6247       switch (Ty->getBitWidth() - ShiftAmt1) {
6248       case 1  :
6249       case 8  :
6250       case 16 :
6251       case 32 :
6252       case 64 :
6253       case 128:
6254         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6255         break;
6256       default: break;
6257       }
6258       if (SExtType) {
6259         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6260         InsertNewInstBefore(NewTrunc, I);
6261         return new SExtInst(NewTrunc, Ty);
6262       }
6263       // Otherwise, we can't handle it yet.
6264     } else if (ShiftAmt1 < ShiftAmt2) {
6265       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6266       
6267       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6268       if (I.getOpcode() == Instruction::Shl) {
6269         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6270                ShiftOp->getOpcode() == Instruction::AShr);
6271         Instruction *Shift =
6272           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6273         InsertNewInstBefore(Shift, I);
6274         
6275         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6276         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6277       }
6278       
6279       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6280       if (I.getOpcode() == Instruction::LShr) {
6281         assert(ShiftOp->getOpcode() == Instruction::Shl);
6282         Instruction *Shift =
6283           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6284         InsertNewInstBefore(Shift, I);
6285         
6286         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6287         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6288       }
6289       
6290       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6291     } else {
6292       assert(ShiftAmt2 < ShiftAmt1);
6293       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6294
6295       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6296       if (I.getOpcode() == Instruction::Shl) {
6297         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6298                ShiftOp->getOpcode() == Instruction::AShr);
6299         Instruction *Shift =
6300           BinaryOperator::create(ShiftOp->getOpcode(), X,
6301                                  ConstantInt::get(Ty, ShiftDiff));
6302         InsertNewInstBefore(Shift, I);
6303         
6304         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6305         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6306       }
6307       
6308       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6309       if (I.getOpcode() == Instruction::LShr) {
6310         assert(ShiftOp->getOpcode() == Instruction::Shl);
6311         Instruction *Shift =
6312           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6313         InsertNewInstBefore(Shift, I);
6314         
6315         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6316         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6317       }
6318       
6319       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6320     }
6321   }
6322   return 0;
6323 }
6324
6325
6326 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6327 /// expression.  If so, decompose it, returning some value X, such that Val is
6328 /// X*Scale+Offset.
6329 ///
6330 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6331                                         int &Offset) {
6332   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6333   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6334     Offset = CI->getZExtValue();
6335     Scale  = 0;
6336     return ConstantInt::get(Type::Int32Ty, 0);
6337   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6338     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6339       if (I->getOpcode() == Instruction::Shl) {
6340         // This is a value scaled by '1 << the shift amt'.
6341         Scale = 1U << RHS->getZExtValue();
6342         Offset = 0;
6343         return I->getOperand(0);
6344       } else if (I->getOpcode() == Instruction::Mul) {
6345         // This value is scaled by 'RHS'.
6346         Scale = RHS->getZExtValue();
6347         Offset = 0;
6348         return I->getOperand(0);
6349       } else if (I->getOpcode() == Instruction::Add) {
6350         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6351         // where C1 is divisible by C2.
6352         unsigned SubScale;
6353         Value *SubVal = 
6354           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6355         Offset += RHS->getZExtValue();
6356         Scale = SubScale;
6357         return SubVal;
6358       }
6359     }
6360   }
6361
6362   // Otherwise, we can't look past this.
6363   Scale = 1;
6364   Offset = 0;
6365   return Val;
6366 }
6367
6368
6369 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6370 /// try to eliminate the cast by moving the type information into the alloc.
6371 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6372                                                    AllocationInst &AI) {
6373   const PointerType *PTy = cast<PointerType>(CI.getType());
6374   
6375   // Remove any uses of AI that are dead.
6376   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6377   
6378   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6379     Instruction *User = cast<Instruction>(*UI++);
6380     if (isInstructionTriviallyDead(User)) {
6381       while (UI != E && *UI == User)
6382         ++UI; // If this instruction uses AI more than once, don't break UI.
6383       
6384       ++NumDeadInst;
6385       DOUT << "IC: DCE: " << *User;
6386       EraseInstFromFunction(*User);
6387     }
6388   }
6389   
6390   // Get the type really allocated and the type casted to.
6391   const Type *AllocElTy = AI.getAllocatedType();
6392   const Type *CastElTy = PTy->getElementType();
6393   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6394
6395   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6396   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6397   if (CastElTyAlign < AllocElTyAlign) return 0;
6398
6399   // If the allocation has multiple uses, only promote it if we are strictly
6400   // increasing the alignment of the resultant allocation.  If we keep it the
6401   // same, we open the door to infinite loops of various kinds.
6402   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6403
6404   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6405   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6406   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6407
6408   // See if we can satisfy the modulus by pulling a scale out of the array
6409   // size argument.
6410   unsigned ArraySizeScale;
6411   int ArrayOffset;
6412   Value *NumElements = // See if the array size is a decomposable linear expr.
6413     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6414  
6415   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6416   // do the xform.
6417   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6418       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6419
6420   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6421   Value *Amt = 0;
6422   if (Scale == 1) {
6423     Amt = NumElements;
6424   } else {
6425     // If the allocation size is constant, form a constant mul expression
6426     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6427     if (isa<ConstantInt>(NumElements))
6428       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6429     // otherwise multiply the amount and the number of elements
6430     else if (Scale != 1) {
6431       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6432       Amt = InsertNewInstBefore(Tmp, AI);
6433     }
6434   }
6435   
6436   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6437     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6438     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6439     Amt = InsertNewInstBefore(Tmp, AI);
6440   }
6441   
6442   AllocationInst *New;
6443   if (isa<MallocInst>(AI))
6444     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6445   else
6446     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6447   InsertNewInstBefore(New, AI);
6448   New->takeName(&AI);
6449   
6450   // If the allocation has multiple uses, insert a cast and change all things
6451   // that used it to use the new cast.  This will also hack on CI, but it will
6452   // die soon.
6453   if (!AI.hasOneUse()) {
6454     AddUsesToWorkList(AI);
6455     // New is the allocation instruction, pointer typed. AI is the original
6456     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6457     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6458     InsertNewInstBefore(NewCast, AI);
6459     AI.replaceAllUsesWith(NewCast);
6460   }
6461   return ReplaceInstUsesWith(CI, New);
6462 }
6463
6464 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6465 /// and return it as type Ty without inserting any new casts and without
6466 /// changing the computed value.  This is used by code that tries to decide
6467 /// whether promoting or shrinking integer operations to wider or smaller types
6468 /// will allow us to eliminate a truncate or extend.
6469 ///
6470 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6471 /// extension operation if Ty is larger.
6472 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6473                                        unsigned CastOpc, int &NumCastsRemoved) {
6474   // We can always evaluate constants in another type.
6475   if (isa<ConstantInt>(V))
6476     return true;
6477   
6478   Instruction *I = dyn_cast<Instruction>(V);
6479   if (!I) return false;
6480   
6481   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6482   
6483   // If this is an extension or truncate, we can often eliminate it.
6484   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6485     // If this is a cast from the destination type, we can trivially eliminate
6486     // it, and this will remove a cast overall.
6487     if (I->getOperand(0)->getType() == Ty) {
6488       // If the first operand is itself a cast, and is eliminable, do not count
6489       // this as an eliminable cast.  We would prefer to eliminate those two
6490       // casts first.
6491       if (!isa<CastInst>(I->getOperand(0)))
6492         ++NumCastsRemoved;
6493       return true;
6494     }
6495   }
6496
6497   // We can't extend or shrink something that has multiple uses: doing so would
6498   // require duplicating the instruction in general, which isn't profitable.
6499   if (!I->hasOneUse()) return false;
6500
6501   switch (I->getOpcode()) {
6502   case Instruction::Add:
6503   case Instruction::Sub:
6504   case Instruction::And:
6505   case Instruction::Or:
6506   case Instruction::Xor:
6507     // These operators can all arbitrarily be extended or truncated.
6508     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6509                                       NumCastsRemoved) &&
6510            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6511                                       NumCastsRemoved);
6512
6513   case Instruction::Shl:
6514     // If we are truncating the result of this SHL, and if it's a shift of a
6515     // constant amount, we can always perform a SHL in a smaller type.
6516     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6517       uint32_t BitWidth = Ty->getBitWidth();
6518       if (BitWidth < OrigTy->getBitWidth() && 
6519           CI->getLimitedValue(BitWidth) < BitWidth)
6520         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6521                                           NumCastsRemoved);
6522     }
6523     break;
6524   case Instruction::LShr:
6525     // If this is a truncate of a logical shr, we can truncate it to a smaller
6526     // lshr iff we know that the bits we would otherwise be shifting in are
6527     // already zeros.
6528     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6529       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6530       uint32_t BitWidth = Ty->getBitWidth();
6531       if (BitWidth < OrigBitWidth &&
6532           MaskedValueIsZero(I->getOperand(0),
6533             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6534           CI->getLimitedValue(BitWidth) < BitWidth) {
6535         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6536                                           NumCastsRemoved);
6537       }
6538     }
6539     break;
6540   case Instruction::ZExt:
6541   case Instruction::SExt:
6542   case Instruction::Trunc:
6543     // If this is the same kind of case as our original (e.g. zext+zext), we
6544     // can safely replace it.  Note that replacing it does not reduce the number
6545     // of casts in the input.
6546     if (I->getOpcode() == CastOpc)
6547       return true;
6548     
6549     break;
6550   default:
6551     // TODO: Can handle more cases here.
6552     break;
6553   }
6554   
6555   return false;
6556 }
6557
6558 /// EvaluateInDifferentType - Given an expression that 
6559 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6560 /// evaluate the expression.
6561 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6562                                              bool isSigned) {
6563   if (Constant *C = dyn_cast<Constant>(V))
6564     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6565
6566   // Otherwise, it must be an instruction.
6567   Instruction *I = cast<Instruction>(V);
6568   Instruction *Res = 0;
6569   switch (I->getOpcode()) {
6570   case Instruction::Add:
6571   case Instruction::Sub:
6572   case Instruction::And:
6573   case Instruction::Or:
6574   case Instruction::Xor:
6575   case Instruction::AShr:
6576   case Instruction::LShr:
6577   case Instruction::Shl: {
6578     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6579     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6580     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6581                                  LHS, RHS, I->getName());
6582     break;
6583   }    
6584   case Instruction::Trunc:
6585   case Instruction::ZExt:
6586   case Instruction::SExt:
6587     // If the source type of the cast is the type we're trying for then we can
6588     // just return the source.  There's no need to insert it because it is not
6589     // new.
6590     if (I->getOperand(0)->getType() == Ty)
6591       return I->getOperand(0);
6592     
6593     // Otherwise, must be the same type of case, so just reinsert a new one.
6594     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6595                            Ty, I->getName());
6596     break;
6597   default: 
6598     // TODO: Can handle more cases here.
6599     assert(0 && "Unreachable!");
6600     break;
6601   }
6602   
6603   return InsertNewInstBefore(Res, *I);
6604 }
6605
6606 /// @brief Implement the transforms common to all CastInst visitors.
6607 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6608   Value *Src = CI.getOperand(0);
6609
6610   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6611   // eliminate it now.
6612   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6613     if (Instruction::CastOps opc = 
6614         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6615       // The first cast (CSrc) is eliminable so we need to fix up or replace
6616       // the second cast (CI). CSrc will then have a good chance of being dead.
6617       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6618     }
6619   }
6620
6621   // If we are casting a select then fold the cast into the select
6622   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6623     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6624       return NV;
6625
6626   // If we are casting a PHI then fold the cast into the PHI
6627   if (isa<PHINode>(Src))
6628     if (Instruction *NV = FoldOpIntoPhi(CI))
6629       return NV;
6630   
6631   return 0;
6632 }
6633
6634 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6635 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6636   Value *Src = CI.getOperand(0);
6637   
6638   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6639     // If casting the result of a getelementptr instruction with no offset, turn
6640     // this into a cast of the original pointer!
6641     if (GEP->hasAllZeroIndices()) {
6642       // Changing the cast operand is usually not a good idea but it is safe
6643       // here because the pointer operand is being replaced with another 
6644       // pointer operand so the opcode doesn't need to change.
6645       AddToWorkList(GEP);
6646       CI.setOperand(0, GEP->getOperand(0));
6647       return &CI;
6648     }
6649     
6650     // If the GEP has a single use, and the base pointer is a bitcast, and the
6651     // GEP computes a constant offset, see if we can convert these three
6652     // instructions into fewer.  This typically happens with unions and other
6653     // non-type-safe code.
6654     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6655       if (GEP->hasAllConstantIndices()) {
6656         // We are guaranteed to get a constant from EmitGEPOffset.
6657         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6658         int64_t Offset = OffsetV->getSExtValue();
6659         
6660         // Get the base pointer input of the bitcast, and the type it points to.
6661         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6662         const Type *GEPIdxTy =
6663           cast<PointerType>(OrigBase->getType())->getElementType();
6664         if (GEPIdxTy->isSized()) {
6665           SmallVector<Value*, 8> NewIndices;
6666           
6667           // Start with the index over the outer type.  Note that the type size
6668           // might be zero (even if the offset isn't zero) if the indexed type
6669           // is something like [0 x {int, int}]
6670           const Type *IntPtrTy = TD->getIntPtrType();
6671           int64_t FirstIdx = 0;
6672           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6673             FirstIdx = Offset/TySize;
6674             Offset %= TySize;
6675           
6676             // Handle silly modulus not returning values values [0..TySize).
6677             if (Offset < 0) {
6678               --FirstIdx;
6679               Offset += TySize;
6680               assert(Offset >= 0);
6681             }
6682             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6683           }
6684           
6685           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6686
6687           // Index into the types.  If we fail, set OrigBase to null.
6688           while (Offset) {
6689             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6690               const StructLayout *SL = TD->getStructLayout(STy);
6691               if (Offset < (int64_t)SL->getSizeInBytes()) {
6692                 unsigned Elt = SL->getElementContainingOffset(Offset);
6693                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6694               
6695                 Offset -= SL->getElementOffset(Elt);
6696                 GEPIdxTy = STy->getElementType(Elt);
6697               } else {
6698                 // Otherwise, we can't index into this, bail out.
6699                 Offset = 0;
6700                 OrigBase = 0;
6701               }
6702             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6703               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6704               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6705                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6706                 Offset %= EltSize;
6707               } else {
6708                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6709               }
6710               GEPIdxTy = STy->getElementType();
6711             } else {
6712               // Otherwise, we can't index into this, bail out.
6713               Offset = 0;
6714               OrigBase = 0;
6715             }
6716           }
6717           if (OrigBase) {
6718             // If we were able to index down into an element, create the GEP
6719             // and bitcast the result.  This eliminates one bitcast, potentially
6720             // two.
6721             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6722                                                       NewIndices.begin(),
6723                                                       NewIndices.end(), "");
6724             InsertNewInstBefore(NGEP, CI);
6725             NGEP->takeName(GEP);
6726             
6727             if (isa<BitCastInst>(CI))
6728               return new BitCastInst(NGEP, CI.getType());
6729             assert(isa<PtrToIntInst>(CI));
6730             return new PtrToIntInst(NGEP, CI.getType());
6731           }
6732         }
6733       }      
6734     }
6735   }
6736     
6737   return commonCastTransforms(CI);
6738 }
6739
6740
6741
6742 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6743 /// integer types. This function implements the common transforms for all those
6744 /// cases.
6745 /// @brief Implement the transforms common to CastInst with integer operands
6746 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6747   if (Instruction *Result = commonCastTransforms(CI))
6748     return Result;
6749
6750   Value *Src = CI.getOperand(0);
6751   const Type *SrcTy = Src->getType();
6752   const Type *DestTy = CI.getType();
6753   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6754   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6755
6756   // See if we can simplify any instructions used by the LHS whose sole 
6757   // purpose is to compute bits we don't care about.
6758   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6759   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6760                            KnownZero, KnownOne))
6761     return &CI;
6762
6763   // If the source isn't an instruction or has more than one use then we
6764   // can't do anything more. 
6765   Instruction *SrcI = dyn_cast<Instruction>(Src);
6766   if (!SrcI || !Src->hasOneUse())
6767     return 0;
6768
6769   // Attempt to propagate the cast into the instruction for int->int casts.
6770   int NumCastsRemoved = 0;
6771   if (!isa<BitCastInst>(CI) &&
6772       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6773                                  CI.getOpcode(), NumCastsRemoved)) {
6774     // If this cast is a truncate, evaluting in a different type always
6775     // eliminates the cast, so it is always a win.  If this is a zero-extension,
6776     // we need to do an AND to maintain the clear top-part of the computation,
6777     // so we require that the input have eliminated at least one cast.  If this
6778     // is a sign extension, we insert two new casts (to do the extension) so we
6779     // require that two casts have been eliminated.
6780     bool DoXForm;
6781     switch (CI.getOpcode()) {
6782     default:
6783       // All the others use floating point so we shouldn't actually 
6784       // get here because of the check above.
6785       assert(0 && "Unknown cast type");
6786     case Instruction::Trunc:
6787       DoXForm = true;
6788       break;
6789     case Instruction::ZExt:
6790       DoXForm = NumCastsRemoved >= 1;
6791       break;
6792     case Instruction::SExt:
6793       DoXForm = NumCastsRemoved >= 2;
6794       break;
6795     }
6796     
6797     if (DoXForm) {
6798       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6799                                            CI.getOpcode() == Instruction::SExt);
6800       assert(Res->getType() == DestTy);
6801       switch (CI.getOpcode()) {
6802       default: assert(0 && "Unknown cast type!");
6803       case Instruction::Trunc:
6804       case Instruction::BitCast:
6805         // Just replace this cast with the result.
6806         return ReplaceInstUsesWith(CI, Res);
6807       case Instruction::ZExt: {
6808         // We need to emit an AND to clear the high bits.
6809         assert(SrcBitSize < DestBitSize && "Not a zext?");
6810         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6811                                                             SrcBitSize));
6812         return BinaryOperator::createAnd(Res, C);
6813       }
6814       case Instruction::SExt:
6815         // We need to emit a cast to truncate, then a cast to sext.
6816         return CastInst::create(Instruction::SExt,
6817             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6818                              CI), DestTy);
6819       }
6820     }
6821   }
6822   
6823   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6824   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6825
6826   switch (SrcI->getOpcode()) {
6827   case Instruction::Add:
6828   case Instruction::Mul:
6829   case Instruction::And:
6830   case Instruction::Or:
6831   case Instruction::Xor:
6832     // If we are discarding information, rewrite.
6833     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6834       // Don't insert two casts if they cannot be eliminated.  We allow 
6835       // two casts to be inserted if the sizes are the same.  This could 
6836       // only be converting signedness, which is a noop.
6837       if (DestBitSize == SrcBitSize || 
6838           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6839           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6840         Instruction::CastOps opcode = CI.getOpcode();
6841         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6842         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6843         return BinaryOperator::create(
6844             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6845       }
6846     }
6847
6848     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6849     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6850         SrcI->getOpcode() == Instruction::Xor &&
6851         Op1 == ConstantInt::getTrue() &&
6852         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6853       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6854       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6855     }
6856     break;
6857   case Instruction::SDiv:
6858   case Instruction::UDiv:
6859   case Instruction::SRem:
6860   case Instruction::URem:
6861     // If we are just changing the sign, rewrite.
6862     if (DestBitSize == SrcBitSize) {
6863       // Don't insert two casts if they cannot be eliminated.  We allow 
6864       // two casts to be inserted if the sizes are the same.  This could 
6865       // only be converting signedness, which is a noop.
6866       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6867           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6868         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6869                                               Op0, DestTy, SrcI);
6870         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6871                                               Op1, DestTy, SrcI);
6872         return BinaryOperator::create(
6873           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6874       }
6875     }
6876     break;
6877
6878   case Instruction::Shl:
6879     // Allow changing the sign of the source operand.  Do not allow 
6880     // changing the size of the shift, UNLESS the shift amount is a 
6881     // constant.  We must not change variable sized shifts to a smaller 
6882     // size, because it is undefined to shift more bits out than exist 
6883     // in the value.
6884     if (DestBitSize == SrcBitSize ||
6885         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6886       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6887           Instruction::BitCast : Instruction::Trunc);
6888       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6889       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6890       return BinaryOperator::createShl(Op0c, Op1c);
6891     }
6892     break;
6893   case Instruction::AShr:
6894     // If this is a signed shr, and if all bits shifted in are about to be
6895     // truncated off, turn it into an unsigned shr to allow greater
6896     // simplifications.
6897     if (DestBitSize < SrcBitSize &&
6898         isa<ConstantInt>(Op1)) {
6899       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6900       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6901         // Insert the new logical shift right.
6902         return BinaryOperator::createLShr(Op0, Op1);
6903       }
6904     }
6905     break;
6906   }
6907   return 0;
6908 }
6909
6910 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6911   if (Instruction *Result = commonIntCastTransforms(CI))
6912     return Result;
6913   
6914   Value *Src = CI.getOperand(0);
6915   const Type *Ty = CI.getType();
6916   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6917   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6918   
6919   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6920     switch (SrcI->getOpcode()) {
6921     default: break;
6922     case Instruction::LShr:
6923       // We can shrink lshr to something smaller if we know the bits shifted in
6924       // are already zeros.
6925       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6926         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6927         
6928         // Get a mask for the bits shifting in.
6929         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6930         Value* SrcIOp0 = SrcI->getOperand(0);
6931         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6932           if (ShAmt >= DestBitWidth)        // All zeros.
6933             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6934
6935           // Okay, we can shrink this.  Truncate the input, then return a new
6936           // shift.
6937           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6938           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6939                                        Ty, CI);
6940           return BinaryOperator::createLShr(V1, V2);
6941         }
6942       } else {     // This is a variable shr.
6943         
6944         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6945         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6946         // loop-invariant and CSE'd.
6947         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6948           Value *One = ConstantInt::get(SrcI->getType(), 1);
6949
6950           Value *V = InsertNewInstBefore(
6951               BinaryOperator::createShl(One, SrcI->getOperand(1),
6952                                      "tmp"), CI);
6953           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6954                                                             SrcI->getOperand(0),
6955                                                             "tmp"), CI);
6956           Value *Zero = Constant::getNullValue(V->getType());
6957           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6958         }
6959       }
6960       break;
6961     }
6962   }
6963   
6964   return 0;
6965 }
6966
6967 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6968   // If one of the common conversion will work ..
6969   if (Instruction *Result = commonIntCastTransforms(CI))
6970     return Result;
6971
6972   Value *Src = CI.getOperand(0);
6973
6974   // If this is a cast of a cast
6975   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6976     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6977     // types and if the sizes are just right we can convert this into a logical
6978     // 'and' which will be much cheaper than the pair of casts.
6979     if (isa<TruncInst>(CSrc)) {
6980       // Get the sizes of the types involved
6981       Value *A = CSrc->getOperand(0);
6982       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6983       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6984       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6985       // If we're actually extending zero bits and the trunc is a no-op
6986       if (MidSize < DstSize && SrcSize == DstSize) {
6987         // Replace both of the casts with an And of the type mask.
6988         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
6989         Constant *AndConst = ConstantInt::get(AndValue);
6990         Instruction *And = 
6991           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6992         // Unfortunately, if the type changed, we need to cast it back.
6993         if (And->getType() != CI.getType()) {
6994           And->setName(CSrc->getName()+".mask");
6995           InsertNewInstBefore(And, CI);
6996           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6997         }
6998         return And;
6999       }
7000     }
7001   }
7002
7003   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7004     // If we are just checking for a icmp eq of a single bit and zext'ing it
7005     // to an integer, then shift the bit to the appropriate place and then
7006     // cast to integer to avoid the comparison.
7007     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7008       const APInt &Op1CV = Op1C->getValue();
7009       
7010       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7011       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7012       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7013           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7014         Value *In = ICI->getOperand(0);
7015         Value *Sh = ConstantInt::get(In->getType(),
7016                                     In->getType()->getPrimitiveSizeInBits()-1);
7017         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7018                                                         In->getName()+".lobit"),
7019                                  CI);
7020         if (In->getType() != CI.getType())
7021           In = CastInst::createIntegerCast(In, CI.getType(),
7022                                            false/*ZExt*/, "tmp", &CI);
7023
7024         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7025           Constant *One = ConstantInt::get(In->getType(), 1);
7026           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7027                                                           In->getName()+".not"),
7028                                    CI);
7029         }
7030
7031         return ReplaceInstUsesWith(CI, In);
7032       }
7033       
7034       
7035       
7036       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7037       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7038       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7039       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7040       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7041       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7042       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7043       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7044       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7045           // This only works for EQ and NE
7046           ICI->isEquality()) {
7047         // If Op1C some other power of two, convert:
7048         uint32_t BitWidth = Op1C->getType()->getBitWidth();
7049         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7050         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7051         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7052         
7053         APInt KnownZeroMask(~KnownZero);
7054         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7055           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7056           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7057             // (X&4) == 2 --> false
7058             // (X&4) != 2 --> true
7059             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7060             Res = ConstantExpr::getZExt(Res, CI.getType());
7061             return ReplaceInstUsesWith(CI, Res);
7062           }
7063           
7064           uint32_t ShiftAmt = KnownZeroMask.logBase2();
7065           Value *In = ICI->getOperand(0);
7066           if (ShiftAmt) {
7067             // Perform a logical shr by shiftamt.
7068             // Insert the shift to put the result in the low bit.
7069             In = InsertNewInstBefore(
7070                    BinaryOperator::createLShr(In,
7071                                      ConstantInt::get(In->getType(), ShiftAmt),
7072                                               In->getName()+".lobit"), CI);
7073           }
7074           
7075           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7076             Constant *One = ConstantInt::get(In->getType(), 1);
7077             In = BinaryOperator::createXor(In, One, "tmp");
7078             InsertNewInstBefore(cast<Instruction>(In), CI);
7079           }
7080           
7081           if (CI.getType() == In->getType())
7082             return ReplaceInstUsesWith(CI, In);
7083           else
7084             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7085         }
7086       }
7087     }
7088   }    
7089   return 0;
7090 }
7091
7092 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7093   if (Instruction *I = commonIntCastTransforms(CI))
7094     return I;
7095   
7096   Value *Src = CI.getOperand(0);
7097   
7098   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7099   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7100   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7101     // If we are just checking for a icmp eq of a single bit and zext'ing it
7102     // to an integer, then shift the bit to the appropriate place and then
7103     // cast to integer to avoid the comparison.
7104     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7105       const APInt &Op1CV = Op1C->getValue();
7106       
7107       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7108       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7109       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7110           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7111         Value *In = ICI->getOperand(0);
7112         Value *Sh = ConstantInt::get(In->getType(),
7113                                      In->getType()->getPrimitiveSizeInBits()-1);
7114         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7115                                                         In->getName()+".lobit"),
7116                                  CI);
7117         if (In->getType() != CI.getType())
7118           In = CastInst::createIntegerCast(In, CI.getType(),
7119                                            true/*SExt*/, "tmp", &CI);
7120         
7121         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7122           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7123                                      In->getName()+".not"), CI);
7124         
7125         return ReplaceInstUsesWith(CI, In);
7126       }
7127     }
7128   }
7129       
7130   return 0;
7131 }
7132
7133 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7134   return commonCastTransforms(CI);
7135 }
7136
7137 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7138   return commonCastTransforms(CI);
7139 }
7140
7141 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7142   return commonCastTransforms(CI);
7143 }
7144
7145 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7146   return commonCastTransforms(CI);
7147 }
7148
7149 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7150   return commonCastTransforms(CI);
7151 }
7152
7153 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7154   return commonCastTransforms(CI);
7155 }
7156
7157 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7158   return commonPointerCastTransforms(CI);
7159 }
7160
7161 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7162   if (Instruction *I = commonCastTransforms(CI))
7163     return I;
7164   
7165   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7166   if (!DestPointee->isSized()) return 0;
7167
7168   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7169   ConstantInt *Cst;
7170   Value *X;
7171   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7172                                     m_ConstantInt(Cst)))) {
7173     // If the source and destination operands have the same type, see if this
7174     // is a single-index GEP.
7175     if (X->getType() == CI.getType()) {
7176       // Get the size of the pointee type.
7177       uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7178
7179       // Convert the constant to intptr type.
7180       APInt Offset = Cst->getValue();
7181       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7182
7183       // If Offset is evenly divisible by Size, we can do this xform.
7184       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7185         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7186         return new GetElementPtrInst(X, ConstantInt::get(Offset));
7187       }
7188     }
7189     // TODO: Could handle other cases, e.g. where add is indexing into field of
7190     // struct etc.
7191   } else if (CI.getOperand(0)->hasOneUse() &&
7192              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7193     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7194     // "inttoptr+GEP" instead of "add+intptr".
7195     
7196     // Get the size of the pointee type.
7197     uint64_t Size = TD->getABITypeSize(DestPointee);
7198     
7199     // Convert the constant to intptr type.
7200     APInt Offset = Cst->getValue();
7201     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7202     
7203     // If Offset is evenly divisible by Size, we can do this xform.
7204     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7205       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7206       
7207       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7208                                                             "tmp"), CI);
7209       return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7210     }
7211   }
7212   return 0;
7213 }
7214
7215 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7216   // If the operands are integer typed then apply the integer transforms,
7217   // otherwise just apply the common ones.
7218   Value *Src = CI.getOperand(0);
7219   const Type *SrcTy = Src->getType();
7220   const Type *DestTy = CI.getType();
7221
7222   if (SrcTy->isInteger() && DestTy->isInteger()) {
7223     if (Instruction *Result = commonIntCastTransforms(CI))
7224       return Result;
7225   } else if (isa<PointerType>(SrcTy)) {
7226     if (Instruction *I = commonPointerCastTransforms(CI))
7227       return I;
7228   } else {
7229     if (Instruction *Result = commonCastTransforms(CI))
7230       return Result;
7231   }
7232
7233
7234   // Get rid of casts from one type to the same type. These are useless and can
7235   // be replaced by the operand.
7236   if (DestTy == Src->getType())
7237     return ReplaceInstUsesWith(CI, Src);
7238
7239   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7240     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7241     const Type *DstElTy = DstPTy->getElementType();
7242     const Type *SrcElTy = SrcPTy->getElementType();
7243     
7244     // If we are casting a malloc or alloca to a pointer to a type of the same
7245     // size, rewrite the allocation instruction to allocate the "right" type.
7246     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7247       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7248         return V;
7249     
7250     // If the source and destination are pointers, and this cast is equivalent
7251     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7252     // This can enhance SROA and other transforms that want type-safe pointers.
7253     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7254     unsigned NumZeros = 0;
7255     while (SrcElTy != DstElTy && 
7256            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7257            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7258       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7259       ++NumZeros;
7260     }
7261
7262     // If we found a path from the src to dest, create the getelementptr now.
7263     if (SrcElTy == DstElTy) {
7264       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7265       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7266                                    ((Instruction*) NULL));
7267     }
7268   }
7269
7270   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7271     if (SVI->hasOneUse()) {
7272       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7273       // a bitconvert to a vector with the same # elts.
7274       if (isa<VectorType>(DestTy) && 
7275           cast<VectorType>(DestTy)->getNumElements() == 
7276                 SVI->getType()->getNumElements()) {
7277         CastInst *Tmp;
7278         // If either of the operands is a cast from CI.getType(), then
7279         // evaluating the shuffle in the casted destination's type will allow
7280         // us to eliminate at least one cast.
7281         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7282              Tmp->getOperand(0)->getType() == DestTy) ||
7283             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7284              Tmp->getOperand(0)->getType() == DestTy)) {
7285           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7286                                                SVI->getOperand(0), DestTy, &CI);
7287           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7288                                                SVI->getOperand(1), DestTy, &CI);
7289           // Return a new shuffle vector.  Use the same element ID's, as we
7290           // know the vector types match #elts.
7291           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7292         }
7293       }
7294     }
7295   }
7296   return 0;
7297 }
7298
7299 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7300 ///   %C = or %A, %B
7301 ///   %D = select %cond, %C, %A
7302 /// into:
7303 ///   %C = select %cond, %B, 0
7304 ///   %D = or %A, %C
7305 ///
7306 /// Assuming that the specified instruction is an operand to the select, return
7307 /// a bitmask indicating which operands of this instruction are foldable if they
7308 /// equal the other incoming value of the select.
7309 ///
7310 static unsigned GetSelectFoldableOperands(Instruction *I) {
7311   switch (I->getOpcode()) {
7312   case Instruction::Add:
7313   case Instruction::Mul:
7314   case Instruction::And:
7315   case Instruction::Or:
7316   case Instruction::Xor:
7317     return 3;              // Can fold through either operand.
7318   case Instruction::Sub:   // Can only fold on the amount subtracted.
7319   case Instruction::Shl:   // Can only fold on the shift amount.
7320   case Instruction::LShr:
7321   case Instruction::AShr:
7322     return 1;
7323   default:
7324     return 0;              // Cannot fold
7325   }
7326 }
7327
7328 /// GetSelectFoldableConstant - For the same transformation as the previous
7329 /// function, return the identity constant that goes into the select.
7330 static Constant *GetSelectFoldableConstant(Instruction *I) {
7331   switch (I->getOpcode()) {
7332   default: assert(0 && "This cannot happen!"); abort();
7333   case Instruction::Add:
7334   case Instruction::Sub:
7335   case Instruction::Or:
7336   case Instruction::Xor:
7337   case Instruction::Shl:
7338   case Instruction::LShr:
7339   case Instruction::AShr:
7340     return Constant::getNullValue(I->getType());
7341   case Instruction::And:
7342     return Constant::getAllOnesValue(I->getType());
7343   case Instruction::Mul:
7344     return ConstantInt::get(I->getType(), 1);
7345   }
7346 }
7347
7348 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7349 /// have the same opcode and only one use each.  Try to simplify this.
7350 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7351                                           Instruction *FI) {
7352   if (TI->getNumOperands() == 1) {
7353     // If this is a non-volatile load or a cast from the same type,
7354     // merge.
7355     if (TI->isCast()) {
7356       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7357         return 0;
7358     } else {
7359       return 0;  // unknown unary op.
7360     }
7361
7362     // Fold this by inserting a select from the input values.
7363     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7364                                        FI->getOperand(0), SI.getName()+".v");
7365     InsertNewInstBefore(NewSI, SI);
7366     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7367                             TI->getType());
7368   }
7369
7370   // Only handle binary operators here.
7371   if (!isa<BinaryOperator>(TI))
7372     return 0;
7373
7374   // Figure out if the operations have any operands in common.
7375   Value *MatchOp, *OtherOpT, *OtherOpF;
7376   bool MatchIsOpZero;
7377   if (TI->getOperand(0) == FI->getOperand(0)) {
7378     MatchOp  = TI->getOperand(0);
7379     OtherOpT = TI->getOperand(1);
7380     OtherOpF = FI->getOperand(1);
7381     MatchIsOpZero = true;
7382   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7383     MatchOp  = TI->getOperand(1);
7384     OtherOpT = TI->getOperand(0);
7385     OtherOpF = FI->getOperand(0);
7386     MatchIsOpZero = false;
7387   } else if (!TI->isCommutative()) {
7388     return 0;
7389   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7390     MatchOp  = TI->getOperand(0);
7391     OtherOpT = TI->getOperand(1);
7392     OtherOpF = FI->getOperand(0);
7393     MatchIsOpZero = true;
7394   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7395     MatchOp  = TI->getOperand(1);
7396     OtherOpT = TI->getOperand(0);
7397     OtherOpF = FI->getOperand(1);
7398     MatchIsOpZero = true;
7399   } else {
7400     return 0;
7401   }
7402
7403   // If we reach here, they do have operations in common.
7404   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7405                                      OtherOpF, SI.getName()+".v");
7406   InsertNewInstBefore(NewSI, SI);
7407
7408   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7409     if (MatchIsOpZero)
7410       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7411     else
7412       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7413   }
7414   assert(0 && "Shouldn't get here");
7415   return 0;
7416 }
7417
7418 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7419   Value *CondVal = SI.getCondition();
7420   Value *TrueVal = SI.getTrueValue();
7421   Value *FalseVal = SI.getFalseValue();
7422
7423   // select true, X, Y  -> X
7424   // select false, X, Y -> Y
7425   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7426     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7427
7428   // select C, X, X -> X
7429   if (TrueVal == FalseVal)
7430     return ReplaceInstUsesWith(SI, TrueVal);
7431
7432   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7433     return ReplaceInstUsesWith(SI, FalseVal);
7434   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7435     return ReplaceInstUsesWith(SI, TrueVal);
7436   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7437     if (isa<Constant>(TrueVal))
7438       return ReplaceInstUsesWith(SI, TrueVal);
7439     else
7440       return ReplaceInstUsesWith(SI, FalseVal);
7441   }
7442
7443   if (SI.getType() == Type::Int1Ty) {
7444     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7445       if (C->getZExtValue()) {
7446         // Change: A = select B, true, C --> A = or B, C
7447         return BinaryOperator::createOr(CondVal, FalseVal);
7448       } else {
7449         // Change: A = select B, false, C --> A = and !B, C
7450         Value *NotCond =
7451           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7452                                              "not."+CondVal->getName()), SI);
7453         return BinaryOperator::createAnd(NotCond, FalseVal);
7454       }
7455     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7456       if (C->getZExtValue() == false) {
7457         // Change: A = select B, C, false --> A = and B, C
7458         return BinaryOperator::createAnd(CondVal, TrueVal);
7459       } else {
7460         // Change: A = select B, C, true --> A = or !B, C
7461         Value *NotCond =
7462           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7463                                              "not."+CondVal->getName()), SI);
7464         return BinaryOperator::createOr(NotCond, TrueVal);
7465       }
7466     }
7467     
7468     // select a, b, a  -> a&b
7469     // select a, a, b  -> a|b
7470     if (CondVal == TrueVal)
7471       return BinaryOperator::createOr(CondVal, FalseVal);
7472     else if (CondVal == FalseVal)
7473       return BinaryOperator::createAnd(CondVal, TrueVal);
7474   }
7475
7476   // Selecting between two integer constants?
7477   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7478     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7479       // select C, 1, 0 -> zext C to int
7480       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7481         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7482       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7483         // select C, 0, 1 -> zext !C to int
7484         Value *NotCond =
7485           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7486                                                "not."+CondVal->getName()), SI);
7487         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7488       }
7489       
7490       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7491
7492       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7493
7494         // (x <s 0) ? -1 : 0 -> ashr x, 31
7495         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7496           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7497             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7498               // The comparison constant and the result are not neccessarily the
7499               // same width. Make an all-ones value by inserting a AShr.
7500               Value *X = IC->getOperand(0);
7501               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7502               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7503               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7504                                                         ShAmt, "ones");
7505               InsertNewInstBefore(SRA, SI);
7506               
7507               // Finally, convert to the type of the select RHS.  We figure out
7508               // if this requires a SExt, Trunc or BitCast based on the sizes.
7509               Instruction::CastOps opc = Instruction::BitCast;
7510               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7511               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7512               if (SRASize < SISize)
7513                 opc = Instruction::SExt;
7514               else if (SRASize > SISize)
7515                 opc = Instruction::Trunc;
7516               return CastInst::create(opc, SRA, SI.getType());
7517             }
7518           }
7519
7520
7521         // If one of the constants is zero (we know they can't both be) and we
7522         // have an icmp instruction with zero, and we have an 'and' with the
7523         // non-constant value, eliminate this whole mess.  This corresponds to
7524         // cases like this: ((X & 27) ? 27 : 0)
7525         if (TrueValC->isZero() || FalseValC->isZero())
7526           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7527               cast<Constant>(IC->getOperand(1))->isNullValue())
7528             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7529               if (ICA->getOpcode() == Instruction::And &&
7530                   isa<ConstantInt>(ICA->getOperand(1)) &&
7531                   (ICA->getOperand(1) == TrueValC ||
7532                    ICA->getOperand(1) == FalseValC) &&
7533                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7534                 // Okay, now we know that everything is set up, we just don't
7535                 // know whether we have a icmp_ne or icmp_eq and whether the 
7536                 // true or false val is the zero.
7537                 bool ShouldNotVal = !TrueValC->isZero();
7538                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7539                 Value *V = ICA;
7540                 if (ShouldNotVal)
7541                   V = InsertNewInstBefore(BinaryOperator::create(
7542                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7543                 return ReplaceInstUsesWith(SI, V);
7544               }
7545       }
7546     }
7547
7548   // See if we are selecting two values based on a comparison of the two values.
7549   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7550     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7551       // Transform (X == Y) ? X : Y  -> Y
7552       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7553         // This is not safe in general for floating point:  
7554         // consider X== -0, Y== +0.
7555         // It becomes safe if either operand is a nonzero constant.
7556         ConstantFP *CFPt, *CFPf;
7557         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7558               !CFPt->getValueAPF().isZero()) ||
7559             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7560              !CFPf->getValueAPF().isZero()))
7561         return ReplaceInstUsesWith(SI, FalseVal);
7562       }
7563       // Transform (X != Y) ? X : Y  -> X
7564       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7565         return ReplaceInstUsesWith(SI, TrueVal);
7566       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7567
7568     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7569       // Transform (X == Y) ? Y : X  -> X
7570       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7571         // This is not safe in general for floating point:  
7572         // consider X== -0, Y== +0.
7573         // It becomes safe if either operand is a nonzero constant.
7574         ConstantFP *CFPt, *CFPf;
7575         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7576               !CFPt->getValueAPF().isZero()) ||
7577             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7578              !CFPf->getValueAPF().isZero()))
7579           return ReplaceInstUsesWith(SI, FalseVal);
7580       }
7581       // Transform (X != Y) ? Y : X  -> Y
7582       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7583         return ReplaceInstUsesWith(SI, TrueVal);
7584       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7585     }
7586   }
7587
7588   // See if we are selecting two values based on a comparison of the two values.
7589   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7590     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7591       // Transform (X == Y) ? X : Y  -> Y
7592       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7593         return ReplaceInstUsesWith(SI, FalseVal);
7594       // Transform (X != Y) ? X : Y  -> X
7595       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7596         return ReplaceInstUsesWith(SI, TrueVal);
7597       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7598
7599     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7600       // Transform (X == Y) ? Y : X  -> X
7601       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7602         return ReplaceInstUsesWith(SI, FalseVal);
7603       // Transform (X != Y) ? Y : X  -> Y
7604       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7605         return ReplaceInstUsesWith(SI, TrueVal);
7606       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7607     }
7608   }
7609
7610   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7611     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7612       if (TI->hasOneUse() && FI->hasOneUse()) {
7613         Instruction *AddOp = 0, *SubOp = 0;
7614
7615         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7616         if (TI->getOpcode() == FI->getOpcode())
7617           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7618             return IV;
7619
7620         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7621         // even legal for FP.
7622         if (TI->getOpcode() == Instruction::Sub &&
7623             FI->getOpcode() == Instruction::Add) {
7624           AddOp = FI; SubOp = TI;
7625         } else if (FI->getOpcode() == Instruction::Sub &&
7626                    TI->getOpcode() == Instruction::Add) {
7627           AddOp = TI; SubOp = FI;
7628         }
7629
7630         if (AddOp) {
7631           Value *OtherAddOp = 0;
7632           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7633             OtherAddOp = AddOp->getOperand(1);
7634           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7635             OtherAddOp = AddOp->getOperand(0);
7636           }
7637
7638           if (OtherAddOp) {
7639             // So at this point we know we have (Y -> OtherAddOp):
7640             //        select C, (add X, Y), (sub X, Z)
7641             Value *NegVal;  // Compute -Z
7642             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7643               NegVal = ConstantExpr::getNeg(C);
7644             } else {
7645               NegVal = InsertNewInstBefore(
7646                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7647             }
7648
7649             Value *NewTrueOp = OtherAddOp;
7650             Value *NewFalseOp = NegVal;
7651             if (AddOp != TI)
7652               std::swap(NewTrueOp, NewFalseOp);
7653             Instruction *NewSel =
7654               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7655
7656             NewSel = InsertNewInstBefore(NewSel, SI);
7657             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7658           }
7659         }
7660       }
7661
7662   // See if we can fold the select into one of our operands.
7663   if (SI.getType()->isInteger()) {
7664     // See the comment above GetSelectFoldableOperands for a description of the
7665     // transformation we are doing here.
7666     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7667       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7668           !isa<Constant>(FalseVal))
7669         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7670           unsigned OpToFold = 0;
7671           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7672             OpToFold = 1;
7673           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7674             OpToFold = 2;
7675           }
7676
7677           if (OpToFold) {
7678             Constant *C = GetSelectFoldableConstant(TVI);
7679             Instruction *NewSel =
7680               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7681             InsertNewInstBefore(NewSel, SI);
7682             NewSel->takeName(TVI);
7683             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7684               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7685             else {
7686               assert(0 && "Unknown instruction!!");
7687             }
7688           }
7689         }
7690
7691     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7692       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7693           !isa<Constant>(TrueVal))
7694         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7695           unsigned OpToFold = 0;
7696           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7697             OpToFold = 1;
7698           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7699             OpToFold = 2;
7700           }
7701
7702           if (OpToFold) {
7703             Constant *C = GetSelectFoldableConstant(FVI);
7704             Instruction *NewSel =
7705               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7706             InsertNewInstBefore(NewSel, SI);
7707             NewSel->takeName(FVI);
7708             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7709               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7710             else
7711               assert(0 && "Unknown instruction!!");
7712           }
7713         }
7714   }
7715
7716   if (BinaryOperator::isNot(CondVal)) {
7717     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7718     SI.setOperand(1, FalseVal);
7719     SI.setOperand(2, TrueVal);
7720     return &SI;
7721   }
7722
7723   return 0;
7724 }
7725
7726 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7727 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
7728 /// and it is more than the alignment of the ultimate object, see if we can
7729 /// increase the alignment of the ultimate object, making this check succeed.
7730 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7731                                            unsigned PrefAlign = 0) {
7732   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7733     unsigned Align = GV->getAlignment();
7734     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
7735       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7736
7737     // If there is a large requested alignment and we can, bump up the alignment
7738     // of the global.
7739     if (PrefAlign > Align && GV->hasInitializer()) {
7740       GV->setAlignment(PrefAlign);
7741       Align = PrefAlign;
7742     }
7743     return Align;
7744   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7745     unsigned Align = AI->getAlignment();
7746     if (Align == 0 && TD) {
7747       if (isa<AllocaInst>(AI))
7748         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7749       else if (isa<MallocInst>(AI)) {
7750         // Malloc returns maximally aligned memory.
7751         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7752         Align =
7753           std::max(Align,
7754                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7755         Align =
7756           std::max(Align,
7757                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7758       }
7759     }
7760     
7761     // If there is a requested alignment and if this is an alloca, round up.  We
7762     // don't do this for malloc, because some systems can't respect the request.
7763     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7764       AI->setAlignment(PrefAlign);
7765       Align = PrefAlign;
7766     }
7767     return Align;
7768   } else if (isa<BitCastInst>(V) ||
7769              (isa<ConstantExpr>(V) && 
7770               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7771     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7772                                       TD, PrefAlign);
7773   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7774     // If all indexes are zero, it is just the alignment of the base pointer.
7775     bool AllZeroOperands = true;
7776     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7777       if (!isa<Constant>(GEPI->getOperand(i)) ||
7778           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7779         AllZeroOperands = false;
7780         break;
7781       }
7782
7783     if (AllZeroOperands) {
7784       // Treat this like a bitcast.
7785       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7786     }
7787
7788     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7789     if (BaseAlignment == 0) return 0;
7790
7791     // Otherwise, if the base alignment is >= the alignment we expect for the
7792     // base pointer type, then we know that the resultant pointer is aligned at
7793     // least as much as its type requires.
7794     if (!TD) return 0;
7795
7796     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7797     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7798     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7799     if (Align <= BaseAlignment) {
7800       const Type *GEPTy = GEPI->getType();
7801       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7802       Align = std::min(Align, (unsigned)
7803                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7804       return Align;
7805     }
7806     return 0;
7807   }
7808   return 0;
7809 }
7810
7811
7812 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7813 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7814 /// the heavy lifting.
7815 ///
7816 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7817   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7818   if (!II) return visitCallSite(&CI);
7819   
7820   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7821   // visitCallSite.
7822   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7823     bool Changed = false;
7824
7825     // memmove/cpy/set of zero bytes is a noop.
7826     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7827       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7828
7829       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7830         if (CI->getZExtValue() == 1) {
7831           // Replace the instruction with just byte operations.  We would
7832           // transform other cases to loads/stores, but we don't know if
7833           // alignment is sufficient.
7834         }
7835     }
7836
7837     // If we have a memmove and the source operation is a constant global,
7838     // then the source and dest pointers can't alias, so we can change this
7839     // into a call to memcpy.
7840     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7841       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7842         if (GVSrc->isConstant()) {
7843           Module *M = CI.getParent()->getParent()->getParent();
7844           Intrinsic::ID MemCpyID;
7845           if (CI.getOperand(3)->getType() == Type::Int32Ty)
7846             MemCpyID = Intrinsic::memcpy_i32;
7847           else
7848             MemCpyID = Intrinsic::memcpy_i64;
7849           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
7850           Changed = true;
7851         }
7852     }
7853
7854     // If we can determine a pointer alignment that is bigger than currently
7855     // set, update the alignment.
7856     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7857       unsigned Alignment1 = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7858       unsigned Alignment2 = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7859       unsigned Align = std::min(Alignment1, Alignment2);
7860       if (MI->getAlignment()->getZExtValue() < Align) {
7861         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7862         Changed = true;
7863       }
7864
7865       // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7866       // load/store.
7867       ConstantInt *MemOpLength = dyn_cast<ConstantInt>(CI.getOperand(3));
7868       if (MemOpLength) {
7869         unsigned Size = MemOpLength->getZExtValue();
7870         unsigned Align = cast<ConstantInt>(CI.getOperand(4))->getZExtValue();
7871         PointerType *NewPtrTy = NULL;
7872         // Destination pointer type is always i8 *
7873         // If Size is 8 then use Int64Ty
7874         // If Size is 4 then use Int32Ty
7875         // If Size is 2 then use Int16Ty
7876         // If Size is 1 then use Int8Ty
7877         if (Size && Size <=8 && !(Size&(Size-1)))
7878           NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
7879
7880         if (NewPtrTy) {
7881           Value *Src = InsertBitCastBefore(CI.getOperand(2), NewPtrTy, CI);
7882           Value *Dest = InsertBitCastBefore(CI.getOperand(1), NewPtrTy, CI);
7883           Value *L = new LoadInst(Src, "tmp", false, Align, &CI);
7884           Value *NS = new StoreInst(L, Dest, false, Align, &CI);
7885           CI.replaceAllUsesWith(NS);
7886           Changed = true;
7887           return EraseInstFromFunction(CI);
7888         }
7889       }
7890     } else if (isa<MemSetInst>(MI)) {
7891       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
7892       if (MI->getAlignment()->getZExtValue() < Alignment) {
7893         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7894         Changed = true;
7895       }
7896     }
7897           
7898     if (Changed) return II;
7899   } else {
7900     switch (II->getIntrinsicID()) {
7901     default: break;
7902     case Intrinsic::ppc_altivec_lvx:
7903     case Intrinsic::ppc_altivec_lvxl:
7904     case Intrinsic::x86_sse_loadu_ps:
7905     case Intrinsic::x86_sse2_loadu_pd:
7906     case Intrinsic::x86_sse2_loadu_dq:
7907       // Turn PPC lvx     -> load if the pointer is known aligned.
7908       // Turn X86 loadups -> load if the pointer is known aligned.
7909       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
7910         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
7911                                          PointerType::getUnqual(II->getType()),
7912                                          CI);
7913         return new LoadInst(Ptr);
7914       }
7915       break;
7916     case Intrinsic::ppc_altivec_stvx:
7917     case Intrinsic::ppc_altivec_stvxl:
7918       // Turn stvx -> store if the pointer is known aligned.
7919       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
7920         const Type *OpPtrTy = 
7921           PointerType::getUnqual(II->getOperand(1)->getType());
7922         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
7923         return new StoreInst(II->getOperand(1), Ptr);
7924       }
7925       break;
7926     case Intrinsic::x86_sse_storeu_ps:
7927     case Intrinsic::x86_sse2_storeu_pd:
7928     case Intrinsic::x86_sse2_storeu_dq:
7929     case Intrinsic::x86_sse2_storel_dq:
7930       // Turn X86 storeu -> store if the pointer is known aligned.
7931       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
7932         const Type *OpPtrTy = 
7933           PointerType::getUnqual(II->getOperand(2)->getType());
7934         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
7935         return new StoreInst(II->getOperand(2), Ptr);
7936       }
7937       break;
7938       
7939     case Intrinsic::x86_sse_cvttss2si: {
7940       // These intrinsics only demands the 0th element of its input vector.  If
7941       // we can simplify the input based on that, do so now.
7942       uint64_t UndefElts;
7943       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7944                                                 UndefElts)) {
7945         II->setOperand(1, V);
7946         return II;
7947       }
7948       break;
7949     }
7950       
7951     case Intrinsic::ppc_altivec_vperm:
7952       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7953       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7954         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7955         
7956         // Check that all of the elements are integer constants or undefs.
7957         bool AllEltsOk = true;
7958         for (unsigned i = 0; i != 16; ++i) {
7959           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7960               !isa<UndefValue>(Mask->getOperand(i))) {
7961             AllEltsOk = false;
7962             break;
7963           }
7964         }
7965         
7966         if (AllEltsOk) {
7967           // Cast the input vectors to byte vectors.
7968           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
7969           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
7970           Value *Result = UndefValue::get(Op0->getType());
7971           
7972           // Only extract each element once.
7973           Value *ExtractedElts[32];
7974           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7975           
7976           for (unsigned i = 0; i != 16; ++i) {
7977             if (isa<UndefValue>(Mask->getOperand(i)))
7978               continue;
7979             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7980             Idx &= 31;  // Match the hardware behavior.
7981             
7982             if (ExtractedElts[Idx] == 0) {
7983               Instruction *Elt = 
7984                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7985               InsertNewInstBefore(Elt, CI);
7986               ExtractedElts[Idx] = Elt;
7987             }
7988           
7989             // Insert this value into the result vector.
7990             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7991             InsertNewInstBefore(cast<Instruction>(Result), CI);
7992           }
7993           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7994         }
7995       }
7996       break;
7997
7998     case Intrinsic::stackrestore: {
7999       // If the save is right next to the restore, remove the restore.  This can
8000       // happen when variable allocas are DCE'd.
8001       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8002         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8003           BasicBlock::iterator BI = SS;
8004           if (&*++BI == II)
8005             return EraseInstFromFunction(CI);
8006         }
8007       }
8008       
8009       // If the stack restore is in a return/unwind block and if there are no
8010       // allocas or calls between the restore and the return, nuke the restore.
8011       TerminatorInst *TI = II->getParent()->getTerminator();
8012       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8013         BasicBlock::iterator BI = II;
8014         bool CannotRemove = false;
8015         for (++BI; &*BI != TI; ++BI) {
8016           if (isa<AllocaInst>(BI) ||
8017               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8018             CannotRemove = true;
8019             break;
8020           }
8021         }
8022         if (!CannotRemove)
8023           return EraseInstFromFunction(CI);
8024       }
8025       break;
8026     }
8027     }
8028   }
8029
8030   return visitCallSite(II);
8031 }
8032
8033 // InvokeInst simplification
8034 //
8035 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8036   return visitCallSite(&II);
8037 }
8038
8039 // visitCallSite - Improvements for call and invoke instructions.
8040 //
8041 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8042   bool Changed = false;
8043
8044   // If the callee is a constexpr cast of a function, attempt to move the cast
8045   // to the arguments of the call/invoke.
8046   if (transformConstExprCastCall(CS)) return 0;
8047
8048   Value *Callee = CS.getCalledValue();
8049
8050   if (Function *CalleeF = dyn_cast<Function>(Callee))
8051     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8052       Instruction *OldCall = CS.getInstruction();
8053       // If the call and callee calling conventions don't match, this call must
8054       // be unreachable, as the call is undefined.
8055       new StoreInst(ConstantInt::getTrue(),
8056                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8057                                     OldCall);
8058       if (!OldCall->use_empty())
8059         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8060       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8061         return EraseInstFromFunction(*OldCall);
8062       return 0;
8063     }
8064
8065   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8066     // This instruction is not reachable, just remove it.  We insert a store to
8067     // undef so that we know that this code is not reachable, despite the fact
8068     // that we can't modify the CFG here.
8069     new StoreInst(ConstantInt::getTrue(),
8070                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8071                   CS.getInstruction());
8072
8073     if (!CS.getInstruction()->use_empty())
8074       CS.getInstruction()->
8075         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8076
8077     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8078       // Don't break the CFG, insert a dummy cond branch.
8079       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8080                      ConstantInt::getTrue(), II);
8081     }
8082     return EraseInstFromFunction(*CS.getInstruction());
8083   }
8084
8085   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8086     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8087       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8088         return transformCallThroughTrampoline(CS);
8089
8090   const PointerType *PTy = cast<PointerType>(Callee->getType());
8091   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8092   if (FTy->isVarArg()) {
8093     // See if we can optimize any arguments passed through the varargs area of
8094     // the call.
8095     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8096            E = CS.arg_end(); I != E; ++I)
8097       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8098         // If this cast does not effect the value passed through the varargs
8099         // area, we can eliminate the use of the cast.
8100         Value *Op = CI->getOperand(0);
8101         if (CI->isLosslessCast()) {
8102           *I = Op;
8103           Changed = true;
8104         }
8105       }
8106   }
8107
8108   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8109     // Inline asm calls cannot throw - mark them 'nounwind'.
8110     CS.setDoesNotThrow();
8111     Changed = true;
8112   }
8113
8114   return Changed ? CS.getInstruction() : 0;
8115 }
8116
8117 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8118 // attempt to move the cast to the arguments of the call/invoke.
8119 //
8120 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8121   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8122   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8123   if (CE->getOpcode() != Instruction::BitCast || 
8124       !isa<Function>(CE->getOperand(0)))
8125     return false;
8126   Function *Callee = cast<Function>(CE->getOperand(0));
8127   Instruction *Caller = CS.getInstruction();
8128   const ParamAttrsList* CallerPAL = CS.getParamAttrs();
8129
8130   // Okay, this is a cast from a function to a different type.  Unless doing so
8131   // would cause a type conversion of one of our arguments, change this call to
8132   // be a direct call with arguments casted to the appropriate types.
8133   //
8134   const FunctionType *FT = Callee->getFunctionType();
8135   const Type *OldRetTy = Caller->getType();
8136
8137   // Check to see if we are changing the return type...
8138   if (OldRetTy != FT->getReturnType()) {
8139     if (Callee->isDeclaration() && !Caller->use_empty() && 
8140         // Conversion is ok if changing from pointer to int of same size.
8141         !(isa<PointerType>(FT->getReturnType()) &&
8142           TD->getIntPtrType() == OldRetTy))
8143       return false;   // Cannot transform this return value.
8144
8145     if (!Caller->use_empty() &&
8146         // void -> non-void is handled specially
8147         FT->getReturnType() != Type::VoidTy &&
8148         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8149       return false;   // Cannot transform this return value.
8150
8151     if (CallerPAL && !Caller->use_empty()) {
8152       uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8153       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8154         return false;   // Attribute not compatible with transformed value.
8155     }
8156
8157     // If the callsite is an invoke instruction, and the return value is used by
8158     // a PHI node in a successor, we cannot change the return type of the call
8159     // because there is no place to put the cast instruction (without breaking
8160     // the critical edge).  Bail out in this case.
8161     if (!Caller->use_empty())
8162       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8163         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8164              UI != E; ++UI)
8165           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8166             if (PN->getParent() == II->getNormalDest() ||
8167                 PN->getParent() == II->getUnwindDest())
8168               return false;
8169   }
8170
8171   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8172   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8173
8174   CallSite::arg_iterator AI = CS.arg_begin();
8175   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8176     const Type *ParamTy = FT->getParamType(i);
8177     const Type *ActTy = (*AI)->getType();
8178
8179     if (!CastInst::isCastable(ActTy, ParamTy))
8180       return false;   // Cannot transform this parameter value.
8181
8182     if (CallerPAL) {
8183       uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8184       if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8185         return false;   // Attribute not compatible with transformed value.
8186     }
8187
8188     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8189     // Some conversions are safe even if we do not have a body.
8190     // Either we can cast directly, or we can upconvert the argument
8191     bool isConvertible = ActTy == ParamTy ||
8192       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8193       (ParamTy->isInteger() && ActTy->isInteger() &&
8194        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8195       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8196        && c->getValue().isStrictlyPositive());
8197     if (Callee->isDeclaration() && !isConvertible) return false;
8198   }
8199
8200   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8201       Callee->isDeclaration())
8202     return false;   // Do not delete arguments unless we have a function body...
8203
8204   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
8205     // In this case we have more arguments than the new function type, but we
8206     // won't be dropping them.  Check that these extra arguments have attributes
8207     // that are compatible with being a vararg call argument.
8208     for (unsigned i = CallerPAL->size(); i; --i) {
8209       if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8210         break;
8211       uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8212       if (PAttrs & ParamAttr::VarArgsIncompatible)
8213         return false;
8214     }
8215
8216   // Okay, we decided that this is a safe thing to do: go ahead and start
8217   // inserting cast instructions as necessary...
8218   std::vector<Value*> Args;
8219   Args.reserve(NumActualArgs);
8220   ParamAttrsVector attrVec;
8221   attrVec.reserve(NumCommonArgs);
8222
8223   // Get any return attributes.
8224   uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8225
8226   // If the return value is not being used, the type may not be compatible
8227   // with the existing attributes.  Wipe out any problematic attributes.
8228   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
8229
8230   // Add the new return attributes.
8231   if (RAttrs)
8232     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8233
8234   AI = CS.arg_begin();
8235   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8236     const Type *ParamTy = FT->getParamType(i);
8237     if ((*AI)->getType() == ParamTy) {
8238       Args.push_back(*AI);
8239     } else {
8240       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8241           false, ParamTy, false);
8242       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8243       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8244     }
8245
8246     // Add any parameter attributes.
8247     uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8248     if (PAttrs)
8249       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8250   }
8251
8252   // If the function takes more arguments than the call was taking, add them
8253   // now...
8254   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8255     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8256
8257   // If we are removing arguments to the function, emit an obnoxious warning...
8258   if (FT->getNumParams() < NumActualArgs)
8259     if (!FT->isVarArg()) {
8260       cerr << "WARNING: While resolving call to function '"
8261            << Callee->getName() << "' arguments were dropped!\n";
8262     } else {
8263       // Add all of the arguments in their promoted form to the arg list...
8264       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8265         const Type *PTy = getPromotedType((*AI)->getType());
8266         if (PTy != (*AI)->getType()) {
8267           // Must promote to pass through va_arg area!
8268           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8269                                                                 PTy, false);
8270           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8271           InsertNewInstBefore(Cast, *Caller);
8272           Args.push_back(Cast);
8273         } else {
8274           Args.push_back(*AI);
8275         }
8276
8277         // Add any parameter attributes.
8278         uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8279         if (PAttrs)
8280           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8281       }
8282     }
8283
8284   if (FT->getReturnType() == Type::VoidTy)
8285     Caller->setName("");   // Void type should not have a name.
8286
8287   const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8288
8289   Instruction *NC;
8290   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8291     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8292                         Args.begin(), Args.end(), Caller->getName(), Caller);
8293     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8294     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8295   } else {
8296     NC = new CallInst(Callee, Args.begin(), Args.end(),
8297                       Caller->getName(), Caller);
8298     CallInst *CI = cast<CallInst>(Caller);
8299     if (CI->isTailCall())
8300       cast<CallInst>(NC)->setTailCall();
8301     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8302     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8303   }
8304
8305   // Insert a cast of the return type as necessary.
8306   Value *NV = NC;
8307   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8308     if (NV->getType() != Type::VoidTy) {
8309       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8310                                                             OldRetTy, false);
8311       NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
8312
8313       // If this is an invoke instruction, we should insert it after the first
8314       // non-phi, instruction in the normal successor block.
8315       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8316         BasicBlock::iterator I = II->getNormalDest()->begin();
8317         while (isa<PHINode>(I)) ++I;
8318         InsertNewInstBefore(NC, *I);
8319       } else {
8320         // Otherwise, it's a call, just insert cast right after the call instr
8321         InsertNewInstBefore(NC, *Caller);
8322       }
8323       AddUsersToWorkList(*Caller);
8324     } else {
8325       NV = UndefValue::get(Caller->getType());
8326     }
8327   }
8328
8329   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8330     Caller->replaceAllUsesWith(NV);
8331   Caller->eraseFromParent();
8332   RemoveFromWorkList(Caller);
8333   return true;
8334 }
8335
8336 // transformCallThroughTrampoline - Turn a call to a function created by the
8337 // init_trampoline intrinsic into a direct call to the underlying function.
8338 //
8339 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8340   Value *Callee = CS.getCalledValue();
8341   const PointerType *PTy = cast<PointerType>(Callee->getType());
8342   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8343
8344   IntrinsicInst *Tramp =
8345     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8346
8347   Function *NestF =
8348     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8349   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8350   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8351
8352   if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
8353     unsigned NestIdx = 1;
8354     const Type *NestTy = 0;
8355     uint16_t NestAttr = 0;
8356
8357     // Look for a parameter marked with the 'nest' attribute.
8358     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8359          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8360       if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8361         // Record the parameter type and any other attributes.
8362         NestTy = *I;
8363         NestAttr = NestAttrs->getParamAttrs(NestIdx);
8364         break;
8365       }
8366
8367     if (NestTy) {
8368       Instruction *Caller = CS.getInstruction();
8369       std::vector<Value*> NewArgs;
8370       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8371
8372       // Insert the nest argument into the call argument list, which may
8373       // mean appending it.
8374       {
8375         unsigned Idx = 1;
8376         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8377         do {
8378           if (Idx == NestIdx) {
8379             // Add the chain argument.
8380             Value *NestVal = Tramp->getOperand(3);
8381             if (NestVal->getType() != NestTy)
8382               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8383             NewArgs.push_back(NestVal);
8384           }
8385
8386           if (I == E)
8387             break;
8388
8389           // Add the original argument.
8390           NewArgs.push_back(*I);
8391
8392           ++Idx, ++I;
8393         } while (1);
8394       }
8395
8396       // The trampoline may have been bitcast to a bogus type (FTy).
8397       // Handle this by synthesizing a new function type, equal to FTy
8398       // with the chain parameter inserted.  Likewise for attributes.
8399
8400       const ParamAttrsList *Attrs = CS.getParamAttrs();
8401       std::vector<const Type*> NewTypes;
8402       ParamAttrsVector NewAttrs;
8403       NewTypes.reserve(FTy->getNumParams()+1);
8404
8405       // Add any function result attributes.
8406       uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8407       if (Attr)
8408         NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8409
8410       // Insert the chain's type into the list of parameter types, which may
8411       // mean appending it.  Likewise for the chain's attributes.
8412       {
8413         unsigned Idx = 1;
8414         FunctionType::param_iterator I = FTy->param_begin(),
8415           E = FTy->param_end();
8416
8417         do {
8418           if (Idx == NestIdx) {
8419             // Add the chain's type and attributes.
8420             NewTypes.push_back(NestTy);
8421             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8422           }
8423
8424           if (I == E)
8425             break;
8426
8427           // Add the original type and attributes.
8428           NewTypes.push_back(*I);
8429           Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8430           if (Attr)
8431             NewAttrs.push_back
8432               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8433
8434           ++Idx, ++I;
8435         } while (1);
8436       }
8437
8438       // Replace the trampoline call with a direct call.  Let the generic
8439       // code sort out any function type mismatches.
8440       FunctionType *NewFTy =
8441         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8442       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8443         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8444       const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
8445
8446       Instruction *NewCaller;
8447       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8448         NewCaller = new InvokeInst(NewCallee,
8449                                    II->getNormalDest(), II->getUnwindDest(),
8450                                    NewArgs.begin(), NewArgs.end(),
8451                                    Caller->getName(), Caller);
8452         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8453         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8454       } else {
8455         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8456                                  Caller->getName(), Caller);
8457         if (cast<CallInst>(Caller)->isTailCall())
8458           cast<CallInst>(NewCaller)->setTailCall();
8459         cast<CallInst>(NewCaller)->
8460           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8461         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8462       }
8463       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8464         Caller->replaceAllUsesWith(NewCaller);
8465       Caller->eraseFromParent();
8466       RemoveFromWorkList(Caller);
8467       return 0;
8468     }
8469   }
8470
8471   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8472   // parameter, there is no need to adjust the argument list.  Let the generic
8473   // code sort out any function type mismatches.
8474   Constant *NewCallee =
8475     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8476   CS.setCalledFunction(NewCallee);
8477   return CS.getInstruction();
8478 }
8479
8480 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8481 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8482 /// and a single binop.
8483 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8484   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8485   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8486          isa<CmpInst>(FirstInst));
8487   unsigned Opc = FirstInst->getOpcode();
8488   Value *LHSVal = FirstInst->getOperand(0);
8489   Value *RHSVal = FirstInst->getOperand(1);
8490     
8491   const Type *LHSType = LHSVal->getType();
8492   const Type *RHSType = RHSVal->getType();
8493   
8494   // Scan to see if all operands are the same opcode, all have one use, and all
8495   // kill their operands (i.e. the operands have one use).
8496   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8497     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8498     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8499         // Verify type of the LHS matches so we don't fold cmp's of different
8500         // types or GEP's with different index types.
8501         I->getOperand(0)->getType() != LHSType ||
8502         I->getOperand(1)->getType() != RHSType)
8503       return 0;
8504
8505     // If they are CmpInst instructions, check their predicates
8506     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8507       if (cast<CmpInst>(I)->getPredicate() !=
8508           cast<CmpInst>(FirstInst)->getPredicate())
8509         return 0;
8510     
8511     // Keep track of which operand needs a phi node.
8512     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8513     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8514   }
8515   
8516   // Otherwise, this is safe to transform, determine if it is profitable.
8517
8518   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8519   // Indexes are often folded into load/store instructions, so we don't want to
8520   // hide them behind a phi.
8521   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8522     return 0;
8523   
8524   Value *InLHS = FirstInst->getOperand(0);
8525   Value *InRHS = FirstInst->getOperand(1);
8526   PHINode *NewLHS = 0, *NewRHS = 0;
8527   if (LHSVal == 0) {
8528     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8529     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8530     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8531     InsertNewInstBefore(NewLHS, PN);
8532     LHSVal = NewLHS;
8533   }
8534   
8535   if (RHSVal == 0) {
8536     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8537     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8538     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8539     InsertNewInstBefore(NewRHS, PN);
8540     RHSVal = NewRHS;
8541   }
8542   
8543   // Add all operands to the new PHIs.
8544   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8545     if (NewLHS) {
8546       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8547       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8548     }
8549     if (NewRHS) {
8550       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8551       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8552     }
8553   }
8554     
8555   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8556     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8557   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8558     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8559                            RHSVal);
8560   else {
8561     assert(isa<GetElementPtrInst>(FirstInst));
8562     return new GetElementPtrInst(LHSVal, RHSVal);
8563   }
8564 }
8565
8566 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8567 /// of the block that defines it.  This means that it must be obvious the value
8568 /// of the load is not changed from the point of the load to the end of the
8569 /// block it is in.
8570 ///
8571 /// Finally, it is safe, but not profitable, to sink a load targetting a
8572 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8573 /// to a register.
8574 static bool isSafeToSinkLoad(LoadInst *L) {
8575   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8576   
8577   for (++BBI; BBI != E; ++BBI)
8578     if (BBI->mayWriteToMemory())
8579       return false;
8580   
8581   // Check for non-address taken alloca.  If not address-taken already, it isn't
8582   // profitable to do this xform.
8583   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8584     bool isAddressTaken = false;
8585     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8586          UI != E; ++UI) {
8587       if (isa<LoadInst>(UI)) continue;
8588       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8589         // If storing TO the alloca, then the address isn't taken.
8590         if (SI->getOperand(1) == AI) continue;
8591       }
8592       isAddressTaken = true;
8593       break;
8594     }
8595     
8596     if (!isAddressTaken)
8597       return false;
8598   }
8599   
8600   return true;
8601 }
8602
8603
8604 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8605 // operator and they all are only used by the PHI, PHI together their
8606 // inputs, and do the operation once, to the result of the PHI.
8607 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8608   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8609
8610   // Scan the instruction, looking for input operations that can be folded away.
8611   // If all input operands to the phi are the same instruction (e.g. a cast from
8612   // the same type or "+42") we can pull the operation through the PHI, reducing
8613   // code size and simplifying code.
8614   Constant *ConstantOp = 0;
8615   const Type *CastSrcTy = 0;
8616   bool isVolatile = false;
8617   if (isa<CastInst>(FirstInst)) {
8618     CastSrcTy = FirstInst->getOperand(0)->getType();
8619   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8620     // Can fold binop, compare or shift here if the RHS is a constant, 
8621     // otherwise call FoldPHIArgBinOpIntoPHI.
8622     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8623     if (ConstantOp == 0)
8624       return FoldPHIArgBinOpIntoPHI(PN);
8625   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8626     isVolatile = LI->isVolatile();
8627     // We can't sink the load if the loaded value could be modified between the
8628     // load and the PHI.
8629     if (LI->getParent() != PN.getIncomingBlock(0) ||
8630         !isSafeToSinkLoad(LI))
8631       return 0;
8632   } else if (isa<GetElementPtrInst>(FirstInst)) {
8633     if (FirstInst->getNumOperands() == 2)
8634       return FoldPHIArgBinOpIntoPHI(PN);
8635     // Can't handle general GEPs yet.
8636     return 0;
8637   } else {
8638     return 0;  // Cannot fold this operation.
8639   }
8640
8641   // Check to see if all arguments are the same operation.
8642   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8643     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8644     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8645     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8646       return 0;
8647     if (CastSrcTy) {
8648       if (I->getOperand(0)->getType() != CastSrcTy)
8649         return 0;  // Cast operation must match.
8650     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8651       // We can't sink the load if the loaded value could be modified between 
8652       // the load and the PHI.
8653       if (LI->isVolatile() != isVolatile ||
8654           LI->getParent() != PN.getIncomingBlock(i) ||
8655           !isSafeToSinkLoad(LI))
8656         return 0;
8657     } else if (I->getOperand(1) != ConstantOp) {
8658       return 0;
8659     }
8660   }
8661
8662   // Okay, they are all the same operation.  Create a new PHI node of the
8663   // correct type, and PHI together all of the LHS's of the instructions.
8664   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8665                                PN.getName()+".in");
8666   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8667
8668   Value *InVal = FirstInst->getOperand(0);
8669   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8670
8671   // Add all operands to the new PHI.
8672   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8673     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8674     if (NewInVal != InVal)
8675       InVal = 0;
8676     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8677   }
8678
8679   Value *PhiVal;
8680   if (InVal) {
8681     // The new PHI unions all of the same values together.  This is really
8682     // common, so we handle it intelligently here for compile-time speed.
8683     PhiVal = InVal;
8684     delete NewPN;
8685   } else {
8686     InsertNewInstBefore(NewPN, PN);
8687     PhiVal = NewPN;
8688   }
8689
8690   // Insert and return the new operation.
8691   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8692     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8693   else if (isa<LoadInst>(FirstInst))
8694     return new LoadInst(PhiVal, "", isVolatile);
8695   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8696     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8697   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8698     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8699                            PhiVal, ConstantOp);
8700   else
8701     assert(0 && "Unknown operation");
8702   return 0;
8703 }
8704
8705 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8706 /// that is dead.
8707 static bool DeadPHICycle(PHINode *PN,
8708                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8709   if (PN->use_empty()) return true;
8710   if (!PN->hasOneUse()) return false;
8711
8712   // Remember this node, and if we find the cycle, return.
8713   if (!PotentiallyDeadPHIs.insert(PN))
8714     return true;
8715   
8716   // Don't scan crazily complex things.
8717   if (PotentiallyDeadPHIs.size() == 16)
8718     return false;
8719
8720   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8721     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8722
8723   return false;
8724 }
8725
8726 /// PHIsEqualValue - Return true if this phi node is always equal to
8727 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
8728 ///   z = some value; x = phi (y, z); y = phi (x, z)
8729 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
8730                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8731   // See if we already saw this PHI node.
8732   if (!ValueEqualPHIs.insert(PN))
8733     return true;
8734   
8735   // Don't scan crazily complex things.
8736   if (ValueEqualPHIs.size() == 16)
8737     return false;
8738  
8739   // Scan the operands to see if they are either phi nodes or are equal to
8740   // the value.
8741   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8742     Value *Op = PN->getIncomingValue(i);
8743     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8744       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8745         return false;
8746     } else if (Op != NonPhiInVal)
8747       return false;
8748   }
8749   
8750   return true;
8751 }
8752
8753
8754 // PHINode simplification
8755 //
8756 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8757   // If LCSSA is around, don't mess with Phi nodes
8758   if (MustPreserveLCSSA) return 0;
8759   
8760   if (Value *V = PN.hasConstantValue())
8761     return ReplaceInstUsesWith(PN, V);
8762
8763   // If all PHI operands are the same operation, pull them through the PHI,
8764   // reducing code size.
8765   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8766       PN.getIncomingValue(0)->hasOneUse())
8767     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8768       return Result;
8769
8770   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8771   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8772   // PHI)... break the cycle.
8773   if (PN.hasOneUse()) {
8774     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8775     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8776       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8777       PotentiallyDeadPHIs.insert(&PN);
8778       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8779         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8780     }
8781    
8782     // If this phi has a single use, and if that use just computes a value for
8783     // the next iteration of a loop, delete the phi.  This occurs with unused
8784     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8785     // common case here is good because the only other things that catch this
8786     // are induction variable analysis (sometimes) and ADCE, which is only run
8787     // late.
8788     if (PHIUser->hasOneUse() &&
8789         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8790         PHIUser->use_back() == &PN) {
8791       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8792     }
8793   }
8794
8795   // We sometimes end up with phi cycles that non-obviously end up being the
8796   // same value, for example:
8797   //   z = some value; x = phi (y, z); y = phi (x, z)
8798   // where the phi nodes don't necessarily need to be in the same block.  Do a
8799   // quick check to see if the PHI node only contains a single non-phi value, if
8800   // so, scan to see if the phi cycle is actually equal to that value.
8801   {
8802     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8803     // Scan for the first non-phi operand.
8804     while (InValNo != NumOperandVals && 
8805            isa<PHINode>(PN.getIncomingValue(InValNo)))
8806       ++InValNo;
8807
8808     if (InValNo != NumOperandVals) {
8809       Value *NonPhiInVal = PN.getOperand(InValNo);
8810       
8811       // Scan the rest of the operands to see if there are any conflicts, if so
8812       // there is no need to recursively scan other phis.
8813       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8814         Value *OpVal = PN.getIncomingValue(InValNo);
8815         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8816           break;
8817       }
8818       
8819       // If we scanned over all operands, then we have one unique value plus
8820       // phi values.  Scan PHI nodes to see if they all merge in each other or
8821       // the value.
8822       if (InValNo == NumOperandVals) {
8823         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8824         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8825           return ReplaceInstUsesWith(PN, NonPhiInVal);
8826       }
8827     }
8828   }
8829   return 0;
8830 }
8831
8832 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8833                                    Instruction *InsertPoint,
8834                                    InstCombiner *IC) {
8835   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8836   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8837   // We must cast correctly to the pointer type. Ensure that we
8838   // sign extend the integer value if it is smaller as this is
8839   // used for address computation.
8840   Instruction::CastOps opcode = 
8841      (VTySize < PtrSize ? Instruction::SExt :
8842       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8843   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8844 }
8845
8846
8847 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8848   Value *PtrOp = GEP.getOperand(0);
8849   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
8850   // If so, eliminate the noop.
8851   if (GEP.getNumOperands() == 1)
8852     return ReplaceInstUsesWith(GEP, PtrOp);
8853
8854   if (isa<UndefValue>(GEP.getOperand(0)))
8855     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8856
8857   bool HasZeroPointerIndex = false;
8858   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8859     HasZeroPointerIndex = C->isNullValue();
8860
8861   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8862     return ReplaceInstUsesWith(GEP, PtrOp);
8863
8864   // Eliminate unneeded casts for indices.
8865   bool MadeChange = false;
8866   
8867   gep_type_iterator GTI = gep_type_begin(GEP);
8868   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8869     if (isa<SequentialType>(*GTI)) {
8870       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8871         if (CI->getOpcode() == Instruction::ZExt ||
8872             CI->getOpcode() == Instruction::SExt) {
8873           const Type *SrcTy = CI->getOperand(0)->getType();
8874           // We can eliminate a cast from i32 to i64 iff the target 
8875           // is a 32-bit pointer target.
8876           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8877             MadeChange = true;
8878             GEP.setOperand(i, CI->getOperand(0));
8879           }
8880         }
8881       }
8882       // If we are using a wider index than needed for this platform, shrink it
8883       // to what we need.  If the incoming value needs a cast instruction,
8884       // insert it.  This explicit cast can make subsequent optimizations more
8885       // obvious.
8886       Value *Op = GEP.getOperand(i);
8887       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
8888         if (Constant *C = dyn_cast<Constant>(Op)) {
8889           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8890           MadeChange = true;
8891         } else {
8892           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8893                                 GEP);
8894           GEP.setOperand(i, Op);
8895           MadeChange = true;
8896         }
8897     }
8898   }
8899   if (MadeChange) return &GEP;
8900
8901   // If this GEP instruction doesn't move the pointer, and if the input operand
8902   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8903   // real input to the dest type.
8904   if (GEP.hasAllZeroIndices()) {
8905     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
8906       // If the bitcast is of an allocation, and the allocation will be
8907       // converted to match the type of the cast, don't touch this.
8908       if (isa<AllocationInst>(BCI->getOperand(0))) {
8909         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
8910         if (Instruction *I = visitBitCast(*BCI)) {
8911           if (I != BCI) {
8912             I->takeName(BCI);
8913             BCI->getParent()->getInstList().insert(BCI, I);
8914             ReplaceInstUsesWith(*BCI, I);
8915           }
8916           return &GEP;
8917         }
8918       }
8919       return new BitCastInst(BCI->getOperand(0), GEP.getType());
8920     }
8921   }
8922   
8923   // Combine Indices - If the source pointer to this getelementptr instruction
8924   // is a getelementptr instruction, combine the indices of the two
8925   // getelementptr instructions into a single instruction.
8926   //
8927   SmallVector<Value*, 8> SrcGEPOperands;
8928   if (User *Src = dyn_castGetElementPtr(PtrOp))
8929     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8930
8931   if (!SrcGEPOperands.empty()) {
8932     // Note that if our source is a gep chain itself that we wait for that
8933     // chain to be resolved before we perform this transformation.  This
8934     // avoids us creating a TON of code in some cases.
8935     //
8936     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8937         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8938       return 0;   // Wait until our source is folded to completion.
8939
8940     SmallVector<Value*, 8> Indices;
8941
8942     // Find out whether the last index in the source GEP is a sequential idx.
8943     bool EndsWithSequential = false;
8944     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8945            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8946       EndsWithSequential = !isa<StructType>(*I);
8947
8948     // Can we combine the two pointer arithmetics offsets?
8949     if (EndsWithSequential) {
8950       // Replace: gep (gep %P, long B), long A, ...
8951       // With:    T = long A+B; gep %P, T, ...
8952       //
8953       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8954       if (SO1 == Constant::getNullValue(SO1->getType())) {
8955         Sum = GO1;
8956       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8957         Sum = SO1;
8958       } else {
8959         // If they aren't the same type, convert both to an integer of the
8960         // target's pointer size.
8961         if (SO1->getType() != GO1->getType()) {
8962           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8963             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8964           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8965             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8966           } else {
8967             unsigned PS = TD->getPointerSizeInBits();
8968             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
8969               // Convert GO1 to SO1's type.
8970               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8971
8972             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
8973               // Convert SO1 to GO1's type.
8974               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8975             } else {
8976               const Type *PT = TD->getIntPtrType();
8977               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8978               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8979             }
8980           }
8981         }
8982         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8983           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8984         else {
8985           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8986           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8987         }
8988       }
8989
8990       // Recycle the GEP we already have if possible.
8991       if (SrcGEPOperands.size() == 2) {
8992         GEP.setOperand(0, SrcGEPOperands[0]);
8993         GEP.setOperand(1, Sum);
8994         return &GEP;
8995       } else {
8996         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8997                        SrcGEPOperands.end()-1);
8998         Indices.push_back(Sum);
8999         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9000       }
9001     } else if (isa<Constant>(*GEP.idx_begin()) &&
9002                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9003                SrcGEPOperands.size() != 1) {
9004       // Otherwise we can do the fold if the first index of the GEP is a zero
9005       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9006                      SrcGEPOperands.end());
9007       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9008     }
9009
9010     if (!Indices.empty())
9011       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9012                                    Indices.end(), GEP.getName());
9013
9014   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9015     // GEP of global variable.  If all of the indices for this GEP are
9016     // constants, we can promote this to a constexpr instead of an instruction.
9017
9018     // Scan for nonconstants...
9019     SmallVector<Constant*, 8> Indices;
9020     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9021     for (; I != E && isa<Constant>(*I); ++I)
9022       Indices.push_back(cast<Constant>(*I));
9023
9024     if (I == E) {  // If they are all constants...
9025       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9026                                                     &Indices[0],Indices.size());
9027
9028       // Replace all uses of the GEP with the new constexpr...
9029       return ReplaceInstUsesWith(GEP, CE);
9030     }
9031   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9032     if (!isa<PointerType>(X->getType())) {
9033       // Not interesting.  Source pointer must be a cast from pointer.
9034     } else if (HasZeroPointerIndex) {
9035       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9036       // into     : GEP [10 x i8]* X, i32 0, ...
9037       //
9038       // This occurs when the program declares an array extern like "int X[];"
9039       //
9040       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9041       const PointerType *XTy = cast<PointerType>(X->getType());
9042       if (const ArrayType *XATy =
9043           dyn_cast<ArrayType>(XTy->getElementType()))
9044         if (const ArrayType *CATy =
9045             dyn_cast<ArrayType>(CPTy->getElementType()))
9046           if (CATy->getElementType() == XATy->getElementType()) {
9047             // At this point, we know that the cast source type is a pointer
9048             // to an array of the same type as the destination pointer
9049             // array.  Because the array type is never stepped over (there
9050             // is a leading zero) we can fold the cast into this GEP.
9051             GEP.setOperand(0, X);
9052             return &GEP;
9053           }
9054     } else if (GEP.getNumOperands() == 2) {
9055       // Transform things like:
9056       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9057       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9058       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9059       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9060       if (isa<ArrayType>(SrcElTy) &&
9061           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9062           TD->getABITypeSize(ResElTy)) {
9063         Value *Idx[2];
9064         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9065         Idx[1] = GEP.getOperand(1);
9066         Value *V = InsertNewInstBefore(
9067                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
9068         // V and GEP are both pointer types --> BitCast
9069         return new BitCastInst(V, GEP.getType());
9070       }
9071       
9072       // Transform things like:
9073       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9074       //   (where tmp = 8*tmp2) into:
9075       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9076       
9077       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9078         uint64_t ArrayEltSize =
9079             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9080         
9081         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9082         // allow either a mul, shift, or constant here.
9083         Value *NewIdx = 0;
9084         ConstantInt *Scale = 0;
9085         if (ArrayEltSize == 1) {
9086           NewIdx = GEP.getOperand(1);
9087           Scale = ConstantInt::get(NewIdx->getType(), 1);
9088         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9089           NewIdx = ConstantInt::get(CI->getType(), 1);
9090           Scale = CI;
9091         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9092           if (Inst->getOpcode() == Instruction::Shl &&
9093               isa<ConstantInt>(Inst->getOperand(1))) {
9094             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9095             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9096             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9097             NewIdx = Inst->getOperand(0);
9098           } else if (Inst->getOpcode() == Instruction::Mul &&
9099                      isa<ConstantInt>(Inst->getOperand(1))) {
9100             Scale = cast<ConstantInt>(Inst->getOperand(1));
9101             NewIdx = Inst->getOperand(0);
9102           }
9103         }
9104         
9105         // If the index will be to exactly the right offset with the scale taken
9106         // out, perform the transformation. Note, we don't know whether Scale is
9107         // signed or not. We'll use unsigned version of division/modulo
9108         // operation after making sure Scale doesn't have the sign bit set.
9109         if (Scale && Scale->getSExtValue() >= 0LL &&
9110             Scale->getZExtValue() % ArrayEltSize == 0) {
9111           Scale = ConstantInt::get(Scale->getType(),
9112                                    Scale->getZExtValue() / ArrayEltSize);
9113           if (Scale->getZExtValue() != 1) {
9114             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9115                                                        false /*ZExt*/);
9116             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9117             NewIdx = InsertNewInstBefore(Sc, GEP);
9118           }
9119
9120           // Insert the new GEP instruction.
9121           Value *Idx[2];
9122           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9123           Idx[1] = NewIdx;
9124           Instruction *NewGEP =
9125             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9126           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9127           // The NewGEP must be pointer typed, so must the old one -> BitCast
9128           return new BitCastInst(NewGEP, GEP.getType());
9129         }
9130       }
9131     }
9132   }
9133
9134   return 0;
9135 }
9136
9137 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9138   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9139   if (AI.isArrayAllocation())    // Check C != 1
9140     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9141       const Type *NewTy = 
9142         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9143       AllocationInst *New = 0;
9144
9145       // Create and insert the replacement instruction...
9146       if (isa<MallocInst>(AI))
9147         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9148       else {
9149         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9150         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9151       }
9152
9153       InsertNewInstBefore(New, AI);
9154
9155       // Scan to the end of the allocation instructions, to skip over a block of
9156       // allocas if possible...
9157       //
9158       BasicBlock::iterator It = New;
9159       while (isa<AllocationInst>(*It)) ++It;
9160
9161       // Now that I is pointing to the first non-allocation-inst in the block,
9162       // insert our getelementptr instruction...
9163       //
9164       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9165       Value *Idx[2];
9166       Idx[0] = NullIdx;
9167       Idx[1] = NullIdx;
9168       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9169                                        New->getName()+".sub", It);
9170
9171       // Now make everything use the getelementptr instead of the original
9172       // allocation.
9173       return ReplaceInstUsesWith(AI, V);
9174     } else if (isa<UndefValue>(AI.getArraySize())) {
9175       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9176     }
9177
9178   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9179   // Note that we only do this for alloca's, because malloc should allocate and
9180   // return a unique pointer, even for a zero byte allocation.
9181   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9182       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9183     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9184
9185   return 0;
9186 }
9187
9188 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9189   Value *Op = FI.getOperand(0);
9190
9191   // free undef -> unreachable.
9192   if (isa<UndefValue>(Op)) {
9193     // Insert a new store to null because we cannot modify the CFG here.
9194     new StoreInst(ConstantInt::getTrue(),
9195                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9196     return EraseInstFromFunction(FI);
9197   }
9198   
9199   // If we have 'free null' delete the instruction.  This can happen in stl code
9200   // when lots of inlining happens.
9201   if (isa<ConstantPointerNull>(Op))
9202     return EraseInstFromFunction(FI);
9203   
9204   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9205   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9206     FI.setOperand(0, CI->getOperand(0));
9207     return &FI;
9208   }
9209   
9210   // Change free (gep X, 0,0,0,0) into free(X)
9211   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9212     if (GEPI->hasAllZeroIndices()) {
9213       AddToWorkList(GEPI);
9214       FI.setOperand(0, GEPI->getOperand(0));
9215       return &FI;
9216     }
9217   }
9218   
9219   // Change free(malloc) into nothing, if the malloc has a single use.
9220   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9221     if (MI->hasOneUse()) {
9222       EraseInstFromFunction(FI);
9223       return EraseInstFromFunction(*MI);
9224     }
9225
9226   return 0;
9227 }
9228
9229
9230 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9231 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9232                                         const TargetData *TD) {
9233   User *CI = cast<User>(LI.getOperand(0));
9234   Value *CastOp = CI->getOperand(0);
9235
9236   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9237     // Instead of loading constant c string, use corresponding integer value
9238     // directly if string length is small enough.
9239     const std::string &Str = CE->getOperand(0)->getStringValue();
9240     if (!Str.empty()) {
9241       unsigned len = Str.length();
9242       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9243       unsigned numBits = Ty->getPrimitiveSizeInBits();
9244       // Replace LI with immediate integer store.
9245       if ((numBits >> 3) == len + 1) {
9246         APInt StrVal(numBits, 0);
9247         APInt SingleChar(numBits, 0);
9248         if (TD->isLittleEndian()) {
9249           for (signed i = len-1; i >= 0; i--) {
9250             SingleChar = (uint64_t) Str[i];
9251             StrVal = (StrVal << 8) | SingleChar;
9252           }
9253         } else {
9254           for (unsigned i = 0; i < len; i++) {
9255             SingleChar = (uint64_t) Str[i];
9256                 StrVal = (StrVal << 8) | SingleChar;
9257           }
9258           // Append NULL at the end.
9259           SingleChar = 0;
9260           StrVal = (StrVal << 8) | SingleChar;
9261         }
9262         Value *NL = ConstantInt::get(StrVal);
9263         return IC.ReplaceInstUsesWith(LI, NL);
9264       }
9265     }
9266   }
9267
9268   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9269   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9270     const Type *SrcPTy = SrcTy->getElementType();
9271
9272     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9273          isa<VectorType>(DestPTy)) {
9274       // If the source is an array, the code below will not succeed.  Check to
9275       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9276       // constants.
9277       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9278         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9279           if (ASrcTy->getNumElements() != 0) {
9280             Value *Idxs[2];
9281             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9282             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9283             SrcTy = cast<PointerType>(CastOp->getType());
9284             SrcPTy = SrcTy->getElementType();
9285           }
9286
9287       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9288             isa<VectorType>(SrcPTy)) &&
9289           // Do not allow turning this into a load of an integer, which is then
9290           // casted to a pointer, this pessimizes pointer analysis a lot.
9291           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9292           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9293                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9294
9295         // Okay, we are casting from one integer or pointer type to another of
9296         // the same size.  Instead of casting the pointer before the load, cast
9297         // the result of the loaded value.
9298         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9299                                                              CI->getName(),
9300                                                          LI.isVolatile()),LI);
9301         // Now cast the result of the load.
9302         return new BitCastInst(NewLoad, LI.getType());
9303       }
9304     }
9305   }
9306   return 0;
9307 }
9308
9309 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9310 /// from this value cannot trap.  If it is not obviously safe to load from the
9311 /// specified pointer, we do a quick local scan of the basic block containing
9312 /// ScanFrom, to determine if the address is already accessed.
9313 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9314   // If it is an alloca it is always safe to load from.
9315   if (isa<AllocaInst>(V)) return true;
9316
9317   // If it is a global variable it is mostly safe to load from.
9318   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9319     // Don't try to evaluate aliases.  External weak GV can be null.
9320     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9321
9322   // Otherwise, be a little bit agressive by scanning the local block where we
9323   // want to check to see if the pointer is already being loaded or stored
9324   // from/to.  If so, the previous load or store would have already trapped,
9325   // so there is no harm doing an extra load (also, CSE will later eliminate
9326   // the load entirely).
9327   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9328
9329   while (BBI != E) {
9330     --BBI;
9331
9332     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9333       if (LI->getOperand(0) == V) return true;
9334     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9335       if (SI->getOperand(1) == V) return true;
9336
9337   }
9338   return false;
9339 }
9340
9341 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9342 /// until we find the underlying object a pointer is referring to or something
9343 /// we don't understand.  Note that the returned pointer may be offset from the
9344 /// input, because we ignore GEP indices.
9345 static Value *GetUnderlyingObject(Value *Ptr) {
9346   while (1) {
9347     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9348       if (CE->getOpcode() == Instruction::BitCast ||
9349           CE->getOpcode() == Instruction::GetElementPtr)
9350         Ptr = CE->getOperand(0);
9351       else
9352         return Ptr;
9353     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9354       Ptr = BCI->getOperand(0);
9355     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9356       Ptr = GEP->getOperand(0);
9357     } else {
9358       return Ptr;
9359     }
9360   }
9361 }
9362
9363 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9364   Value *Op = LI.getOperand(0);
9365
9366   // Attempt to improve the alignment.
9367   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9368   if (KnownAlign > LI.getAlignment())
9369     LI.setAlignment(KnownAlign);
9370
9371   // load (cast X) --> cast (load X) iff safe
9372   if (isa<CastInst>(Op))
9373     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9374       return Res;
9375
9376   // None of the following transforms are legal for volatile loads.
9377   if (LI.isVolatile()) return 0;
9378   
9379   if (&LI.getParent()->front() != &LI) {
9380     BasicBlock::iterator BBI = &LI; --BBI;
9381     // If the instruction immediately before this is a store to the same
9382     // address, do a simple form of store->load forwarding.
9383     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9384       if (SI->getOperand(1) == LI.getOperand(0))
9385         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9386     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9387       if (LIB->getOperand(0) == LI.getOperand(0))
9388         return ReplaceInstUsesWith(LI, LIB);
9389   }
9390
9391   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9392     const Value *GEPI0 = GEPI->getOperand(0);
9393     // TODO: Consider a target hook for valid address spaces for this xform.
9394     if (isa<ConstantPointerNull>(GEPI0) &&
9395         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
9396       // Insert a new store to null instruction before the load to indicate
9397       // that this code is not reachable.  We do this instead of inserting
9398       // an unreachable instruction directly because we cannot modify the
9399       // CFG.
9400       new StoreInst(UndefValue::get(LI.getType()),
9401                     Constant::getNullValue(Op->getType()), &LI);
9402       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9403     }
9404   } 
9405
9406   if (Constant *C = dyn_cast<Constant>(Op)) {
9407     // load null/undef -> undef
9408     // TODO: Consider a target hook for valid address spaces for this xform.
9409     if (isa<UndefValue>(C) || (C->isNullValue() && 
9410         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
9411       // Insert a new store to null instruction before the load to indicate that
9412       // this code is not reachable.  We do this instead of inserting an
9413       // unreachable instruction directly because we cannot modify the CFG.
9414       new StoreInst(UndefValue::get(LI.getType()),
9415                     Constant::getNullValue(Op->getType()), &LI);
9416       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9417     }
9418
9419     // Instcombine load (constant global) into the value loaded.
9420     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9421       if (GV->isConstant() && !GV->isDeclaration())
9422         return ReplaceInstUsesWith(LI, GV->getInitializer());
9423
9424     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9425     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9426       if (CE->getOpcode() == Instruction::GetElementPtr) {
9427         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9428           if (GV->isConstant() && !GV->isDeclaration())
9429             if (Constant *V = 
9430                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9431               return ReplaceInstUsesWith(LI, V);
9432         if (CE->getOperand(0)->isNullValue()) {
9433           // Insert a new store to null instruction before the load to indicate
9434           // that this code is not reachable.  We do this instead of inserting
9435           // an unreachable instruction directly because we cannot modify the
9436           // CFG.
9437           new StoreInst(UndefValue::get(LI.getType()),
9438                         Constant::getNullValue(Op->getType()), &LI);
9439           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9440         }
9441
9442       } else if (CE->isCast()) {
9443         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9444           return Res;
9445       }
9446   }
9447     
9448   // If this load comes from anywhere in a constant global, and if the global
9449   // is all undef or zero, we know what it loads.
9450   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9451     if (GV->isConstant() && GV->hasInitializer()) {
9452       if (GV->getInitializer()->isNullValue())
9453         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9454       else if (isa<UndefValue>(GV->getInitializer()))
9455         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9456     }
9457   }
9458
9459   if (Op->hasOneUse()) {
9460     // Change select and PHI nodes to select values instead of addresses: this
9461     // helps alias analysis out a lot, allows many others simplifications, and
9462     // exposes redundancy in the code.
9463     //
9464     // Note that we cannot do the transformation unless we know that the
9465     // introduced loads cannot trap!  Something like this is valid as long as
9466     // the condition is always false: load (select bool %C, int* null, int* %G),
9467     // but it would not be valid if we transformed it to load from null
9468     // unconditionally.
9469     //
9470     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9471       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9472       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9473           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9474         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9475                                      SI->getOperand(1)->getName()+".val"), LI);
9476         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9477                                      SI->getOperand(2)->getName()+".val"), LI);
9478         return new SelectInst(SI->getCondition(), V1, V2);
9479       }
9480
9481       // load (select (cond, null, P)) -> load P
9482       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9483         if (C->isNullValue()) {
9484           LI.setOperand(0, SI->getOperand(2));
9485           return &LI;
9486         }
9487
9488       // load (select (cond, P, null)) -> load P
9489       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9490         if (C->isNullValue()) {
9491           LI.setOperand(0, SI->getOperand(1));
9492           return &LI;
9493         }
9494     }
9495   }
9496   return 0;
9497 }
9498
9499 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9500 /// when possible.
9501 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9502   User *CI = cast<User>(SI.getOperand(1));
9503   Value *CastOp = CI->getOperand(0);
9504
9505   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9506   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9507     const Type *SrcPTy = SrcTy->getElementType();
9508
9509     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9510       // If the source is an array, the code below will not succeed.  Check to
9511       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9512       // constants.
9513       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9514         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9515           if (ASrcTy->getNumElements() != 0) {
9516             Value* Idxs[2];
9517             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9518             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9519             SrcTy = cast<PointerType>(CastOp->getType());
9520             SrcPTy = SrcTy->getElementType();
9521           }
9522
9523       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9524           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9525                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9526
9527         // Okay, we are casting from one integer or pointer type to another of
9528         // the same size.  Instead of casting the pointer before 
9529         // the store, cast the value to be stored.
9530         Value *NewCast;
9531         Value *SIOp0 = SI.getOperand(0);
9532         Instruction::CastOps opcode = Instruction::BitCast;
9533         const Type* CastSrcTy = SIOp0->getType();
9534         const Type* CastDstTy = SrcPTy;
9535         if (isa<PointerType>(CastDstTy)) {
9536           if (CastSrcTy->isInteger())
9537             opcode = Instruction::IntToPtr;
9538         } else if (isa<IntegerType>(CastDstTy)) {
9539           if (isa<PointerType>(SIOp0->getType()))
9540             opcode = Instruction::PtrToInt;
9541         }
9542         if (Constant *C = dyn_cast<Constant>(SIOp0))
9543           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9544         else
9545           NewCast = IC.InsertNewInstBefore(
9546             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9547             SI);
9548         return new StoreInst(NewCast, CastOp);
9549       }
9550     }
9551   }
9552   return 0;
9553 }
9554
9555 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9556   Value *Val = SI.getOperand(0);
9557   Value *Ptr = SI.getOperand(1);
9558
9559   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9560     EraseInstFromFunction(SI);
9561     ++NumCombined;
9562     return 0;
9563   }
9564   
9565   // If the RHS is an alloca with a single use, zapify the store, making the
9566   // alloca dead.
9567   if (Ptr->hasOneUse()) {
9568     if (isa<AllocaInst>(Ptr)) {
9569       EraseInstFromFunction(SI);
9570       ++NumCombined;
9571       return 0;
9572     }
9573     
9574     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9575       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9576           GEP->getOperand(0)->hasOneUse()) {
9577         EraseInstFromFunction(SI);
9578         ++NumCombined;
9579         return 0;
9580       }
9581   }
9582
9583   // Attempt to improve the alignment.
9584   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9585   if (KnownAlign > SI.getAlignment())
9586     SI.setAlignment(KnownAlign);
9587
9588   // Do really simple DSE, to catch cases where there are several consequtive
9589   // stores to the same location, separated by a few arithmetic operations. This
9590   // situation often occurs with bitfield accesses.
9591   BasicBlock::iterator BBI = &SI;
9592   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9593        --ScanInsts) {
9594     --BBI;
9595     
9596     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9597       // Prev store isn't volatile, and stores to the same location?
9598       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9599         ++NumDeadStore;
9600         ++BBI;
9601         EraseInstFromFunction(*PrevSI);
9602         continue;
9603       }
9604       break;
9605     }
9606     
9607     // If this is a load, we have to stop.  However, if the loaded value is from
9608     // the pointer we're loading and is producing the pointer we're storing,
9609     // then *this* store is dead (X = load P; store X -> P).
9610     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9611       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
9612         EraseInstFromFunction(SI);
9613         ++NumCombined;
9614         return 0;
9615       }
9616       // Otherwise, this is a load from some other location.  Stores before it
9617       // may not be dead.
9618       break;
9619     }
9620     
9621     // Don't skip over loads or things that can modify memory.
9622     if (BBI->mayWriteToMemory())
9623       break;
9624   }
9625   
9626   
9627   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9628
9629   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9630   if (isa<ConstantPointerNull>(Ptr)) {
9631     if (!isa<UndefValue>(Val)) {
9632       SI.setOperand(0, UndefValue::get(Val->getType()));
9633       if (Instruction *U = dyn_cast<Instruction>(Val))
9634         AddToWorkList(U);  // Dropped a use.
9635       ++NumCombined;
9636     }
9637     return 0;  // Do not modify these!
9638   }
9639
9640   // store undef, Ptr -> noop
9641   if (isa<UndefValue>(Val)) {
9642     EraseInstFromFunction(SI);
9643     ++NumCombined;
9644     return 0;
9645   }
9646
9647   // If the pointer destination is a cast, see if we can fold the cast into the
9648   // source instead.
9649   if (isa<CastInst>(Ptr))
9650     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9651       return Res;
9652   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9653     if (CE->isCast())
9654       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9655         return Res;
9656
9657   
9658   // If this store is the last instruction in the basic block, and if the block
9659   // ends with an unconditional branch, try to move it to the successor block.
9660   BBI = &SI; ++BBI;
9661   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9662     if (BI->isUnconditional())
9663       if (SimplifyStoreAtEndOfBlock(SI))
9664         return 0;  // xform done!
9665   
9666   return 0;
9667 }
9668
9669 /// SimplifyStoreAtEndOfBlock - Turn things like:
9670 ///   if () { *P = v1; } else { *P = v2 }
9671 /// into a phi node with a store in the successor.
9672 ///
9673 /// Simplify things like:
9674 ///   *P = v1; if () { *P = v2; }
9675 /// into a phi node with a store in the successor.
9676 ///
9677 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9678   BasicBlock *StoreBB = SI.getParent();
9679   
9680   // Check to see if the successor block has exactly two incoming edges.  If
9681   // so, see if the other predecessor contains a store to the same location.
9682   // if so, insert a PHI node (if needed) and move the stores down.
9683   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9684   
9685   // Determine whether Dest has exactly two predecessors and, if so, compute
9686   // the other predecessor.
9687   pred_iterator PI = pred_begin(DestBB);
9688   BasicBlock *OtherBB = 0;
9689   if (*PI != StoreBB)
9690     OtherBB = *PI;
9691   ++PI;
9692   if (PI == pred_end(DestBB))
9693     return false;
9694   
9695   if (*PI != StoreBB) {
9696     if (OtherBB)
9697       return false;
9698     OtherBB = *PI;
9699   }
9700   if (++PI != pred_end(DestBB))
9701     return false;
9702   
9703   
9704   // Verify that the other block ends in a branch and is not otherwise empty.
9705   BasicBlock::iterator BBI = OtherBB->getTerminator();
9706   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9707   if (!OtherBr || BBI == OtherBB->begin())
9708     return false;
9709   
9710   // If the other block ends in an unconditional branch, check for the 'if then
9711   // else' case.  there is an instruction before the branch.
9712   StoreInst *OtherStore = 0;
9713   if (OtherBr->isUnconditional()) {
9714     // If this isn't a store, or isn't a store to the same location, bail out.
9715     --BBI;
9716     OtherStore = dyn_cast<StoreInst>(BBI);
9717     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9718       return false;
9719   } else {
9720     // Otherwise, the other block ended with a conditional branch. If one of the
9721     // destinations is StoreBB, then we have the if/then case.
9722     if (OtherBr->getSuccessor(0) != StoreBB && 
9723         OtherBr->getSuccessor(1) != StoreBB)
9724       return false;
9725     
9726     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9727     // if/then triangle.  See if there is a store to the same ptr as SI that
9728     // lives in OtherBB.
9729     for (;; --BBI) {
9730       // Check to see if we find the matching store.
9731       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9732         if (OtherStore->getOperand(1) != SI.getOperand(1))
9733           return false;
9734         break;
9735       }
9736       // If we find something that may be using the stored value, or if we run
9737       // out of instructions, we can't do the xform.
9738       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9739           BBI == OtherBB->begin())
9740         return false;
9741     }
9742     
9743     // In order to eliminate the store in OtherBr, we have to
9744     // make sure nothing reads the stored value in StoreBB.
9745     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9746       // FIXME: This should really be AA driven.
9747       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9748         return false;
9749     }
9750   }
9751   
9752   // Insert a PHI node now if we need it.
9753   Value *MergedVal = OtherStore->getOperand(0);
9754   if (MergedVal != SI.getOperand(0)) {
9755     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9756     PN->reserveOperandSpace(2);
9757     PN->addIncoming(SI.getOperand(0), SI.getParent());
9758     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9759     MergedVal = InsertNewInstBefore(PN, DestBB->front());
9760   }
9761   
9762   // Advance to a place where it is safe to insert the new store and
9763   // insert it.
9764   BBI = DestBB->begin();
9765   while (isa<PHINode>(BBI)) ++BBI;
9766   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9767                                     OtherStore->isVolatile()), *BBI);
9768   
9769   // Nuke the old stores.
9770   EraseInstFromFunction(SI);
9771   EraseInstFromFunction(*OtherStore);
9772   ++NumCombined;
9773   return true;
9774 }
9775
9776
9777 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9778   // Change br (not X), label True, label False to: br X, label False, True
9779   Value *X = 0;
9780   BasicBlock *TrueDest;
9781   BasicBlock *FalseDest;
9782   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9783       !isa<Constant>(X)) {
9784     // Swap Destinations and condition...
9785     BI.setCondition(X);
9786     BI.setSuccessor(0, FalseDest);
9787     BI.setSuccessor(1, TrueDest);
9788     return &BI;
9789   }
9790
9791   // Cannonicalize fcmp_one -> fcmp_oeq
9792   FCmpInst::Predicate FPred; Value *Y;
9793   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
9794                              TrueDest, FalseDest)))
9795     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9796          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9797       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9798       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9799       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9800       NewSCC->takeName(I);
9801       // Swap Destinations and condition...
9802       BI.setCondition(NewSCC);
9803       BI.setSuccessor(0, FalseDest);
9804       BI.setSuccessor(1, TrueDest);
9805       RemoveFromWorkList(I);
9806       I->eraseFromParent();
9807       AddToWorkList(NewSCC);
9808       return &BI;
9809     }
9810
9811   // Cannonicalize icmp_ne -> icmp_eq
9812   ICmpInst::Predicate IPred;
9813   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9814                       TrueDest, FalseDest)))
9815     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
9816          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9817          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9818       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9819       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9820       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9821       NewSCC->takeName(I);
9822       // Swap Destinations and condition...
9823       BI.setCondition(NewSCC);
9824       BI.setSuccessor(0, FalseDest);
9825       BI.setSuccessor(1, TrueDest);
9826       RemoveFromWorkList(I);
9827       I->eraseFromParent();;
9828       AddToWorkList(NewSCC);
9829       return &BI;
9830     }
9831
9832   return 0;
9833 }
9834
9835 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9836   Value *Cond = SI.getCondition();
9837   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9838     if (I->getOpcode() == Instruction::Add)
9839       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9840         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9841         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9842           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9843                                                 AddRHS));
9844         SI.setOperand(0, I->getOperand(0));
9845         AddToWorkList(I);
9846         return &SI;
9847       }
9848   }
9849   return 0;
9850 }
9851
9852 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9853 /// is to leave as a vector operation.
9854 static bool CheapToScalarize(Value *V, bool isConstant) {
9855   if (isa<ConstantAggregateZero>(V)) 
9856     return true;
9857   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9858     if (isConstant) return true;
9859     // If all elts are the same, we can extract.
9860     Constant *Op0 = C->getOperand(0);
9861     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9862       if (C->getOperand(i) != Op0)
9863         return false;
9864     return true;
9865   }
9866   Instruction *I = dyn_cast<Instruction>(V);
9867   if (!I) return false;
9868   
9869   // Insert element gets simplified to the inserted element or is deleted if
9870   // this is constant idx extract element and its a constant idx insertelt.
9871   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9872       isa<ConstantInt>(I->getOperand(2)))
9873     return true;
9874   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9875     return true;
9876   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9877     if (BO->hasOneUse() &&
9878         (CheapToScalarize(BO->getOperand(0), isConstant) ||
9879          CheapToScalarize(BO->getOperand(1), isConstant)))
9880       return true;
9881   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9882     if (CI->hasOneUse() &&
9883         (CheapToScalarize(CI->getOperand(0), isConstant) ||
9884          CheapToScalarize(CI->getOperand(1), isConstant)))
9885       return true;
9886   
9887   return false;
9888 }
9889
9890 /// Read and decode a shufflevector mask.
9891 ///
9892 /// It turns undef elements into values that are larger than the number of
9893 /// elements in the input.
9894 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9895   unsigned NElts = SVI->getType()->getNumElements();
9896   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9897     return std::vector<unsigned>(NElts, 0);
9898   if (isa<UndefValue>(SVI->getOperand(2)))
9899     return std::vector<unsigned>(NElts, 2*NElts);
9900
9901   std::vector<unsigned> Result;
9902   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9903   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9904     if (isa<UndefValue>(CP->getOperand(i)))
9905       Result.push_back(NElts*2);  // undef -> 8
9906     else
9907       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9908   return Result;
9909 }
9910
9911 /// FindScalarElement - Given a vector and an element number, see if the scalar
9912 /// value is already around as a register, for example if it were inserted then
9913 /// extracted from the vector.
9914 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9915   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9916   const VectorType *PTy = cast<VectorType>(V->getType());
9917   unsigned Width = PTy->getNumElements();
9918   if (EltNo >= Width)  // Out of range access.
9919     return UndefValue::get(PTy->getElementType());
9920   
9921   if (isa<UndefValue>(V))
9922     return UndefValue::get(PTy->getElementType());
9923   else if (isa<ConstantAggregateZero>(V))
9924     return Constant::getNullValue(PTy->getElementType());
9925   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9926     return CP->getOperand(EltNo);
9927   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9928     // If this is an insert to a variable element, we don't know what it is.
9929     if (!isa<ConstantInt>(III->getOperand(2))) 
9930       return 0;
9931     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9932     
9933     // If this is an insert to the element we are looking for, return the
9934     // inserted value.
9935     if (EltNo == IIElt) 
9936       return III->getOperand(1);
9937     
9938     // Otherwise, the insertelement doesn't modify the value, recurse on its
9939     // vector input.
9940     return FindScalarElement(III->getOperand(0), EltNo);
9941   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9942     unsigned InEl = getShuffleMask(SVI)[EltNo];
9943     if (InEl < Width)
9944       return FindScalarElement(SVI->getOperand(0), InEl);
9945     else if (InEl < Width*2)
9946       return FindScalarElement(SVI->getOperand(1), InEl - Width);
9947     else
9948       return UndefValue::get(PTy->getElementType());
9949   }
9950   
9951   // Otherwise, we don't know.
9952   return 0;
9953 }
9954
9955 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9956
9957   // If vector val is undef, replace extract with scalar undef.
9958   if (isa<UndefValue>(EI.getOperand(0)))
9959     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9960
9961   // If vector val is constant 0, replace extract with scalar 0.
9962   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9963     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9964   
9965   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9966     // If vector val is constant with uniform operands, replace EI
9967     // with that operand
9968     Constant *op0 = C->getOperand(0);
9969     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9970       if (C->getOperand(i) != op0) {
9971         op0 = 0; 
9972         break;
9973       }
9974     if (op0)
9975       return ReplaceInstUsesWith(EI, op0);
9976   }
9977   
9978   // If extracting a specified index from the vector, see if we can recursively
9979   // find a previously computed scalar that was inserted into the vector.
9980   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9981     unsigned IndexVal = IdxC->getZExtValue();
9982     unsigned VectorWidth = 
9983       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9984       
9985     // If this is extracting an invalid index, turn this into undef, to avoid
9986     // crashing the code below.
9987     if (IndexVal >= VectorWidth)
9988       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9989     
9990     // This instruction only demands the single element from the input vector.
9991     // If the input vector has a single use, simplify it based on this use
9992     // property.
9993     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
9994       uint64_t UndefElts;
9995       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9996                                                 1 << IndexVal,
9997                                                 UndefElts)) {
9998         EI.setOperand(0, V);
9999         return &EI;
10000       }
10001     }
10002     
10003     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10004       return ReplaceInstUsesWith(EI, Elt);
10005     
10006     // If the this extractelement is directly using a bitcast from a vector of
10007     // the same number of elements, see if we can find the source element from
10008     // it.  In this case, we will end up needing to bitcast the scalars.
10009     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10010       if (const VectorType *VT = 
10011               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10012         if (VT->getNumElements() == VectorWidth)
10013           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10014             return new BitCastInst(Elt, EI.getType());
10015     }
10016   }
10017   
10018   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10019     if (I->hasOneUse()) {
10020       // Push extractelement into predecessor operation if legal and
10021       // profitable to do so
10022       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10023         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10024         if (CheapToScalarize(BO, isConstantElt)) {
10025           ExtractElementInst *newEI0 = 
10026             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10027                                    EI.getName()+".lhs");
10028           ExtractElementInst *newEI1 =
10029             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10030                                    EI.getName()+".rhs");
10031           InsertNewInstBefore(newEI0, EI);
10032           InsertNewInstBefore(newEI1, EI);
10033           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10034         }
10035       } else if (isa<LoadInst>(I)) {
10036         unsigned AS = 
10037           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10038         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10039                                          PointerType::get(EI.getType(), AS),EI);
10040         GetElementPtrInst *GEP = 
10041           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10042         InsertNewInstBefore(GEP, EI);
10043         return new LoadInst(GEP);
10044       }
10045     }
10046     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10047       // Extracting the inserted element?
10048       if (IE->getOperand(2) == EI.getOperand(1))
10049         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10050       // If the inserted and extracted elements are constants, they must not
10051       // be the same value, extract from the pre-inserted value instead.
10052       if (isa<Constant>(IE->getOperand(2)) &&
10053           isa<Constant>(EI.getOperand(1))) {
10054         AddUsesToWorkList(EI);
10055         EI.setOperand(0, IE->getOperand(0));
10056         return &EI;
10057       }
10058     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10059       // If this is extracting an element from a shufflevector, figure out where
10060       // it came from and extract from the appropriate input element instead.
10061       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10062         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10063         Value *Src;
10064         if (SrcIdx < SVI->getType()->getNumElements())
10065           Src = SVI->getOperand(0);
10066         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10067           SrcIdx -= SVI->getType()->getNumElements();
10068           Src = SVI->getOperand(1);
10069         } else {
10070           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10071         }
10072         return new ExtractElementInst(Src, SrcIdx);
10073       }
10074     }
10075   }
10076   return 0;
10077 }
10078
10079 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10080 /// elements from either LHS or RHS, return the shuffle mask and true. 
10081 /// Otherwise, return false.
10082 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10083                                          std::vector<Constant*> &Mask) {
10084   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10085          "Invalid CollectSingleShuffleElements");
10086   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10087
10088   if (isa<UndefValue>(V)) {
10089     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10090     return true;
10091   } else if (V == LHS) {
10092     for (unsigned i = 0; i != NumElts; ++i)
10093       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10094     return true;
10095   } else if (V == RHS) {
10096     for (unsigned i = 0; i != NumElts; ++i)
10097       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10098     return true;
10099   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10100     // If this is an insert of an extract from some other vector, include it.
10101     Value *VecOp    = IEI->getOperand(0);
10102     Value *ScalarOp = IEI->getOperand(1);
10103     Value *IdxOp    = IEI->getOperand(2);
10104     
10105     if (!isa<ConstantInt>(IdxOp))
10106       return false;
10107     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10108     
10109     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10110       // Okay, we can handle this if the vector we are insertinting into is
10111       // transitively ok.
10112       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10113         // If so, update the mask to reflect the inserted undef.
10114         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10115         return true;
10116       }      
10117     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10118       if (isa<ConstantInt>(EI->getOperand(1)) &&
10119           EI->getOperand(0)->getType() == V->getType()) {
10120         unsigned ExtractedIdx =
10121           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10122         
10123         // This must be extracting from either LHS or RHS.
10124         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10125           // Okay, we can handle this if the vector we are insertinting into is
10126           // transitively ok.
10127           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10128             // If so, update the mask to reflect the inserted value.
10129             if (EI->getOperand(0) == LHS) {
10130               Mask[InsertedIdx & (NumElts-1)] = 
10131                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10132             } else {
10133               assert(EI->getOperand(0) == RHS);
10134               Mask[InsertedIdx & (NumElts-1)] = 
10135                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10136               
10137             }
10138             return true;
10139           }
10140         }
10141       }
10142     }
10143   }
10144   // TODO: Handle shufflevector here!
10145   
10146   return false;
10147 }
10148
10149 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10150 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10151 /// that computes V and the LHS value of the shuffle.
10152 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10153                                      Value *&RHS) {
10154   assert(isa<VectorType>(V->getType()) && 
10155          (RHS == 0 || V->getType() == RHS->getType()) &&
10156          "Invalid shuffle!");
10157   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10158
10159   if (isa<UndefValue>(V)) {
10160     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10161     return V;
10162   } else if (isa<ConstantAggregateZero>(V)) {
10163     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10164     return V;
10165   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10166     // If this is an insert of an extract from some other vector, include it.
10167     Value *VecOp    = IEI->getOperand(0);
10168     Value *ScalarOp = IEI->getOperand(1);
10169     Value *IdxOp    = IEI->getOperand(2);
10170     
10171     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10172       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10173           EI->getOperand(0)->getType() == V->getType()) {
10174         unsigned ExtractedIdx =
10175           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10176         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10177         
10178         // Either the extracted from or inserted into vector must be RHSVec,
10179         // otherwise we'd end up with a shuffle of three inputs.
10180         if (EI->getOperand(0) == RHS || RHS == 0) {
10181           RHS = EI->getOperand(0);
10182           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10183           Mask[InsertedIdx & (NumElts-1)] = 
10184             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10185           return V;
10186         }
10187         
10188         if (VecOp == RHS) {
10189           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10190           // Everything but the extracted element is replaced with the RHS.
10191           for (unsigned i = 0; i != NumElts; ++i) {
10192             if (i != InsertedIdx)
10193               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10194           }
10195           return V;
10196         }
10197         
10198         // If this insertelement is a chain that comes from exactly these two
10199         // vectors, return the vector and the effective shuffle.
10200         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10201           return EI->getOperand(0);
10202         
10203       }
10204     }
10205   }
10206   // TODO: Handle shufflevector here!
10207   
10208   // Otherwise, can't do anything fancy.  Return an identity vector.
10209   for (unsigned i = 0; i != NumElts; ++i)
10210     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10211   return V;
10212 }
10213
10214 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10215   Value *VecOp    = IE.getOperand(0);
10216   Value *ScalarOp = IE.getOperand(1);
10217   Value *IdxOp    = IE.getOperand(2);
10218   
10219   // Inserting an undef or into an undefined place, remove this.
10220   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10221     ReplaceInstUsesWith(IE, VecOp);
10222   
10223   // If the inserted element was extracted from some other vector, and if the 
10224   // indexes are constant, try to turn this into a shufflevector operation.
10225   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10226     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10227         EI->getOperand(0)->getType() == IE.getType()) {
10228       unsigned NumVectorElts = IE.getType()->getNumElements();
10229       unsigned ExtractedIdx =
10230         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10231       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10232       
10233       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10234         return ReplaceInstUsesWith(IE, VecOp);
10235       
10236       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10237         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10238       
10239       // If we are extracting a value from a vector, then inserting it right
10240       // back into the same place, just use the input vector.
10241       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10242         return ReplaceInstUsesWith(IE, VecOp);      
10243       
10244       // We could theoretically do this for ANY input.  However, doing so could
10245       // turn chains of insertelement instructions into a chain of shufflevector
10246       // instructions, and right now we do not merge shufflevectors.  As such,
10247       // only do this in a situation where it is clear that there is benefit.
10248       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10249         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10250         // the values of VecOp, except then one read from EIOp0.
10251         // Build a new shuffle mask.
10252         std::vector<Constant*> Mask;
10253         if (isa<UndefValue>(VecOp))
10254           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10255         else {
10256           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10257           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10258                                                        NumVectorElts));
10259         } 
10260         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10261         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10262                                      ConstantVector::get(Mask));
10263       }
10264       
10265       // If this insertelement isn't used by some other insertelement, turn it
10266       // (and any insertelements it points to), into one big shuffle.
10267       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10268         std::vector<Constant*> Mask;
10269         Value *RHS = 0;
10270         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10271         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10272         // We now have a shuffle of LHS, RHS, Mask.
10273         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10274       }
10275     }
10276   }
10277
10278   return 0;
10279 }
10280
10281
10282 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10283   Value *LHS = SVI.getOperand(0);
10284   Value *RHS = SVI.getOperand(1);
10285   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10286
10287   bool MadeChange = false;
10288   
10289   // Undefined shuffle mask -> undefined value.
10290   if (isa<UndefValue>(SVI.getOperand(2)))
10291     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10292   
10293   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10294   // the undef, change them to undefs.
10295   if (isa<UndefValue>(SVI.getOperand(1))) {
10296     // Scan to see if there are any references to the RHS.  If so, replace them
10297     // with undef element refs and set MadeChange to true.
10298     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10299       if (Mask[i] >= e && Mask[i] != 2*e) {
10300         Mask[i] = 2*e;
10301         MadeChange = true;
10302       }
10303     }
10304     
10305     if (MadeChange) {
10306       // Remap any references to RHS to use LHS.
10307       std::vector<Constant*> Elts;
10308       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10309         if (Mask[i] == 2*e)
10310           Elts.push_back(UndefValue::get(Type::Int32Ty));
10311         else
10312           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10313       }
10314       SVI.setOperand(2, ConstantVector::get(Elts));
10315     }
10316   }
10317   
10318   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10319   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10320   if (LHS == RHS || isa<UndefValue>(LHS)) {
10321     if (isa<UndefValue>(LHS) && LHS == RHS) {
10322       // shuffle(undef,undef,mask) -> undef.
10323       return ReplaceInstUsesWith(SVI, LHS);
10324     }
10325     
10326     // Remap any references to RHS to use LHS.
10327     std::vector<Constant*> Elts;
10328     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10329       if (Mask[i] >= 2*e)
10330         Elts.push_back(UndefValue::get(Type::Int32Ty));
10331       else {
10332         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10333             (Mask[i] <  e && isa<UndefValue>(LHS)))
10334           Mask[i] = 2*e;     // Turn into undef.
10335         else
10336           Mask[i] &= (e-1);  // Force to LHS.
10337         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10338       }
10339     }
10340     SVI.setOperand(0, SVI.getOperand(1));
10341     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10342     SVI.setOperand(2, ConstantVector::get(Elts));
10343     LHS = SVI.getOperand(0);
10344     RHS = SVI.getOperand(1);
10345     MadeChange = true;
10346   }
10347   
10348   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10349   bool isLHSID = true, isRHSID = true;
10350     
10351   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10352     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10353     // Is this an identity shuffle of the LHS value?
10354     isLHSID &= (Mask[i] == i);
10355       
10356     // Is this an identity shuffle of the RHS value?
10357     isRHSID &= (Mask[i]-e == i);
10358   }
10359
10360   // Eliminate identity shuffles.
10361   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10362   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10363   
10364   // If the LHS is a shufflevector itself, see if we can combine it with this
10365   // one without producing an unusual shuffle.  Here we are really conservative:
10366   // we are absolutely afraid of producing a shuffle mask not in the input
10367   // program, because the code gen may not be smart enough to turn a merged
10368   // shuffle into two specific shuffles: it may produce worse code.  As such,
10369   // we only merge two shuffles if the result is one of the two input shuffle
10370   // masks.  In this case, merging the shuffles just removes one instruction,
10371   // which we know is safe.  This is good for things like turning:
10372   // (splat(splat)) -> splat.
10373   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10374     if (isa<UndefValue>(RHS)) {
10375       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10376
10377       std::vector<unsigned> NewMask;
10378       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10379         if (Mask[i] >= 2*e)
10380           NewMask.push_back(2*e);
10381         else
10382           NewMask.push_back(LHSMask[Mask[i]]);
10383       
10384       // If the result mask is equal to the src shuffle or this shuffle mask, do
10385       // the replacement.
10386       if (NewMask == LHSMask || NewMask == Mask) {
10387         std::vector<Constant*> Elts;
10388         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10389           if (NewMask[i] >= e*2) {
10390             Elts.push_back(UndefValue::get(Type::Int32Ty));
10391           } else {
10392             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10393           }
10394         }
10395         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10396                                      LHSSVI->getOperand(1),
10397                                      ConstantVector::get(Elts));
10398       }
10399     }
10400   }
10401
10402   return MadeChange ? &SVI : 0;
10403 }
10404
10405
10406
10407
10408 /// TryToSinkInstruction - Try to move the specified instruction from its
10409 /// current block into the beginning of DestBlock, which can only happen if it's
10410 /// safe to move the instruction past all of the instructions between it and the
10411 /// end of its block.
10412 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10413   assert(I->hasOneUse() && "Invariants didn't hold!");
10414
10415   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10416   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10417
10418   // Do not sink alloca instructions out of the entry block.
10419   if (isa<AllocaInst>(I) && I->getParent() ==
10420         &DestBlock->getParent()->getEntryBlock())
10421     return false;
10422
10423   // We can only sink load instructions if there is nothing between the load and
10424   // the end of block that could change the value.
10425   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10426     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10427          Scan != E; ++Scan)
10428       if (Scan->mayWriteToMemory())
10429         return false;
10430   }
10431
10432   BasicBlock::iterator InsertPos = DestBlock->begin();
10433   while (isa<PHINode>(InsertPos)) ++InsertPos;
10434
10435   I->moveBefore(InsertPos);
10436   ++NumSunkInst;
10437   return true;
10438 }
10439
10440
10441 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10442 /// all reachable code to the worklist.
10443 ///
10444 /// This has a couple of tricks to make the code faster and more powerful.  In
10445 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10446 /// them to the worklist (this significantly speeds up instcombine on code where
10447 /// many instructions are dead or constant).  Additionally, if we find a branch
10448 /// whose condition is a known constant, we only visit the reachable successors.
10449 ///
10450 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10451                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10452                                        InstCombiner &IC,
10453                                        const TargetData *TD) {
10454   std::vector<BasicBlock*> Worklist;
10455   Worklist.push_back(BB);
10456
10457   while (!Worklist.empty()) {
10458     BB = Worklist.back();
10459     Worklist.pop_back();
10460     
10461     // We have now visited this block!  If we've already been here, ignore it.
10462     if (!Visited.insert(BB)) continue;
10463     
10464     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10465       Instruction *Inst = BBI++;
10466       
10467       // DCE instruction if trivially dead.
10468       if (isInstructionTriviallyDead(Inst)) {
10469         ++NumDeadInst;
10470         DOUT << "IC: DCE: " << *Inst;
10471         Inst->eraseFromParent();
10472         continue;
10473       }
10474       
10475       // ConstantProp instruction if trivially constant.
10476       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10477         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10478         Inst->replaceAllUsesWith(C);
10479         ++NumConstProp;
10480         Inst->eraseFromParent();
10481         continue;
10482       }
10483      
10484       IC.AddToWorkList(Inst);
10485     }
10486
10487     // Recursively visit successors.  If this is a branch or switch on a
10488     // constant, only visit the reachable successor.
10489     TerminatorInst *TI = BB->getTerminator();
10490     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10491       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10492         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10493         Worklist.push_back(BI->getSuccessor(!CondVal));
10494         continue;
10495       }
10496     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10497       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10498         // See if this is an explicit destination.
10499         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10500           if (SI->getCaseValue(i) == Cond) {
10501             Worklist.push_back(SI->getSuccessor(i));
10502             continue;
10503           }
10504         
10505         // Otherwise it is the default destination.
10506         Worklist.push_back(SI->getSuccessor(0));
10507         continue;
10508       }
10509     }
10510     
10511     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10512       Worklist.push_back(TI->getSuccessor(i));
10513   }
10514 }
10515
10516 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10517   bool Changed = false;
10518   TD = &getAnalysis<TargetData>();
10519   
10520   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10521              << F.getNameStr() << "\n");
10522
10523   {
10524     // Do a depth-first traversal of the function, populate the worklist with
10525     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10526     // track of which blocks we visit.
10527     SmallPtrSet<BasicBlock*, 64> Visited;
10528     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10529
10530     // Do a quick scan over the function.  If we find any blocks that are
10531     // unreachable, remove any instructions inside of them.  This prevents
10532     // the instcombine code from having to deal with some bad special cases.
10533     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10534       if (!Visited.count(BB)) {
10535         Instruction *Term = BB->getTerminator();
10536         while (Term != BB->begin()) {   // Remove instrs bottom-up
10537           BasicBlock::iterator I = Term; --I;
10538
10539           DOUT << "IC: DCE: " << *I;
10540           ++NumDeadInst;
10541
10542           if (!I->use_empty())
10543             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10544           I->eraseFromParent();
10545         }
10546       }
10547   }
10548
10549   while (!Worklist.empty()) {
10550     Instruction *I = RemoveOneFromWorkList();
10551     if (I == 0) continue;  // skip null values.
10552
10553     // Check to see if we can DCE the instruction.
10554     if (isInstructionTriviallyDead(I)) {
10555       // Add operands to the worklist.
10556       if (I->getNumOperands() < 4)
10557         AddUsesToWorkList(*I);
10558       ++NumDeadInst;
10559
10560       DOUT << "IC: DCE: " << *I;
10561
10562       I->eraseFromParent();
10563       RemoveFromWorkList(I);
10564       continue;
10565     }
10566
10567     // Instruction isn't dead, see if we can constant propagate it.
10568     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10569       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10570
10571       // Add operands to the worklist.
10572       AddUsesToWorkList(*I);
10573       ReplaceInstUsesWith(*I, C);
10574
10575       ++NumConstProp;
10576       I->eraseFromParent();
10577       RemoveFromWorkList(I);
10578       continue;
10579     }
10580
10581     // See if we can trivially sink this instruction to a successor basic block.
10582     if (I->hasOneUse()) {
10583       BasicBlock *BB = I->getParent();
10584       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10585       if (UserParent != BB) {
10586         bool UserIsSuccessor = false;
10587         // See if the user is one of our successors.
10588         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10589           if (*SI == UserParent) {
10590             UserIsSuccessor = true;
10591             break;
10592           }
10593
10594         // If the user is one of our immediate successors, and if that successor
10595         // only has us as a predecessors (we'd have to split the critical edge
10596         // otherwise), we can keep going.
10597         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10598             next(pred_begin(UserParent)) == pred_end(UserParent))
10599           // Okay, the CFG is simple enough, try to sink this instruction.
10600           Changed |= TryToSinkInstruction(I, UserParent);
10601       }
10602     }
10603
10604     // Now that we have an instruction, try combining it to simplify it...
10605 #ifndef NDEBUG
10606     std::string OrigI;
10607 #endif
10608     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10609     if (Instruction *Result = visit(*I)) {
10610       ++NumCombined;
10611       // Should we replace the old instruction with a new one?
10612       if (Result != I) {
10613         DOUT << "IC: Old = " << *I
10614              << "    New = " << *Result;
10615
10616         // Everything uses the new instruction now.
10617         I->replaceAllUsesWith(Result);
10618
10619         // Push the new instruction and any users onto the worklist.
10620         AddToWorkList(Result);
10621         AddUsersToWorkList(*Result);
10622
10623         // Move the name to the new instruction first.
10624         Result->takeName(I);
10625
10626         // Insert the new instruction into the basic block...
10627         BasicBlock *InstParent = I->getParent();
10628         BasicBlock::iterator InsertPos = I;
10629
10630         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10631           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10632             ++InsertPos;
10633
10634         InstParent->getInstList().insert(InsertPos, Result);
10635
10636         // Make sure that we reprocess all operands now that we reduced their
10637         // use counts.
10638         AddUsesToWorkList(*I);
10639
10640         // Instructions can end up on the worklist more than once.  Make sure
10641         // we do not process an instruction that has been deleted.
10642         RemoveFromWorkList(I);
10643
10644         // Erase the old instruction.
10645         InstParent->getInstList().erase(I);
10646       } else {
10647 #ifndef NDEBUG
10648         DOUT << "IC: Mod = " << OrigI
10649              << "    New = " << *I;
10650 #endif
10651
10652         // If the instruction was modified, it's possible that it is now dead.
10653         // if so, remove it.
10654         if (isInstructionTriviallyDead(I)) {
10655           // Make sure we process all operands now that we are reducing their
10656           // use counts.
10657           AddUsesToWorkList(*I);
10658
10659           // Instructions may end up in the worklist more than once.  Erase all
10660           // occurrences of this instruction.
10661           RemoveFromWorkList(I);
10662           I->eraseFromParent();
10663         } else {
10664           AddToWorkList(I);
10665           AddUsersToWorkList(*I);
10666         }
10667       }
10668       Changed = true;
10669     }
10670   }
10671
10672   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10673     
10674   // Do an explicit clear, this shrinks the map if needed.
10675   WorklistMap.clear();
10676   return Changed;
10677 }
10678
10679
10680 bool InstCombiner::runOnFunction(Function &F) {
10681   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10682   
10683   bool EverMadeChange = false;
10684
10685   // Iterate while there is work to do.
10686   unsigned Iteration = 0;
10687   while (DoOneIteration(F, Iteration++)) 
10688     EverMadeChange = true;
10689   return EverMadeChange;
10690 }
10691
10692 FunctionPass *llvm::createInstructionCombiningPass() {
10693   return new InstCombiner();
10694 }
10695