optimize away stackrestore calls that have no intervening alloca or call.
[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/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <sstream>
62 using namespace llvm;
63 using namespace llvm::PatternMatch;
64
65 STATISTIC(NumCombined , "Number of insts combined");
66 STATISTIC(NumConstProp, "Number of constant folds");
67 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69 STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71 namespace {
72   class VISIBILITY_HIDDEN InstCombiner
73     : public FunctionPass,
74       public InstVisitor<InstCombiner, Instruction*> {
75     // Worklist of all of the instructions that need to be simplified.
76     std::vector<Instruction*> Worklist;
77     DenseMap<Instruction*, unsigned> WorklistMap;
78     TargetData *TD;
79     bool MustPreserveLCSSA;
80   public:
81     static char ID; // Pass identification, replacement for typeid
82     InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84     /// AddToWorkList - Add the specified instruction to the worklist if it
85     /// isn't already in it.
86     void AddToWorkList(Instruction *I) {
87       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88         Worklist.push_back(I);
89     }
90     
91     // RemoveFromWorkList - remove I from the worklist if it exists.
92     void RemoveFromWorkList(Instruction *I) {
93       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94       if (It == WorklistMap.end()) return; // Not in worklist.
95       
96       // Don't bother moving everything down, just null out the slot.
97       Worklist[It->second] = 0;
98       
99       WorklistMap.erase(It);
100     }
101     
102     Instruction *RemoveOneFromWorkList() {
103       Instruction *I = Worklist.back();
104       Worklist.pop_back();
105       WorklistMap.erase(I);
106       return I;
107     }
108
109     
110     /// AddUsersToWorkList - When an instruction is simplified, add all users of
111     /// the instruction to the work lists because they might get more simplified
112     /// now.
113     ///
114     void AddUsersToWorkList(Value &I) {
115       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116            UI != UE; ++UI)
117         AddToWorkList(cast<Instruction>(*UI));
118     }
119
120     /// AddUsesToWorkList - When an instruction is simplified, add operands to
121     /// the work lists because they might get more simplified now.
122     ///
123     void AddUsesToWorkList(Instruction &I) {
124       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126           AddToWorkList(Op);
127     }
128     
129     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130     /// dead.  Add all of its operands to the worklist, turning them into
131     /// undef's to reduce the number of uses of those instructions.
132     ///
133     /// Return the specified operand before it is turned into an undef.
134     ///
135     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136       Value *R = I.getOperand(op);
137       
138       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140           AddToWorkList(Op);
141           // Set the operand to undef to drop the use.
142           I.setOperand(i, UndefValue::get(Op->getType()));
143         }
144       
145       return R;
146     }
147
148   public:
149     virtual bool runOnFunction(Function &F);
150     
151     bool DoOneIteration(Function &F, unsigned ItNum);
152
153     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154       AU.addRequired<TargetData>();
155       AU.addPreservedID(LCSSAID);
156       AU.setPreservesCFG();
157     }
158
159     TargetData &getTargetData() const { return *TD; }
160
161     // Visitation implementation - Implement instruction combining for different
162     // instruction types.  The semantics are as follows:
163     // Return Value:
164     //    null        - No change was made
165     //     I          - Change was made, I is still valid, I may be dead though
166     //   otherwise    - Change was made, replace I with returned instruction
167     //
168     Instruction *visitAdd(BinaryOperator &I);
169     Instruction *visitSub(BinaryOperator &I);
170     Instruction *visitMul(BinaryOperator &I);
171     Instruction *visitURem(BinaryOperator &I);
172     Instruction *visitSRem(BinaryOperator &I);
173     Instruction *visitFRem(BinaryOperator &I);
174     Instruction *commonRemTransforms(BinaryOperator &I);
175     Instruction *commonIRemTransforms(BinaryOperator &I);
176     Instruction *commonDivTransforms(BinaryOperator &I);
177     Instruction *commonIDivTransforms(BinaryOperator &I);
178     Instruction *visitUDiv(BinaryOperator &I);
179     Instruction *visitSDiv(BinaryOperator &I);
180     Instruction *visitFDiv(BinaryOperator &I);
181     Instruction *visitAnd(BinaryOperator &I);
182     Instruction *visitOr (BinaryOperator &I);
183     Instruction *visitXor(BinaryOperator &I);
184     Instruction *visitShl(BinaryOperator &I);
185     Instruction *visitAShr(BinaryOperator &I);
186     Instruction *visitLShr(BinaryOperator &I);
187     Instruction *commonShiftTransforms(BinaryOperator &I);
188     Instruction *visitFCmpInst(FCmpInst &I);
189     Instruction *visitICmpInst(ICmpInst &I);
190     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
191     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192                                                 Instruction *LHS,
193                                                 ConstantInt *RHS);
194     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195                                 ConstantInt *DivRHS);
196
197     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198                              ICmpInst::Predicate Cond, Instruction &I);
199     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
200                                      BinaryOperator &I);
201     Instruction *commonCastTransforms(CastInst &CI);
202     Instruction *commonIntCastTransforms(CastInst &CI);
203     Instruction *commonPointerCastTransforms(CastInst &CI);
204     Instruction *visitTrunc(TruncInst &CI);
205     Instruction *visitZExt(ZExtInst &CI);
206     Instruction *visitSExt(SExtInst &CI);
207     Instruction *visitFPTrunc(FPTruncInst &CI);
208     Instruction *visitFPExt(CastInst &CI);
209     Instruction *visitFPToUI(CastInst &CI);
210     Instruction *visitFPToSI(CastInst &CI);
211     Instruction *visitUIToFP(CastInst &CI);
212     Instruction *visitSIToFP(CastInst &CI);
213     Instruction *visitPtrToInt(CastInst &CI);
214     Instruction *visitIntToPtr(IntToPtrInst &CI);
215     Instruction *visitBitCast(BitCastInst &CI);
216     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217                                 Instruction *FI);
218     Instruction *visitSelectInst(SelectInst &CI);
219     Instruction *visitCallInst(CallInst &CI);
220     Instruction *visitInvokeInst(InvokeInst &II);
221     Instruction *visitPHINode(PHINode &PN);
222     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
223     Instruction *visitAllocationInst(AllocationInst &AI);
224     Instruction *visitFreeInst(FreeInst &FI);
225     Instruction *visitLoadInst(LoadInst &LI);
226     Instruction *visitStoreInst(StoreInst &SI);
227     Instruction *visitBranchInst(BranchInst &BI);
228     Instruction *visitSwitchInst(SwitchInst &SI);
229     Instruction *visitInsertElementInst(InsertElementInst &IE);
230     Instruction *visitExtractElementInst(ExtractElementInst &EI);
231     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
232
233     // visitInstruction - Specify what to return for unhandled instructions...
234     Instruction *visitInstruction(Instruction &I) { return 0; }
235
236   private:
237     Instruction *visitCallSite(CallSite CS);
238     bool transformConstExprCastCall(CallSite CS);
239     Instruction *transformCallThroughTrampoline(CallSite CS);
240
241   public:
242     // InsertNewInstBefore - insert an instruction New before instruction Old
243     // in the program.  Add the new instruction to the worklist.
244     //
245     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
246       assert(New && New->getParent() == 0 &&
247              "New instruction already inserted into a basic block!");
248       BasicBlock *BB = Old.getParent();
249       BB->getInstList().insert(&Old, New);  // Insert inst
250       AddToWorkList(New);
251       return New;
252     }
253
254     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
255     /// This also adds the cast to the worklist.  Finally, this returns the
256     /// cast.
257     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
258                             Instruction &Pos) {
259       if (V->getType() == Ty) return V;
260
261       if (Constant *CV = dyn_cast<Constant>(V))
262         return ConstantExpr::getCast(opc, CV, Ty);
263       
264       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
265       AddToWorkList(C);
266       return C;
267     }
268         
269     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
270       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
271     }
272
273
274     // ReplaceInstUsesWith - This method is to be used when an instruction is
275     // found to be dead, replacable with another preexisting expression.  Here
276     // we add all uses of I to the worklist, replace all uses of I with the new
277     // value, then return I, so that the inst combiner will know that I was
278     // modified.
279     //
280     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
281       AddUsersToWorkList(I);         // Add all modified instrs to worklist
282       if (&I != V) {
283         I.replaceAllUsesWith(V);
284         return &I;
285       } else {
286         // If we are replacing the instruction with itself, this must be in a
287         // segment of unreachable code, so just clobber the instruction.
288         I.replaceAllUsesWith(UndefValue::get(I.getType()));
289         return &I;
290       }
291     }
292
293     // UpdateValueUsesWith - This method is to be used when an value is
294     // found to be replacable with another preexisting expression or was
295     // updated.  Here we add all uses of I to the worklist, replace all uses of
296     // I with the new value (unless the instruction was just updated), then
297     // return true, so that the inst combiner will know that I was modified.
298     //
299     bool UpdateValueUsesWith(Value *Old, Value *New) {
300       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
301       if (Old != New)
302         Old->replaceAllUsesWith(New);
303       if (Instruction *I = dyn_cast<Instruction>(Old))
304         AddToWorkList(I);
305       if (Instruction *I = dyn_cast<Instruction>(New))
306         AddToWorkList(I);
307       return true;
308     }
309     
310     // EraseInstFromFunction - When dealing with an instruction that has side
311     // effects or produces a void value, we can't rely on DCE to delete the
312     // instruction.  Instead, visit methods should return the value returned by
313     // this function.
314     Instruction *EraseInstFromFunction(Instruction &I) {
315       assert(I.use_empty() && "Cannot erase instruction that is used!");
316       AddUsesToWorkList(I);
317       RemoveFromWorkList(&I);
318       I.eraseFromParent();
319       return 0;  // Don't do anything with FI
320     }
321
322   private:
323     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
324     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
325     /// casts that are known to not do anything...
326     ///
327     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
328                                    Value *V, const Type *DestTy,
329                                    Instruction *InsertBefore);
330
331     /// SimplifyCommutative - This performs a few simplifications for 
332     /// commutative operators.
333     bool SimplifyCommutative(BinaryOperator &I);
334
335     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
336     /// most-complex to least-complex order.
337     bool SimplifyCompare(CmpInst &I);
338
339     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
340     /// on the demanded bits.
341     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
342                               APInt& KnownZero, APInt& KnownOne,
343                               unsigned Depth = 0);
344
345     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
346                                       uint64_t &UndefElts, unsigned Depth = 0);
347       
348     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
349     // PHI node as operand #0, see if we can fold the instruction into the PHI
350     // (which is only possible if all operands to the PHI are constants).
351     Instruction *FoldOpIntoPhi(Instruction &I);
352
353     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
354     // operator and they all are only used by the PHI, PHI together their
355     // inputs, and do the operation once, to the result of the PHI.
356     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
357     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
358     
359     
360     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
361                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
362     
363     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
364                               bool isSub, Instruction &I);
365     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
366                                  bool isSigned, bool Inside, Instruction &IB);
367     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
368     Instruction *MatchBSwap(BinaryOperator &I);
369     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
370     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
371
372
373     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
374   };
375
376   char InstCombiner::ID = 0;
377   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
378 }
379
380 // getComplexity:  Assign a complexity or rank value to LLVM Values...
381 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
382 static unsigned getComplexity(Value *V) {
383   if (isa<Instruction>(V)) {
384     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
385       return 3;
386     return 4;
387   }
388   if (isa<Argument>(V)) return 3;
389   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
390 }
391
392 // isOnlyUse - Return true if this instruction will be deleted if we stop using
393 // it.
394 static bool isOnlyUse(Value *V) {
395   return V->hasOneUse() || isa<Constant>(V);
396 }
397
398 // getPromotedType - Return the specified type promoted as it would be to pass
399 // though a va_arg area...
400 static const Type *getPromotedType(const Type *Ty) {
401   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
402     if (ITy->getBitWidth() < 32)
403       return Type::Int32Ty;
404   }
405   return Ty;
406 }
407
408 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
409 /// expression bitcast,  return the operand value, otherwise return null.
410 static Value *getBitCastOperand(Value *V) {
411   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
412     return I->getOperand(0);
413   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
414     if (CE->getOpcode() == Instruction::BitCast)
415       return CE->getOperand(0);
416   return 0;
417 }
418
419 /// This function is a wrapper around CastInst::isEliminableCastPair. It
420 /// simply extracts arguments and returns what that function returns.
421 static Instruction::CastOps 
422 isEliminableCastPair(
423   const CastInst *CI, ///< The first cast instruction
424   unsigned opcode,       ///< The opcode of the second cast instruction
425   const Type *DstTy,     ///< The target type for the second cast instruction
426   TargetData *TD         ///< The target data for pointer size
427 ) {
428   
429   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
430   const Type *MidTy = CI->getType();                  // B from above
431
432   // Get the opcodes of the two Cast instructions
433   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
434   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
435
436   return Instruction::CastOps(
437       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
438                                      DstTy, TD->getIntPtrType()));
439 }
440
441 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442 /// in any code being generated.  It does not require codegen if V is simple
443 /// enough or if the cast can be folded into other casts.
444 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
445                               const Type *Ty, TargetData *TD) {
446   if (V->getType() == Ty || isa<Constant>(V)) return false;
447   
448   // If this is another cast that can be eliminated, it isn't codegen either.
449   if (const CastInst *CI = dyn_cast<CastInst>(V))
450     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
451       return false;
452   return true;
453 }
454
455 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
456 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
457 /// casts that are known to not do anything...
458 ///
459 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
460                                              Value *V, const Type *DestTy,
461                                              Instruction *InsertBefore) {
462   if (V->getType() == DestTy) return V;
463   if (Constant *C = dyn_cast<Constant>(V))
464     return ConstantExpr::getCast(opcode, C, DestTy);
465   
466   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
467 }
468
469 // SimplifyCommutative - This performs a few simplifications for commutative
470 // operators:
471 //
472 //  1. Order operands such that they are listed from right (least complex) to
473 //     left (most complex).  This puts constants before unary operators before
474 //     binary operators.
475 //
476 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
478 //
479 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
480   bool Changed = false;
481   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482     Changed = !I.swapOperands();
483
484   if (!I.isAssociative()) return Changed;
485   Instruction::BinaryOps Opcode = I.getOpcode();
486   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488       if (isa<Constant>(I.getOperand(1))) {
489         Constant *Folded = ConstantExpr::get(I.getOpcode(),
490                                              cast<Constant>(I.getOperand(1)),
491                                              cast<Constant>(Op->getOperand(1)));
492         I.setOperand(0, Op->getOperand(0));
493         I.setOperand(1, Folded);
494         return true;
495       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497             isOnlyUse(Op) && isOnlyUse(Op1)) {
498           Constant *C1 = cast<Constant>(Op->getOperand(1));
499           Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
502           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
503           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504                                                     Op1->getOperand(0),
505                                                     Op1->getName(), &I);
506           AddToWorkList(New);
507           I.setOperand(0, New);
508           I.setOperand(1, Folded);
509           return true;
510         }
511     }
512   return Changed;
513 }
514
515 /// SimplifyCompare - For a CmpInst this function just orders the operands
516 /// so that theyare listed from right (least complex) to left (most complex).
517 /// This puts constants before unary operators before binary operators.
518 bool InstCombiner::SimplifyCompare(CmpInst &I) {
519   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
520     return false;
521   I.swapOperands();
522   // Compare instructions are not associative so there's nothing else we can do.
523   return true;
524 }
525
526 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
527 // if the LHS is a constant zero (which is the 'negate' form).
528 //
529 static inline Value *dyn_castNegVal(Value *V) {
530   if (BinaryOperator::isNeg(V))
531     return BinaryOperator::getNegArgument(V);
532
533   // Constants can be considered to be negated values if they can be folded.
534   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535     return ConstantExpr::getNeg(C);
536   return 0;
537 }
538
539 static inline Value *dyn_castNotVal(Value *V) {
540   if (BinaryOperator::isNot(V))
541     return BinaryOperator::getNotArgument(V);
542
543   // Constants can be considered to be not'ed values...
544   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
545     return ConstantInt::get(~C->getValue());
546   return 0;
547 }
548
549 // dyn_castFoldableMul - If this value is a multiply that can be folded into
550 // other computations (because it has a constant operand), return the
551 // non-constant operand of the multiply, and set CST to point to the multiplier.
552 // Otherwise, return null.
553 //
554 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
555   if (V->hasOneUse() && V->getType()->isInteger())
556     if (Instruction *I = dyn_cast<Instruction>(V)) {
557       if (I->getOpcode() == Instruction::Mul)
558         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
559           return I->getOperand(0);
560       if (I->getOpcode() == Instruction::Shl)
561         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
562           // The multiplier is really 1 << CST.
563           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
564           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
565           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
566           return I->getOperand(0);
567         }
568     }
569   return 0;
570 }
571
572 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
573 /// expression, return it.
574 static User *dyn_castGetElementPtr(Value *V) {
575   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
576   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
577     if (CE->getOpcode() == Instruction::GetElementPtr)
578       return cast<User>(V);
579   return false;
580 }
581
582 /// AddOne - Add one to a ConstantInt
583 static ConstantInt *AddOne(ConstantInt *C) {
584   APInt Val(C->getValue());
585   return ConstantInt::get(++Val);
586 }
587 /// SubOne - Subtract one from a ConstantInt
588 static ConstantInt *SubOne(ConstantInt *C) {
589   APInt Val(C->getValue());
590   return ConstantInt::get(--Val);
591 }
592 /// Add - Add two ConstantInts together
593 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
594   return ConstantInt::get(C1->getValue() + C2->getValue());
595 }
596 /// And - Bitwise AND two ConstantInts together
597 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
598   return ConstantInt::get(C1->getValue() & C2->getValue());
599 }
600 /// Subtract - Subtract one ConstantInt from another
601 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
602   return ConstantInt::get(C1->getValue() - C2->getValue());
603 }
604 /// Multiply - Multiply two ConstantInts together
605 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
606   return ConstantInt::get(C1->getValue() * C2->getValue());
607 }
608
609 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
610 /// known to be either zero or one and return them in the KnownZero/KnownOne
611 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
612 /// processing.
613 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
614 /// we cannot optimize based on the assumption that it is zero without changing
615 /// it to be an explicit zero.  If we don't change it to zero, other code could
616 /// optimized based on the contradictory assumption that it is non-zero.
617 /// Because instcombine aggressively folds operations with undef args anyway,
618 /// this won't lose us code quality.
619 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
620                               APInt& KnownOne, unsigned Depth = 0) {
621   assert(V && "No Value?");
622   assert(Depth <= 6 && "Limit Search Depth");
623   uint32_t BitWidth = Mask.getBitWidth();
624   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
625          KnownZero.getBitWidth() == BitWidth && 
626          KnownOne.getBitWidth() == BitWidth &&
627          "V, Mask, KnownOne and KnownZero should have same BitWidth");
628   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
629     // We know all of the bits for a constant!
630     KnownOne = CI->getValue() & Mask;
631     KnownZero = ~KnownOne & Mask;
632     return;
633   }
634
635   if (Depth == 6 || Mask == 0)
636     return;  // Limit search depth.
637
638   Instruction *I = dyn_cast<Instruction>(V);
639   if (!I) return;
640
641   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
642   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
643   
644   switch (I->getOpcode()) {
645   case Instruction::And: {
646     // If either the LHS or the RHS are Zero, the result is zero.
647     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
648     APInt Mask2(Mask & ~KnownZero);
649     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
650     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
651     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
652     
653     // Output known-1 bits are only known if set in both the LHS & RHS.
654     KnownOne &= KnownOne2;
655     // Output known-0 are known to be clear if zero in either the LHS | RHS.
656     KnownZero |= KnownZero2;
657     return;
658   }
659   case Instruction::Or: {
660     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
661     APInt Mask2(Mask & ~KnownOne);
662     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
663     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
664     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
665     
666     // Output known-0 bits are only known if clear in both the LHS & RHS.
667     KnownZero &= KnownZero2;
668     // Output known-1 are known to be set if set in either the LHS | RHS.
669     KnownOne |= KnownOne2;
670     return;
671   }
672   case Instruction::Xor: {
673     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
674     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
675     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
676     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
677     
678     // Output known-0 bits are known if clear or set in both the LHS & RHS.
679     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
680     // Output known-1 are known to be set if set in only one of the LHS, RHS.
681     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
682     KnownZero = KnownZeroOut;
683     return;
684   }
685   case Instruction::Select:
686     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
687     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
688     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
689     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
690
691     // Only known if known in both the LHS and RHS.
692     KnownOne &= KnownOne2;
693     KnownZero &= KnownZero2;
694     return;
695   case Instruction::FPTrunc:
696   case Instruction::FPExt:
697   case Instruction::FPToUI:
698   case Instruction::FPToSI:
699   case Instruction::SIToFP:
700   case Instruction::PtrToInt:
701   case Instruction::UIToFP:
702   case Instruction::IntToPtr:
703     return; // Can't work with floating point or pointers
704   case Instruction::Trunc: {
705     // All these have integer operands
706     uint32_t SrcBitWidth = 
707       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
708     APInt MaskIn(Mask);
709     MaskIn.zext(SrcBitWidth);
710     KnownZero.zext(SrcBitWidth);
711     KnownOne.zext(SrcBitWidth);
712     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
713     KnownZero.trunc(BitWidth);
714     KnownOne.trunc(BitWidth);
715     return;
716   }
717   case Instruction::BitCast: {
718     const Type *SrcTy = I->getOperand(0)->getType();
719     if (SrcTy->isInteger()) {
720       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
721       return;
722     }
723     break;
724   }
725   case Instruction::ZExt:  {
726     // Compute the bits in the result that are not present in the input.
727     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
728     uint32_t SrcBitWidth = SrcTy->getBitWidth();
729       
730     APInt MaskIn(Mask);
731     MaskIn.trunc(SrcBitWidth);
732     KnownZero.trunc(SrcBitWidth);
733     KnownOne.trunc(SrcBitWidth);
734     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
735     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
736     // The top bits are known to be zero.
737     KnownZero.zext(BitWidth);
738     KnownOne.zext(BitWidth);
739     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
740     return;
741   }
742   case Instruction::SExt: {
743     // Compute the bits in the result that are not present in the input.
744     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
745     uint32_t SrcBitWidth = SrcTy->getBitWidth();
746       
747     APInt MaskIn(Mask); 
748     MaskIn.trunc(SrcBitWidth);
749     KnownZero.trunc(SrcBitWidth);
750     KnownOne.trunc(SrcBitWidth);
751     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
752     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
753     KnownZero.zext(BitWidth);
754     KnownOne.zext(BitWidth);
755
756     // If the sign bit of the input is known set or clear, then we know the
757     // top bits of the result.
758     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
759       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
760     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
761       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
762     return;
763   }
764   case Instruction::Shl:
765     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
766     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
767       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
768       APInt Mask2(Mask.lshr(ShiftAmt));
769       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
770       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
771       KnownZero <<= ShiftAmt;
772       KnownOne  <<= ShiftAmt;
773       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
774       return;
775     }
776     break;
777   case Instruction::LShr:
778     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
779     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
780       // Compute the new bits that are at the top now.
781       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
782       
783       // Unsigned shift right.
784       APInt Mask2(Mask.shl(ShiftAmt));
785       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
786       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
787       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
788       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
789       // high bits known zero.
790       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
791       return;
792     }
793     break;
794   case Instruction::AShr:
795     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
796     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
797       // Compute the new bits that are at the top now.
798       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
799       
800       // Signed shift right.
801       APInt Mask2(Mask.shl(ShiftAmt));
802       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
803       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
804       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
805       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
806         
807       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
808       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
809         KnownZero |= HighBits;
810       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
811         KnownOne |= HighBits;
812       return;
813     }
814     break;
815   }
816 }
817
818 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
819 /// this predicate to simplify operations downstream.  Mask is known to be zero
820 /// for bits that V cannot have.
821 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
822   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
823   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
824   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
825   return (KnownZero & Mask) == Mask;
826 }
827
828 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
829 /// specified instruction is a constant integer.  If so, check to see if there
830 /// are any bits set in the constant that are not demanded.  If so, shrink the
831 /// constant and return true.
832 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
833                                    APInt Demanded) {
834   assert(I && "No instruction?");
835   assert(OpNo < I->getNumOperands() && "Operand index too large");
836
837   // If the operand is not a constant integer, nothing to do.
838   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
839   if (!OpC) return false;
840
841   // If there are no bits set that aren't demanded, nothing to do.
842   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
843   if ((~Demanded & OpC->getValue()) == 0)
844     return false;
845
846   // This instruction is producing bits that are not demanded. Shrink the RHS.
847   Demanded &= OpC->getValue();
848   I->setOperand(OpNo, ConstantInt::get(Demanded));
849   return true;
850 }
851
852 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
853 // set of known zero and one bits, compute the maximum and minimum values that
854 // could have the specified known zero and known one bits, returning them in
855 // min/max.
856 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
857                                                    const APInt& KnownZero,
858                                                    const APInt& KnownOne,
859                                                    APInt& Min, APInt& Max) {
860   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
861   assert(KnownZero.getBitWidth() == BitWidth && 
862          KnownOne.getBitWidth() == BitWidth &&
863          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
864          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
865   APInt UnknownBits = ~(KnownZero|KnownOne);
866
867   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
868   // bit if it is unknown.
869   Min = KnownOne;
870   Max = KnownOne|UnknownBits;
871   
872   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
873     Min.set(BitWidth-1);
874     Max.clear(BitWidth-1);
875   }
876 }
877
878 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
879 // a set of known zero and one bits, compute the maximum and minimum values that
880 // could have the specified known zero and known one bits, returning them in
881 // min/max.
882 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
883                                                      const APInt &KnownZero,
884                                                      const APInt &KnownOne,
885                                                      APInt &Min, APInt &Max) {
886   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
887   assert(KnownZero.getBitWidth() == BitWidth && 
888          KnownOne.getBitWidth() == BitWidth &&
889          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
890          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
891   APInt UnknownBits = ~(KnownZero|KnownOne);
892   
893   // The minimum value is when the unknown bits are all zeros.
894   Min = KnownOne;
895   // The maximum value is when the unknown bits are all ones.
896   Max = KnownOne|UnknownBits;
897 }
898
899 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
900 /// value based on the demanded bits. When this function is called, it is known
901 /// that only the bits set in DemandedMask of the result of V are ever used
902 /// downstream. Consequently, depending on the mask and V, it may be possible
903 /// to replace V with a constant or one of its operands. In such cases, this
904 /// function does the replacement and returns true. In all other cases, it
905 /// returns false after analyzing the expression and setting KnownOne and known
906 /// to be one in the expression. KnownZero contains all the bits that are known
907 /// to be zero in the expression. These are provided to potentially allow the
908 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
909 /// the expression. KnownOne and KnownZero always follow the invariant that 
910 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
911 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
912 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
913 /// and KnownOne must all be the same.
914 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
915                                         APInt& KnownZero, APInt& KnownOne,
916                                         unsigned Depth) {
917   assert(V != 0 && "Null pointer of Value???");
918   assert(Depth <= 6 && "Limit Search Depth");
919   uint32_t BitWidth = DemandedMask.getBitWidth();
920   const IntegerType *VTy = cast<IntegerType>(V->getType());
921   assert(VTy->getBitWidth() == BitWidth && 
922          KnownZero.getBitWidth() == BitWidth && 
923          KnownOne.getBitWidth() == BitWidth &&
924          "Value *V, DemandedMask, KnownZero and KnownOne \
925           must have same BitWidth");
926   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
927     // We know all of the bits for a constant!
928     KnownOne = CI->getValue() & DemandedMask;
929     KnownZero = ~KnownOne & DemandedMask;
930     return false;
931   }
932   
933   KnownZero.clear(); 
934   KnownOne.clear();
935   if (!V->hasOneUse()) {    // Other users may use these bits.
936     if (Depth != 0) {       // Not at the root.
937       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
938       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
939       return false;
940     }
941     // If this is the root being simplified, allow it to have multiple uses,
942     // just set the DemandedMask to all bits.
943     DemandedMask = APInt::getAllOnesValue(BitWidth);
944   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
945     if (V != UndefValue::get(VTy))
946       return UpdateValueUsesWith(V, UndefValue::get(VTy));
947     return false;
948   } else if (Depth == 6) {        // Limit search depth.
949     return false;
950   }
951   
952   Instruction *I = dyn_cast<Instruction>(V);
953   if (!I) return false;        // Only analyze instructions.
954
955   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
956   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
957   switch (I->getOpcode()) {
958   default: break;
959   case Instruction::And:
960     // If either the LHS or the RHS are Zero, the result is zero.
961     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962                              RHSKnownZero, RHSKnownOne, Depth+1))
963       return true;
964     assert((RHSKnownZero & RHSKnownOne) == 0 && 
965            "Bits known to be one AND zero?"); 
966
967     // If something is known zero on the RHS, the bits aren't demanded on the
968     // LHS.
969     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
970                              LHSKnownZero, LHSKnownOne, Depth+1))
971       return true;
972     assert((LHSKnownZero & LHSKnownOne) == 0 && 
973            "Bits known to be one AND zero?"); 
974
975     // If all of the demanded bits are known 1 on one side, return the other.
976     // These bits cannot contribute to the result of the 'and'.
977     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
978         (DemandedMask & ~LHSKnownZero))
979       return UpdateValueUsesWith(I, I->getOperand(0));
980     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
981         (DemandedMask & ~RHSKnownZero))
982       return UpdateValueUsesWith(I, I->getOperand(1));
983     
984     // If all of the demanded bits in the inputs are known zeros, return zero.
985     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
986       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
987       
988     // If the RHS is a constant, see if we can simplify it.
989     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
990       return UpdateValueUsesWith(I, I);
991       
992     // Output known-1 bits are only known if set in both the LHS & RHS.
993     RHSKnownOne &= LHSKnownOne;
994     // Output known-0 are known to be clear if zero in either the LHS | RHS.
995     RHSKnownZero |= LHSKnownZero;
996     break;
997   case Instruction::Or:
998     // If either the LHS or the RHS are One, the result is One.
999     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1000                              RHSKnownZero, RHSKnownOne, Depth+1))
1001       return true;
1002     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1003            "Bits known to be one AND zero?"); 
1004     // If something is known one on the RHS, the bits aren't demanded on the
1005     // LHS.
1006     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1007                              LHSKnownZero, LHSKnownOne, Depth+1))
1008       return true;
1009     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1010            "Bits known to be one AND zero?"); 
1011     
1012     // If all of the demanded bits are known zero on one side, return the other.
1013     // These bits cannot contribute to the result of the 'or'.
1014     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1015         (DemandedMask & ~LHSKnownOne))
1016       return UpdateValueUsesWith(I, I->getOperand(0));
1017     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1018         (DemandedMask & ~RHSKnownOne))
1019       return UpdateValueUsesWith(I, I->getOperand(1));
1020
1021     // If all of the potentially set bits on one side are known to be set on
1022     // the other side, just use the 'other' side.
1023     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1024         (DemandedMask & (~RHSKnownZero)))
1025       return UpdateValueUsesWith(I, I->getOperand(0));
1026     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1027         (DemandedMask & (~LHSKnownZero)))
1028       return UpdateValueUsesWith(I, I->getOperand(1));
1029         
1030     // If the RHS is a constant, see if we can simplify it.
1031     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1032       return UpdateValueUsesWith(I, I);
1033           
1034     // Output known-0 bits are only known if clear in both the LHS & RHS.
1035     RHSKnownZero &= LHSKnownZero;
1036     // Output known-1 are known to be set if set in either the LHS | RHS.
1037     RHSKnownOne |= LHSKnownOne;
1038     break;
1039   case Instruction::Xor: {
1040     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1041                              RHSKnownZero, RHSKnownOne, Depth+1))
1042       return true;
1043     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1044            "Bits known to be one AND zero?"); 
1045     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1046                              LHSKnownZero, LHSKnownOne, Depth+1))
1047       return true;
1048     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1049            "Bits known to be one AND zero?"); 
1050     
1051     // If all of the demanded bits are known zero on one side, return the other.
1052     // These bits cannot contribute to the result of the 'xor'.
1053     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1054       return UpdateValueUsesWith(I, I->getOperand(0));
1055     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1056       return UpdateValueUsesWith(I, I->getOperand(1));
1057     
1058     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1059     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1060                          (RHSKnownOne & LHSKnownOne);
1061     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1062     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1063                         (RHSKnownOne & LHSKnownZero);
1064     
1065     // If all of the demanded bits are known to be zero on one side or the
1066     // other, turn this into an *inclusive* or.
1067     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1068     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1069       Instruction *Or =
1070         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1071                                  I->getName());
1072       InsertNewInstBefore(Or, *I);
1073       return UpdateValueUsesWith(I, Or);
1074     }
1075     
1076     // If all of the demanded bits on one side are known, and all of the set
1077     // bits on that side are also known to be set on the other side, turn this
1078     // into an AND, as we know the bits will be cleared.
1079     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1080     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1081       // all known
1082       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1083         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1084         Instruction *And = 
1085           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1086         InsertNewInstBefore(And, *I);
1087         return UpdateValueUsesWith(I, And);
1088       }
1089     }
1090     
1091     // If the RHS is a constant, see if we can simplify it.
1092     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1093     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1094       return UpdateValueUsesWith(I, I);
1095     
1096     RHSKnownZero = KnownZeroOut;
1097     RHSKnownOne  = KnownOneOut;
1098     break;
1099   }
1100   case Instruction::Select:
1101     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1102                              RHSKnownZero, RHSKnownOne, Depth+1))
1103       return true;
1104     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1105                              LHSKnownZero, LHSKnownOne, Depth+1))
1106       return true;
1107     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1108            "Bits known to be one AND zero?"); 
1109     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1110            "Bits known to be one AND zero?"); 
1111     
1112     // If the operands are constants, see if we can simplify them.
1113     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1114       return UpdateValueUsesWith(I, I);
1115     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1116       return UpdateValueUsesWith(I, I);
1117     
1118     // Only known if known in both the LHS and RHS.
1119     RHSKnownOne &= LHSKnownOne;
1120     RHSKnownZero &= LHSKnownZero;
1121     break;
1122   case Instruction::Trunc: {
1123     uint32_t truncBf = 
1124       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1125     DemandedMask.zext(truncBf);
1126     RHSKnownZero.zext(truncBf);
1127     RHSKnownOne.zext(truncBf);
1128     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1129                              RHSKnownZero, RHSKnownOne, Depth+1))
1130       return true;
1131     DemandedMask.trunc(BitWidth);
1132     RHSKnownZero.trunc(BitWidth);
1133     RHSKnownOne.trunc(BitWidth);
1134     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1135            "Bits known to be one AND zero?"); 
1136     break;
1137   }
1138   case Instruction::BitCast:
1139     if (!I->getOperand(0)->getType()->isInteger())
1140       return false;
1141       
1142     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1143                              RHSKnownZero, RHSKnownOne, Depth+1))
1144       return true;
1145     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1146            "Bits known to be one AND zero?"); 
1147     break;
1148   case Instruction::ZExt: {
1149     // Compute the bits in the result that are not present in the input.
1150     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1151     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1152     
1153     DemandedMask.trunc(SrcBitWidth);
1154     RHSKnownZero.trunc(SrcBitWidth);
1155     RHSKnownOne.trunc(SrcBitWidth);
1156     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1157                              RHSKnownZero, RHSKnownOne, Depth+1))
1158       return true;
1159     DemandedMask.zext(BitWidth);
1160     RHSKnownZero.zext(BitWidth);
1161     RHSKnownOne.zext(BitWidth);
1162     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1163            "Bits known to be one AND zero?"); 
1164     // The top bits are known to be zero.
1165     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1166     break;
1167   }
1168   case Instruction::SExt: {
1169     // Compute the bits in the result that are not present in the input.
1170     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1171     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1172     
1173     APInt InputDemandedBits = DemandedMask & 
1174                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1175
1176     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1177     // If any of the sign extended bits are demanded, we know that the sign
1178     // bit is demanded.
1179     if ((NewBits & DemandedMask) != 0)
1180       InputDemandedBits.set(SrcBitWidth-1);
1181       
1182     InputDemandedBits.trunc(SrcBitWidth);
1183     RHSKnownZero.trunc(SrcBitWidth);
1184     RHSKnownOne.trunc(SrcBitWidth);
1185     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1186                              RHSKnownZero, RHSKnownOne, Depth+1))
1187       return true;
1188     InputDemandedBits.zext(BitWidth);
1189     RHSKnownZero.zext(BitWidth);
1190     RHSKnownOne.zext(BitWidth);
1191     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1192            "Bits known to be one AND zero?"); 
1193       
1194     // If the sign bit of the input is known set or clear, then we know the
1195     // top bits of the result.
1196
1197     // If the input sign bit is known zero, or if the NewBits are not demanded
1198     // convert this into a zero extension.
1199     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1200     {
1201       // Convert to ZExt cast
1202       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1203       return UpdateValueUsesWith(I, NewCast);
1204     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1205       RHSKnownOne |= NewBits;
1206     }
1207     break;
1208   }
1209   case Instruction::Add: {
1210     // Figure out what the input bits are.  If the top bits of the and result
1211     // are not demanded, then the add doesn't demand them from its input
1212     // either.
1213     uint32_t NLZ = DemandedMask.countLeadingZeros();
1214       
1215     // If there is a constant on the RHS, there are a variety of xformations
1216     // we can do.
1217     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218       // If null, this should be simplified elsewhere.  Some of the xforms here
1219       // won't work if the RHS is zero.
1220       if (RHS->isZero())
1221         break;
1222       
1223       // If the top bit of the output is demanded, demand everything from the
1224       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1225       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1226
1227       // Find information about known zero/one bits in the input.
1228       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1229                                LHSKnownZero, LHSKnownOne, Depth+1))
1230         return true;
1231
1232       // If the RHS of the add has bits set that can't affect the input, reduce
1233       // the constant.
1234       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1235         return UpdateValueUsesWith(I, I);
1236       
1237       // Avoid excess work.
1238       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1239         break;
1240       
1241       // Turn it into OR if input bits are zero.
1242       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1243         Instruction *Or =
1244           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1245                                    I->getName());
1246         InsertNewInstBefore(Or, *I);
1247         return UpdateValueUsesWith(I, Or);
1248       }
1249       
1250       // We can say something about the output known-zero and known-one bits,
1251       // depending on potential carries from the input constant and the
1252       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1253       // bits set and the RHS constant is 0x01001, then we know we have a known
1254       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1255       
1256       // To compute this, we first compute the potential carry bits.  These are
1257       // the bits which may be modified.  I'm not aware of a better way to do
1258       // this scan.
1259       const APInt& RHSVal = RHS->getValue();
1260       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1261       
1262       // Now that we know which bits have carries, compute the known-1/0 sets.
1263       
1264       // Bits are known one if they are known zero in one operand and one in the
1265       // other, and there is no input carry.
1266       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1267                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1268       
1269       // Bits are known zero if they are known zero in both operands and there
1270       // is no input carry.
1271       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1272     } else {
1273       // If the high-bits of this ADD are not demanded, then it does not demand
1274       // the high bits of its LHS or RHS.
1275       if (DemandedMask[BitWidth-1] == 0) {
1276         // Right fill the mask of bits for this ADD to demand the most
1277         // significant bit and all those below it.
1278         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1279         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1280                                  LHSKnownZero, LHSKnownOne, Depth+1))
1281           return true;
1282         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1283                                  LHSKnownZero, LHSKnownOne, Depth+1))
1284           return true;
1285       }
1286     }
1287     break;
1288   }
1289   case Instruction::Sub:
1290     // If the high-bits of this SUB are not demanded, then it does not demand
1291     // the high bits of its LHS or RHS.
1292     if (DemandedMask[BitWidth-1] == 0) {
1293       // Right fill the mask of bits for this SUB to demand the most
1294       // significant bit and all those below it.
1295       uint32_t NLZ = DemandedMask.countLeadingZeros();
1296       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1297       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1298                                LHSKnownZero, LHSKnownOne, Depth+1))
1299         return true;
1300       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1301                                LHSKnownZero, LHSKnownOne, Depth+1))
1302         return true;
1303     }
1304     break;
1305   case Instruction::Shl:
1306     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1307       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1308       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1309       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1310                                RHSKnownZero, RHSKnownOne, Depth+1))
1311         return true;
1312       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1313              "Bits known to be one AND zero?"); 
1314       RHSKnownZero <<= ShiftAmt;
1315       RHSKnownOne  <<= ShiftAmt;
1316       // low bits known zero.
1317       if (ShiftAmt)
1318         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1319     }
1320     break;
1321   case Instruction::LShr:
1322     // For a logical shift right
1323     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1324       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1325       
1326       // Unsigned shift right.
1327       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1328       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1329                                RHSKnownZero, RHSKnownOne, Depth+1))
1330         return true;
1331       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1332              "Bits known to be one AND zero?"); 
1333       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1334       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1335       if (ShiftAmt) {
1336         // Compute the new bits that are at the top now.
1337         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1338         RHSKnownZero |= HighBits;  // high bits known zero.
1339       }
1340     }
1341     break;
1342   case Instruction::AShr:
1343     // If this is an arithmetic shift right and only the low-bit is set, we can
1344     // always convert this into a logical shr, even if the shift amount is
1345     // variable.  The low bit of the shift cannot be an input sign bit unless
1346     // the shift amount is >= the size of the datatype, which is undefined.
1347     if (DemandedMask == 1) {
1348       // Perform the logical shift right.
1349       Value *NewVal = BinaryOperator::createLShr(
1350                         I->getOperand(0), I->getOperand(1), I->getName());
1351       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1352       return UpdateValueUsesWith(I, NewVal);
1353     }    
1354
1355     // If the sign bit is the only bit demanded by this ashr, then there is no
1356     // need to do it, the shift doesn't change the high bit.
1357     if (DemandedMask.isSignBit())
1358       return UpdateValueUsesWith(I, I->getOperand(0));
1359     
1360     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1361       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1362       
1363       // Signed shift right.
1364       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1365       // If any of the "high bits" are demanded, we should set the sign bit as
1366       // demanded.
1367       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1368         DemandedMaskIn.set(BitWidth-1);
1369       if (SimplifyDemandedBits(I->getOperand(0),
1370                                DemandedMaskIn,
1371                                RHSKnownZero, RHSKnownOne, Depth+1))
1372         return true;
1373       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1374              "Bits known to be one AND zero?"); 
1375       // Compute the new bits that are at the top now.
1376       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1377       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1378       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1379         
1380       // Handle the sign bits.
1381       APInt SignBit(APInt::getSignBit(BitWidth));
1382       // Adjust to where it is now in the mask.
1383       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1384         
1385       // If the input sign bit is known to be zero, or if none of the top bits
1386       // are demanded, turn this into an unsigned shift right.
1387       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1388           (HighBits & ~DemandedMask) == HighBits) {
1389         // Perform the logical shift right.
1390         Value *NewVal = BinaryOperator::createLShr(
1391                           I->getOperand(0), SA, I->getName());
1392         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1393         return UpdateValueUsesWith(I, NewVal);
1394       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1395         RHSKnownOne |= HighBits;
1396       }
1397     }
1398     break;
1399   }
1400   
1401   // If the client is only demanding bits that we know, return the known
1402   // constant.
1403   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1404     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1405   return false;
1406 }
1407
1408
1409 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1410 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1411 /// actually used by the caller.  This method analyzes which elements of the
1412 /// operand are undef and returns that information in UndefElts.
1413 ///
1414 /// If the information about demanded elements can be used to simplify the
1415 /// operation, the operation is simplified, then the resultant value is
1416 /// returned.  This returns null if no change was made.
1417 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1418                                                 uint64_t &UndefElts,
1419                                                 unsigned Depth) {
1420   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1421   assert(VWidth <= 64 && "Vector too wide to analyze!");
1422   uint64_t EltMask = ~0ULL >> (64-VWidth);
1423   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1424          "Invalid DemandedElts!");
1425
1426   if (isa<UndefValue>(V)) {
1427     // If the entire vector is undefined, just return this info.
1428     UndefElts = EltMask;
1429     return 0;
1430   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1431     UndefElts = EltMask;
1432     return UndefValue::get(V->getType());
1433   }
1434   
1435   UndefElts = 0;
1436   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1437     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1438     Constant *Undef = UndefValue::get(EltTy);
1439
1440     std::vector<Constant*> Elts;
1441     for (unsigned i = 0; i != VWidth; ++i)
1442       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1443         Elts.push_back(Undef);
1444         UndefElts |= (1ULL << i);
1445       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1446         Elts.push_back(Undef);
1447         UndefElts |= (1ULL << i);
1448       } else {                               // Otherwise, defined.
1449         Elts.push_back(CP->getOperand(i));
1450       }
1451         
1452     // If we changed the constant, return it.
1453     Constant *NewCP = ConstantVector::get(Elts);
1454     return NewCP != CP ? NewCP : 0;
1455   } else if (isa<ConstantAggregateZero>(V)) {
1456     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1457     // set to undef.
1458     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1459     Constant *Zero = Constant::getNullValue(EltTy);
1460     Constant *Undef = UndefValue::get(EltTy);
1461     std::vector<Constant*> Elts;
1462     for (unsigned i = 0; i != VWidth; ++i)
1463       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1464     UndefElts = DemandedElts ^ EltMask;
1465     return ConstantVector::get(Elts);
1466   }
1467   
1468   if (!V->hasOneUse()) {    // Other users may use these bits.
1469     if (Depth != 0) {       // Not at the root.
1470       // TODO: Just compute the UndefElts information recursively.
1471       return false;
1472     }
1473     return false;
1474   } else if (Depth == 10) {        // Limit search depth.
1475     return false;
1476   }
1477   
1478   Instruction *I = dyn_cast<Instruction>(V);
1479   if (!I) return false;        // Only analyze instructions.
1480   
1481   bool MadeChange = false;
1482   uint64_t UndefElts2;
1483   Value *TmpV;
1484   switch (I->getOpcode()) {
1485   default: break;
1486     
1487   case Instruction::InsertElement: {
1488     // If this is a variable index, we don't know which element it overwrites.
1489     // demand exactly the same input as we produce.
1490     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1491     if (Idx == 0) {
1492       // Note that we can't propagate undef elt info, because we don't know
1493       // which elt is getting updated.
1494       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1495                                         UndefElts2, Depth+1);
1496       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1497       break;
1498     }
1499     
1500     // If this is inserting an element that isn't demanded, remove this
1501     // insertelement.
1502     unsigned IdxNo = Idx->getZExtValue();
1503     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1504       return AddSoonDeadInstToWorklist(*I, 0);
1505     
1506     // Otherwise, the element inserted overwrites whatever was there, so the
1507     // input demanded set is simpler than the output set.
1508     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1509                                       DemandedElts & ~(1ULL << IdxNo),
1510                                       UndefElts, Depth+1);
1511     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1512
1513     // The inserted element is defined.
1514     UndefElts |= 1ULL << IdxNo;
1515     break;
1516   }
1517   case Instruction::BitCast: {
1518     // Vector->vector casts only.
1519     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1520     if (!VTy) break;
1521     unsigned InVWidth = VTy->getNumElements();
1522     uint64_t InputDemandedElts = 0;
1523     unsigned Ratio;
1524
1525     if (VWidth == InVWidth) {
1526       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1527       // elements as are demanded of us.
1528       Ratio = 1;
1529       InputDemandedElts = DemandedElts;
1530     } else if (VWidth > InVWidth) {
1531       // Untested so far.
1532       break;
1533       
1534       // If there are more elements in the result than there are in the source,
1535       // then an input element is live if any of the corresponding output
1536       // elements are live.
1537       Ratio = VWidth/InVWidth;
1538       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1539         if (DemandedElts & (1ULL << OutIdx))
1540           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1541       }
1542     } else {
1543       // Untested so far.
1544       break;
1545       
1546       // If there are more elements in the source than there are in the result,
1547       // then an input element is live if the corresponding output element is
1548       // live.
1549       Ratio = InVWidth/VWidth;
1550       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1551         if (DemandedElts & (1ULL << InIdx/Ratio))
1552           InputDemandedElts |= 1ULL << InIdx;
1553     }
1554     
1555     // div/rem demand all inputs, because they don't want divide by zero.
1556     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1557                                       UndefElts2, Depth+1);
1558     if (TmpV) {
1559       I->setOperand(0, TmpV);
1560       MadeChange = true;
1561     }
1562     
1563     UndefElts = UndefElts2;
1564     if (VWidth > InVWidth) {
1565       assert(0 && "Unimp");
1566       // If there are more elements in the result than there are in the source,
1567       // then an output element is undef if the corresponding input element is
1568       // undef.
1569       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1570         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1571           UndefElts |= 1ULL << OutIdx;
1572     } else if (VWidth < InVWidth) {
1573       assert(0 && "Unimp");
1574       // If there are more elements in the source than there are in the result,
1575       // then a result element is undef if all of the corresponding input
1576       // elements are undef.
1577       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1578       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1579         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1580           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1581     }
1582     break;
1583   }
1584   case Instruction::And:
1585   case Instruction::Or:
1586   case Instruction::Xor:
1587   case Instruction::Add:
1588   case Instruction::Sub:
1589   case Instruction::Mul:
1590     // div/rem demand all inputs, because they don't want divide by zero.
1591     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1592                                       UndefElts, Depth+1);
1593     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1594     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1595                                       UndefElts2, Depth+1);
1596     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1597       
1598     // Output elements are undefined if both are undefined.  Consider things
1599     // like undef&0.  The result is known zero, not undef.
1600     UndefElts &= UndefElts2;
1601     break;
1602     
1603   case Instruction::Call: {
1604     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1605     if (!II) break;
1606     switch (II->getIntrinsicID()) {
1607     default: break;
1608       
1609     // Binary vector operations that work column-wise.  A dest element is a
1610     // function of the corresponding input elements from the two inputs.
1611     case Intrinsic::x86_sse_sub_ss:
1612     case Intrinsic::x86_sse_mul_ss:
1613     case Intrinsic::x86_sse_min_ss:
1614     case Intrinsic::x86_sse_max_ss:
1615     case Intrinsic::x86_sse2_sub_sd:
1616     case Intrinsic::x86_sse2_mul_sd:
1617     case Intrinsic::x86_sse2_min_sd:
1618     case Intrinsic::x86_sse2_max_sd:
1619       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1620                                         UndefElts, Depth+1);
1621       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1622       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1623                                         UndefElts2, Depth+1);
1624       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1625
1626       // If only the low elt is demanded and this is a scalarizable intrinsic,
1627       // scalarize it now.
1628       if (DemandedElts == 1) {
1629         switch (II->getIntrinsicID()) {
1630         default: break;
1631         case Intrinsic::x86_sse_sub_ss:
1632         case Intrinsic::x86_sse_mul_ss:
1633         case Intrinsic::x86_sse2_sub_sd:
1634         case Intrinsic::x86_sse2_mul_sd:
1635           // TODO: Lower MIN/MAX/ABS/etc
1636           Value *LHS = II->getOperand(1);
1637           Value *RHS = II->getOperand(2);
1638           // Extract the element as scalars.
1639           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1640           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1641           
1642           switch (II->getIntrinsicID()) {
1643           default: assert(0 && "Case stmts out of sync!");
1644           case Intrinsic::x86_sse_sub_ss:
1645           case Intrinsic::x86_sse2_sub_sd:
1646             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1647                                                         II->getName()), *II);
1648             break;
1649           case Intrinsic::x86_sse_mul_ss:
1650           case Intrinsic::x86_sse2_mul_sd:
1651             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1652                                                          II->getName()), *II);
1653             break;
1654           }
1655           
1656           Instruction *New =
1657             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1658                                   II->getName());
1659           InsertNewInstBefore(New, *II);
1660           AddSoonDeadInstToWorklist(*II, 0);
1661           return New;
1662         }            
1663       }
1664         
1665       // Output elements are undefined if both are undefined.  Consider things
1666       // like undef&0.  The result is known zero, not undef.
1667       UndefElts &= UndefElts2;
1668       break;
1669     }
1670     break;
1671   }
1672   }
1673   return MadeChange ? I : 0;
1674 }
1675
1676 /// @returns true if the specified compare predicate is
1677 /// true when both operands are equal...
1678 /// @brief Determine if the icmp Predicate is true when both operands are equal
1679 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1680   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1681          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1682          pred == ICmpInst::ICMP_SLE;
1683 }
1684
1685 /// @returns true if the specified compare instruction is
1686 /// true when both operands are equal...
1687 /// @brief Determine if the ICmpInst returns true when both operands are equal
1688 static bool isTrueWhenEqual(ICmpInst &ICI) {
1689   return isTrueWhenEqual(ICI.getPredicate());
1690 }
1691
1692 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1693 /// function is designed to check a chain of associative operators for a
1694 /// potential to apply a certain optimization.  Since the optimization may be
1695 /// applicable if the expression was reassociated, this checks the chain, then
1696 /// reassociates the expression as necessary to expose the optimization
1697 /// opportunity.  This makes use of a special Functor, which must define
1698 /// 'shouldApply' and 'apply' methods.
1699 ///
1700 template<typename Functor>
1701 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1702   unsigned Opcode = Root.getOpcode();
1703   Value *LHS = Root.getOperand(0);
1704
1705   // Quick check, see if the immediate LHS matches...
1706   if (F.shouldApply(LHS))
1707     return F.apply(Root);
1708
1709   // Otherwise, if the LHS is not of the same opcode as the root, return.
1710   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1711   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1712     // Should we apply this transform to the RHS?
1713     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1714
1715     // If not to the RHS, check to see if we should apply to the LHS...
1716     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1717       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1718       ShouldApply = true;
1719     }
1720
1721     // If the functor wants to apply the optimization to the RHS of LHSI,
1722     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1723     if (ShouldApply) {
1724       BasicBlock *BB = Root.getParent();
1725
1726       // Now all of the instructions are in the current basic block, go ahead
1727       // and perform the reassociation.
1728       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1729
1730       // First move the selected RHS to the LHS of the root...
1731       Root.setOperand(0, LHSI->getOperand(1));
1732
1733       // Make what used to be the LHS of the root be the user of the root...
1734       Value *ExtraOperand = TmpLHSI->getOperand(1);
1735       if (&Root == TmpLHSI) {
1736         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1737         return 0;
1738       }
1739       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1740       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1741       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1742       BasicBlock::iterator ARI = &Root; ++ARI;
1743       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1744       ARI = Root;
1745
1746       // Now propagate the ExtraOperand down the chain of instructions until we
1747       // get to LHSI.
1748       while (TmpLHSI != LHSI) {
1749         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1750         // Move the instruction to immediately before the chain we are
1751         // constructing to avoid breaking dominance properties.
1752         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1753         BB->getInstList().insert(ARI, NextLHSI);
1754         ARI = NextLHSI;
1755
1756         Value *NextOp = NextLHSI->getOperand(1);
1757         NextLHSI->setOperand(1, ExtraOperand);
1758         TmpLHSI = NextLHSI;
1759         ExtraOperand = NextOp;
1760       }
1761
1762       // Now that the instructions are reassociated, have the functor perform
1763       // the transformation...
1764       return F.apply(Root);
1765     }
1766
1767     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1768   }
1769   return 0;
1770 }
1771
1772
1773 // AddRHS - Implements: X + X --> X << 1
1774 struct AddRHS {
1775   Value *RHS;
1776   AddRHS(Value *rhs) : RHS(rhs) {}
1777   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1778   Instruction *apply(BinaryOperator &Add) const {
1779     return BinaryOperator::createShl(Add.getOperand(0),
1780                                   ConstantInt::get(Add.getType(), 1));
1781   }
1782 };
1783
1784 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1785 //                 iff C1&C2 == 0
1786 struct AddMaskingAnd {
1787   Constant *C2;
1788   AddMaskingAnd(Constant *c) : C2(c) {}
1789   bool shouldApply(Value *LHS) const {
1790     ConstantInt *C1;
1791     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1792            ConstantExpr::getAnd(C1, C2)->isNullValue();
1793   }
1794   Instruction *apply(BinaryOperator &Add) const {
1795     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1796   }
1797 };
1798
1799 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1800                                              InstCombiner *IC) {
1801   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1802     if (Constant *SOC = dyn_cast<Constant>(SO))
1803       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1804
1805     return IC->InsertNewInstBefore(CastInst::create(
1806           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1807   }
1808
1809   // Figure out if the constant is the left or the right argument.
1810   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1811   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1812
1813   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1814     if (ConstIsRHS)
1815       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1816     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1817   }
1818
1819   Value *Op0 = SO, *Op1 = ConstOperand;
1820   if (!ConstIsRHS)
1821     std::swap(Op0, Op1);
1822   Instruction *New;
1823   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1824     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1825   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1826     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1827                           SO->getName()+".cmp");
1828   else {
1829     assert(0 && "Unknown binary instruction type!");
1830     abort();
1831   }
1832   return IC->InsertNewInstBefore(New, I);
1833 }
1834
1835 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1836 // constant as the other operand, try to fold the binary operator into the
1837 // select arguments.  This also works for Cast instructions, which obviously do
1838 // not have a second operand.
1839 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1840                                      InstCombiner *IC) {
1841   // Don't modify shared select instructions
1842   if (!SI->hasOneUse()) return 0;
1843   Value *TV = SI->getOperand(1);
1844   Value *FV = SI->getOperand(2);
1845
1846   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1847     // Bool selects with constant operands can be folded to logical ops.
1848     if (SI->getType() == Type::Int1Ty) return 0;
1849
1850     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1851     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1852
1853     return new SelectInst(SI->getCondition(), SelectTrueVal,
1854                           SelectFalseVal);
1855   }
1856   return 0;
1857 }
1858
1859
1860 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1861 /// node as operand #0, see if we can fold the instruction into the PHI (which
1862 /// is only possible if all operands to the PHI are constants).
1863 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1864   PHINode *PN = cast<PHINode>(I.getOperand(0));
1865   unsigned NumPHIValues = PN->getNumIncomingValues();
1866   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1867
1868   // Check to see if all of the operands of the PHI are constants.  If there is
1869   // one non-constant value, remember the BB it is.  If there is more than one
1870   // or if *it* is a PHI, bail out.
1871   BasicBlock *NonConstBB = 0;
1872   for (unsigned i = 0; i != NumPHIValues; ++i)
1873     if (!isa<Constant>(PN->getIncomingValue(i))) {
1874       if (NonConstBB) return 0;  // More than one non-const value.
1875       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1876       NonConstBB = PN->getIncomingBlock(i);
1877       
1878       // If the incoming non-constant value is in I's block, we have an infinite
1879       // loop.
1880       if (NonConstBB == I.getParent())
1881         return 0;
1882     }
1883   
1884   // If there is exactly one non-constant value, we can insert a copy of the
1885   // operation in that block.  However, if this is a critical edge, we would be
1886   // inserting the computation one some other paths (e.g. inside a loop).  Only
1887   // do this if the pred block is unconditionally branching into the phi block.
1888   if (NonConstBB) {
1889     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1890     if (!BI || !BI->isUnconditional()) return 0;
1891   }
1892
1893   // Okay, we can do the transformation: create the new PHI node.
1894   PHINode *NewPN = new PHINode(I.getType(), "");
1895   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1896   InsertNewInstBefore(NewPN, *PN);
1897   NewPN->takeName(PN);
1898
1899   // Next, add all of the operands to the PHI.
1900   if (I.getNumOperands() == 2) {
1901     Constant *C = cast<Constant>(I.getOperand(1));
1902     for (unsigned i = 0; i != NumPHIValues; ++i) {
1903       Value *InV = 0;
1904       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1905         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1906           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1907         else
1908           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1909       } else {
1910         assert(PN->getIncomingBlock(i) == NonConstBB);
1911         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1912           InV = BinaryOperator::create(BO->getOpcode(),
1913                                        PN->getIncomingValue(i), C, "phitmp",
1914                                        NonConstBB->getTerminator());
1915         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1916           InV = CmpInst::create(CI->getOpcode(), 
1917                                 CI->getPredicate(),
1918                                 PN->getIncomingValue(i), C, "phitmp",
1919                                 NonConstBB->getTerminator());
1920         else
1921           assert(0 && "Unknown binop!");
1922         
1923         AddToWorkList(cast<Instruction>(InV));
1924       }
1925       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1926     }
1927   } else { 
1928     CastInst *CI = cast<CastInst>(&I);
1929     const Type *RetTy = CI->getType();
1930     for (unsigned i = 0; i != NumPHIValues; ++i) {
1931       Value *InV;
1932       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1933         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1934       } else {
1935         assert(PN->getIncomingBlock(i) == NonConstBB);
1936         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1937                                I.getType(), "phitmp", 
1938                                NonConstBB->getTerminator());
1939         AddToWorkList(cast<Instruction>(InV));
1940       }
1941       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1942     }
1943   }
1944   return ReplaceInstUsesWith(I, NewPN);
1945 }
1946
1947
1948 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
1949 /// value is never equal to -0.0.
1950 ///
1951 /// Note that this function will need to be revisited when we support nondefault
1952 /// rounding modes!
1953 ///
1954 static bool CannotBeNegativeZero(const Value *V) {
1955   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1956     return !CFP->getValueAPF().isNegZero();
1957
1958   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1959   if (const Instruction *I = dyn_cast<Instruction>(V)) {
1960     if (I->getOpcode() == Instruction::Add &&
1961         isa<ConstantFP>(I->getOperand(1)) && 
1962         cast<ConstantFP>(I->getOperand(1))->isNullValue())
1963       return true;
1964     
1965     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1966       if (II->getIntrinsicID() == Intrinsic::sqrt)
1967         return CannotBeNegativeZero(II->getOperand(1));
1968     
1969     if (const CallInst *CI = dyn_cast<CallInst>(I))
1970       if (const Function *F = CI->getCalledFunction()) {
1971         if (F->isDeclaration()) {
1972           switch (F->getNameLen()) {
1973           case 3:  // abs(x) != -0.0
1974             if (!strcmp(F->getNameStart(), "abs")) return true;
1975             break;
1976           case 4:  // abs[lf](x) != -0.0
1977             if (!strcmp(F->getNameStart(), "absf")) return true;
1978             if (!strcmp(F->getNameStart(), "absl")) return true;
1979             break;
1980           }
1981         }
1982       }
1983   }
1984   
1985   return false;
1986 }
1987
1988
1989 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1990   bool Changed = SimplifyCommutative(I);
1991   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1992
1993   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1994     // X + undef -> undef
1995     if (isa<UndefValue>(RHS))
1996       return ReplaceInstUsesWith(I, RHS);
1997
1998     // X + 0 --> X
1999     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2000       if (RHSC->isNullValue())
2001         return ReplaceInstUsesWith(I, LHS);
2002     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2003       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2004                               (I.getType())->getValueAPF()))
2005         return ReplaceInstUsesWith(I, LHS);
2006     }
2007
2008     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2009       // X + (signbit) --> X ^ signbit
2010       const APInt& Val = CI->getValue();
2011       uint32_t BitWidth = Val.getBitWidth();
2012       if (Val == APInt::getSignBit(BitWidth))
2013         return BinaryOperator::createXor(LHS, RHS);
2014       
2015       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2016       // (X & 254)+1 -> (X&254)|1
2017       if (!isa<VectorType>(I.getType())) {
2018         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2019         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2020                                  KnownZero, KnownOne))
2021           return &I;
2022       }
2023     }
2024
2025     if (isa<PHINode>(LHS))
2026       if (Instruction *NV = FoldOpIntoPhi(I))
2027         return NV;
2028     
2029     ConstantInt *XorRHS = 0;
2030     Value *XorLHS = 0;
2031     if (isa<ConstantInt>(RHSC) &&
2032         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2033       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2034       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2035       
2036       uint32_t Size = TySizeBits / 2;
2037       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2038       APInt CFF80Val(-C0080Val);
2039       do {
2040         if (TySizeBits > Size) {
2041           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2042           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2043           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2044               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2045             // This is a sign extend if the top bits are known zero.
2046             if (!MaskedValueIsZero(XorLHS, 
2047                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2048               Size = 0;  // Not a sign ext, but can't be any others either.
2049             break;
2050           }
2051         }
2052         Size >>= 1;
2053         C0080Val = APIntOps::lshr(C0080Val, Size);
2054         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2055       } while (Size >= 1);
2056       
2057       // FIXME: This shouldn't be necessary. When the backends can handle types
2058       // with funny bit widths then this whole cascade of if statements should
2059       // be removed. It is just here to get the size of the "middle" type back
2060       // up to something that the back ends can handle.
2061       const Type *MiddleType = 0;
2062       switch (Size) {
2063         default: break;
2064         case 32: MiddleType = Type::Int32Ty; break;
2065         case 16: MiddleType = Type::Int16Ty; break;
2066         case  8: MiddleType = Type::Int8Ty; break;
2067       }
2068       if (MiddleType) {
2069         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2070         InsertNewInstBefore(NewTrunc, I);
2071         return new SExtInst(NewTrunc, I.getType(), I.getName());
2072       }
2073     }
2074   }
2075
2076   // X + X --> X << 1
2077   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2078     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2079
2080     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2081       if (RHSI->getOpcode() == Instruction::Sub)
2082         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2083           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2084     }
2085     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2086       if (LHSI->getOpcode() == Instruction::Sub)
2087         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2088           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2089     }
2090   }
2091
2092   // -A + B  -->  B - A
2093   // -A + -B  -->  -(A + B)
2094   if (Value *LHSV = dyn_castNegVal(LHS)) {
2095     if (Value *RHSV = dyn_castNegVal(RHS)) {
2096       Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2097       InsertNewInstBefore(NewAdd, I);
2098       return BinaryOperator::createNeg(NewAdd);
2099     }
2100     
2101     return BinaryOperator::createSub(RHS, LHSV);
2102   }
2103
2104   // A + -B  -->  A - B
2105   if (!isa<Constant>(RHS))
2106     if (Value *V = dyn_castNegVal(RHS))
2107       return BinaryOperator::createSub(LHS, V);
2108
2109
2110   ConstantInt *C2;
2111   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2112     if (X == RHS)   // X*C + X --> X * (C+1)
2113       return BinaryOperator::createMul(RHS, AddOne(C2));
2114
2115     // X*C1 + X*C2 --> X * (C1+C2)
2116     ConstantInt *C1;
2117     if (X == dyn_castFoldableMul(RHS, C1))
2118       return BinaryOperator::createMul(X, Add(C1, C2));
2119   }
2120
2121   // X + X*C --> X * (C+1)
2122   if (dyn_castFoldableMul(RHS, C2) == LHS)
2123     return BinaryOperator::createMul(LHS, AddOne(C2));
2124
2125   // X + ~X --> -1   since   ~X = -X-1
2126   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2127     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2128   
2129
2130   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2131   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2132     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2133       return R;
2134
2135   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2136   if (I.getType()->isIntOrIntVector()) {
2137     Value *W, *X, *Y, *Z;
2138     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2139         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2140       if (W != Y) {
2141         if (W == Z) {
2142           std::swap(Y, Z);
2143         } else if (Y == X) {
2144           std::swap(W, X);
2145         } else if (X == Z) {
2146           std::swap(Y, Z);
2147           std::swap(W, X);
2148         }
2149       }
2150
2151       if (W == Y) {
2152         Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2153                                                             LHS->getName()), I);
2154         return BinaryOperator::createMul(W, NewAdd);
2155       }
2156     }
2157   }
2158
2159   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2160     Value *X = 0;
2161     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2162       return BinaryOperator::createSub(SubOne(CRHS), X);
2163
2164     // (X & FF00) + xx00  -> (X+xx00) & FF00
2165     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2166       Constant *Anded = And(CRHS, C2);
2167       if (Anded == CRHS) {
2168         // See if all bits from the first bit set in the Add RHS up are included
2169         // in the mask.  First, get the rightmost bit.
2170         const APInt& AddRHSV = CRHS->getValue();
2171
2172         // Form a mask of all bits from the lowest bit added through the top.
2173         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2174
2175         // See if the and mask includes all of these bits.
2176         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2177
2178         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2179           // Okay, the xform is safe.  Insert the new add pronto.
2180           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2181                                                             LHS->getName()), I);
2182           return BinaryOperator::createAnd(NewAdd, C2);
2183         }
2184       }
2185     }
2186
2187     // Try to fold constant add into select arguments.
2188     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2189       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2190         return R;
2191   }
2192
2193   // add (cast *A to intptrtype) B -> 
2194   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2195   {
2196     CastInst *CI = dyn_cast<CastInst>(LHS);
2197     Value *Other = RHS;
2198     if (!CI) {
2199       CI = dyn_cast<CastInst>(RHS);
2200       Other = LHS;
2201     }
2202     if (CI && CI->getType()->isSized() && 
2203         (CI->getType()->getPrimitiveSizeInBits() == 
2204          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2205         && isa<PointerType>(CI->getOperand(0)->getType())) {
2206       unsigned AS =
2207         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2208       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2209                                       PointerType::get(Type::Int8Ty, AS), I);
2210       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2211       return new PtrToIntInst(I2, CI->getType());
2212     }
2213   }
2214   
2215   // add (select X 0 (sub n A)) A  -->  select X A n
2216   {
2217     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2218     Value *Other = RHS;
2219     if (!SI) {
2220       SI = dyn_cast<SelectInst>(RHS);
2221       Other = LHS;
2222     }
2223     if (SI && SI->hasOneUse()) {
2224       Value *TV = SI->getTrueValue();
2225       Value *FV = SI->getFalseValue();
2226       Value *A, *N;
2227
2228       // Can we fold the add into the argument of the select?
2229       // We check both true and false select arguments for a matching subtract.
2230       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2231           A == Other)  // Fold the add into the true select value.
2232         return new SelectInst(SI->getCondition(), N, A);
2233       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2234           A == Other)  // Fold the add into the false select value.
2235         return new SelectInst(SI->getCondition(), A, N);
2236     }
2237   }
2238   
2239   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2240   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2241     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2242       return ReplaceInstUsesWith(I, LHS);
2243
2244   return Changed ? &I : 0;
2245 }
2246
2247 // isSignBit - Return true if the value represented by the constant only has the
2248 // highest order bit set.
2249 static bool isSignBit(ConstantInt *CI) {
2250   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2251   return CI->getValue() == APInt::getSignBit(NumBits);
2252 }
2253
2254 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2255   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2256
2257   if (Op0 == Op1)         // sub X, X  -> 0
2258     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2259
2260   // If this is a 'B = x-(-A)', change to B = x+A...
2261   if (Value *V = dyn_castNegVal(Op1))
2262     return BinaryOperator::createAdd(Op0, V);
2263
2264   if (isa<UndefValue>(Op0))
2265     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2266   if (isa<UndefValue>(Op1))
2267     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2268
2269   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2270     // Replace (-1 - A) with (~A)...
2271     if (C->isAllOnesValue())
2272       return BinaryOperator::createNot(Op1);
2273
2274     // C - ~X == X + (1+C)
2275     Value *X = 0;
2276     if (match(Op1, m_Not(m_Value(X))))
2277       return BinaryOperator::createAdd(X, AddOne(C));
2278
2279     // -(X >>u 31) -> (X >>s 31)
2280     // -(X >>s 31) -> (X >>u 31)
2281     if (C->isZero()) {
2282       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2283         if (SI->getOpcode() == Instruction::LShr) {
2284           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2285             // Check to see if we are shifting out everything but the sign bit.
2286             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2287                 SI->getType()->getPrimitiveSizeInBits()-1) {
2288               // Ok, the transformation is safe.  Insert AShr.
2289               return BinaryOperator::create(Instruction::AShr, 
2290                                           SI->getOperand(0), CU, SI->getName());
2291             }
2292           }
2293         }
2294         else if (SI->getOpcode() == Instruction::AShr) {
2295           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2296             // Check to see if we are shifting out everything but the sign bit.
2297             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2298                 SI->getType()->getPrimitiveSizeInBits()-1) {
2299               // Ok, the transformation is safe.  Insert LShr. 
2300               return BinaryOperator::createLShr(
2301                                           SI->getOperand(0), CU, SI->getName());
2302             }
2303           }
2304         } 
2305     }
2306
2307     // Try to fold constant sub into select arguments.
2308     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2309       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2310         return R;
2311
2312     if (isa<PHINode>(Op0))
2313       if (Instruction *NV = FoldOpIntoPhi(I))
2314         return NV;
2315   }
2316
2317   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2318     if (Op1I->getOpcode() == Instruction::Add &&
2319         !Op0->getType()->isFPOrFPVector()) {
2320       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2321         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2322       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2323         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2324       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2325         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2326           // C1-(X+C2) --> (C1-C2)-X
2327           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2328                                            Op1I->getOperand(0));
2329       }
2330     }
2331
2332     if (Op1I->hasOneUse()) {
2333       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2334       // is not used by anyone else...
2335       //
2336       if (Op1I->getOpcode() == Instruction::Sub &&
2337           !Op1I->getType()->isFPOrFPVector()) {
2338         // Swap the two operands of the subexpr...
2339         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2340         Op1I->setOperand(0, IIOp1);
2341         Op1I->setOperand(1, IIOp0);
2342
2343         // Create the new top level add instruction...
2344         return BinaryOperator::createAdd(Op0, Op1);
2345       }
2346
2347       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2348       //
2349       if (Op1I->getOpcode() == Instruction::And &&
2350           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2351         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2352
2353         Value *NewNot =
2354           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2355         return BinaryOperator::createAnd(Op0, NewNot);
2356       }
2357
2358       // 0 - (X sdiv C)  -> (X sdiv -C)
2359       if (Op1I->getOpcode() == Instruction::SDiv)
2360         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2361           if (CSI->isZero())
2362             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2363               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2364                                                ConstantExpr::getNeg(DivRHS));
2365
2366       // X - X*C --> X * (1-C)
2367       ConstantInt *C2 = 0;
2368       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2369         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2370         return BinaryOperator::createMul(Op0, CP1);
2371       }
2372
2373       // X - ((X / Y) * Y) --> X % Y
2374       if (Op1I->getOpcode() == Instruction::Mul)
2375         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2376           if (Op0 == I->getOperand(0) &&
2377               Op1I->getOperand(1) == I->getOperand(1)) {
2378             if (I->getOpcode() == Instruction::SDiv)
2379               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2380             if (I->getOpcode() == Instruction::UDiv)
2381               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2382           }
2383     }
2384   }
2385
2386   if (!Op0->getType()->isFPOrFPVector())
2387     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2388       if (Op0I->getOpcode() == Instruction::Add) {
2389         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2390           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2391         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2392           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2393       } else if (Op0I->getOpcode() == Instruction::Sub) {
2394         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2395           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2396       }
2397
2398   ConstantInt *C1;
2399   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2400     if (X == Op1)  // X*C - X --> X * (C-1)
2401       return BinaryOperator::createMul(Op1, SubOne(C1));
2402
2403     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2404     if (X == dyn_castFoldableMul(Op1, C2))
2405       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2406   }
2407   return 0;
2408 }
2409
2410 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2411 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2412 /// TrueIfSigned if the result of the comparison is true when the input value is
2413 /// signed.
2414 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2415                            bool &TrueIfSigned) {
2416   switch (pred) {
2417   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2418     TrueIfSigned = true;
2419     return RHS->isZero();
2420   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2421     TrueIfSigned = true;
2422     return RHS->isAllOnesValue();
2423   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2424     TrueIfSigned = false;
2425     return RHS->isAllOnesValue();
2426   case ICmpInst::ICMP_UGT:
2427     // True if LHS u> RHS and RHS == high-bit-mask - 1
2428     TrueIfSigned = true;
2429     return RHS->getValue() ==
2430       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2431   case ICmpInst::ICMP_UGE: 
2432     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2433     TrueIfSigned = true;
2434     return RHS->getValue() == 
2435       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2436   default:
2437     return false;
2438   }
2439 }
2440
2441 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2442   bool Changed = SimplifyCommutative(I);
2443   Value *Op0 = I.getOperand(0);
2444
2445   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2446     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2447
2448   // Simplify mul instructions with a constant RHS...
2449   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2450     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2451
2452       // ((X << C1)*C2) == (X * (C2 << C1))
2453       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2454         if (SI->getOpcode() == Instruction::Shl)
2455           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2456             return BinaryOperator::createMul(SI->getOperand(0),
2457                                              ConstantExpr::getShl(CI, ShOp));
2458
2459       if (CI->isZero())
2460         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2461       if (CI->equalsInt(1))                  // X * 1  == X
2462         return ReplaceInstUsesWith(I, Op0);
2463       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2464         return BinaryOperator::createNeg(Op0, I.getName());
2465
2466       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2467       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2468         return BinaryOperator::createShl(Op0,
2469                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2470       }
2471     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2472       if (Op1F->isNullValue())
2473         return ReplaceInstUsesWith(I, Op1);
2474
2475       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2476       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2477       // We need a better interface for long double here.
2478       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2479         if (Op1F->isExactlyValue(1.0))
2480           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2481     }
2482     
2483     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2484       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2485           isa<ConstantInt>(Op0I->getOperand(1))) {
2486         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2487         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2488                                                      Op1, "tmp");
2489         InsertNewInstBefore(Add, I);
2490         Value *C1C2 = ConstantExpr::getMul(Op1, 
2491                                            cast<Constant>(Op0I->getOperand(1)));
2492         return BinaryOperator::createAdd(Add, C1C2);
2493         
2494       }
2495
2496     // Try to fold constant mul into select arguments.
2497     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2498       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2499         return R;
2500
2501     if (isa<PHINode>(Op0))
2502       if (Instruction *NV = FoldOpIntoPhi(I))
2503         return NV;
2504   }
2505
2506   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2507     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2508       return BinaryOperator::createMul(Op0v, Op1v);
2509
2510   // If one of the operands of the multiply is a cast from a boolean value, then
2511   // we know the bool is either zero or one, so this is a 'masking' multiply.
2512   // See if we can simplify things based on how the boolean was originally
2513   // formed.
2514   CastInst *BoolCast = 0;
2515   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2516     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2517       BoolCast = CI;
2518   if (!BoolCast)
2519     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2520       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2521         BoolCast = CI;
2522   if (BoolCast) {
2523     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2524       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2525       const Type *SCOpTy = SCIOp0->getType();
2526       bool TIS = false;
2527       
2528       // If the icmp is true iff the sign bit of X is set, then convert this
2529       // multiply into a shift/and combination.
2530       if (isa<ConstantInt>(SCIOp1) &&
2531           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2532           TIS) {
2533         // Shift the X value right to turn it into "all signbits".
2534         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2535                                           SCOpTy->getPrimitiveSizeInBits()-1);
2536         Value *V =
2537           InsertNewInstBefore(
2538             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2539                                             BoolCast->getOperand(0)->getName()+
2540                                             ".mask"), I);
2541
2542         // If the multiply type is not the same as the source type, sign extend
2543         // or truncate to the multiply type.
2544         if (I.getType() != V->getType()) {
2545           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2546           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2547           Instruction::CastOps opcode = 
2548             (SrcBits == DstBits ? Instruction::BitCast : 
2549              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2550           V = InsertCastBefore(opcode, V, I.getType(), I);
2551         }
2552
2553         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2554         return BinaryOperator::createAnd(V, OtherOp);
2555       }
2556     }
2557   }
2558
2559   return Changed ? &I : 0;
2560 }
2561
2562 /// This function implements the transforms on div instructions that work
2563 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2564 /// used by the visitors to those instructions.
2565 /// @brief Transforms common to all three div instructions
2566 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2567   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569   // undef / X -> 0
2570   if (isa<UndefValue>(Op0))
2571     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2572
2573   // X / undef -> undef
2574   if (isa<UndefValue>(Op1))
2575     return ReplaceInstUsesWith(I, Op1);
2576
2577   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2578   // This does not apply for fdiv.
2579   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2580     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2581     // the same basic block, then we replace the select with Y, and the
2582     // condition of the select with false (if the cond value is in the same BB).
2583     // If the select has uses other than the div, this allows them to be
2584     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2585     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2586       if (ST->isNullValue()) {
2587         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2588         if (CondI && CondI->getParent() == I.getParent())
2589           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2590         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2591           I.setOperand(1, SI->getOperand(2));
2592         else
2593           UpdateValueUsesWith(SI, SI->getOperand(2));
2594         return &I;
2595       }
2596
2597     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2598     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2599       if (ST->isNullValue()) {
2600         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2601         if (CondI && CondI->getParent() == I.getParent())
2602           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2603         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2604           I.setOperand(1, SI->getOperand(1));
2605         else
2606           UpdateValueUsesWith(SI, SI->getOperand(1));
2607         return &I;
2608       }
2609   }
2610
2611   return 0;
2612 }
2613
2614 /// This function implements the transforms common to both integer division
2615 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2616 /// division instructions.
2617 /// @brief Common integer divide transforms
2618 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2619   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2620
2621   if (Instruction *Common = commonDivTransforms(I))
2622     return Common;
2623
2624   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2625     // div X, 1 == X
2626     if (RHS->equalsInt(1))
2627       return ReplaceInstUsesWith(I, Op0);
2628
2629     // (X / C1) / C2  -> X / (C1*C2)
2630     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2631       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2632         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2633           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2634                                         Multiply(RHS, LHSRHS));
2635         }
2636
2637     if (!RHS->isZero()) { // avoid X udiv 0
2638       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2639         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2640           return R;
2641       if (isa<PHINode>(Op0))
2642         if (Instruction *NV = FoldOpIntoPhi(I))
2643           return NV;
2644     }
2645   }
2646
2647   // 0 / X == 0, we don't need to preserve faults!
2648   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2649     if (LHS->equalsInt(0))
2650       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2651
2652   return 0;
2653 }
2654
2655 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2656   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2657
2658   // Handle the integer div common cases
2659   if (Instruction *Common = commonIDivTransforms(I))
2660     return Common;
2661
2662   // X udiv C^2 -> X >> C
2663   // Check to see if this is an unsigned division with an exact power of 2,
2664   // if so, convert to a right shift.
2665   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2666     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2667       return BinaryOperator::createLShr(Op0, 
2668                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2669   }
2670
2671   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2672   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2673     if (RHSI->getOpcode() == Instruction::Shl &&
2674         isa<ConstantInt>(RHSI->getOperand(0))) {
2675       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2676       if (C1.isPowerOf2()) {
2677         Value *N = RHSI->getOperand(1);
2678         const Type *NTy = N->getType();
2679         if (uint32_t C2 = C1.logBase2()) {
2680           Constant *C2V = ConstantInt::get(NTy, C2);
2681           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2682         }
2683         return BinaryOperator::createLShr(Op0, N);
2684       }
2685     }
2686   }
2687   
2688   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2689   // where C1&C2 are powers of two.
2690   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2691     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2692       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2693         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2694         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2695           // Compute the shift amounts
2696           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2697           // Construct the "on true" case of the select
2698           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2699           Instruction *TSI = BinaryOperator::createLShr(
2700                                                  Op0, TC, SI->getName()+".t");
2701           TSI = InsertNewInstBefore(TSI, I);
2702   
2703           // Construct the "on false" case of the select
2704           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2705           Instruction *FSI = BinaryOperator::createLShr(
2706                                                  Op0, FC, SI->getName()+".f");
2707           FSI = InsertNewInstBefore(FSI, I);
2708
2709           // construct the select instruction and return it.
2710           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2711         }
2712       }
2713   return 0;
2714 }
2715
2716 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2717   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2718
2719   // Handle the integer div common cases
2720   if (Instruction *Common = commonIDivTransforms(I))
2721     return Common;
2722
2723   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2724     // sdiv X, -1 == -X
2725     if (RHS->isAllOnesValue())
2726       return BinaryOperator::createNeg(Op0);
2727
2728     // -X/C -> X/-C
2729     if (Value *LHSNeg = dyn_castNegVal(Op0))
2730       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2731   }
2732
2733   // If the sign bits of both operands are zero (i.e. we can prove they are
2734   // unsigned inputs), turn this into a udiv.
2735   if (I.getType()->isInteger()) {
2736     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2737     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2738       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2739       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2740     }
2741   }      
2742   
2743   return 0;
2744 }
2745
2746 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2747   return commonDivTransforms(I);
2748 }
2749
2750 /// GetFactor - If we can prove that the specified value is at least a multiple
2751 /// of some factor, return that factor.
2752 static Constant *GetFactor(Value *V) {
2753   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2754     return CI;
2755   
2756   // Unless we can be tricky, we know this is a multiple of 1.
2757   Constant *Result = ConstantInt::get(V->getType(), 1);
2758   
2759   Instruction *I = dyn_cast<Instruction>(V);
2760   if (!I) return Result;
2761   
2762   if (I->getOpcode() == Instruction::Mul) {
2763     // Handle multiplies by a constant, etc.
2764     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2765                                 GetFactor(I->getOperand(1)));
2766   } else if (I->getOpcode() == Instruction::Shl) {
2767     // (X<<C) -> X * (1 << C)
2768     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2769       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2770       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2771     }
2772   } else if (I->getOpcode() == Instruction::And) {
2773     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2774       // X & 0xFFF0 is known to be a multiple of 16.
2775       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2776       if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
2777         return ConstantExpr::getShl(Result, 
2778                                     ConstantInt::get(Result->getType(), Zeros));
2779     }
2780   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2781     // Only handle int->int casts.
2782     if (!CI->isIntegerCast())
2783       return Result;
2784     Value *Op = CI->getOperand(0);
2785     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2786   }    
2787   return Result;
2788 }
2789
2790 /// This function implements the transforms on rem instructions that work
2791 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2792 /// is used by the visitors to those instructions.
2793 /// @brief Transforms common to all three rem instructions
2794 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2795   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2796
2797   // 0 % X == 0, we don't need to preserve faults!
2798   if (Constant *LHS = dyn_cast<Constant>(Op0))
2799     if (LHS->isNullValue())
2800       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2801
2802   if (isa<UndefValue>(Op0))              // undef % X -> 0
2803     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2804   if (isa<UndefValue>(Op1))
2805     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2806
2807   // Handle cases involving: rem X, (select Cond, Y, Z)
2808   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2809     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2810     // the same basic block, then we replace the select with Y, and the
2811     // condition of the select with false (if the cond value is in the same
2812     // BB).  If the select has uses other than the div, this allows them to be
2813     // simplified also.
2814     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2815       if (ST->isNullValue()) {
2816         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2817         if (CondI && CondI->getParent() == I.getParent())
2818           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2819         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2820           I.setOperand(1, SI->getOperand(2));
2821         else
2822           UpdateValueUsesWith(SI, SI->getOperand(2));
2823         return &I;
2824       }
2825     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2826     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2827       if (ST->isNullValue()) {
2828         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2829         if (CondI && CondI->getParent() == I.getParent())
2830           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2831         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2832           I.setOperand(1, SI->getOperand(1));
2833         else
2834           UpdateValueUsesWith(SI, SI->getOperand(1));
2835         return &I;
2836       }
2837   }
2838
2839   return 0;
2840 }
2841
2842 /// This function implements the transforms common to both integer remainder
2843 /// instructions (urem and srem). It is called by the visitors to those integer
2844 /// remainder instructions.
2845 /// @brief Common integer remainder transforms
2846 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2847   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2848
2849   if (Instruction *common = commonRemTransforms(I))
2850     return common;
2851
2852   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2853     // X % 0 == undef, we don't need to preserve faults!
2854     if (RHS->equalsInt(0))
2855       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2856     
2857     if (RHS->equalsInt(1))  // X % 1 == 0
2858       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2859
2860     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2861       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2862         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2863           return R;
2864       } else if (isa<PHINode>(Op0I)) {
2865         if (Instruction *NV = FoldOpIntoPhi(I))
2866           return NV;
2867       }
2868       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2869       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2870         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2871     }
2872   }
2873
2874   return 0;
2875 }
2876
2877 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2878   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2879
2880   if (Instruction *common = commonIRemTransforms(I))
2881     return common;
2882   
2883   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2884     // X urem C^2 -> X and C
2885     // Check to see if this is an unsigned remainder with an exact power of 2,
2886     // if so, convert to a bitwise and.
2887     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2888       if (C->getValue().isPowerOf2())
2889         return BinaryOperator::createAnd(Op0, SubOne(C));
2890   }
2891
2892   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2893     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2894     if (RHSI->getOpcode() == Instruction::Shl &&
2895         isa<ConstantInt>(RHSI->getOperand(0))) {
2896       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2897         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2898         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2899                                                                    "tmp"), I);
2900         return BinaryOperator::createAnd(Op0, Add);
2901       }
2902     }
2903   }
2904
2905   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2906   // where C1&C2 are powers of two.
2907   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2908     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2909       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2910         // STO == 0 and SFO == 0 handled above.
2911         if ((STO->getValue().isPowerOf2()) && 
2912             (SFO->getValue().isPowerOf2())) {
2913           Value *TrueAnd = InsertNewInstBefore(
2914             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2915           Value *FalseAnd = InsertNewInstBefore(
2916             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2917           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2918         }
2919       }
2920   }
2921   
2922   return 0;
2923 }
2924
2925 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2926   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2927
2928   // Handle the integer rem common cases
2929   if (Instruction *common = commonIRemTransforms(I))
2930     return common;
2931   
2932   if (Value *RHSNeg = dyn_castNegVal(Op1))
2933     if (!isa<ConstantInt>(RHSNeg) || 
2934         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2935       // X % -Y -> X % Y
2936       AddUsesToWorkList(I);
2937       I.setOperand(1, RHSNeg);
2938       return &I;
2939     }
2940  
2941   // If the sign bits of both operands are zero (i.e. we can prove they are
2942   // unsigned inputs), turn this into a urem.
2943   if (I.getType()->isInteger()) {
2944     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2945     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2946       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2947       return BinaryOperator::createURem(Op0, Op1, I.getName());
2948     }
2949   }
2950
2951   return 0;
2952 }
2953
2954 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2955   return commonRemTransforms(I);
2956 }
2957
2958 // isMaxValueMinusOne - return true if this is Max-1
2959 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2960   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2961   if (!isSigned)
2962     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2963   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2964 }
2965
2966 // isMinValuePlusOne - return true if this is Min+1
2967 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2968   if (!isSigned)
2969     return C->getValue() == 1; // unsigned
2970     
2971   // Calculate 1111111111000000000000
2972   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2973   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2974 }
2975
2976 // isOneBitSet - Return true if there is exactly one bit set in the specified
2977 // constant.
2978 static bool isOneBitSet(const ConstantInt *CI) {
2979   return CI->getValue().isPowerOf2();
2980 }
2981
2982 // isHighOnes - Return true if the constant is of the form 1+0+.
2983 // This is the same as lowones(~X).
2984 static bool isHighOnes(const ConstantInt *CI) {
2985   return (~CI->getValue() + 1).isPowerOf2();
2986 }
2987
2988 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2989 /// are carefully arranged to allow folding of expressions such as:
2990 ///
2991 ///      (A < B) | (A > B) --> (A != B)
2992 ///
2993 /// Note that this is only valid if the first and second predicates have the
2994 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2995 ///
2996 /// Three bits are used to represent the condition, as follows:
2997 ///   0  A > B
2998 ///   1  A == B
2999 ///   2  A < B
3000 ///
3001 /// <=>  Value  Definition
3002 /// 000     0   Always false
3003 /// 001     1   A >  B
3004 /// 010     2   A == B
3005 /// 011     3   A >= B
3006 /// 100     4   A <  B
3007 /// 101     5   A != B
3008 /// 110     6   A <= B
3009 /// 111     7   Always true
3010 ///  
3011 static unsigned getICmpCode(const ICmpInst *ICI) {
3012   switch (ICI->getPredicate()) {
3013     // False -> 0
3014   case ICmpInst::ICMP_UGT: return 1;  // 001
3015   case ICmpInst::ICMP_SGT: return 1;  // 001
3016   case ICmpInst::ICMP_EQ:  return 2;  // 010
3017   case ICmpInst::ICMP_UGE: return 3;  // 011
3018   case ICmpInst::ICMP_SGE: return 3;  // 011
3019   case ICmpInst::ICMP_ULT: return 4;  // 100
3020   case ICmpInst::ICMP_SLT: return 4;  // 100
3021   case ICmpInst::ICMP_NE:  return 5;  // 101
3022   case ICmpInst::ICMP_ULE: return 6;  // 110
3023   case ICmpInst::ICMP_SLE: return 6;  // 110
3024     // True -> 7
3025   default:
3026     assert(0 && "Invalid ICmp predicate!");
3027     return 0;
3028   }
3029 }
3030
3031 /// getICmpValue - This is the complement of getICmpCode, which turns an
3032 /// opcode and two operands into either a constant true or false, or a brand 
3033 /// new ICmp instruction. The sign is passed in to determine which kind
3034 /// of predicate to use in new icmp instructions.
3035 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3036   switch (code) {
3037   default: assert(0 && "Illegal ICmp code!");
3038   case  0: return ConstantInt::getFalse();
3039   case  1: 
3040     if (sign)
3041       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3042     else
3043       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3044   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3045   case  3: 
3046     if (sign)
3047       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3048     else
3049       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3050   case  4: 
3051     if (sign)
3052       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3053     else
3054       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3055   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3056   case  6: 
3057     if (sign)
3058       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3059     else
3060       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3061   case  7: return ConstantInt::getTrue();
3062   }
3063 }
3064
3065 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3066   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3067     (ICmpInst::isSignedPredicate(p1) && 
3068      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3069     (ICmpInst::isSignedPredicate(p2) && 
3070      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3071 }
3072
3073 namespace { 
3074 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3075 struct FoldICmpLogical {
3076   InstCombiner &IC;
3077   Value *LHS, *RHS;
3078   ICmpInst::Predicate pred;
3079   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3080     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3081       pred(ICI->getPredicate()) {}
3082   bool shouldApply(Value *V) const {
3083     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3084       if (PredicatesFoldable(pred, ICI->getPredicate()))
3085         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3086                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3087     return false;
3088   }
3089   Instruction *apply(Instruction &Log) const {
3090     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3091     if (ICI->getOperand(0) != LHS) {
3092       assert(ICI->getOperand(1) == LHS);
3093       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3094     }
3095
3096     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3097     unsigned LHSCode = getICmpCode(ICI);
3098     unsigned RHSCode = getICmpCode(RHSICI);
3099     unsigned Code;
3100     switch (Log.getOpcode()) {
3101     case Instruction::And: Code = LHSCode & RHSCode; break;
3102     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3103     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3104     default: assert(0 && "Illegal logical opcode!"); return 0;
3105     }
3106
3107     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3108                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3109       
3110     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3111     if (Instruction *I = dyn_cast<Instruction>(RV))
3112       return I;
3113     // Otherwise, it's a constant boolean value...
3114     return IC.ReplaceInstUsesWith(Log, RV);
3115   }
3116 };
3117 } // end anonymous namespace
3118
3119 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3120 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3121 // guaranteed to be a binary operator.
3122 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3123                                     ConstantInt *OpRHS,
3124                                     ConstantInt *AndRHS,
3125                                     BinaryOperator &TheAnd) {
3126   Value *X = Op->getOperand(0);
3127   Constant *Together = 0;
3128   if (!Op->isShift())
3129     Together = And(AndRHS, OpRHS);
3130
3131   switch (Op->getOpcode()) {
3132   case Instruction::Xor:
3133     if (Op->hasOneUse()) {
3134       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3135       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3136       InsertNewInstBefore(And, TheAnd);
3137       And->takeName(Op);
3138       return BinaryOperator::createXor(And, Together);
3139     }
3140     break;
3141   case Instruction::Or:
3142     if (Together == AndRHS) // (X | C) & C --> C
3143       return ReplaceInstUsesWith(TheAnd, AndRHS);
3144
3145     if (Op->hasOneUse() && Together != OpRHS) {
3146       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3147       Instruction *Or = BinaryOperator::createOr(X, Together);
3148       InsertNewInstBefore(Or, TheAnd);
3149       Or->takeName(Op);
3150       return BinaryOperator::createAnd(Or, AndRHS);
3151     }
3152     break;
3153   case Instruction::Add:
3154     if (Op->hasOneUse()) {
3155       // Adding a one to a single bit bit-field should be turned into an XOR
3156       // of the bit.  First thing to check is to see if this AND is with a
3157       // single bit constant.
3158       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3159
3160       // If there is only one bit set...
3161       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3162         // Ok, at this point, we know that we are masking the result of the
3163         // ADD down to exactly one bit.  If the constant we are adding has
3164         // no bits set below this bit, then we can eliminate the ADD.
3165         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3166
3167         // Check to see if any bits below the one bit set in AndRHSV are set.
3168         if ((AddRHS & (AndRHSV-1)) == 0) {
3169           // If not, the only thing that can effect the output of the AND is
3170           // the bit specified by AndRHSV.  If that bit is set, the effect of
3171           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3172           // no effect.
3173           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3174             TheAnd.setOperand(0, X);
3175             return &TheAnd;
3176           } else {
3177             // Pull the XOR out of the AND.
3178             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3179             InsertNewInstBefore(NewAnd, TheAnd);
3180             NewAnd->takeName(Op);
3181             return BinaryOperator::createXor(NewAnd, AndRHS);
3182           }
3183         }
3184       }
3185     }
3186     break;
3187
3188   case Instruction::Shl: {
3189     // We know that the AND will not produce any of the bits shifted in, so if
3190     // the anded constant includes them, clear them now!
3191     //
3192     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3193     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3194     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3195     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3196
3197     if (CI->getValue() == ShlMask) { 
3198     // Masking out bits that the shift already masks
3199       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3200     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3201       TheAnd.setOperand(1, CI);
3202       return &TheAnd;
3203     }
3204     break;
3205   }
3206   case Instruction::LShr:
3207   {
3208     // We know that the AND will not produce any of the bits shifted in, so if
3209     // the anded constant includes them, clear them now!  This only applies to
3210     // unsigned shifts, because a signed shr may bring in set bits!
3211     //
3212     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3213     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3214     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3215     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3216
3217     if (CI->getValue() == ShrMask) {   
3218     // Masking out bits that the shift already masks.
3219       return ReplaceInstUsesWith(TheAnd, Op);
3220     } else if (CI != AndRHS) {
3221       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3222       return &TheAnd;
3223     }
3224     break;
3225   }
3226   case Instruction::AShr:
3227     // Signed shr.
3228     // See if this is shifting in some sign extension, then masking it out
3229     // with an and.
3230     if (Op->hasOneUse()) {
3231       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3232       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3233       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3234       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3235       if (C == AndRHS) {          // Masking out bits shifted in.
3236         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3237         // Make the argument unsigned.
3238         Value *ShVal = Op->getOperand(0);
3239         ShVal = InsertNewInstBefore(
3240             BinaryOperator::createLShr(ShVal, OpRHS, 
3241                                    Op->getName()), TheAnd);
3242         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3243       }
3244     }
3245     break;
3246   }
3247   return 0;
3248 }
3249
3250
3251 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3252 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3253 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3254 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3255 /// insert new instructions.
3256 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3257                                            bool isSigned, bool Inside, 
3258                                            Instruction &IB) {
3259   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3260             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3261          "Lo is not <= Hi in range emission code!");
3262     
3263   if (Inside) {
3264     if (Lo == Hi)  // Trivially false.
3265       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3266
3267     // V >= Min && V < Hi --> V < Hi
3268     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3269       ICmpInst::Predicate pred = (isSigned ? 
3270         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3271       return new ICmpInst(pred, V, Hi);
3272     }
3273
3274     // Emit V-Lo <u Hi-Lo
3275     Constant *NegLo = ConstantExpr::getNeg(Lo);
3276     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3277     InsertNewInstBefore(Add, IB);
3278     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3279     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3280   }
3281
3282   if (Lo == Hi)  // Trivially true.
3283     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3284
3285   // V < Min || V >= Hi -> V > Hi-1
3286   Hi = SubOne(cast<ConstantInt>(Hi));
3287   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3288     ICmpInst::Predicate pred = (isSigned ? 
3289         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3290     return new ICmpInst(pred, V, Hi);
3291   }
3292
3293   // Emit V-Lo >u Hi-1-Lo
3294   // Note that Hi has already had one subtracted from it, above.
3295   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3296   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3297   InsertNewInstBefore(Add, IB);
3298   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3299   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3300 }
3301
3302 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3303 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3304 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3305 // not, since all 1s are not contiguous.
3306 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3307   const APInt& V = Val->getValue();
3308   uint32_t BitWidth = Val->getType()->getBitWidth();
3309   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3310
3311   // look for the first zero bit after the run of ones
3312   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3313   // look for the first non-zero bit
3314   ME = V.getActiveBits(); 
3315   return true;
3316 }
3317
3318 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3319 /// where isSub determines whether the operator is a sub.  If we can fold one of
3320 /// the following xforms:
3321 /// 
3322 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3323 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3324 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3325 ///
3326 /// return (A +/- B).
3327 ///
3328 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3329                                         ConstantInt *Mask, bool isSub,
3330                                         Instruction &I) {
3331   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3332   if (!LHSI || LHSI->getNumOperands() != 2 ||
3333       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3334
3335   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3336
3337   switch (LHSI->getOpcode()) {
3338   default: return 0;
3339   case Instruction::And:
3340     if (And(N, Mask) == Mask) {
3341       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3342       if ((Mask->getValue().countLeadingZeros() + 
3343            Mask->getValue().countPopulation()) == 
3344           Mask->getValue().getBitWidth())
3345         break;
3346
3347       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3348       // part, we don't need any explicit masks to take them out of A.  If that
3349       // is all N is, ignore it.
3350       uint32_t MB = 0, ME = 0;
3351       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3352         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3353         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3354         if (MaskedValueIsZero(RHS, Mask))
3355           break;
3356       }
3357     }
3358     return 0;
3359   case Instruction::Or:
3360   case Instruction::Xor:
3361     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3362     if ((Mask->getValue().countLeadingZeros() + 
3363          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3364         && And(N, Mask)->isZero())
3365       break;
3366     return 0;
3367   }
3368   
3369   Instruction *New;
3370   if (isSub)
3371     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3372   else
3373     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3374   return InsertNewInstBefore(New, I);
3375 }
3376
3377 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3378   bool Changed = SimplifyCommutative(I);
3379   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3380
3381   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3382     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3383
3384   // and X, X = X
3385   if (Op0 == Op1)
3386     return ReplaceInstUsesWith(I, Op1);
3387
3388   // See if we can simplify any instructions used by the instruction whose sole 
3389   // purpose is to compute bits we don't care about.
3390   if (!isa<VectorType>(I.getType())) {
3391     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3392     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3393     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3394                              KnownZero, KnownOne))
3395       return &I;
3396   } else {
3397     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3398       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3399         return ReplaceInstUsesWith(I, I.getOperand(0));
3400     } else if (isa<ConstantAggregateZero>(Op1)) {
3401       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3402     }
3403   }
3404   
3405   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3406     const APInt& AndRHSMask = AndRHS->getValue();
3407     APInt NotAndRHS(~AndRHSMask);
3408
3409     // Optimize a variety of ((val OP C1) & C2) combinations...
3410     if (isa<BinaryOperator>(Op0)) {
3411       Instruction *Op0I = cast<Instruction>(Op0);
3412       Value *Op0LHS = Op0I->getOperand(0);
3413       Value *Op0RHS = Op0I->getOperand(1);
3414       switch (Op0I->getOpcode()) {
3415       case Instruction::Xor:
3416       case Instruction::Or:
3417         // If the mask is only needed on one incoming arm, push it up.
3418         if (Op0I->hasOneUse()) {
3419           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3420             // Not masking anything out for the LHS, move to RHS.
3421             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3422                                                    Op0RHS->getName()+".masked");
3423             InsertNewInstBefore(NewRHS, I);
3424             return BinaryOperator::create(
3425                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3426           }
3427           if (!isa<Constant>(Op0RHS) &&
3428               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3429             // Not masking anything out for the RHS, move to LHS.
3430             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3431                                                    Op0LHS->getName()+".masked");
3432             InsertNewInstBefore(NewLHS, I);
3433             return BinaryOperator::create(
3434                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3435           }
3436         }
3437
3438         break;
3439       case Instruction::Add:
3440         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3441         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3442         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3443         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3444           return BinaryOperator::createAnd(V, AndRHS);
3445         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3446           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3447         break;
3448
3449       case Instruction::Sub:
3450         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3451         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3452         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3453         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3454           return BinaryOperator::createAnd(V, AndRHS);
3455         break;
3456       }
3457
3458       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3459         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3460           return Res;
3461     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3462       // If this is an integer truncation or change from signed-to-unsigned, and
3463       // if the source is an and/or with immediate, transform it.  This
3464       // frequently occurs for bitfield accesses.
3465       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3466         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3467             CastOp->getNumOperands() == 2)
3468           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3469             if (CastOp->getOpcode() == Instruction::And) {
3470               // Change: and (cast (and X, C1) to T), C2
3471               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3472               // This will fold the two constants together, which may allow 
3473               // other simplifications.
3474               Instruction *NewCast = CastInst::createTruncOrBitCast(
3475                 CastOp->getOperand(0), I.getType(), 
3476                 CastOp->getName()+".shrunk");
3477               NewCast = InsertNewInstBefore(NewCast, I);
3478               // trunc_or_bitcast(C1)&C2
3479               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3480               C3 = ConstantExpr::getAnd(C3, AndRHS);
3481               return BinaryOperator::createAnd(NewCast, C3);
3482             } else if (CastOp->getOpcode() == Instruction::Or) {
3483               // Change: and (cast (or X, C1) to T), C2
3484               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3485               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3486               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3487                 return ReplaceInstUsesWith(I, AndRHS);
3488             }
3489       }
3490     }
3491
3492     // Try to fold constant and into select arguments.
3493     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3494       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3495         return R;
3496     if (isa<PHINode>(Op0))
3497       if (Instruction *NV = FoldOpIntoPhi(I))
3498         return NV;
3499   }
3500
3501   Value *Op0NotVal = dyn_castNotVal(Op0);
3502   Value *Op1NotVal = dyn_castNotVal(Op1);
3503
3504   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3505     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3506
3507   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3508   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3509     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3510                                                I.getName()+".demorgan");
3511     InsertNewInstBefore(Or, I);
3512     return BinaryOperator::createNot(Or);
3513   }
3514   
3515   {
3516     Value *A = 0, *B = 0, *C = 0, *D = 0;
3517     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3518       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3519         return ReplaceInstUsesWith(I, Op1);
3520     
3521       // (A|B) & ~(A&B) -> A^B
3522       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3523         if ((A == C && B == D) || (A == D && B == C))
3524           return BinaryOperator::createXor(A, B);
3525       }
3526     }
3527     
3528     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3529       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3530         return ReplaceInstUsesWith(I, Op0);
3531
3532       // ~(A&B) & (A|B) -> A^B
3533       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3534         if ((A == C && B == D) || (A == D && B == C))
3535           return BinaryOperator::createXor(A, B);
3536       }
3537     }
3538     
3539     if (Op0->hasOneUse() &&
3540         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3541       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3542         I.swapOperands();     // Simplify below
3543         std::swap(Op0, Op1);
3544       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3545         cast<BinaryOperator>(Op0)->swapOperands();
3546         I.swapOperands();     // Simplify below
3547         std::swap(Op0, Op1);
3548       }
3549     }
3550     if (Op1->hasOneUse() &&
3551         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3552       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3553         cast<BinaryOperator>(Op1)->swapOperands();
3554         std::swap(A, B);
3555       }
3556       if (A == Op0) {                                // A&(A^B) -> A & ~B
3557         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3558         InsertNewInstBefore(NotB, I);
3559         return BinaryOperator::createAnd(A, NotB);
3560       }
3561     }
3562   }
3563   
3564   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3565     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3566     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3567       return R;
3568
3569     Value *LHSVal, *RHSVal;
3570     ConstantInt *LHSCst, *RHSCst;
3571     ICmpInst::Predicate LHSCC, RHSCC;
3572     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3573       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3574         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3575             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3576             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3577             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3578             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3579             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3580             
3581             // Don't try to fold ICMP_SLT + ICMP_ULT.
3582             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3583              ICmpInst::isSignedPredicate(LHSCC) == 
3584                  ICmpInst::isSignedPredicate(RHSCC))) {
3585           // Ensure that the larger constant is on the RHS.
3586           ICmpInst::Predicate GT;
3587           if (ICmpInst::isSignedPredicate(LHSCC) ||
3588               (ICmpInst::isEquality(LHSCC) && 
3589                ICmpInst::isSignedPredicate(RHSCC)))
3590             GT = ICmpInst::ICMP_SGT;
3591           else
3592             GT = ICmpInst::ICMP_UGT;
3593           
3594           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3595           ICmpInst *LHS = cast<ICmpInst>(Op0);
3596           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3597             std::swap(LHS, RHS);
3598             std::swap(LHSCst, RHSCst);
3599             std::swap(LHSCC, RHSCC);
3600           }
3601
3602           // At this point, we know we have have two icmp instructions
3603           // comparing a value against two constants and and'ing the result
3604           // together.  Because of the above check, we know that we only have
3605           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3606           // (from the FoldICmpLogical check above), that the two constants 
3607           // are not equal and that the larger constant is on the RHS
3608           assert(LHSCst != RHSCst && "Compares not folded above?");
3609
3610           switch (LHSCC) {
3611           default: assert(0 && "Unknown integer condition code!");
3612           case ICmpInst::ICMP_EQ:
3613             switch (RHSCC) {
3614             default: assert(0 && "Unknown integer condition code!");
3615             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3616             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3617             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3618               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3619             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3620             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3621             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3622               return ReplaceInstUsesWith(I, LHS);
3623             }
3624           case ICmpInst::ICMP_NE:
3625             switch (RHSCC) {
3626             default: assert(0 && "Unknown integer condition code!");
3627             case ICmpInst::ICMP_ULT:
3628               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3629                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3630               break;                        // (X != 13 & X u< 15) -> no change
3631             case ICmpInst::ICMP_SLT:
3632               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3633                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3634               break;                        // (X != 13 & X s< 15) -> no change
3635             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3636             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3637             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3638               return ReplaceInstUsesWith(I, RHS);
3639             case ICmpInst::ICMP_NE:
3640               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3641                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3642                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3643                                                       LHSVal->getName()+".off");
3644                 InsertNewInstBefore(Add, I);
3645                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3646                                     ConstantInt::get(Add->getType(), 1));
3647               }
3648               break;                        // (X != 13 & X != 15) -> no change
3649             }
3650             break;
3651           case ICmpInst::ICMP_ULT:
3652             switch (RHSCC) {
3653             default: assert(0 && "Unknown integer condition code!");
3654             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3655             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3656               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3657             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3658               break;
3659             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3660             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3661               return ReplaceInstUsesWith(I, LHS);
3662             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3663               break;
3664             }
3665             break;
3666           case ICmpInst::ICMP_SLT:
3667             switch (RHSCC) {
3668             default: assert(0 && "Unknown integer condition code!");
3669             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3670             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3671               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3672             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3673               break;
3674             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3675             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3676               return ReplaceInstUsesWith(I, LHS);
3677             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3678               break;
3679             }
3680             break;
3681           case ICmpInst::ICMP_UGT:
3682             switch (RHSCC) {
3683             default: assert(0 && "Unknown integer condition code!");
3684             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3685               return ReplaceInstUsesWith(I, LHS);
3686             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3687               return ReplaceInstUsesWith(I, RHS);
3688             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3689               break;
3690             case ICmpInst::ICMP_NE:
3691               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3692                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3693               break;                        // (X u> 13 & X != 15) -> no change
3694             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3695               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3696                                      true, I);
3697             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3698               break;
3699             }
3700             break;
3701           case ICmpInst::ICMP_SGT:
3702             switch (RHSCC) {
3703             default: assert(0 && "Unknown integer condition code!");
3704             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3705             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3706               return ReplaceInstUsesWith(I, RHS);
3707             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3708               break;
3709             case ICmpInst::ICMP_NE:
3710               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3711                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3712               break;                        // (X s> 13 & X != 15) -> no change
3713             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3714               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3715                                      true, I);
3716             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3717               break;
3718             }
3719             break;
3720           }
3721         }
3722   }
3723
3724   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3725   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3726     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3727       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3728         const Type *SrcTy = Op0C->getOperand(0)->getType();
3729         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3730             // Only do this if the casts both really cause code to be generated.
3731             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3732                               I.getType(), TD) &&
3733             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3734                               I.getType(), TD)) {
3735           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3736                                                          Op1C->getOperand(0),
3737                                                          I.getName());
3738           InsertNewInstBefore(NewOp, I);
3739           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3740         }
3741       }
3742     
3743   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3744   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3745     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3746       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3747           SI0->getOperand(1) == SI1->getOperand(1) &&
3748           (SI0->hasOneUse() || SI1->hasOneUse())) {
3749         Instruction *NewOp =
3750           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3751                                                         SI1->getOperand(0),
3752                                                         SI0->getName()), I);
3753         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3754                                       SI1->getOperand(1));
3755       }
3756   }
3757
3758   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3759   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3760     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3761       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3762           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3763         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3764           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3765             // If either of the constants are nans, then the whole thing returns
3766             // false.
3767             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3768               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3769             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3770                                 RHS->getOperand(0));
3771           }
3772     }
3773   }
3774       
3775   return Changed ? &I : 0;
3776 }
3777
3778 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3779 /// in the result.  If it does, and if the specified byte hasn't been filled in
3780 /// yet, fill it in and return false.
3781 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3782   Instruction *I = dyn_cast<Instruction>(V);
3783   if (I == 0) return true;
3784
3785   // If this is an or instruction, it is an inner node of the bswap.
3786   if (I->getOpcode() == Instruction::Or)
3787     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3788            CollectBSwapParts(I->getOperand(1), ByteValues);
3789   
3790   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3791   // If this is a shift by a constant int, and it is "24", then its operand
3792   // defines a byte.  We only handle unsigned types here.
3793   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3794     // Not shifting the entire input by N-1 bytes?
3795     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3796         8*(ByteValues.size()-1))
3797       return true;
3798     
3799     unsigned DestNo;
3800     if (I->getOpcode() == Instruction::Shl) {
3801       // X << 24 defines the top byte with the lowest of the input bytes.
3802       DestNo = ByteValues.size()-1;
3803     } else {
3804       // X >>u 24 defines the low byte with the highest of the input bytes.
3805       DestNo = 0;
3806     }
3807     
3808     // If the destination byte value is already defined, the values are or'd
3809     // together, which isn't a bswap (unless it's an or of the same bits).
3810     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3811       return true;
3812     ByteValues[DestNo] = I->getOperand(0);
3813     return false;
3814   }
3815   
3816   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3817   // don't have this.
3818   Value *Shift = 0, *ShiftLHS = 0;
3819   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3820   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3821       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3822     return true;
3823   Instruction *SI = cast<Instruction>(Shift);
3824
3825   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3826   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3827       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3828     return true;
3829   
3830   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3831   unsigned DestByte;
3832   if (AndAmt->getValue().getActiveBits() > 64)
3833     return true;
3834   uint64_t AndAmtVal = AndAmt->getZExtValue();
3835   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3836     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3837       break;
3838   // Unknown mask for bswap.
3839   if (DestByte == ByteValues.size()) return true;
3840   
3841   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3842   unsigned SrcByte;
3843   if (SI->getOpcode() == Instruction::Shl)
3844     SrcByte = DestByte - ShiftBytes;
3845   else
3846     SrcByte = DestByte + ShiftBytes;
3847   
3848   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3849   if (SrcByte != ByteValues.size()-DestByte-1)
3850     return true;
3851   
3852   // If the destination byte value is already defined, the values are or'd
3853   // together, which isn't a bswap (unless it's an or of the same bits).
3854   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3855     return true;
3856   ByteValues[DestByte] = SI->getOperand(0);
3857   return false;
3858 }
3859
3860 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3861 /// If so, insert the new bswap intrinsic and return it.
3862 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3863   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3864   if (!ITy || ITy->getBitWidth() % 16) 
3865     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3866   
3867   /// ByteValues - For each byte of the result, we keep track of which value
3868   /// defines each byte.
3869   SmallVector<Value*, 8> ByteValues;
3870   ByteValues.resize(ITy->getBitWidth()/8);
3871     
3872   // Try to find all the pieces corresponding to the bswap.
3873   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3874       CollectBSwapParts(I.getOperand(1), ByteValues))
3875     return 0;
3876   
3877   // Check to see if all of the bytes come from the same value.
3878   Value *V = ByteValues[0];
3879   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3880   
3881   // Check to make sure that all of the bytes come from the same value.
3882   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3883     if (ByteValues[i] != V)
3884       return 0;
3885   const Type *Tys[] = { ITy };
3886   Module *M = I.getParent()->getParent()->getParent();
3887   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3888   return new CallInst(F, V);
3889 }
3890
3891
3892 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3893   bool Changed = SimplifyCommutative(I);
3894   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3895
3896   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3897     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3898
3899   // or X, X = X
3900   if (Op0 == Op1)
3901     return ReplaceInstUsesWith(I, Op0);
3902
3903   // See if we can simplify any instructions used by the instruction whose sole 
3904   // purpose is to compute bits we don't care about.
3905   if (!isa<VectorType>(I.getType())) {
3906     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3907     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3908     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3909                              KnownZero, KnownOne))
3910       return &I;
3911   } else if (isa<ConstantAggregateZero>(Op1)) {
3912     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3913   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3914     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3915       return ReplaceInstUsesWith(I, I.getOperand(1));
3916   }
3917     
3918
3919   
3920   // or X, -1 == -1
3921   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3922     ConstantInt *C1 = 0; Value *X = 0;
3923     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3924     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3925       Instruction *Or = BinaryOperator::createOr(X, RHS);
3926       InsertNewInstBefore(Or, I);
3927       Or->takeName(Op0);
3928       return BinaryOperator::createAnd(Or, 
3929                ConstantInt::get(RHS->getValue() | C1->getValue()));
3930     }
3931
3932     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3933     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3934       Instruction *Or = BinaryOperator::createOr(X, RHS);
3935       InsertNewInstBefore(Or, I);
3936       Or->takeName(Op0);
3937       return BinaryOperator::createXor(Or,
3938                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3939     }
3940
3941     // Try to fold constant and into select arguments.
3942     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3943       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3944         return R;
3945     if (isa<PHINode>(Op0))
3946       if (Instruction *NV = FoldOpIntoPhi(I))
3947         return NV;
3948   }
3949
3950   Value *A = 0, *B = 0;
3951   ConstantInt *C1 = 0, *C2 = 0;
3952
3953   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3954     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3955       return ReplaceInstUsesWith(I, Op1);
3956   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3957     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3958       return ReplaceInstUsesWith(I, Op0);
3959
3960   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3961   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3962   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3963       match(Op1, m_Or(m_Value(), m_Value())) ||
3964       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3965        match(Op1, m_Shift(m_Value(), m_Value())))) {
3966     if (Instruction *BSwap = MatchBSwap(I))
3967       return BSwap;
3968   }
3969   
3970   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3971   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3972       MaskedValueIsZero(Op1, C1->getValue())) {
3973     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3974     InsertNewInstBefore(NOr, I);
3975     NOr->takeName(Op0);
3976     return BinaryOperator::createXor(NOr, C1);
3977   }
3978
3979   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3980   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3981       MaskedValueIsZero(Op0, C1->getValue())) {
3982     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3983     InsertNewInstBefore(NOr, I);
3984     NOr->takeName(Op0);
3985     return BinaryOperator::createXor(NOr, C1);
3986   }
3987
3988   // (A & C)|(B & D)
3989   Value *C = 0, *D = 0;
3990   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3991       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3992     Value *V1 = 0, *V2 = 0, *V3 = 0;
3993     C1 = dyn_cast<ConstantInt>(C);
3994     C2 = dyn_cast<ConstantInt>(D);
3995     if (C1 && C2) {  // (A & C1)|(B & C2)
3996       // If we have: ((V + N) & C1) | (V & C2)
3997       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3998       // replace with V+N.
3999       if (C1->getValue() == ~C2->getValue()) {
4000         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4001             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4002           // Add commutes, try both ways.
4003           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4004             return ReplaceInstUsesWith(I, A);
4005           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4006             return ReplaceInstUsesWith(I, A);
4007         }
4008         // Or commutes, try both ways.
4009         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4010             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4011           // Add commutes, try both ways.
4012           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4013             return ReplaceInstUsesWith(I, B);
4014           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4015             return ReplaceInstUsesWith(I, B);
4016         }
4017       }
4018       V1 = 0; V2 = 0; V3 = 0;
4019     }
4020     
4021     // Check to see if we have any common things being and'ed.  If so, find the
4022     // terms for V1 & (V2|V3).
4023     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4024       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4025         V1 = A, V2 = C, V3 = D;
4026       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4027         V1 = A, V2 = B, V3 = C;
4028       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4029         V1 = C, V2 = A, V3 = D;
4030       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4031         V1 = C, V2 = A, V3 = B;
4032       
4033       if (V1) {
4034         Value *Or =
4035           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4036         return BinaryOperator::createAnd(V1, Or);
4037       }
4038     }
4039   }
4040   
4041   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4042   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4043     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4044       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4045           SI0->getOperand(1) == SI1->getOperand(1) &&
4046           (SI0->hasOneUse() || SI1->hasOneUse())) {
4047         Instruction *NewOp =
4048         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4049                                                      SI1->getOperand(0),
4050                                                      SI0->getName()), I);
4051         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4052                                       SI1->getOperand(1));
4053       }
4054   }
4055
4056   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4057     if (A == Op1)   // ~A | A == -1
4058       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4059   } else {
4060     A = 0;
4061   }
4062   // Note, A is still live here!
4063   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4064     if (Op0 == B)
4065       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4066
4067     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4068     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4069       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4070                                               I.getName()+".demorgan"), I);
4071       return BinaryOperator::createNot(And);
4072     }
4073   }
4074
4075   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4076   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4077     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4078       return R;
4079
4080     Value *LHSVal, *RHSVal;
4081     ConstantInt *LHSCst, *RHSCst;
4082     ICmpInst::Predicate LHSCC, RHSCC;
4083     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4084       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4085         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4086             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4087             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4088             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4089             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4090             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4091             // We can't fold (ugt x, C) | (sgt x, C2).
4092             PredicatesFoldable(LHSCC, RHSCC)) {
4093           // Ensure that the larger constant is on the RHS.
4094           ICmpInst *LHS = cast<ICmpInst>(Op0);
4095           bool NeedsSwap;
4096           if (ICmpInst::isSignedPredicate(LHSCC))
4097             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4098           else
4099             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4100             
4101           if (NeedsSwap) {
4102             std::swap(LHS, RHS);
4103             std::swap(LHSCst, RHSCst);
4104             std::swap(LHSCC, RHSCC);
4105           }
4106
4107           // At this point, we know we have have two icmp instructions
4108           // comparing a value against two constants and or'ing the result
4109           // together.  Because of the above check, we know that we only have
4110           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4111           // FoldICmpLogical check above), that the two constants are not
4112           // equal.
4113           assert(LHSCst != RHSCst && "Compares not folded above?");
4114
4115           switch (LHSCC) {
4116           default: assert(0 && "Unknown integer condition code!");
4117           case ICmpInst::ICMP_EQ:
4118             switch (RHSCC) {
4119             default: assert(0 && "Unknown integer condition code!");
4120             case ICmpInst::ICMP_EQ:
4121               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4122                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4123                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4124                                                       LHSVal->getName()+".off");
4125                 InsertNewInstBefore(Add, I);
4126                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4127                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4128               }
4129               break;                         // (X == 13 | X == 15) -> no change
4130             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4131             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4132               break;
4133             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4134             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4135             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4136               return ReplaceInstUsesWith(I, RHS);
4137             }
4138             break;
4139           case ICmpInst::ICMP_NE:
4140             switch (RHSCC) {
4141             default: assert(0 && "Unknown integer condition code!");
4142             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4143             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4144             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4145               return ReplaceInstUsesWith(I, LHS);
4146             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4147             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4148             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4149               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4150             }
4151             break;
4152           case ICmpInst::ICMP_ULT:
4153             switch (RHSCC) {
4154             default: assert(0 && "Unknown integer condition code!");
4155             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4156               break;
4157             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4158               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4159               // this can cause overflow.
4160               if (RHSCst->isMaxValue(false))
4161                 return ReplaceInstUsesWith(I, LHS);
4162               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4163                                      false, I);
4164             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4165               break;
4166             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4167             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4168               return ReplaceInstUsesWith(I, RHS);
4169             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4170               break;
4171             }
4172             break;
4173           case ICmpInst::ICMP_SLT:
4174             switch (RHSCC) {
4175             default: assert(0 && "Unknown integer condition code!");
4176             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4177               break;
4178             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4179               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4180               // this can cause overflow.
4181               if (RHSCst->isMaxValue(true))
4182                 return ReplaceInstUsesWith(I, LHS);
4183               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4184                                      false, I);
4185             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4186               break;
4187             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4188             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4189               return ReplaceInstUsesWith(I, RHS);
4190             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4191               break;
4192             }
4193             break;
4194           case ICmpInst::ICMP_UGT:
4195             switch (RHSCC) {
4196             default: assert(0 && "Unknown integer condition code!");
4197             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4198             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4199               return ReplaceInstUsesWith(I, LHS);
4200             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4201               break;
4202             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4203             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4204               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4205             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4206               break;
4207             }
4208             break;
4209           case ICmpInst::ICMP_SGT:
4210             switch (RHSCC) {
4211             default: assert(0 && "Unknown integer condition code!");
4212             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4213             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4214               return ReplaceInstUsesWith(I, LHS);
4215             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4216               break;
4217             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4218             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4219               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4220             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4221               break;
4222             }
4223             break;
4224           }
4225         }
4226   }
4227     
4228   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4229   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4230     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4231       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4232         const Type *SrcTy = Op0C->getOperand(0)->getType();
4233         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4234             // Only do this if the casts both really cause code to be generated.
4235             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4236                               I.getType(), TD) &&
4237             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4238                               I.getType(), TD)) {
4239           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4240                                                         Op1C->getOperand(0),
4241                                                         I.getName());
4242           InsertNewInstBefore(NewOp, I);
4243           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4244         }
4245       }
4246   }
4247   
4248     
4249   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4250   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4251     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4252       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4253           RHS->getPredicate() == FCmpInst::FCMP_UNO)
4254         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4255           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4256             // If either of the constants are nans, then the whole thing returns
4257             // true.
4258             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4259               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4260             
4261             // Otherwise, no need to compare the two constants, compare the
4262             // rest.
4263             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4264                                 RHS->getOperand(0));
4265           }
4266     }
4267   }
4268
4269   return Changed ? &I : 0;
4270 }
4271
4272 // XorSelf - Implements: X ^ X --> 0
4273 struct XorSelf {
4274   Value *RHS;
4275   XorSelf(Value *rhs) : RHS(rhs) {}
4276   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4277   Instruction *apply(BinaryOperator &Xor) const {
4278     return &Xor;
4279   }
4280 };
4281
4282
4283 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4284   bool Changed = SimplifyCommutative(I);
4285   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4286
4287   if (isa<UndefValue>(Op1))
4288     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4289
4290   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4291   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4292     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4293     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4294   }
4295   
4296   // See if we can simplify any instructions used by the instruction whose sole 
4297   // purpose is to compute bits we don't care about.
4298   if (!isa<VectorType>(I.getType())) {
4299     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4300     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4301     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4302                              KnownZero, KnownOne))
4303       return &I;
4304   } else if (isa<ConstantAggregateZero>(Op1)) {
4305     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4306   }
4307
4308   // Is this a ~ operation?
4309   if (Value *NotOp = dyn_castNotVal(&I)) {
4310     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4311     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4312     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4313       if (Op0I->getOpcode() == Instruction::And || 
4314           Op0I->getOpcode() == Instruction::Or) {
4315         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4316         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4317           Instruction *NotY =
4318             BinaryOperator::createNot(Op0I->getOperand(1),
4319                                       Op0I->getOperand(1)->getName()+".not");
4320           InsertNewInstBefore(NotY, I);
4321           if (Op0I->getOpcode() == Instruction::And)
4322             return BinaryOperator::createOr(Op0NotVal, NotY);
4323           else
4324             return BinaryOperator::createAnd(Op0NotVal, NotY);
4325         }
4326       }
4327     }
4328   }
4329   
4330   
4331   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4332     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4333     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4334       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4335         return new ICmpInst(ICI->getInversePredicate(),
4336                             ICI->getOperand(0), ICI->getOperand(1));
4337
4338       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4339         return new FCmpInst(FCI->getInversePredicate(),
4340                             FCI->getOperand(0), FCI->getOperand(1));
4341     }
4342
4343     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4344       // ~(c-X) == X-c-1 == X+(-c-1)
4345       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4346         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4347           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4348           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4349                                               ConstantInt::get(I.getType(), 1));
4350           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4351         }
4352           
4353       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4354         if (Op0I->getOpcode() == Instruction::Add) {
4355           // ~(X-c) --> (-c-1)-X
4356           if (RHS->isAllOnesValue()) {
4357             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4358             return BinaryOperator::createSub(
4359                            ConstantExpr::getSub(NegOp0CI,
4360                                              ConstantInt::get(I.getType(), 1)),
4361                                           Op0I->getOperand(0));
4362           } else if (RHS->getValue().isSignBit()) {
4363             // (X + C) ^ signbit -> (X + C + signbit)
4364             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4365             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4366
4367           }
4368         } else if (Op0I->getOpcode() == Instruction::Or) {
4369           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4370           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4371             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4372             // Anything in both C1 and C2 is known to be zero, remove it from
4373             // NewRHS.
4374             Constant *CommonBits = And(Op0CI, RHS);
4375             NewRHS = ConstantExpr::getAnd(NewRHS, 
4376                                           ConstantExpr::getNot(CommonBits));
4377             AddToWorkList(Op0I);
4378             I.setOperand(0, Op0I->getOperand(0));
4379             I.setOperand(1, NewRHS);
4380             return &I;
4381           }
4382         }
4383     }
4384
4385     // Try to fold constant and into select arguments.
4386     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4387       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4388         return R;
4389     if (isa<PHINode>(Op0))
4390       if (Instruction *NV = FoldOpIntoPhi(I))
4391         return NV;
4392   }
4393
4394   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4395     if (X == Op1)
4396       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4397
4398   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4399     if (X == Op0)
4400       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4401
4402   
4403   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4404   if (Op1I) {
4405     Value *A, *B;
4406     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4407       if (A == Op0) {              // B^(B|A) == (A|B)^B
4408         Op1I->swapOperands();
4409         I.swapOperands();
4410         std::swap(Op0, Op1);
4411       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4412         I.swapOperands();     // Simplified below.
4413         std::swap(Op0, Op1);
4414       }
4415     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4416       if (Op0 == A)                                          // A^(A^B) == B
4417         return ReplaceInstUsesWith(I, B);
4418       else if (Op0 == B)                                     // A^(B^A) == B
4419         return ReplaceInstUsesWith(I, A);
4420     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4421       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4422         Op1I->swapOperands();
4423         std::swap(A, B);
4424       }
4425       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4426         I.swapOperands();     // Simplified below.
4427         std::swap(Op0, Op1);
4428       }
4429     }
4430   }
4431   
4432   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4433   if (Op0I) {
4434     Value *A, *B;
4435     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4436       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4437         std::swap(A, B);
4438       if (B == Op1) {                                // (A|B)^B == A & ~B
4439         Instruction *NotB =
4440           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4441         return BinaryOperator::createAnd(A, NotB);
4442       }
4443     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4444       if (Op1 == A)                                          // (A^B)^A == B
4445         return ReplaceInstUsesWith(I, B);
4446       else if (Op1 == B)                                     // (B^A)^A == B
4447         return ReplaceInstUsesWith(I, A);
4448     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4449       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4450         std::swap(A, B);
4451       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4452           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4453         Instruction *N =
4454           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4455         return BinaryOperator::createAnd(N, Op1);
4456       }
4457     }
4458   }
4459   
4460   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4461   if (Op0I && Op1I && Op0I->isShift() && 
4462       Op0I->getOpcode() == Op1I->getOpcode() && 
4463       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4464       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4465     Instruction *NewOp =
4466       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4467                                                     Op1I->getOperand(0),
4468                                                     Op0I->getName()), I);
4469     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4470                                   Op1I->getOperand(1));
4471   }
4472     
4473   if (Op0I && Op1I) {
4474     Value *A, *B, *C, *D;
4475     // (A & B)^(A | B) -> A ^ B
4476     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4477         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4478       if ((A == C && B == D) || (A == D && B == C)) 
4479         return BinaryOperator::createXor(A, B);
4480     }
4481     // (A | B)^(A & B) -> A ^ B
4482     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4483         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4484       if ((A == C && B == D) || (A == D && B == C)) 
4485         return BinaryOperator::createXor(A, B);
4486     }
4487     
4488     // (A & B)^(C & D)
4489     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4490         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4491         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4492       // (X & Y)^(X & Y) -> (Y^Z) & X
4493       Value *X = 0, *Y = 0, *Z = 0;
4494       if (A == C)
4495         X = A, Y = B, Z = D;
4496       else if (A == D)
4497         X = A, Y = B, Z = C;
4498       else if (B == C)
4499         X = B, Y = A, Z = D;
4500       else if (B == D)
4501         X = B, Y = A, Z = C;
4502       
4503       if (X) {
4504         Instruction *NewOp =
4505         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4506         return BinaryOperator::createAnd(NewOp, X);
4507       }
4508     }
4509   }
4510     
4511   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4512   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4513     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4514       return R;
4515
4516   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4517   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4518     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4519       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4520         const Type *SrcTy = Op0C->getOperand(0)->getType();
4521         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4522             // Only do this if the casts both really cause code to be generated.
4523             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4524                               I.getType(), TD) &&
4525             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4526                               I.getType(), TD)) {
4527           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4528                                                          Op1C->getOperand(0),
4529                                                          I.getName());
4530           InsertNewInstBefore(NewOp, I);
4531           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4532         }
4533       }
4534   }
4535   return Changed ? &I : 0;
4536 }
4537
4538 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4539 /// overflowed for this type.
4540 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4541                             ConstantInt *In2, bool IsSigned = false) {
4542   Result = cast<ConstantInt>(Add(In1, In2));
4543
4544   if (IsSigned)
4545     if (In2->getValue().isNegative())
4546       return Result->getValue().sgt(In1->getValue());
4547     else
4548       return Result->getValue().slt(In1->getValue());
4549   else
4550     return Result->getValue().ult(In1->getValue());
4551 }
4552
4553 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4554 /// code necessary to compute the offset from the base pointer (without adding
4555 /// in the base pointer).  Return the result as a signed integer of intptr size.
4556 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4557   TargetData &TD = IC.getTargetData();
4558   gep_type_iterator GTI = gep_type_begin(GEP);
4559   const Type *IntPtrTy = TD.getIntPtrType();
4560   Value *Result = Constant::getNullValue(IntPtrTy);
4561
4562   // Build a mask for high order bits.
4563   unsigned IntPtrWidth = TD.getPointerSize()*8;
4564   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4565
4566   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4567     Value *Op = GEP->getOperand(i);
4568     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4569     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4570       if (OpC->isZero()) continue;
4571       
4572       // Handle a struct index, which adds its field offset to the pointer.
4573       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4574         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4575         
4576         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4577           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4578         else
4579           Result = IC.InsertNewInstBefore(
4580                    BinaryOperator::createAdd(Result,
4581                                              ConstantInt::get(IntPtrTy, Size),
4582                                              GEP->getName()+".offs"), I);
4583         continue;
4584       }
4585       
4586       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4587       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4588       Scale = ConstantExpr::getMul(OC, Scale);
4589       if (Constant *RC = dyn_cast<Constant>(Result))
4590         Result = ConstantExpr::getAdd(RC, Scale);
4591       else {
4592         // Emit an add instruction.
4593         Result = IC.InsertNewInstBefore(
4594            BinaryOperator::createAdd(Result, Scale,
4595                                      GEP->getName()+".offs"), I);
4596       }
4597       continue;
4598     }
4599     // Convert to correct type.
4600     if (Op->getType() != IntPtrTy) {
4601       if (Constant *OpC = dyn_cast<Constant>(Op))
4602         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4603       else
4604         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4605                                                  Op->getName()+".c"), I);
4606     }
4607     if (Size != 1) {
4608       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4609       if (Constant *OpC = dyn_cast<Constant>(Op))
4610         Op = ConstantExpr::getMul(OpC, Scale);
4611       else    // We'll let instcombine(mul) convert this to a shl if possible.
4612         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4613                                                   GEP->getName()+".idx"), I);
4614     }
4615
4616     // Emit an add instruction.
4617     if (isa<Constant>(Op) && isa<Constant>(Result))
4618       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4619                                     cast<Constant>(Result));
4620     else
4621       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4622                                                   GEP->getName()+".offs"), I);
4623   }
4624   return Result;
4625 }
4626
4627 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4628 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4629 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4630                                        ICmpInst::Predicate Cond,
4631                                        Instruction &I) {
4632   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4633
4634   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4635     if (isa<PointerType>(CI->getOperand(0)->getType()))
4636       RHS = CI->getOperand(0);
4637
4638   Value *PtrBase = GEPLHS->getOperand(0);
4639   if (PtrBase == RHS) {
4640     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4641     // This transformation is valid because we know pointers can't overflow.
4642     Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4643     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4644                         Constant::getNullValue(Offset->getType()));
4645   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4646     // If the base pointers are different, but the indices are the same, just
4647     // compare the base pointer.
4648     if (PtrBase != GEPRHS->getOperand(0)) {
4649       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4650       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4651                         GEPRHS->getOperand(0)->getType();
4652       if (IndicesTheSame)
4653         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4654           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4655             IndicesTheSame = false;
4656             break;
4657           }
4658
4659       // If all indices are the same, just compare the base pointers.
4660       if (IndicesTheSame)
4661         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4662                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4663
4664       // Otherwise, the base pointers are different and the indices are
4665       // different, bail out.
4666       return 0;
4667     }
4668
4669     // If one of the GEPs has all zero indices, recurse.
4670     bool AllZeros = true;
4671     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4672       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4673           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4674         AllZeros = false;
4675         break;
4676       }
4677     if (AllZeros)
4678       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4679                           ICmpInst::getSwappedPredicate(Cond), I);
4680
4681     // If the other GEP has all zero indices, recurse.
4682     AllZeros = true;
4683     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4684       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4685           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4686         AllZeros = false;
4687         break;
4688       }
4689     if (AllZeros)
4690       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4691
4692     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4693       // If the GEPs only differ by one index, compare it.
4694       unsigned NumDifferences = 0;  // Keep track of # differences.
4695       unsigned DiffOperand = 0;     // The operand that differs.
4696       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4697         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4698           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4699                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4700             // Irreconcilable differences.
4701             NumDifferences = 2;
4702             break;
4703           } else {
4704             if (NumDifferences++) break;
4705             DiffOperand = i;
4706           }
4707         }
4708
4709       if (NumDifferences == 0)   // SAME GEP?
4710         return ReplaceInstUsesWith(I, // No comparison is needed here.
4711                                    ConstantInt::get(Type::Int1Ty,
4712                                                     isTrueWhenEqual(Cond)));
4713
4714       else if (NumDifferences == 1) {
4715         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4716         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4717         // Make sure we do a signed comparison here.
4718         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4719       }
4720     }
4721
4722     // Only lower this if the icmp is the only user of the GEP or if we expect
4723     // the result to fold to a constant!
4724     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4725         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4726       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4727       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4728       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4729       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4730     }
4731   }
4732   return 0;
4733 }
4734
4735 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4736   bool Changed = SimplifyCompare(I);
4737   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4738
4739   // Fold trivial predicates.
4740   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4741     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4742   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4743     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4744   
4745   // Simplify 'fcmp pred X, X'
4746   if (Op0 == Op1) {
4747     switch (I.getPredicate()) {
4748     default: assert(0 && "Unknown predicate!");
4749     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4750     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4751     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4752       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4753     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4754     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4755     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4756       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4757       
4758     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4759     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4760     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4761     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4762       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4763       I.setPredicate(FCmpInst::FCMP_UNO);
4764       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4765       return &I;
4766       
4767     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4768     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4769     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4770     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4771       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4772       I.setPredicate(FCmpInst::FCMP_ORD);
4773       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4774       return &I;
4775     }
4776   }
4777     
4778   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4779     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4780
4781   // Handle fcmp with constant RHS
4782   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4783     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4784       switch (LHSI->getOpcode()) {
4785       case Instruction::PHI:
4786         if (Instruction *NV = FoldOpIntoPhi(I))
4787           return NV;
4788         break;
4789       case Instruction::Select:
4790         // If either operand of the select is a constant, we can fold the
4791         // comparison into the select arms, which will cause one to be
4792         // constant folded and the select turned into a bitwise or.
4793         Value *Op1 = 0, *Op2 = 0;
4794         if (LHSI->hasOneUse()) {
4795           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4796             // Fold the known value into the constant operand.
4797             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4798             // Insert a new FCmp of the other select operand.
4799             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4800                                                       LHSI->getOperand(2), RHSC,
4801                                                       I.getName()), I);
4802           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4803             // Fold the known value into the constant operand.
4804             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4805             // Insert a new FCmp of the other select operand.
4806             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4807                                                       LHSI->getOperand(1), RHSC,
4808                                                       I.getName()), I);
4809           }
4810         }
4811
4812         if (Op1)
4813           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4814         break;
4815       }
4816   }
4817
4818   return Changed ? &I : 0;
4819 }
4820
4821 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4822   bool Changed = SimplifyCompare(I);
4823   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4824   const Type *Ty = Op0->getType();
4825
4826   // icmp X, X
4827   if (Op0 == Op1)
4828     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4829                                                    isTrueWhenEqual(I)));
4830
4831   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4832     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4833   
4834   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4835   // addresses never equal each other!  We already know that Op0 != Op1.
4836   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4837        isa<ConstantPointerNull>(Op0)) &&
4838       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4839        isa<ConstantPointerNull>(Op1)))
4840     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4841                                                    !isTrueWhenEqual(I)));
4842
4843   // icmp's with boolean values can always be turned into bitwise operations
4844   if (Ty == Type::Int1Ty) {
4845     switch (I.getPredicate()) {
4846     default: assert(0 && "Invalid icmp instruction!");
4847     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4848       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4849       InsertNewInstBefore(Xor, I);
4850       return BinaryOperator::createNot(Xor);
4851     }
4852     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4853       return BinaryOperator::createXor(Op0, Op1);
4854
4855     case ICmpInst::ICMP_UGT:
4856     case ICmpInst::ICMP_SGT:
4857       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4858       // FALL THROUGH
4859     case ICmpInst::ICMP_ULT:
4860     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4861       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4862       InsertNewInstBefore(Not, I);
4863       return BinaryOperator::createAnd(Not, Op1);
4864     }
4865     case ICmpInst::ICMP_UGE:
4866     case ICmpInst::ICMP_SGE:
4867       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4868       // FALL THROUGH
4869     case ICmpInst::ICMP_ULE:
4870     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4871       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4872       InsertNewInstBefore(Not, I);
4873       return BinaryOperator::createOr(Not, Op1);
4874     }
4875     }
4876   }
4877
4878   // See if we are doing a comparison between a constant and an instruction that
4879   // can be folded into the comparison.
4880   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4881       Value *A, *B;
4882     
4883     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4884     if (I.isEquality() && CI->isNullValue() &&
4885         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4886       // (icmp cond A B) if cond is equality
4887       return new ICmpInst(I.getPredicate(), A, B);
4888     }
4889     
4890     switch (I.getPredicate()) {
4891     default: break;
4892     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4893       if (CI->isMinValue(false))
4894         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4895       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4896         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4897       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4898         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4899       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4900       if (CI->isMinValue(true))
4901         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4902                             ConstantInt::getAllOnesValue(Op0->getType()));
4903           
4904       break;
4905
4906     case ICmpInst::ICMP_SLT:
4907       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4908         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4909       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4910         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4911       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4912         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4913       break;
4914
4915     case ICmpInst::ICMP_UGT:
4916       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4917         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4918       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4919         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4920       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4921         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4922         
4923       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4924       if (CI->isMaxValue(true))
4925         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4926                             ConstantInt::getNullValue(Op0->getType()));
4927       break;
4928
4929     case ICmpInst::ICMP_SGT:
4930       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4931         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4932       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4933         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4934       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4935         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4936       break;
4937
4938     case ICmpInst::ICMP_ULE:
4939       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4940         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4941       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4942         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4943       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4944         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4945       break;
4946
4947     case ICmpInst::ICMP_SLE:
4948       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4949         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4950       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4951         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4952       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4953         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4954       break;
4955
4956     case ICmpInst::ICMP_UGE:
4957       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4958         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4959       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4960         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4961       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4962         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4963       break;
4964
4965     case ICmpInst::ICMP_SGE:
4966       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4967         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4968       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4969         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4970       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4971         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4972       break;
4973     }
4974
4975     // If we still have a icmp le or icmp ge instruction, turn it into the
4976     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4977     // already been handled above, this requires little checking.
4978     //
4979     switch (I.getPredicate()) {
4980     default: break;
4981     case ICmpInst::ICMP_ULE: 
4982       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4983     case ICmpInst::ICMP_SLE:
4984       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4985     case ICmpInst::ICMP_UGE:
4986       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4987     case ICmpInst::ICMP_SGE:
4988       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4989     }
4990     
4991     // See if we can fold the comparison based on bits known to be zero or one
4992     // in the input.  If this comparison is a normal comparison, it demands all
4993     // bits, if it is a sign bit comparison, it only demands the sign bit.
4994     
4995     bool UnusedBit;
4996     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4997     
4998     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4999     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5000     if (SimplifyDemandedBits(Op0, 
5001                              isSignBit ? APInt::getSignBit(BitWidth)
5002                                        : APInt::getAllOnesValue(BitWidth),
5003                              KnownZero, KnownOne, 0))
5004       return &I;
5005         
5006     // Given the known and unknown bits, compute a range that the LHS could be
5007     // in.
5008     if ((KnownOne | KnownZero) != 0) {
5009       // Compute the Min, Max and RHS values based on the known bits. For the
5010       // EQ and NE we use unsigned values.
5011       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5012       const APInt& RHSVal = CI->getValue();
5013       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5014         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5015                                                Max);
5016       } else {
5017         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5018                                                  Max);
5019       }
5020       switch (I.getPredicate()) {  // LE/GE have been folded already.
5021       default: assert(0 && "Unknown icmp opcode!");
5022       case ICmpInst::ICMP_EQ:
5023         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5024           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5025         break;
5026       case ICmpInst::ICMP_NE:
5027         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5028           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5029         break;
5030       case ICmpInst::ICMP_ULT:
5031         if (Max.ult(RHSVal))
5032           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5033         if (Min.uge(RHSVal))
5034           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5035         break;
5036       case ICmpInst::ICMP_UGT:
5037         if (Min.ugt(RHSVal))
5038           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5039         if (Max.ule(RHSVal))
5040           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5041         break;
5042       case ICmpInst::ICMP_SLT:
5043         if (Max.slt(RHSVal))
5044           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5045         if (Min.sgt(RHSVal))
5046           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5047         break;
5048       case ICmpInst::ICMP_SGT: 
5049         if (Min.sgt(RHSVal))
5050           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5051         if (Max.sle(RHSVal))
5052           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5053         break;
5054       }
5055     }
5056           
5057     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5058     // instruction, see if that instruction also has constants so that the 
5059     // instruction can be folded into the icmp 
5060     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5061       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5062         return Res;
5063   }
5064
5065   // Handle icmp with constant (but not simple integer constant) RHS
5066   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5067     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5068       switch (LHSI->getOpcode()) {
5069       case Instruction::GetElementPtr:
5070         if (RHSC->isNullValue()) {
5071           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5072           bool isAllZeros = true;
5073           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5074             if (!isa<Constant>(LHSI->getOperand(i)) ||
5075                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5076               isAllZeros = false;
5077               break;
5078             }
5079           if (isAllZeros)
5080             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5081                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5082         }
5083         break;
5084
5085       case Instruction::PHI:
5086         if (Instruction *NV = FoldOpIntoPhi(I))
5087           return NV;
5088         break;
5089       case Instruction::Select: {
5090         // If either operand of the select is a constant, we can fold the
5091         // comparison into the select arms, which will cause one to be
5092         // constant folded and the select turned into a bitwise or.
5093         Value *Op1 = 0, *Op2 = 0;
5094         if (LHSI->hasOneUse()) {
5095           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5096             // Fold the known value into the constant operand.
5097             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5098             // Insert a new ICmp of the other select operand.
5099             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5100                                                    LHSI->getOperand(2), RHSC,
5101                                                    I.getName()), I);
5102           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5103             // Fold the known value into the constant operand.
5104             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5105             // Insert a new ICmp of the other select operand.
5106             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5107                                                    LHSI->getOperand(1), RHSC,
5108                                                    I.getName()), I);
5109           }
5110         }
5111
5112         if (Op1)
5113           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5114         break;
5115       }
5116       case Instruction::Malloc:
5117         // If we have (malloc != null), and if the malloc has a single use, we
5118         // can assume it is successful and remove the malloc.
5119         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5120           AddToWorkList(LHSI);
5121           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5122                                                          !isTrueWhenEqual(I)));
5123         }
5124         break;
5125       }
5126   }
5127
5128   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5129   if (User *GEP = dyn_castGetElementPtr(Op0))
5130     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5131       return NI;
5132   if (User *GEP = dyn_castGetElementPtr(Op1))
5133     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5134                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5135       return NI;
5136
5137   // Test to see if the operands of the icmp are casted versions of other
5138   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5139   // now.
5140   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5141     if (isa<PointerType>(Op0->getType()) && 
5142         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5143       // We keep moving the cast from the left operand over to the right
5144       // operand, where it can often be eliminated completely.
5145       Op0 = CI->getOperand(0);
5146
5147       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5148       // so eliminate it as well.
5149       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5150         Op1 = CI2->getOperand(0);
5151
5152       // If Op1 is a constant, we can fold the cast into the constant.
5153       if (Op0->getType() != Op1->getType())
5154         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5155           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5156         } else {
5157           // Otherwise, cast the RHS right before the icmp
5158           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5159         }
5160       return new ICmpInst(I.getPredicate(), Op0, Op1);
5161     }
5162   }
5163   
5164   if (isa<CastInst>(Op0)) {
5165     // Handle the special case of: icmp (cast bool to X), <cst>
5166     // This comes up when you have code like
5167     //   int X = A < B;
5168     //   if (X) ...
5169     // For generality, we handle any zero-extension of any operand comparison
5170     // with a constant or another cast from the same type.
5171     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5172       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5173         return R;
5174   }
5175   
5176   if (I.isEquality()) {
5177     Value *A, *B, *C, *D;
5178     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5179       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5180         Value *OtherVal = A == Op1 ? B : A;
5181         return new ICmpInst(I.getPredicate(), OtherVal,
5182                             Constant::getNullValue(A->getType()));
5183       }
5184
5185       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5186         // A^c1 == C^c2 --> A == C^(c1^c2)
5187         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5188           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5189             if (Op1->hasOneUse()) {
5190               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5191               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5192               return new ICmpInst(I.getPredicate(), A,
5193                                   InsertNewInstBefore(Xor, I));
5194             }
5195         
5196         // A^B == A^D -> B == D
5197         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5198         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5199         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5200         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5201       }
5202     }
5203     
5204     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5205         (A == Op0 || B == Op0)) {
5206       // A == (A^B)  ->  B == 0
5207       Value *OtherVal = A == Op0 ? B : A;
5208       return new ICmpInst(I.getPredicate(), OtherVal,
5209                           Constant::getNullValue(A->getType()));
5210     }
5211     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5212       // (A-B) == A  ->  B == 0
5213       return new ICmpInst(I.getPredicate(), B,
5214                           Constant::getNullValue(B->getType()));
5215     }
5216     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5217       // A == (A-B)  ->  B == 0
5218       return new ICmpInst(I.getPredicate(), B,
5219                           Constant::getNullValue(B->getType()));
5220     }
5221     
5222     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5223     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5224         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5225         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5226       Value *X = 0, *Y = 0, *Z = 0;
5227       
5228       if (A == C) {
5229         X = B; Y = D; Z = A;
5230       } else if (A == D) {
5231         X = B; Y = C; Z = A;
5232       } else if (B == C) {
5233         X = A; Y = D; Z = B;
5234       } else if (B == D) {
5235         X = A; Y = C; Z = B;
5236       }
5237       
5238       if (X) {   // Build (X^Y) & Z
5239         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5240         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5241         I.setOperand(0, Op1);
5242         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5243         return &I;
5244       }
5245     }
5246   }
5247   return Changed ? &I : 0;
5248 }
5249
5250
5251 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5252 /// and CmpRHS are both known to be integer constants.
5253 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5254                                           ConstantInt *DivRHS) {
5255   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5256   const APInt &CmpRHSV = CmpRHS->getValue();
5257   
5258   // FIXME: If the operand types don't match the type of the divide 
5259   // then don't attempt this transform. The code below doesn't have the
5260   // logic to deal with a signed divide and an unsigned compare (and
5261   // vice versa). This is because (x /s C1) <s C2  produces different 
5262   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5263   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5264   // work. :(  The if statement below tests that condition and bails 
5265   // if it finds it. 
5266   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5267   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5268     return 0;
5269   if (DivRHS->isZero())
5270     return 0; // The ProdOV computation fails on divide by zero.
5271
5272   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5273   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5274   // C2 (CI). By solving for X we can turn this into a range check 
5275   // instead of computing a divide. 
5276   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5277
5278   // Determine if the product overflows by seeing if the product is
5279   // not equal to the divide. Make sure we do the same kind of divide
5280   // as in the LHS instruction that we're folding. 
5281   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5282                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5283
5284   // Get the ICmp opcode
5285   ICmpInst::Predicate Pred = ICI.getPredicate();
5286
5287   // Figure out the interval that is being checked.  For example, a comparison
5288   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5289   // Compute this interval based on the constants involved and the signedness of
5290   // the compare/divide.  This computes a half-open interval, keeping track of
5291   // whether either value in the interval overflows.  After analysis each
5292   // overflow variable is set to 0 if it's corresponding bound variable is valid
5293   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5294   int LoOverflow = 0, HiOverflow = 0;
5295   ConstantInt *LoBound = 0, *HiBound = 0;
5296   
5297   
5298   if (!DivIsSigned) {  // udiv
5299     // e.g. X/5 op 3  --> [15, 20)
5300     LoBound = Prod;
5301     HiOverflow = LoOverflow = ProdOV;
5302     if (!HiOverflow)
5303       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5304   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5305     if (CmpRHSV == 0) {       // (X / pos) op 0
5306       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5307       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5308       HiBound = DivRHS;
5309     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5310       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5311       HiOverflow = LoOverflow = ProdOV;
5312       if (!HiOverflow)
5313         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5314     } else {                       // (X / pos) op neg
5315       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5316       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5317       LoOverflow = AddWithOverflow(LoBound, Prod,
5318                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5319       HiBound = AddOne(Prod);
5320       HiOverflow = ProdOV ? -1 : 0;
5321     }
5322   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5323     if (CmpRHSV == 0) {       // (X / neg) op 0
5324       // e.g. X/-5 op 0  --> [-4, 5)
5325       LoBound = AddOne(DivRHS);
5326       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5327       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5328         HiOverflow = 1;            // [INTMIN+1, overflow)
5329         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5330       }
5331     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5332       // e.g. X/-5 op 3  --> [-19, -14)
5333       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5334       if (!LoOverflow)
5335         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5336       HiBound = AddOne(Prod);
5337     } else {                       // (X / neg) op neg
5338       // e.g. X/-5 op -3  --> [15, 20)
5339       LoBound = Prod;
5340       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5341       HiBound = Subtract(Prod, DivRHS);
5342     }
5343     
5344     // Dividing by a negative swaps the condition.  LT <-> GT
5345     Pred = ICmpInst::getSwappedPredicate(Pred);
5346   }
5347
5348   Value *X = DivI->getOperand(0);
5349   switch (Pred) {
5350   default: assert(0 && "Unhandled icmp opcode!");
5351   case ICmpInst::ICMP_EQ:
5352     if (LoOverflow && HiOverflow)
5353       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5354     else if (HiOverflow)
5355       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5356                           ICmpInst::ICMP_UGE, X, LoBound);
5357     else if (LoOverflow)
5358       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5359                           ICmpInst::ICMP_ULT, X, HiBound);
5360     else
5361       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5362   case ICmpInst::ICMP_NE:
5363     if (LoOverflow && HiOverflow)
5364       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5365     else if (HiOverflow)
5366       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5367                           ICmpInst::ICMP_ULT, X, LoBound);
5368     else if (LoOverflow)
5369       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5370                           ICmpInst::ICMP_UGE, X, HiBound);
5371     else
5372       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5373   case ICmpInst::ICMP_ULT:
5374   case ICmpInst::ICMP_SLT:
5375     if (LoOverflow == +1)   // Low bound is greater than input range.
5376       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5377     if (LoOverflow == -1)   // Low bound is less than input range.
5378       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5379     return new ICmpInst(Pred, X, LoBound);
5380   case ICmpInst::ICMP_UGT:
5381   case ICmpInst::ICMP_SGT:
5382     if (HiOverflow == +1)       // High bound greater than input range.
5383       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5384     else if (HiOverflow == -1)  // High bound less than input range.
5385       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5386     if (Pred == ICmpInst::ICMP_UGT)
5387       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5388     else
5389       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5390   }
5391 }
5392
5393
5394 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5395 ///
5396 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5397                                                           Instruction *LHSI,
5398                                                           ConstantInt *RHS) {
5399   const APInt &RHSV = RHS->getValue();
5400   
5401   switch (LHSI->getOpcode()) {
5402   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5403     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5404       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5405       // fold the xor.
5406       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5407           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5408         Value *CompareVal = LHSI->getOperand(0);
5409         
5410         // If the sign bit of the XorCST is not set, there is no change to
5411         // the operation, just stop using the Xor.
5412         if (!XorCST->getValue().isNegative()) {
5413           ICI.setOperand(0, CompareVal);
5414           AddToWorkList(LHSI);
5415           return &ICI;
5416         }
5417         
5418         // Was the old condition true if the operand is positive?
5419         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5420         
5421         // If so, the new one isn't.
5422         isTrueIfPositive ^= true;
5423         
5424         if (isTrueIfPositive)
5425           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5426         else
5427           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5428       }
5429     }
5430     break;
5431   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5432     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5433         LHSI->getOperand(0)->hasOneUse()) {
5434       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5435       
5436       // If the LHS is an AND of a truncating cast, we can widen the
5437       // and/compare to be the input width without changing the value
5438       // produced, eliminating a cast.
5439       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5440         // We can do this transformation if either the AND constant does not
5441         // have its sign bit set or if it is an equality comparison. 
5442         // Extending a relational comparison when we're checking the sign
5443         // bit would not work.
5444         if (Cast->hasOneUse() &&
5445             (ICI.isEquality() || AndCST->getValue().isNonNegative() && 
5446              RHSV.isNonNegative())) {
5447           uint32_t BitWidth = 
5448             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5449           APInt NewCST = AndCST->getValue();
5450           NewCST.zext(BitWidth);
5451           APInt NewCI = RHSV;
5452           NewCI.zext(BitWidth);
5453           Instruction *NewAnd = 
5454             BinaryOperator::createAnd(Cast->getOperand(0),
5455                                       ConstantInt::get(NewCST),LHSI->getName());
5456           InsertNewInstBefore(NewAnd, ICI);
5457           return new ICmpInst(ICI.getPredicate(), NewAnd,
5458                               ConstantInt::get(NewCI));
5459         }
5460       }
5461       
5462       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5463       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5464       // happens a LOT in code produced by the C front-end, for bitfield
5465       // access.
5466       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5467       if (Shift && !Shift->isShift())
5468         Shift = 0;
5469       
5470       ConstantInt *ShAmt;
5471       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5472       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5473       const Type *AndTy = AndCST->getType();          // Type of the and.
5474       
5475       // We can fold this as long as we can't shift unknown bits
5476       // into the mask.  This can only happen with signed shift
5477       // rights, as they sign-extend.
5478       if (ShAmt) {
5479         bool CanFold = Shift->isLogicalShift();
5480         if (!CanFold) {
5481           // To test for the bad case of the signed shr, see if any
5482           // of the bits shifted in could be tested after the mask.
5483           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5484           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5485           
5486           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5487           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5488                AndCST->getValue()) == 0)
5489             CanFold = true;
5490         }
5491         
5492         if (CanFold) {
5493           Constant *NewCst;
5494           if (Shift->getOpcode() == Instruction::Shl)
5495             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5496           else
5497             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5498           
5499           // Check to see if we are shifting out any of the bits being
5500           // compared.
5501           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5502             // If we shifted bits out, the fold is not going to work out.
5503             // As a special case, check to see if this means that the
5504             // result is always true or false now.
5505             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5506               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5507             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5508               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5509           } else {
5510             ICI.setOperand(1, NewCst);
5511             Constant *NewAndCST;
5512             if (Shift->getOpcode() == Instruction::Shl)
5513               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5514             else
5515               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5516             LHSI->setOperand(1, NewAndCST);
5517             LHSI->setOperand(0, Shift->getOperand(0));
5518             AddToWorkList(Shift); // Shift is dead.
5519             AddUsesToWorkList(ICI);
5520             return &ICI;
5521           }
5522         }
5523       }
5524       
5525       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5526       // preferable because it allows the C<<Y expression to be hoisted out
5527       // of a loop if Y is invariant and X is not.
5528       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5529           ICI.isEquality() && !Shift->isArithmeticShift() &&
5530           isa<Instruction>(Shift->getOperand(0))) {
5531         // Compute C << Y.
5532         Value *NS;
5533         if (Shift->getOpcode() == Instruction::LShr) {
5534           NS = BinaryOperator::createShl(AndCST, 
5535                                          Shift->getOperand(1), "tmp");
5536         } else {
5537           // Insert a logical shift.
5538           NS = BinaryOperator::createLShr(AndCST,
5539                                           Shift->getOperand(1), "tmp");
5540         }
5541         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5542         
5543         // Compute X & (C << Y).
5544         Instruction *NewAnd = 
5545           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5546         InsertNewInstBefore(NewAnd, ICI);
5547         
5548         ICI.setOperand(0, NewAnd);
5549         return &ICI;
5550       }
5551     }
5552     break;
5553     
5554   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5555     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5556     if (!ShAmt) break;
5557     
5558     uint32_t TypeBits = RHSV.getBitWidth();
5559     
5560     // Check that the shift amount is in range.  If not, don't perform
5561     // undefined shifts.  When the shift is visited it will be
5562     // simplified.
5563     if (ShAmt->uge(TypeBits))
5564       break;
5565     
5566     if (ICI.isEquality()) {
5567       // If we are comparing against bits always shifted out, the
5568       // comparison cannot succeed.
5569       Constant *Comp =
5570         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5571       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5572         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5573         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5574         return ReplaceInstUsesWith(ICI, Cst);
5575       }
5576       
5577       if (LHSI->hasOneUse()) {
5578         // Otherwise strength reduce the shift into an and.
5579         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5580         Constant *Mask =
5581           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5582         
5583         Instruction *AndI =
5584           BinaryOperator::createAnd(LHSI->getOperand(0),
5585                                     Mask, LHSI->getName()+".mask");
5586         Value *And = InsertNewInstBefore(AndI, ICI);
5587         return new ICmpInst(ICI.getPredicate(), And,
5588                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5589       }
5590     }
5591     
5592     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5593     bool TrueIfSigned = false;
5594     if (LHSI->hasOneUse() &&
5595         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5596       // (X << 31) <s 0  --> (X&1) != 0
5597       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5598                                            (TypeBits-ShAmt->getZExtValue()-1));
5599       Instruction *AndI =
5600         BinaryOperator::createAnd(LHSI->getOperand(0),
5601                                   Mask, LHSI->getName()+".mask");
5602       Value *And = InsertNewInstBefore(AndI, ICI);
5603       
5604       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5605                           And, Constant::getNullValue(And->getType()));
5606     }
5607     break;
5608   }
5609     
5610   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5611   case Instruction::AShr: {
5612     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5613     if (!ShAmt) break;
5614
5615     if (ICI.isEquality()) {
5616       // Check that the shift amount is in range.  If not, don't perform
5617       // undefined shifts.  When the shift is visited it will be
5618       // simplified.
5619       uint32_t TypeBits = RHSV.getBitWidth();
5620       if (ShAmt->uge(TypeBits))
5621         break;
5622       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5623       
5624       // If we are comparing against bits always shifted out, the
5625       // comparison cannot succeed.
5626       APInt Comp = RHSV << ShAmtVal;
5627       if (LHSI->getOpcode() == Instruction::LShr)
5628         Comp = Comp.lshr(ShAmtVal);
5629       else
5630         Comp = Comp.ashr(ShAmtVal);
5631       
5632       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5633         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5634         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5635         return ReplaceInstUsesWith(ICI, Cst);
5636       }
5637       
5638       if (LHSI->hasOneUse() || RHSV == 0) {
5639         // Otherwise strength reduce the shift into an and.
5640         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5641         Constant *Mask = ConstantInt::get(Val);
5642         
5643         Instruction *AndI =
5644           BinaryOperator::createAnd(LHSI->getOperand(0),
5645                                     Mask, LHSI->getName()+".mask");
5646         Value *And = InsertNewInstBefore(AndI, ICI);
5647         return new ICmpInst(ICI.getPredicate(), And,
5648                             ConstantExpr::getShl(RHS, ShAmt));
5649       }
5650     }
5651     break;
5652   }
5653     
5654   case Instruction::SDiv:
5655   case Instruction::UDiv:
5656     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5657     // Fold this div into the comparison, producing a range check. 
5658     // Determine, based on the divide type, what the range is being 
5659     // checked.  If there is an overflow on the low or high side, remember 
5660     // it, otherwise compute the range [low, hi) bounding the new value.
5661     // See: InsertRangeTest above for the kinds of replacements possible.
5662     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5663       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5664                                           DivRHS))
5665         return R;
5666     break;
5667
5668   case Instruction::Add:
5669     // Fold: icmp pred (add, X, C1), C2
5670
5671     if (!ICI.isEquality()) {
5672       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5673       if (!LHSC) break;
5674       const APInt &LHSV = LHSC->getValue();
5675
5676       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5677                             .subtract(LHSV);
5678
5679       if (ICI.isSignedPredicate()) {
5680         if (CR.getLower().isSignBit()) {
5681           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5682                               ConstantInt::get(CR.getUpper()));
5683         } else if (CR.getUpper().isSignBit()) {
5684           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5685                               ConstantInt::get(CR.getLower()));
5686         }
5687       } else {
5688         if (CR.getLower().isMinValue()) {
5689           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5690                               ConstantInt::get(CR.getUpper()));
5691         } else if (CR.getUpper().isMinValue()) {
5692           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5693                               ConstantInt::get(CR.getLower()));
5694         }
5695       }
5696     }
5697     break;
5698   }
5699   
5700   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5701   if (ICI.isEquality()) {
5702     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5703     
5704     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5705     // the second operand is a constant, simplify a bit.
5706     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5707       switch (BO->getOpcode()) {
5708       case Instruction::SRem:
5709         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5710         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5711           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5712           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5713             Instruction *NewRem =
5714               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5715                                          BO->getName());
5716             InsertNewInstBefore(NewRem, ICI);
5717             return new ICmpInst(ICI.getPredicate(), NewRem, 
5718                                 Constant::getNullValue(BO->getType()));
5719           }
5720         }
5721         break;
5722       case Instruction::Add:
5723         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5724         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5725           if (BO->hasOneUse())
5726             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5727                                 Subtract(RHS, BOp1C));
5728         } else if (RHSV == 0) {
5729           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5730           // efficiently invertible, or if the add has just this one use.
5731           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5732           
5733           if (Value *NegVal = dyn_castNegVal(BOp1))
5734             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5735           else if (Value *NegVal = dyn_castNegVal(BOp0))
5736             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5737           else if (BO->hasOneUse()) {
5738             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5739             InsertNewInstBefore(Neg, ICI);
5740             Neg->takeName(BO);
5741             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5742           }
5743         }
5744         break;
5745       case Instruction::Xor:
5746         // For the xor case, we can xor two constants together, eliminating
5747         // the explicit xor.
5748         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5749           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5750                               ConstantExpr::getXor(RHS, BOC));
5751         
5752         // FALLTHROUGH
5753       case Instruction::Sub:
5754         // Replace (([sub|xor] A, B) != 0) with (A != B)
5755         if (RHSV == 0)
5756           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5757                               BO->getOperand(1));
5758         break;
5759         
5760       case Instruction::Or:
5761         // If bits are being or'd in that are not present in the constant we
5762         // are comparing against, then the comparison could never succeed!
5763         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5764           Constant *NotCI = ConstantExpr::getNot(RHS);
5765           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5766             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5767                                                              isICMP_NE));
5768         }
5769         break;
5770         
5771       case Instruction::And:
5772         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5773           // If bits are being compared against that are and'd out, then the
5774           // comparison can never succeed!
5775           if ((RHSV & ~BOC->getValue()) != 0)
5776             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5777                                                              isICMP_NE));
5778           
5779           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5780           if (RHS == BOC && RHSV.isPowerOf2())
5781             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5782                                 ICmpInst::ICMP_NE, LHSI,
5783                                 Constant::getNullValue(RHS->getType()));
5784           
5785           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5786           if (isSignBit(BOC)) {
5787             Value *X = BO->getOperand(0);
5788             Constant *Zero = Constant::getNullValue(X->getType());
5789             ICmpInst::Predicate pred = isICMP_NE ? 
5790               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5791             return new ICmpInst(pred, X, Zero);
5792           }
5793           
5794           // ((X & ~7) == 0) --> X < 8
5795           if (RHSV == 0 && isHighOnes(BOC)) {
5796             Value *X = BO->getOperand(0);
5797             Constant *NegX = ConstantExpr::getNeg(BOC);
5798             ICmpInst::Predicate pred = isICMP_NE ? 
5799               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5800             return new ICmpInst(pred, X, NegX);
5801           }
5802         }
5803       default: break;
5804       }
5805     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5806       // Handle icmp {eq|ne} <intrinsic>, intcst.
5807       if (II->getIntrinsicID() == Intrinsic::bswap) {
5808         AddToWorkList(II);
5809         ICI.setOperand(0, II->getOperand(1));
5810         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5811         return &ICI;
5812       }
5813     }
5814   } else {  // Not a ICMP_EQ/ICMP_NE
5815             // If the LHS is a cast from an integral value of the same size, 
5816             // then since we know the RHS is a constant, try to simlify.
5817     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5818       Value *CastOp = Cast->getOperand(0);
5819       const Type *SrcTy = CastOp->getType();
5820       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5821       if (SrcTy->isInteger() && 
5822           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5823         // If this is an unsigned comparison, try to make the comparison use
5824         // smaller constant values.
5825         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5826           // X u< 128 => X s> -1
5827           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5828                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5829         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5830                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5831           // X u> 127 => X s< 0
5832           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5833                               Constant::getNullValue(SrcTy));
5834         }
5835       }
5836     }
5837   }
5838   return 0;
5839 }
5840
5841 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5842 /// We only handle extending casts so far.
5843 ///
5844 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5845   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5846   Value *LHSCIOp        = LHSCI->getOperand(0);
5847   const Type *SrcTy     = LHSCIOp->getType();
5848   const Type *DestTy    = LHSCI->getType();
5849   Value *RHSCIOp;
5850
5851   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5852   // integer type is the same size as the pointer type.
5853   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5854       getTargetData().getPointerSizeInBits() == 
5855          cast<IntegerType>(DestTy)->getBitWidth()) {
5856     Value *RHSOp = 0;
5857     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5858       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5859     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5860       RHSOp = RHSC->getOperand(0);
5861       // If the pointer types don't match, insert a bitcast.
5862       if (LHSCIOp->getType() != RHSOp->getType())
5863         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
5864     }
5865
5866     if (RHSOp)
5867       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5868   }
5869   
5870   // The code below only handles extension cast instructions, so far.
5871   // Enforce this.
5872   if (LHSCI->getOpcode() != Instruction::ZExt &&
5873       LHSCI->getOpcode() != Instruction::SExt)
5874     return 0;
5875
5876   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5877   bool isSignedCmp = ICI.isSignedPredicate();
5878
5879   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5880     // Not an extension from the same type?
5881     RHSCIOp = CI->getOperand(0);
5882     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5883       return 0;
5884     
5885     // If the signedness of the two casts doesn't agree (i.e. one is a sext
5886     // and the other is a zext), then we can't handle this.
5887     if (CI->getOpcode() != LHSCI->getOpcode())
5888       return 0;
5889
5890     // Deal with equality cases early.
5891     if (ICI.isEquality())
5892       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5893
5894     // A signed comparison of sign extended values simplifies into a
5895     // signed comparison.
5896     if (isSignedCmp && isSignedExt)
5897       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5898
5899     // The other three cases all fold into an unsigned comparison.
5900     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
5901   }
5902
5903   // If we aren't dealing with a constant on the RHS, exit early
5904   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5905   if (!CI)
5906     return 0;
5907
5908   // Compute the constant that would happen if we truncated to SrcTy then
5909   // reextended to DestTy.
5910   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5911   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5912
5913   // If the re-extended constant didn't change...
5914   if (Res2 == CI) {
5915     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5916     // For example, we might have:
5917     //    %A = sext short %X to uint
5918     //    %B = icmp ugt uint %A, 1330
5919     // It is incorrect to transform this into 
5920     //    %B = icmp ugt short %X, 1330 
5921     // because %A may have negative value. 
5922     //
5923     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5924     // OR operation is EQ/NE.
5925     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5926       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5927     else
5928       return 0;
5929   }
5930
5931   // The re-extended constant changed so the constant cannot be represented 
5932   // in the shorter type. Consequently, we cannot emit a simple comparison.
5933
5934   // First, handle some easy cases. We know the result cannot be equal at this
5935   // point so handle the ICI.isEquality() cases
5936   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5937     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5938   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5939     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5940
5941   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5942   // should have been folded away previously and not enter in here.
5943   Value *Result;
5944   if (isSignedCmp) {
5945     // We're performing a signed comparison.
5946     if (cast<ConstantInt>(CI)->getValue().isNegative())
5947       Result = ConstantInt::getFalse();          // X < (small) --> false
5948     else
5949       Result = ConstantInt::getTrue();           // X < (large) --> true
5950   } else {
5951     // We're performing an unsigned comparison.
5952     if (isSignedExt) {
5953       // We're performing an unsigned comp with a sign extended value.
5954       // This is true if the input is >= 0. [aka >s -1]
5955       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5956       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5957                                    NegOne, ICI.getName()), ICI);
5958     } else {
5959       // Unsigned extend & unsigned compare -> always true.
5960       Result = ConstantInt::getTrue();
5961     }
5962   }
5963
5964   // Finally, return the value computed.
5965   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5966       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5967     return ReplaceInstUsesWith(ICI, Result);
5968   } else {
5969     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5970             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5971            "ICmp should be folded!");
5972     if (Constant *CI = dyn_cast<Constant>(Result))
5973       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5974     else
5975       return BinaryOperator::createNot(Result);
5976   }
5977 }
5978
5979 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5980   return commonShiftTransforms(I);
5981 }
5982
5983 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5984   return commonShiftTransforms(I);
5985 }
5986
5987 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5988   if (Instruction *R = commonShiftTransforms(I))
5989     return R;
5990   
5991   Value *Op0 = I.getOperand(0);
5992   
5993   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5994   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5995     if (CSI->isAllOnesValue())
5996       return ReplaceInstUsesWith(I, CSI);
5997   
5998   // See if we can turn a signed shr into an unsigned shr.
5999   if (MaskedValueIsZero(Op0, 
6000                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6001     return BinaryOperator::createLShr(Op0, I.getOperand(1));
6002   
6003   return 0;
6004 }
6005
6006 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6007   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6008   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6009
6010   // shl X, 0 == X and shr X, 0 == X
6011   // shl 0, X == 0 and shr 0, X == 0
6012   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6013       Op0 == Constant::getNullValue(Op0->getType()))
6014     return ReplaceInstUsesWith(I, Op0);
6015   
6016   if (isa<UndefValue>(Op0)) {            
6017     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6018       return ReplaceInstUsesWith(I, Op0);
6019     else                                    // undef << X -> 0, undef >>u X -> 0
6020       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6021   }
6022   if (isa<UndefValue>(Op1)) {
6023     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6024       return ReplaceInstUsesWith(I, Op0);          
6025     else                                     // X << undef, X >>u undef -> 0
6026       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6027   }
6028
6029   // Try to fold constant and into select arguments.
6030   if (isa<Constant>(Op0))
6031     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6032       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6033         return R;
6034
6035   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6036     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6037       return Res;
6038   return 0;
6039 }
6040
6041 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6042                                                BinaryOperator &I) {
6043   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6044
6045   // See if we can simplify any instructions used by the instruction whose sole 
6046   // purpose is to compute bits we don't care about.
6047   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6048   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6049   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6050                            KnownZero, KnownOne))
6051     return &I;
6052   
6053   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6054   // of a signed value.
6055   //
6056   if (Op1->uge(TypeBits)) {
6057     if (I.getOpcode() != Instruction::AShr)
6058       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6059     else {
6060       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6061       return &I;
6062     }
6063   }
6064   
6065   // ((X*C1) << C2) == (X * (C1 << C2))
6066   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6067     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6068       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6069         return BinaryOperator::createMul(BO->getOperand(0),
6070                                          ConstantExpr::getShl(BOOp, Op1));
6071   
6072   // Try to fold constant and into select arguments.
6073   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6074     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6075       return R;
6076   if (isa<PHINode>(Op0))
6077     if (Instruction *NV = FoldOpIntoPhi(I))
6078       return NV;
6079   
6080   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6081   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6082     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6083     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6084     // place.  Don't try to do this transformation in this case.  Also, we
6085     // require that the input operand is a shift-by-constant so that we have
6086     // confidence that the shifts will get folded together.  We could do this
6087     // xform in more cases, but it is unlikely to be profitable.
6088     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6089         isa<ConstantInt>(TrOp->getOperand(1))) {
6090       // Okay, we'll do this xform.  Make the shift of shift.
6091       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6092       Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6093                                                 I.getName());
6094       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6095
6096       // For logical shifts, the truncation has the effect of making the high
6097       // part of the register be zeros.  Emulate this by inserting an AND to
6098       // clear the top bits as needed.  This 'and' will usually be zapped by
6099       // other xforms later if dead.
6100       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6101       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6102       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6103       
6104       // The mask we constructed says what the trunc would do if occurring
6105       // between the shifts.  We want to know the effect *after* the second
6106       // shift.  We know that it is a logical shift by a constant, so adjust the
6107       // mask as appropriate.
6108       if (I.getOpcode() == Instruction::Shl)
6109         MaskV <<= Op1->getZExtValue();
6110       else {
6111         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6112         MaskV = MaskV.lshr(Op1->getZExtValue());
6113       }
6114
6115       Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6116                                                    TI->getName());
6117       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6118
6119       // Return the value truncated to the interesting size.
6120       return new TruncInst(And, I.getType());
6121     }
6122   }
6123   
6124   if (Op0->hasOneUse()) {
6125     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6126       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6127       Value *V1, *V2;
6128       ConstantInt *CC;
6129       switch (Op0BO->getOpcode()) {
6130         default: break;
6131         case Instruction::Add:
6132         case Instruction::And:
6133         case Instruction::Or:
6134         case Instruction::Xor: {
6135           // These operators commute.
6136           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6137           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6138               match(Op0BO->getOperand(1),
6139                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6140             Instruction *YS = BinaryOperator::createShl(
6141                                             Op0BO->getOperand(0), Op1,
6142                                             Op0BO->getName());
6143             InsertNewInstBefore(YS, I); // (Y << C)
6144             Instruction *X = 
6145               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6146                                      Op0BO->getOperand(1)->getName());
6147             InsertNewInstBefore(X, I);  // (X + (Y << C))
6148             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6149             return BinaryOperator::createAnd(X, ConstantInt::get(
6150                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6151           }
6152           
6153           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6154           Value *Op0BOOp1 = Op0BO->getOperand(1);
6155           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6156               match(Op0BOOp1, 
6157                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6158               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6159               V2 == Op1) {
6160             Instruction *YS = BinaryOperator::createShl(
6161                                                      Op0BO->getOperand(0), Op1,
6162                                                      Op0BO->getName());
6163             InsertNewInstBefore(YS, I); // (Y << C)
6164             Instruction *XM =
6165               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6166                                         V1->getName()+".mask");
6167             InsertNewInstBefore(XM, I); // X & (CC << C)
6168             
6169             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6170           }
6171         }
6172           
6173         // FALL THROUGH.
6174         case Instruction::Sub: {
6175           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6176           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6177               match(Op0BO->getOperand(0),
6178                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6179             Instruction *YS = BinaryOperator::createShl(
6180                                                      Op0BO->getOperand(1), Op1,
6181                                                      Op0BO->getName());
6182             InsertNewInstBefore(YS, I); // (Y << C)
6183             Instruction *X =
6184               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6185                                      Op0BO->getOperand(0)->getName());
6186             InsertNewInstBefore(X, I);  // (X + (Y << C))
6187             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6188             return BinaryOperator::createAnd(X, ConstantInt::get(
6189                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6190           }
6191           
6192           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6193           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6194               match(Op0BO->getOperand(0),
6195                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6196                           m_ConstantInt(CC))) && V2 == Op1 &&
6197               cast<BinaryOperator>(Op0BO->getOperand(0))
6198                   ->getOperand(0)->hasOneUse()) {
6199             Instruction *YS = BinaryOperator::createShl(
6200                                                      Op0BO->getOperand(1), Op1,
6201                                                      Op0BO->getName());
6202             InsertNewInstBefore(YS, I); // (Y << C)
6203             Instruction *XM =
6204               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6205                                         V1->getName()+".mask");
6206             InsertNewInstBefore(XM, I); // X & (CC << C)
6207             
6208             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6209           }
6210           
6211           break;
6212         }
6213       }
6214       
6215       
6216       // If the operand is an bitwise operator with a constant RHS, and the
6217       // shift is the only use, we can pull it out of the shift.
6218       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6219         bool isValid = true;     // Valid only for And, Or, Xor
6220         bool highBitSet = false; // Transform if high bit of constant set?
6221         
6222         switch (Op0BO->getOpcode()) {
6223           default: isValid = false; break;   // Do not perform transform!
6224           case Instruction::Add:
6225             isValid = isLeftShift;
6226             break;
6227           case Instruction::Or:
6228           case Instruction::Xor:
6229             highBitSet = false;
6230             break;
6231           case Instruction::And:
6232             highBitSet = true;
6233             break;
6234         }
6235         
6236         // If this is a signed shift right, and the high bit is modified
6237         // by the logical operation, do not perform the transformation.
6238         // The highBitSet boolean indicates the value of the high bit of
6239         // the constant which would cause it to be modified for this
6240         // operation.
6241         //
6242         if (isValid && I.getOpcode() == Instruction::AShr)
6243           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6244         
6245         if (isValid) {
6246           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6247           
6248           Instruction *NewShift =
6249             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6250           InsertNewInstBefore(NewShift, I);
6251           NewShift->takeName(Op0BO);
6252           
6253           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6254                                         NewRHS);
6255         }
6256       }
6257     }
6258   }
6259   
6260   // Find out if this is a shift of a shift by a constant.
6261   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6262   if (ShiftOp && !ShiftOp->isShift())
6263     ShiftOp = 0;
6264   
6265   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6266     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6267     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6268     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6269     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6270     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6271     Value *X = ShiftOp->getOperand(0);
6272     
6273     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6274     if (AmtSum > TypeBits)
6275       AmtSum = TypeBits;
6276     
6277     const IntegerType *Ty = cast<IntegerType>(I.getType());
6278     
6279     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6280     if (I.getOpcode() == ShiftOp->getOpcode()) {
6281       return BinaryOperator::create(I.getOpcode(), X,
6282                                     ConstantInt::get(Ty, AmtSum));
6283     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6284                I.getOpcode() == Instruction::AShr) {
6285       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6286       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6287     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6288                I.getOpcode() == Instruction::LShr) {
6289       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6290       Instruction *Shift =
6291         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6292       InsertNewInstBefore(Shift, I);
6293
6294       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6295       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6296     }
6297     
6298     // Okay, if we get here, one shift must be left, and the other shift must be
6299     // right.  See if the amounts are equal.
6300     if (ShiftAmt1 == ShiftAmt2) {
6301       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6302       if (I.getOpcode() == Instruction::Shl) {
6303         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6304         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6305       }
6306       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6307       if (I.getOpcode() == Instruction::LShr) {
6308         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6309         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6310       }
6311       // We can simplify ((X << C) >>s C) into a trunc + sext.
6312       // NOTE: we could do this for any C, but that would make 'unusual' integer
6313       // types.  For now, just stick to ones well-supported by the code
6314       // generators.
6315       const Type *SExtType = 0;
6316       switch (Ty->getBitWidth() - ShiftAmt1) {
6317       case 1  :
6318       case 8  :
6319       case 16 :
6320       case 32 :
6321       case 64 :
6322       case 128:
6323         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6324         break;
6325       default: break;
6326       }
6327       if (SExtType) {
6328         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6329         InsertNewInstBefore(NewTrunc, I);
6330         return new SExtInst(NewTrunc, Ty);
6331       }
6332       // Otherwise, we can't handle it yet.
6333     } else if (ShiftAmt1 < ShiftAmt2) {
6334       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6335       
6336       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6337       if (I.getOpcode() == Instruction::Shl) {
6338         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6339                ShiftOp->getOpcode() == Instruction::AShr);
6340         Instruction *Shift =
6341           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6342         InsertNewInstBefore(Shift, I);
6343         
6344         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6345         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6346       }
6347       
6348       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6349       if (I.getOpcode() == Instruction::LShr) {
6350         assert(ShiftOp->getOpcode() == Instruction::Shl);
6351         Instruction *Shift =
6352           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6353         InsertNewInstBefore(Shift, I);
6354         
6355         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6356         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6357       }
6358       
6359       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6360     } else {
6361       assert(ShiftAmt2 < ShiftAmt1);
6362       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6363
6364       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6365       if (I.getOpcode() == Instruction::Shl) {
6366         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6367                ShiftOp->getOpcode() == Instruction::AShr);
6368         Instruction *Shift =
6369           BinaryOperator::create(ShiftOp->getOpcode(), X,
6370                                  ConstantInt::get(Ty, ShiftDiff));
6371         InsertNewInstBefore(Shift, I);
6372         
6373         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6374         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6375       }
6376       
6377       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6378       if (I.getOpcode() == Instruction::LShr) {
6379         assert(ShiftOp->getOpcode() == Instruction::Shl);
6380         Instruction *Shift =
6381           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6382         InsertNewInstBefore(Shift, I);
6383         
6384         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6385         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6386       }
6387       
6388       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6389     }
6390   }
6391   return 0;
6392 }
6393
6394
6395 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6396 /// expression.  If so, decompose it, returning some value X, such that Val is
6397 /// X*Scale+Offset.
6398 ///
6399 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6400                                         int &Offset) {
6401   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6402   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6403     Offset = CI->getZExtValue();
6404     Scale  = 0;
6405     return ConstantInt::get(Type::Int32Ty, 0);
6406   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6407     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6408       if (I->getOpcode() == Instruction::Shl) {
6409         // This is a value scaled by '1 << the shift amt'.
6410         Scale = 1U << RHS->getZExtValue();
6411         Offset = 0;
6412         return I->getOperand(0);
6413       } else if (I->getOpcode() == Instruction::Mul) {
6414         // This value is scaled by 'RHS'.
6415         Scale = RHS->getZExtValue();
6416         Offset = 0;
6417         return I->getOperand(0);
6418       } else if (I->getOpcode() == Instruction::Add) {
6419         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6420         // where C1 is divisible by C2.
6421         unsigned SubScale;
6422         Value *SubVal = 
6423           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6424         Offset += RHS->getZExtValue();
6425         Scale = SubScale;
6426         return SubVal;
6427       }
6428     }
6429   }
6430
6431   // Otherwise, we can't look past this.
6432   Scale = 1;
6433   Offset = 0;
6434   return Val;
6435 }
6436
6437
6438 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6439 /// try to eliminate the cast by moving the type information into the alloc.
6440 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6441                                                    AllocationInst &AI) {
6442   const PointerType *PTy = cast<PointerType>(CI.getType());
6443   
6444   // Remove any uses of AI that are dead.
6445   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6446   
6447   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6448     Instruction *User = cast<Instruction>(*UI++);
6449     if (isInstructionTriviallyDead(User)) {
6450       while (UI != E && *UI == User)
6451         ++UI; // If this instruction uses AI more than once, don't break UI.
6452       
6453       ++NumDeadInst;
6454       DOUT << "IC: DCE: " << *User;
6455       EraseInstFromFunction(*User);
6456     }
6457   }
6458   
6459   // Get the type really allocated and the type casted to.
6460   const Type *AllocElTy = AI.getAllocatedType();
6461   const Type *CastElTy = PTy->getElementType();
6462   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6463
6464   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6465   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6466   if (CastElTyAlign < AllocElTyAlign) return 0;
6467
6468   // If the allocation has multiple uses, only promote it if we are strictly
6469   // increasing the alignment of the resultant allocation.  If we keep it the
6470   // same, we open the door to infinite loops of various kinds.
6471   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6472
6473   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6474   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6475   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6476
6477   // See if we can satisfy the modulus by pulling a scale out of the array
6478   // size argument.
6479   unsigned ArraySizeScale;
6480   int ArrayOffset;
6481   Value *NumElements = // See if the array size is a decomposable linear expr.
6482     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6483  
6484   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6485   // do the xform.
6486   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6487       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6488
6489   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6490   Value *Amt = 0;
6491   if (Scale == 1) {
6492     Amt = NumElements;
6493   } else {
6494     // If the allocation size is constant, form a constant mul expression
6495     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6496     if (isa<ConstantInt>(NumElements))
6497       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6498     // otherwise multiply the amount and the number of elements
6499     else if (Scale != 1) {
6500       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6501       Amt = InsertNewInstBefore(Tmp, AI);
6502     }
6503   }
6504   
6505   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6506     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6507     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6508     Amt = InsertNewInstBefore(Tmp, AI);
6509   }
6510   
6511   AllocationInst *New;
6512   if (isa<MallocInst>(AI))
6513     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6514   else
6515     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6516   InsertNewInstBefore(New, AI);
6517   New->takeName(&AI);
6518   
6519   // If the allocation has multiple uses, insert a cast and change all things
6520   // that used it to use the new cast.  This will also hack on CI, but it will
6521   // die soon.
6522   if (!AI.hasOneUse()) {
6523     AddUsesToWorkList(AI);
6524     // New is the allocation instruction, pointer typed. AI is the original
6525     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6526     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6527     InsertNewInstBefore(NewCast, AI);
6528     AI.replaceAllUsesWith(NewCast);
6529   }
6530   return ReplaceInstUsesWith(CI, New);
6531 }
6532
6533 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6534 /// and return it as type Ty without inserting any new casts and without
6535 /// changing the computed value.  This is used by code that tries to decide
6536 /// whether promoting or shrinking integer operations to wider or smaller types
6537 /// will allow us to eliminate a truncate or extend.
6538 ///
6539 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6540 /// extension operation if Ty is larger.
6541 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6542                                        unsigned CastOpc, int &NumCastsRemoved) {
6543   // We can always evaluate constants in another type.
6544   if (isa<ConstantInt>(V))
6545     return true;
6546   
6547   Instruction *I = dyn_cast<Instruction>(V);
6548   if (!I) return false;
6549   
6550   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6551   
6552   // If this is an extension or truncate, we can often eliminate it.
6553   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6554     // If this is a cast from the destination type, we can trivially eliminate
6555     // it, and this will remove a cast overall.
6556     if (I->getOperand(0)->getType() == Ty) {
6557       // If the first operand is itself a cast, and is eliminable, do not count
6558       // this as an eliminable cast.  We would prefer to eliminate those two
6559       // casts first.
6560       if (!isa<CastInst>(I->getOperand(0)))
6561         ++NumCastsRemoved;
6562       return true;
6563     }
6564   }
6565
6566   // We can't extend or shrink something that has multiple uses: doing so would
6567   // require duplicating the instruction in general, which isn't profitable.
6568   if (!I->hasOneUse()) return false;
6569
6570   switch (I->getOpcode()) {
6571   case Instruction::Add:
6572   case Instruction::Sub:
6573   case Instruction::And:
6574   case Instruction::Or:
6575   case Instruction::Xor:
6576     // These operators can all arbitrarily be extended or truncated.
6577     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6578                                       NumCastsRemoved) &&
6579            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6580                                       NumCastsRemoved);
6581
6582   case Instruction::Mul:
6583     // A multiply can be truncated by truncating its operands.
6584     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6585            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6586                                       NumCastsRemoved) &&
6587            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6588                                       NumCastsRemoved);
6589
6590   case Instruction::Shl:
6591     // If we are truncating the result of this SHL, and if it's a shift of a
6592     // constant amount, we can always perform a SHL in a smaller type.
6593     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6594       uint32_t BitWidth = Ty->getBitWidth();
6595       if (BitWidth < OrigTy->getBitWidth() && 
6596           CI->getLimitedValue(BitWidth) < BitWidth)
6597         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6598                                           NumCastsRemoved);
6599     }
6600     break;
6601   case Instruction::LShr:
6602     // If this is a truncate of a logical shr, we can truncate it to a smaller
6603     // lshr iff we know that the bits we would otherwise be shifting in are
6604     // already zeros.
6605     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6606       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6607       uint32_t BitWidth = Ty->getBitWidth();
6608       if (BitWidth < OrigBitWidth &&
6609           MaskedValueIsZero(I->getOperand(0),
6610             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6611           CI->getLimitedValue(BitWidth) < BitWidth) {
6612         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6613                                           NumCastsRemoved);
6614       }
6615     }
6616     break;
6617   case Instruction::ZExt:
6618   case Instruction::SExt:
6619   case Instruction::Trunc:
6620     // If this is the same kind of case as our original (e.g. zext+zext), we
6621     // can safely replace it.  Note that replacing it does not reduce the number
6622     // of casts in the input.
6623     if (I->getOpcode() == CastOpc)
6624       return true;
6625     
6626     break;
6627   default:
6628     // TODO: Can handle more cases here.
6629     break;
6630   }
6631   
6632   return false;
6633 }
6634
6635 /// EvaluateInDifferentType - Given an expression that 
6636 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6637 /// evaluate the expression.
6638 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6639                                              bool isSigned) {
6640   if (Constant *C = dyn_cast<Constant>(V))
6641     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6642
6643   // Otherwise, it must be an instruction.
6644   Instruction *I = cast<Instruction>(V);
6645   Instruction *Res = 0;
6646   switch (I->getOpcode()) {
6647   case Instruction::Add:
6648   case Instruction::Sub:
6649   case Instruction::Mul:
6650   case Instruction::And:
6651   case Instruction::Or:
6652   case Instruction::Xor:
6653   case Instruction::AShr:
6654   case Instruction::LShr:
6655   case Instruction::Shl: {
6656     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6657     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6658     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6659                                  LHS, RHS, I->getName());
6660     break;
6661   }    
6662   case Instruction::Trunc:
6663   case Instruction::ZExt:
6664   case Instruction::SExt:
6665     // If the source type of the cast is the type we're trying for then we can
6666     // just return the source.  There's no need to insert it because it is not
6667     // new.
6668     if (I->getOperand(0)->getType() == Ty)
6669       return I->getOperand(0);
6670     
6671     // Otherwise, must be the same type of case, so just reinsert a new one.
6672     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6673                            Ty, I->getName());
6674     break;
6675   default: 
6676     // TODO: Can handle more cases here.
6677     assert(0 && "Unreachable!");
6678     break;
6679   }
6680   
6681   return InsertNewInstBefore(Res, *I);
6682 }
6683
6684 /// @brief Implement the transforms common to all CastInst visitors.
6685 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6686   Value *Src = CI.getOperand(0);
6687
6688   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6689   // eliminate it now.
6690   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6691     if (Instruction::CastOps opc = 
6692         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6693       // The first cast (CSrc) is eliminable so we need to fix up or replace
6694       // the second cast (CI). CSrc will then have a good chance of being dead.
6695       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6696     }
6697   }
6698
6699   // If we are casting a select then fold the cast into the select
6700   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6701     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6702       return NV;
6703
6704   // If we are casting a PHI then fold the cast into the PHI
6705   if (isa<PHINode>(Src))
6706     if (Instruction *NV = FoldOpIntoPhi(CI))
6707       return NV;
6708   
6709   return 0;
6710 }
6711
6712 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6713 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6714   Value *Src = CI.getOperand(0);
6715   
6716   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6717     // If casting the result of a getelementptr instruction with no offset, turn
6718     // this into a cast of the original pointer!
6719     if (GEP->hasAllZeroIndices()) {
6720       // Changing the cast operand is usually not a good idea but it is safe
6721       // here because the pointer operand is being replaced with another 
6722       // pointer operand so the opcode doesn't need to change.
6723       AddToWorkList(GEP);
6724       CI.setOperand(0, GEP->getOperand(0));
6725       return &CI;
6726     }
6727     
6728     // If the GEP has a single use, and the base pointer is a bitcast, and the
6729     // GEP computes a constant offset, see if we can convert these three
6730     // instructions into fewer.  This typically happens with unions and other
6731     // non-type-safe code.
6732     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6733       if (GEP->hasAllConstantIndices()) {
6734         // We are guaranteed to get a constant from EmitGEPOffset.
6735         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6736         int64_t Offset = OffsetV->getSExtValue();
6737         
6738         // Get the base pointer input of the bitcast, and the type it points to.
6739         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6740         const Type *GEPIdxTy =
6741           cast<PointerType>(OrigBase->getType())->getElementType();
6742         if (GEPIdxTy->isSized()) {
6743           SmallVector<Value*, 8> NewIndices;
6744           
6745           // Start with the index over the outer type.  Note that the type size
6746           // might be zero (even if the offset isn't zero) if the indexed type
6747           // is something like [0 x {int, int}]
6748           const Type *IntPtrTy = TD->getIntPtrType();
6749           int64_t FirstIdx = 0;
6750           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6751             FirstIdx = Offset/TySize;
6752             Offset %= TySize;
6753           
6754             // Handle silly modulus not returning values values [0..TySize).
6755             if (Offset < 0) {
6756               --FirstIdx;
6757               Offset += TySize;
6758               assert(Offset >= 0);
6759             }
6760             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6761           }
6762           
6763           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6764
6765           // Index into the types.  If we fail, set OrigBase to null.
6766           while (Offset) {
6767             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6768               const StructLayout *SL = TD->getStructLayout(STy);
6769               if (Offset < (int64_t)SL->getSizeInBytes()) {
6770                 unsigned Elt = SL->getElementContainingOffset(Offset);
6771                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6772               
6773                 Offset -= SL->getElementOffset(Elt);
6774                 GEPIdxTy = STy->getElementType(Elt);
6775               } else {
6776                 // Otherwise, we can't index into this, bail out.
6777                 Offset = 0;
6778                 OrigBase = 0;
6779               }
6780             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6781               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6782               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6783                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6784                 Offset %= EltSize;
6785               } else {
6786                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6787               }
6788               GEPIdxTy = STy->getElementType();
6789             } else {
6790               // Otherwise, we can't index into this, bail out.
6791               Offset = 0;
6792               OrigBase = 0;
6793             }
6794           }
6795           if (OrigBase) {
6796             // If we were able to index down into an element, create the GEP
6797             // and bitcast the result.  This eliminates one bitcast, potentially
6798             // two.
6799             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6800                                                       NewIndices.begin(),
6801                                                       NewIndices.end(), "");
6802             InsertNewInstBefore(NGEP, CI);
6803             NGEP->takeName(GEP);
6804             
6805             if (isa<BitCastInst>(CI))
6806               return new BitCastInst(NGEP, CI.getType());
6807             assert(isa<PtrToIntInst>(CI));
6808             return new PtrToIntInst(NGEP, CI.getType());
6809           }
6810         }
6811       }      
6812     }
6813   }
6814     
6815   return commonCastTransforms(CI);
6816 }
6817
6818
6819
6820 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6821 /// integer types. This function implements the common transforms for all those
6822 /// cases.
6823 /// @brief Implement the transforms common to CastInst with integer operands
6824 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6825   if (Instruction *Result = commonCastTransforms(CI))
6826     return Result;
6827
6828   Value *Src = CI.getOperand(0);
6829   const Type *SrcTy = Src->getType();
6830   const Type *DestTy = CI.getType();
6831   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6832   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6833
6834   // See if we can simplify any instructions used by the LHS whose sole 
6835   // purpose is to compute bits we don't care about.
6836   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6837   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6838                            KnownZero, KnownOne))
6839     return &CI;
6840
6841   // If the source isn't an instruction or has more than one use then we
6842   // can't do anything more. 
6843   Instruction *SrcI = dyn_cast<Instruction>(Src);
6844   if (!SrcI || !Src->hasOneUse())
6845     return 0;
6846
6847   // Attempt to propagate the cast into the instruction for int->int casts.
6848   int NumCastsRemoved = 0;
6849   if (!isa<BitCastInst>(CI) &&
6850       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6851                                  CI.getOpcode(), NumCastsRemoved)) {
6852     // If this cast is a truncate, evaluting in a different type always
6853     // eliminates the cast, so it is always a win.  If this is a zero-extension,
6854     // we need to do an AND to maintain the clear top-part of the computation,
6855     // so we require that the input have eliminated at least one cast.  If this
6856     // is a sign extension, we insert two new casts (to do the extension) so we
6857     // require that two casts have been eliminated.
6858     bool DoXForm;
6859     switch (CI.getOpcode()) {
6860     default:
6861       // All the others use floating point so we shouldn't actually 
6862       // get here because of the check above.
6863       assert(0 && "Unknown cast type");
6864     case Instruction::Trunc:
6865       DoXForm = true;
6866       break;
6867     case Instruction::ZExt:
6868       DoXForm = NumCastsRemoved >= 1;
6869       break;
6870     case Instruction::SExt:
6871       DoXForm = NumCastsRemoved >= 2;
6872       break;
6873     }
6874     
6875     if (DoXForm) {
6876       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6877                                            CI.getOpcode() == Instruction::SExt);
6878       assert(Res->getType() == DestTy);
6879       switch (CI.getOpcode()) {
6880       default: assert(0 && "Unknown cast type!");
6881       case Instruction::Trunc:
6882       case Instruction::BitCast:
6883         // Just replace this cast with the result.
6884         return ReplaceInstUsesWith(CI, Res);
6885       case Instruction::ZExt: {
6886         // We need to emit an AND to clear the high bits.
6887         assert(SrcBitSize < DestBitSize && "Not a zext?");
6888         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6889                                                             SrcBitSize));
6890         return BinaryOperator::createAnd(Res, C);
6891       }
6892       case Instruction::SExt:
6893         // We need to emit a cast to truncate, then a cast to sext.
6894         return CastInst::create(Instruction::SExt,
6895             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6896                              CI), DestTy);
6897       }
6898     }
6899   }
6900   
6901   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6902   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6903
6904   switch (SrcI->getOpcode()) {
6905   case Instruction::Add:
6906   case Instruction::Mul:
6907   case Instruction::And:
6908   case Instruction::Or:
6909   case Instruction::Xor:
6910     // If we are discarding information, rewrite.
6911     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6912       // Don't insert two casts if they cannot be eliminated.  We allow 
6913       // two casts to be inserted if the sizes are the same.  This could 
6914       // only be converting signedness, which is a noop.
6915       if (DestBitSize == SrcBitSize || 
6916           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6917           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6918         Instruction::CastOps opcode = CI.getOpcode();
6919         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6920         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6921         return BinaryOperator::create(
6922             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6923       }
6924     }
6925
6926     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6927     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6928         SrcI->getOpcode() == Instruction::Xor &&
6929         Op1 == ConstantInt::getTrue() &&
6930         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6931       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6932       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6933     }
6934     break;
6935   case Instruction::SDiv:
6936   case Instruction::UDiv:
6937   case Instruction::SRem:
6938   case Instruction::URem:
6939     // If we are just changing the sign, rewrite.
6940     if (DestBitSize == SrcBitSize) {
6941       // Don't insert two casts if they cannot be eliminated.  We allow 
6942       // two casts to be inserted if the sizes are the same.  This could 
6943       // only be converting signedness, which is a noop.
6944       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6945           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6946         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6947                                               Op0, DestTy, SrcI);
6948         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6949                                               Op1, DestTy, SrcI);
6950         return BinaryOperator::create(
6951           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6952       }
6953     }
6954     break;
6955
6956   case Instruction::Shl:
6957     // Allow changing the sign of the source operand.  Do not allow 
6958     // changing the size of the shift, UNLESS the shift amount is a 
6959     // constant.  We must not change variable sized shifts to a smaller 
6960     // size, because it is undefined to shift more bits out than exist 
6961     // in the value.
6962     if (DestBitSize == SrcBitSize ||
6963         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6964       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6965           Instruction::BitCast : Instruction::Trunc);
6966       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6967       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6968       return BinaryOperator::createShl(Op0c, Op1c);
6969     }
6970     break;
6971   case Instruction::AShr:
6972     // If this is a signed shr, and if all bits shifted in are about to be
6973     // truncated off, turn it into an unsigned shr to allow greater
6974     // simplifications.
6975     if (DestBitSize < SrcBitSize &&
6976         isa<ConstantInt>(Op1)) {
6977       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6978       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6979         // Insert the new logical shift right.
6980         return BinaryOperator::createLShr(Op0, Op1);
6981       }
6982     }
6983     break;
6984   }
6985   return 0;
6986 }
6987
6988 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6989   if (Instruction *Result = commonIntCastTransforms(CI))
6990     return Result;
6991   
6992   Value *Src = CI.getOperand(0);
6993   const Type *Ty = CI.getType();
6994   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6995   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6996   
6997   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6998     switch (SrcI->getOpcode()) {
6999     default: break;
7000     case Instruction::LShr:
7001       // We can shrink lshr to something smaller if we know the bits shifted in
7002       // are already zeros.
7003       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7004         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7005         
7006         // Get a mask for the bits shifting in.
7007         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7008         Value* SrcIOp0 = SrcI->getOperand(0);
7009         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7010           if (ShAmt >= DestBitWidth)        // All zeros.
7011             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7012
7013           // Okay, we can shrink this.  Truncate the input, then return a new
7014           // shift.
7015           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7016           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7017                                        Ty, CI);
7018           return BinaryOperator::createLShr(V1, V2);
7019         }
7020       } else {     // This is a variable shr.
7021         
7022         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7023         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7024         // loop-invariant and CSE'd.
7025         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7026           Value *One = ConstantInt::get(SrcI->getType(), 1);
7027
7028           Value *V = InsertNewInstBefore(
7029               BinaryOperator::createShl(One, SrcI->getOperand(1),
7030                                      "tmp"), CI);
7031           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7032                                                             SrcI->getOperand(0),
7033                                                             "tmp"), CI);
7034           Value *Zero = Constant::getNullValue(V->getType());
7035           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7036         }
7037       }
7038       break;
7039     }
7040   }
7041   
7042   return 0;
7043 }
7044
7045 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7046   // If one of the common conversion will work ..
7047   if (Instruction *Result = commonIntCastTransforms(CI))
7048     return Result;
7049
7050   Value *Src = CI.getOperand(0);
7051
7052   // If this is a cast of a cast
7053   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7054     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7055     // types and if the sizes are just right we can convert this into a logical
7056     // 'and' which will be much cheaper than the pair of casts.
7057     if (isa<TruncInst>(CSrc)) {
7058       // Get the sizes of the types involved
7059       Value *A = CSrc->getOperand(0);
7060       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7061       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7062       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7063       // If we're actually extending zero bits and the trunc is a no-op
7064       if (MidSize < DstSize && SrcSize == DstSize) {
7065         // Replace both of the casts with an And of the type mask.
7066         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7067         Constant *AndConst = ConstantInt::get(AndValue);
7068         Instruction *And = 
7069           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7070         // Unfortunately, if the type changed, we need to cast it back.
7071         if (And->getType() != CI.getType()) {
7072           And->setName(CSrc->getName()+".mask");
7073           InsertNewInstBefore(And, CI);
7074           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7075         }
7076         return And;
7077       }
7078     }
7079   }
7080
7081   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7082     // If we are just checking for a icmp eq of a single bit and zext'ing it
7083     // to an integer, then shift the bit to the appropriate place and then
7084     // cast to integer to avoid the comparison.
7085     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7086       const APInt &Op1CV = Op1C->getValue();
7087       
7088       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7089       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7090       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7091           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7092         Value *In = ICI->getOperand(0);
7093         Value *Sh = ConstantInt::get(In->getType(),
7094                                     In->getType()->getPrimitiveSizeInBits()-1);
7095         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7096                                                         In->getName()+".lobit"),
7097                                  CI);
7098         if (In->getType() != CI.getType())
7099           In = CastInst::createIntegerCast(In, CI.getType(),
7100                                            false/*ZExt*/, "tmp", &CI);
7101
7102         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7103           Constant *One = ConstantInt::get(In->getType(), 1);
7104           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7105                                                           In->getName()+".not"),
7106                                    CI);
7107         }
7108
7109         return ReplaceInstUsesWith(CI, In);
7110       }
7111       
7112       
7113       
7114       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7115       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7116       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7117       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7118       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7119       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7120       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7121       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7122       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7123           // This only works for EQ and NE
7124           ICI->isEquality()) {
7125         // If Op1C some other power of two, convert:
7126         uint32_t BitWidth = Op1C->getType()->getBitWidth();
7127         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7128         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7129         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7130         
7131         APInt KnownZeroMask(~KnownZero);
7132         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7133           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7134           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7135             // (X&4) == 2 --> false
7136             // (X&4) != 2 --> true
7137             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7138             Res = ConstantExpr::getZExt(Res, CI.getType());
7139             return ReplaceInstUsesWith(CI, Res);
7140           }
7141           
7142           uint32_t ShiftAmt = KnownZeroMask.logBase2();
7143           Value *In = ICI->getOperand(0);
7144           if (ShiftAmt) {
7145             // Perform a logical shr by shiftamt.
7146             // Insert the shift to put the result in the low bit.
7147             In = InsertNewInstBefore(
7148                    BinaryOperator::createLShr(In,
7149                                      ConstantInt::get(In->getType(), ShiftAmt),
7150                                               In->getName()+".lobit"), CI);
7151           }
7152           
7153           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7154             Constant *One = ConstantInt::get(In->getType(), 1);
7155             In = BinaryOperator::createXor(In, One, "tmp");
7156             InsertNewInstBefore(cast<Instruction>(In), CI);
7157           }
7158           
7159           if (CI.getType() == In->getType())
7160             return ReplaceInstUsesWith(CI, In);
7161           else
7162             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7163         }
7164       }
7165     }
7166   }    
7167   return 0;
7168 }
7169
7170 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7171   if (Instruction *I = commonIntCastTransforms(CI))
7172     return I;
7173   
7174   Value *Src = CI.getOperand(0);
7175   
7176   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7177   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7178   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7179     // If we are just checking for a icmp eq of a single bit and zext'ing it
7180     // to an integer, then shift the bit to the appropriate place and then
7181     // cast to integer to avoid the comparison.
7182     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7183       const APInt &Op1CV = Op1C->getValue();
7184       
7185       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7186       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7187       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7188           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7189         Value *In = ICI->getOperand(0);
7190         Value *Sh = ConstantInt::get(In->getType(),
7191                                      In->getType()->getPrimitiveSizeInBits()-1);
7192         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7193                                                         In->getName()+".lobit"),
7194                                  CI);
7195         if (In->getType() != CI.getType())
7196           In = CastInst::createIntegerCast(In, CI.getType(),
7197                                            true/*SExt*/, "tmp", &CI);
7198         
7199         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7200           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7201                                      In->getName()+".not"), CI);
7202         
7203         return ReplaceInstUsesWith(CI, In);
7204       }
7205     }
7206   }
7207       
7208   return 0;
7209 }
7210
7211 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7212 /// in the specified FP type without changing its value.
7213 static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy, 
7214                               const fltSemantics &Sem) {
7215   APFloat F = CFP->getValueAPF();
7216   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7217     return ConstantFP::get(FPTy, F);
7218   return 0;
7219 }
7220
7221 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7222 /// through it until we get the source value.
7223 static Value *LookThroughFPExtensions(Value *V) {
7224   if (Instruction *I = dyn_cast<Instruction>(V))
7225     if (I->getOpcode() == Instruction::FPExt)
7226       return LookThroughFPExtensions(I->getOperand(0));
7227   
7228   // If this value is a constant, return the constant in the smallest FP type
7229   // that can accurately represent it.  This allows us to turn
7230   // (float)((double)X+2.0) into x+2.0f.
7231   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7232     if (CFP->getType() == Type::PPC_FP128Ty)
7233       return V;  // No constant folding of this.
7234     // See if the value can be truncated to float and then reextended.
7235     if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7236       return V;
7237     if (CFP->getType() == Type::DoubleTy)
7238       return V;  // Won't shrink.
7239     if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7240       return V;
7241     // Don't try to shrink to various long double types.
7242   }
7243   
7244   return V;
7245 }
7246
7247 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7248   if (Instruction *I = commonCastTransforms(CI))
7249     return I;
7250   
7251   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7252   // smaller than the destination type, we can eliminate the truncate by doing
7253   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7254   // many builtins (sqrt, etc).
7255   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7256   if (OpI && OpI->hasOneUse()) {
7257     switch (OpI->getOpcode()) {
7258     default: break;
7259     case Instruction::Add:
7260     case Instruction::Sub:
7261     case Instruction::Mul:
7262     case Instruction::FDiv:
7263     case Instruction::FRem:
7264       const Type *SrcTy = OpI->getType();
7265       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7266       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7267       if (LHSTrunc->getType() != SrcTy && 
7268           RHSTrunc->getType() != SrcTy) {
7269         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7270         // If the source types were both smaller than the destination type of
7271         // the cast, do this xform.
7272         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7273             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7274           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7275                                       CI.getType(), CI);
7276           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7277                                       CI.getType(), CI);
7278           return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7279         }
7280       }
7281       break;  
7282     }
7283   }
7284   return 0;
7285 }
7286
7287 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7288   return commonCastTransforms(CI);
7289 }
7290
7291 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7292   return commonCastTransforms(CI);
7293 }
7294
7295 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7296   return commonCastTransforms(CI);
7297 }
7298
7299 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7300   return commonCastTransforms(CI);
7301 }
7302
7303 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7304   return commonCastTransforms(CI);
7305 }
7306
7307 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7308   return commonPointerCastTransforms(CI);
7309 }
7310
7311 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7312   if (Instruction *I = commonCastTransforms(CI))
7313     return I;
7314   
7315   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7316   if (!DestPointee->isSized()) return 0;
7317
7318   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7319   ConstantInt *Cst;
7320   Value *X;
7321   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7322                                     m_ConstantInt(Cst)))) {
7323     // If the source and destination operands have the same type, see if this
7324     // is a single-index GEP.
7325     if (X->getType() == CI.getType()) {
7326       // Get the size of the pointee type.
7327       uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7328
7329       // Convert the constant to intptr type.
7330       APInt Offset = Cst->getValue();
7331       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7332
7333       // If Offset is evenly divisible by Size, we can do this xform.
7334       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7335         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7336         return new GetElementPtrInst(X, ConstantInt::get(Offset));
7337       }
7338     }
7339     // TODO: Could handle other cases, e.g. where add is indexing into field of
7340     // struct etc.
7341   } else if (CI.getOperand(0)->hasOneUse() &&
7342              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7343     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7344     // "inttoptr+GEP" instead of "add+intptr".
7345     
7346     // Get the size of the pointee type.
7347     uint64_t Size = TD->getABITypeSize(DestPointee);
7348     
7349     // Convert the constant to intptr type.
7350     APInt Offset = Cst->getValue();
7351     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7352     
7353     // If Offset is evenly divisible by Size, we can do this xform.
7354     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7355       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7356       
7357       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7358                                                             "tmp"), CI);
7359       return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7360     }
7361   }
7362   return 0;
7363 }
7364
7365 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7366   // If the operands are integer typed then apply the integer transforms,
7367   // otherwise just apply the common ones.
7368   Value *Src = CI.getOperand(0);
7369   const Type *SrcTy = Src->getType();
7370   const Type *DestTy = CI.getType();
7371
7372   if (SrcTy->isInteger() && DestTy->isInteger()) {
7373     if (Instruction *Result = commonIntCastTransforms(CI))
7374       return Result;
7375   } else if (isa<PointerType>(SrcTy)) {
7376     if (Instruction *I = commonPointerCastTransforms(CI))
7377       return I;
7378   } else {
7379     if (Instruction *Result = commonCastTransforms(CI))
7380       return Result;
7381   }
7382
7383
7384   // Get rid of casts from one type to the same type. These are useless and can
7385   // be replaced by the operand.
7386   if (DestTy == Src->getType())
7387     return ReplaceInstUsesWith(CI, Src);
7388
7389   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7390     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7391     const Type *DstElTy = DstPTy->getElementType();
7392     const Type *SrcElTy = SrcPTy->getElementType();
7393     
7394     // If we are casting a malloc or alloca to a pointer to a type of the same
7395     // size, rewrite the allocation instruction to allocate the "right" type.
7396     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7397       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7398         return V;
7399     
7400     // If the source and destination are pointers, and this cast is equivalent
7401     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7402     // This can enhance SROA and other transforms that want type-safe pointers.
7403     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7404     unsigned NumZeros = 0;
7405     while (SrcElTy != DstElTy && 
7406            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7407            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7408       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7409       ++NumZeros;
7410     }
7411
7412     // If we found a path from the src to dest, create the getelementptr now.
7413     if (SrcElTy == DstElTy) {
7414       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7415       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7416                                    ((Instruction*) NULL));
7417     }
7418   }
7419
7420   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7421     if (SVI->hasOneUse()) {
7422       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7423       // a bitconvert to a vector with the same # elts.
7424       if (isa<VectorType>(DestTy) && 
7425           cast<VectorType>(DestTy)->getNumElements() == 
7426                 SVI->getType()->getNumElements()) {
7427         CastInst *Tmp;
7428         // If either of the operands is a cast from CI.getType(), then
7429         // evaluating the shuffle in the casted destination's type will allow
7430         // us to eliminate at least one cast.
7431         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7432              Tmp->getOperand(0)->getType() == DestTy) ||
7433             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7434              Tmp->getOperand(0)->getType() == DestTy)) {
7435           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7436                                                SVI->getOperand(0), DestTy, &CI);
7437           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7438                                                SVI->getOperand(1), DestTy, &CI);
7439           // Return a new shuffle vector.  Use the same element ID's, as we
7440           // know the vector types match #elts.
7441           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7442         }
7443       }
7444     }
7445   }
7446   return 0;
7447 }
7448
7449 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7450 ///   %C = or %A, %B
7451 ///   %D = select %cond, %C, %A
7452 /// into:
7453 ///   %C = select %cond, %B, 0
7454 ///   %D = or %A, %C
7455 ///
7456 /// Assuming that the specified instruction is an operand to the select, return
7457 /// a bitmask indicating which operands of this instruction are foldable if they
7458 /// equal the other incoming value of the select.
7459 ///
7460 static unsigned GetSelectFoldableOperands(Instruction *I) {
7461   switch (I->getOpcode()) {
7462   case Instruction::Add:
7463   case Instruction::Mul:
7464   case Instruction::And:
7465   case Instruction::Or:
7466   case Instruction::Xor:
7467     return 3;              // Can fold through either operand.
7468   case Instruction::Sub:   // Can only fold on the amount subtracted.
7469   case Instruction::Shl:   // Can only fold on the shift amount.
7470   case Instruction::LShr:
7471   case Instruction::AShr:
7472     return 1;
7473   default:
7474     return 0;              // Cannot fold
7475   }
7476 }
7477
7478 /// GetSelectFoldableConstant - For the same transformation as the previous
7479 /// function, return the identity constant that goes into the select.
7480 static Constant *GetSelectFoldableConstant(Instruction *I) {
7481   switch (I->getOpcode()) {
7482   default: assert(0 && "This cannot happen!"); abort();
7483   case Instruction::Add:
7484   case Instruction::Sub:
7485   case Instruction::Or:
7486   case Instruction::Xor:
7487   case Instruction::Shl:
7488   case Instruction::LShr:
7489   case Instruction::AShr:
7490     return Constant::getNullValue(I->getType());
7491   case Instruction::And:
7492     return Constant::getAllOnesValue(I->getType());
7493   case Instruction::Mul:
7494     return ConstantInt::get(I->getType(), 1);
7495   }
7496 }
7497
7498 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7499 /// have the same opcode and only one use each.  Try to simplify this.
7500 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7501                                           Instruction *FI) {
7502   if (TI->getNumOperands() == 1) {
7503     // If this is a non-volatile load or a cast from the same type,
7504     // merge.
7505     if (TI->isCast()) {
7506       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7507         return 0;
7508     } else {
7509       return 0;  // unknown unary op.
7510     }
7511
7512     // Fold this by inserting a select from the input values.
7513     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7514                                        FI->getOperand(0), SI.getName()+".v");
7515     InsertNewInstBefore(NewSI, SI);
7516     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7517                             TI->getType());
7518   }
7519
7520   // Only handle binary operators here.
7521   if (!isa<BinaryOperator>(TI))
7522     return 0;
7523
7524   // Figure out if the operations have any operands in common.
7525   Value *MatchOp, *OtherOpT, *OtherOpF;
7526   bool MatchIsOpZero;
7527   if (TI->getOperand(0) == FI->getOperand(0)) {
7528     MatchOp  = TI->getOperand(0);
7529     OtherOpT = TI->getOperand(1);
7530     OtherOpF = FI->getOperand(1);
7531     MatchIsOpZero = true;
7532   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7533     MatchOp  = TI->getOperand(1);
7534     OtherOpT = TI->getOperand(0);
7535     OtherOpF = FI->getOperand(0);
7536     MatchIsOpZero = false;
7537   } else if (!TI->isCommutative()) {
7538     return 0;
7539   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7540     MatchOp  = TI->getOperand(0);
7541     OtherOpT = TI->getOperand(1);
7542     OtherOpF = FI->getOperand(0);
7543     MatchIsOpZero = true;
7544   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7545     MatchOp  = TI->getOperand(1);
7546     OtherOpT = TI->getOperand(0);
7547     OtherOpF = FI->getOperand(1);
7548     MatchIsOpZero = true;
7549   } else {
7550     return 0;
7551   }
7552
7553   // If we reach here, they do have operations in common.
7554   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7555                                      OtherOpF, SI.getName()+".v");
7556   InsertNewInstBefore(NewSI, SI);
7557
7558   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7559     if (MatchIsOpZero)
7560       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7561     else
7562       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7563   }
7564   assert(0 && "Shouldn't get here");
7565   return 0;
7566 }
7567
7568 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7569   Value *CondVal = SI.getCondition();
7570   Value *TrueVal = SI.getTrueValue();
7571   Value *FalseVal = SI.getFalseValue();
7572
7573   // select true, X, Y  -> X
7574   // select false, X, Y -> Y
7575   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7576     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7577
7578   // select C, X, X -> X
7579   if (TrueVal == FalseVal)
7580     return ReplaceInstUsesWith(SI, TrueVal);
7581
7582   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7583     return ReplaceInstUsesWith(SI, FalseVal);
7584   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7585     return ReplaceInstUsesWith(SI, TrueVal);
7586   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7587     if (isa<Constant>(TrueVal))
7588       return ReplaceInstUsesWith(SI, TrueVal);
7589     else
7590       return ReplaceInstUsesWith(SI, FalseVal);
7591   }
7592
7593   if (SI.getType() == Type::Int1Ty) {
7594     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7595       if (C->getZExtValue()) {
7596         // Change: A = select B, true, C --> A = or B, C
7597         return BinaryOperator::createOr(CondVal, FalseVal);
7598       } else {
7599         // Change: A = select B, false, C --> A = and !B, C
7600         Value *NotCond =
7601           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7602                                              "not."+CondVal->getName()), SI);
7603         return BinaryOperator::createAnd(NotCond, FalseVal);
7604       }
7605     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7606       if (C->getZExtValue() == false) {
7607         // Change: A = select B, C, false --> A = and B, C
7608         return BinaryOperator::createAnd(CondVal, TrueVal);
7609       } else {
7610         // Change: A = select B, C, true --> A = or !B, C
7611         Value *NotCond =
7612           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7613                                              "not."+CondVal->getName()), SI);
7614         return BinaryOperator::createOr(NotCond, TrueVal);
7615       }
7616     }
7617     
7618     // select a, b, a  -> a&b
7619     // select a, a, b  -> a|b
7620     if (CondVal == TrueVal)
7621       return BinaryOperator::createOr(CondVal, FalseVal);
7622     else if (CondVal == FalseVal)
7623       return BinaryOperator::createAnd(CondVal, TrueVal);
7624   }
7625
7626   // Selecting between two integer constants?
7627   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7628     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7629       // select C, 1, 0 -> zext C to int
7630       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7631         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7632       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7633         // select C, 0, 1 -> zext !C to int
7634         Value *NotCond =
7635           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7636                                                "not."+CondVal->getName()), SI);
7637         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7638       }
7639       
7640       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7641
7642       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7643
7644         // (x <s 0) ? -1 : 0 -> ashr x, 31
7645         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7646           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7647             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7648               // The comparison constant and the result are not neccessarily the
7649               // same width. Make an all-ones value by inserting a AShr.
7650               Value *X = IC->getOperand(0);
7651               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7652               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7653               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7654                                                         ShAmt, "ones");
7655               InsertNewInstBefore(SRA, SI);
7656               
7657               // Finally, convert to the type of the select RHS.  We figure out
7658               // if this requires a SExt, Trunc or BitCast based on the sizes.
7659               Instruction::CastOps opc = Instruction::BitCast;
7660               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7661               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7662               if (SRASize < SISize)
7663                 opc = Instruction::SExt;
7664               else if (SRASize > SISize)
7665                 opc = Instruction::Trunc;
7666               return CastInst::create(opc, SRA, SI.getType());
7667             }
7668           }
7669
7670
7671         // If one of the constants is zero (we know they can't both be) and we
7672         // have an icmp instruction with zero, and we have an 'and' with the
7673         // non-constant value, eliminate this whole mess.  This corresponds to
7674         // cases like this: ((X & 27) ? 27 : 0)
7675         if (TrueValC->isZero() || FalseValC->isZero())
7676           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7677               cast<Constant>(IC->getOperand(1))->isNullValue())
7678             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7679               if (ICA->getOpcode() == Instruction::And &&
7680                   isa<ConstantInt>(ICA->getOperand(1)) &&
7681                   (ICA->getOperand(1) == TrueValC ||
7682                    ICA->getOperand(1) == FalseValC) &&
7683                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7684                 // Okay, now we know that everything is set up, we just don't
7685                 // know whether we have a icmp_ne or icmp_eq and whether the 
7686                 // true or false val is the zero.
7687                 bool ShouldNotVal = !TrueValC->isZero();
7688                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7689                 Value *V = ICA;
7690                 if (ShouldNotVal)
7691                   V = InsertNewInstBefore(BinaryOperator::create(
7692                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7693                 return ReplaceInstUsesWith(SI, V);
7694               }
7695       }
7696     }
7697
7698   // See if we are selecting two values based on a comparison of the two values.
7699   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7700     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7701       // Transform (X == Y) ? X : Y  -> Y
7702       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7703         // This is not safe in general for floating point:  
7704         // consider X== -0, Y== +0.
7705         // It becomes safe if either operand is a nonzero constant.
7706         ConstantFP *CFPt, *CFPf;
7707         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7708               !CFPt->getValueAPF().isZero()) ||
7709             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7710              !CFPf->getValueAPF().isZero()))
7711         return ReplaceInstUsesWith(SI, FalseVal);
7712       }
7713       // Transform (X != Y) ? X : Y  -> X
7714       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7715         return ReplaceInstUsesWith(SI, TrueVal);
7716       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7717
7718     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7719       // Transform (X == Y) ? Y : X  -> X
7720       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7721         // This is not safe in general for floating point:  
7722         // consider X== -0, Y== +0.
7723         // It becomes safe if either operand is a nonzero constant.
7724         ConstantFP *CFPt, *CFPf;
7725         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7726               !CFPt->getValueAPF().isZero()) ||
7727             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7728              !CFPf->getValueAPF().isZero()))
7729           return ReplaceInstUsesWith(SI, FalseVal);
7730       }
7731       // Transform (X != Y) ? Y : X  -> Y
7732       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7733         return ReplaceInstUsesWith(SI, TrueVal);
7734       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7735     }
7736   }
7737
7738   // See if we are selecting two values based on a comparison of the two values.
7739   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7740     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7741       // Transform (X == Y) ? X : Y  -> Y
7742       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7743         return ReplaceInstUsesWith(SI, FalseVal);
7744       // Transform (X != Y) ? X : Y  -> X
7745       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7746         return ReplaceInstUsesWith(SI, TrueVal);
7747       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7748
7749     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7750       // Transform (X == Y) ? Y : X  -> X
7751       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7752         return ReplaceInstUsesWith(SI, FalseVal);
7753       // Transform (X != Y) ? Y : X  -> Y
7754       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7755         return ReplaceInstUsesWith(SI, TrueVal);
7756       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7757     }
7758   }
7759
7760   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7761     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7762       if (TI->hasOneUse() && FI->hasOneUse()) {
7763         Instruction *AddOp = 0, *SubOp = 0;
7764
7765         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7766         if (TI->getOpcode() == FI->getOpcode())
7767           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7768             return IV;
7769
7770         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7771         // even legal for FP.
7772         if (TI->getOpcode() == Instruction::Sub &&
7773             FI->getOpcode() == Instruction::Add) {
7774           AddOp = FI; SubOp = TI;
7775         } else if (FI->getOpcode() == Instruction::Sub &&
7776                    TI->getOpcode() == Instruction::Add) {
7777           AddOp = TI; SubOp = FI;
7778         }
7779
7780         if (AddOp) {
7781           Value *OtherAddOp = 0;
7782           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7783             OtherAddOp = AddOp->getOperand(1);
7784           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7785             OtherAddOp = AddOp->getOperand(0);
7786           }
7787
7788           if (OtherAddOp) {
7789             // So at this point we know we have (Y -> OtherAddOp):
7790             //        select C, (add X, Y), (sub X, Z)
7791             Value *NegVal;  // Compute -Z
7792             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7793               NegVal = ConstantExpr::getNeg(C);
7794             } else {
7795               NegVal = InsertNewInstBefore(
7796                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7797             }
7798
7799             Value *NewTrueOp = OtherAddOp;
7800             Value *NewFalseOp = NegVal;
7801             if (AddOp != TI)
7802               std::swap(NewTrueOp, NewFalseOp);
7803             Instruction *NewSel =
7804               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7805
7806             NewSel = InsertNewInstBefore(NewSel, SI);
7807             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7808           }
7809         }
7810       }
7811
7812   // See if we can fold the select into one of our operands.
7813   if (SI.getType()->isInteger()) {
7814     // See the comment above GetSelectFoldableOperands for a description of the
7815     // transformation we are doing here.
7816     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7817       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7818           !isa<Constant>(FalseVal))
7819         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7820           unsigned OpToFold = 0;
7821           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7822             OpToFold = 1;
7823           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7824             OpToFold = 2;
7825           }
7826
7827           if (OpToFold) {
7828             Constant *C = GetSelectFoldableConstant(TVI);
7829             Instruction *NewSel =
7830               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7831             InsertNewInstBefore(NewSel, SI);
7832             NewSel->takeName(TVI);
7833             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7834               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7835             else {
7836               assert(0 && "Unknown instruction!!");
7837             }
7838           }
7839         }
7840
7841     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7842       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7843           !isa<Constant>(TrueVal))
7844         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7845           unsigned OpToFold = 0;
7846           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7847             OpToFold = 1;
7848           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7849             OpToFold = 2;
7850           }
7851
7852           if (OpToFold) {
7853             Constant *C = GetSelectFoldableConstant(FVI);
7854             Instruction *NewSel =
7855               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7856             InsertNewInstBefore(NewSel, SI);
7857             NewSel->takeName(FVI);
7858             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7859               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7860             else
7861               assert(0 && "Unknown instruction!!");
7862           }
7863         }
7864   }
7865
7866   if (BinaryOperator::isNot(CondVal)) {
7867     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7868     SI.setOperand(1, FalseVal);
7869     SI.setOperand(2, TrueVal);
7870     return &SI;
7871   }
7872
7873   return 0;
7874 }
7875
7876 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7877 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
7878 /// and it is more than the alignment of the ultimate object, see if we can
7879 /// increase the alignment of the ultimate object, making this check succeed.
7880 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7881                                            unsigned PrefAlign = 0) {
7882   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7883     unsigned Align = GV->getAlignment();
7884     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
7885       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7886
7887     // If there is a large requested alignment and we can, bump up the alignment
7888     // of the global.
7889     if (PrefAlign > Align && GV->hasInitializer()) {
7890       GV->setAlignment(PrefAlign);
7891       Align = PrefAlign;
7892     }
7893     return Align;
7894   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7895     unsigned Align = AI->getAlignment();
7896     if (Align == 0 && TD) {
7897       if (isa<AllocaInst>(AI))
7898         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7899       else if (isa<MallocInst>(AI)) {
7900         // Malloc returns maximally aligned memory.
7901         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7902         Align =
7903           std::max(Align,
7904                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7905         Align =
7906           std::max(Align,
7907                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7908       }
7909     }
7910     
7911     // If there is a requested alignment and if this is an alloca, round up.  We
7912     // don't do this for malloc, because some systems can't respect the request.
7913     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7914       AI->setAlignment(PrefAlign);
7915       Align = PrefAlign;
7916     }
7917     return Align;
7918   } else if (isa<BitCastInst>(V) ||
7919              (isa<ConstantExpr>(V) && 
7920               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7921     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7922                                       TD, PrefAlign);
7923   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7924     // If all indexes are zero, it is just the alignment of the base pointer.
7925     bool AllZeroOperands = true;
7926     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7927       if (!isa<Constant>(GEPI->getOperand(i)) ||
7928           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7929         AllZeroOperands = false;
7930         break;
7931       }
7932
7933     if (AllZeroOperands) {
7934       // Treat this like a bitcast.
7935       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7936     }
7937
7938     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7939     if (BaseAlignment == 0) return 0;
7940
7941     // Otherwise, if the base alignment is >= the alignment we expect for the
7942     // base pointer type, then we know that the resultant pointer is aligned at
7943     // least as much as its type requires.
7944     if (!TD) return 0;
7945
7946     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7947     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7948     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7949     if (Align <= BaseAlignment) {
7950       const Type *GEPTy = GEPI->getType();
7951       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7952       Align = std::min(Align, (unsigned)
7953                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7954       return Align;
7955     }
7956     return 0;
7957   }
7958   return 0;
7959 }
7960
7961 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7962   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7963   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7964   unsigned MinAlign = std::min(DstAlign, SrcAlign);
7965   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7966
7967   if (CopyAlign < MinAlign) {
7968     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7969     return MI;
7970   }
7971   
7972   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7973   // load/store.
7974   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7975   if (MemOpLength == 0) return 0;
7976   
7977   // Source and destination pointer types are always "i8*" for intrinsic.  See
7978   // if the size is something we can handle with a single primitive load/store.
7979   // A single load+store correctly handles overlapping memory in the memmove
7980   // case.
7981   unsigned Size = MemOpLength->getZExtValue();
7982   if (Size == 0 || Size > 8 || (Size&(Size-1)))
7983     return 0;  // If not 1/2/4/8 bytes, exit.
7984   
7985   // Use an integer load+store unless we can find something better.
7986   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
7987   
7988   // Memcpy forces the use of i8* for the source and destination.  That means
7989   // that if you're using memcpy to move one double around, you'll get a cast
7990   // from double* to i8*.  We'd much rather use a double load+store rather than
7991   // an i64 load+store, here because this improves the odds that the source or
7992   // dest address will be promotable.  See if we can find a better type than the
7993   // integer datatype.
7994   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
7995     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
7996     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
7997       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
7998       // down through these levels if so.
7999       while (!SrcETy->isFirstClassType()) {
8000         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8001           if (STy->getNumElements() == 1)
8002             SrcETy = STy->getElementType(0);
8003           else
8004             break;
8005         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8006           if (ATy->getNumElements() == 1)
8007             SrcETy = ATy->getElementType();
8008           else
8009             break;
8010         } else
8011           break;
8012       }
8013       
8014       if (SrcETy->isFirstClassType())
8015         NewPtrTy = PointerType::getUnqual(SrcETy);
8016     }
8017   }
8018   
8019   
8020   // If the memcpy/memmove provides better alignment info than we can
8021   // infer, use it.
8022   SrcAlign = std::max(SrcAlign, CopyAlign);
8023   DstAlign = std::max(DstAlign, CopyAlign);
8024   
8025   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8026   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8027   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8028   InsertNewInstBefore(L, *MI);
8029   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8030
8031   // Set the size of the copy to 0, it will be deleted on the next iteration.
8032   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8033   return MI;
8034 }
8035
8036 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8037 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8038 /// the heavy lifting.
8039 ///
8040 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8041   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8042   if (!II) return visitCallSite(&CI);
8043   
8044   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8045   // visitCallSite.
8046   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8047     bool Changed = false;
8048
8049     // memmove/cpy/set of zero bytes is a noop.
8050     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8051       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8052
8053       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8054         if (CI->getZExtValue() == 1) {
8055           // Replace the instruction with just byte operations.  We would
8056           // transform other cases to loads/stores, but we don't know if
8057           // alignment is sufficient.
8058         }
8059     }
8060
8061     // If we have a memmove and the source operation is a constant global,
8062     // then the source and dest pointers can't alias, so we can change this
8063     // into a call to memcpy.
8064     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8065       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8066         if (GVSrc->isConstant()) {
8067           Module *M = CI.getParent()->getParent()->getParent();
8068           Intrinsic::ID MemCpyID;
8069           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8070             MemCpyID = Intrinsic::memcpy_i32;
8071           else
8072             MemCpyID = Intrinsic::memcpy_i64;
8073           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8074           Changed = true;
8075         }
8076     }
8077
8078     // If we can determine a pointer alignment that is bigger than currently
8079     // set, update the alignment.
8080     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8081       if (Instruction *I = SimplifyMemTransfer(MI))
8082         return I;
8083     } else if (isa<MemSetInst>(MI)) {
8084       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
8085       if (MI->getAlignment()->getZExtValue() < Alignment) {
8086         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8087         Changed = true;
8088       }
8089     }
8090           
8091     if (Changed) return II;
8092   } else {
8093     switch (II->getIntrinsicID()) {
8094     default: break;
8095     case Intrinsic::ppc_altivec_lvx:
8096     case Intrinsic::ppc_altivec_lvxl:
8097     case Intrinsic::x86_sse_loadu_ps:
8098     case Intrinsic::x86_sse2_loadu_pd:
8099     case Intrinsic::x86_sse2_loadu_dq:
8100       // Turn PPC lvx     -> load if the pointer is known aligned.
8101       // Turn X86 loadups -> load if the pointer is known aligned.
8102       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8103         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8104                                          PointerType::getUnqual(II->getType()),
8105                                          CI);
8106         return new LoadInst(Ptr);
8107       }
8108       break;
8109     case Intrinsic::ppc_altivec_stvx:
8110     case Intrinsic::ppc_altivec_stvxl:
8111       // Turn stvx -> store if the pointer is known aligned.
8112       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
8113         const Type *OpPtrTy = 
8114           PointerType::getUnqual(II->getOperand(1)->getType());
8115         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8116         return new StoreInst(II->getOperand(1), Ptr);
8117       }
8118       break;
8119     case Intrinsic::x86_sse_storeu_ps:
8120     case Intrinsic::x86_sse2_storeu_pd:
8121     case Intrinsic::x86_sse2_storeu_dq:
8122     case Intrinsic::x86_sse2_storel_dq:
8123       // Turn X86 storeu -> store if the pointer is known aligned.
8124       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8125         const Type *OpPtrTy = 
8126           PointerType::getUnqual(II->getOperand(2)->getType());
8127         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8128         return new StoreInst(II->getOperand(2), Ptr);
8129       }
8130       break;
8131       
8132     case Intrinsic::x86_sse_cvttss2si: {
8133       // These intrinsics only demands the 0th element of its input vector.  If
8134       // we can simplify the input based on that, do so now.
8135       uint64_t UndefElts;
8136       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8137                                                 UndefElts)) {
8138         II->setOperand(1, V);
8139         return II;
8140       }
8141       break;
8142     }
8143       
8144     case Intrinsic::ppc_altivec_vperm:
8145       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8146       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8147         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8148         
8149         // Check that all of the elements are integer constants or undefs.
8150         bool AllEltsOk = true;
8151         for (unsigned i = 0; i != 16; ++i) {
8152           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8153               !isa<UndefValue>(Mask->getOperand(i))) {
8154             AllEltsOk = false;
8155             break;
8156           }
8157         }
8158         
8159         if (AllEltsOk) {
8160           // Cast the input vectors to byte vectors.
8161           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8162           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8163           Value *Result = UndefValue::get(Op0->getType());
8164           
8165           // Only extract each element once.
8166           Value *ExtractedElts[32];
8167           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8168           
8169           for (unsigned i = 0; i != 16; ++i) {
8170             if (isa<UndefValue>(Mask->getOperand(i)))
8171               continue;
8172             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8173             Idx &= 31;  // Match the hardware behavior.
8174             
8175             if (ExtractedElts[Idx] == 0) {
8176               Instruction *Elt = 
8177                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8178               InsertNewInstBefore(Elt, CI);
8179               ExtractedElts[Idx] = Elt;
8180             }
8181           
8182             // Insert this value into the result vector.
8183             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8184             InsertNewInstBefore(cast<Instruction>(Result), CI);
8185           }
8186           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8187         }
8188       }
8189       break;
8190
8191     case Intrinsic::stackrestore: {
8192       // If the save is right next to the restore, remove the restore.  This can
8193       // happen when variable allocas are DCE'd.
8194       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8195         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8196           BasicBlock::iterator BI = SS;
8197           if (&*++BI == II)
8198             return EraseInstFromFunction(CI);
8199         }
8200       }
8201       
8202       // Scan down this block to see if there is another stack restore in the
8203       // same block without an intervening call/alloca.
8204       BasicBlock::iterator BI = II;
8205       TerminatorInst *TI = II->getParent()->getTerminator();
8206       bool CannotRemove = false;
8207       for (++BI; &*BI != TI; ++BI) {
8208         if (isa<AllocaInst>(BI)) {
8209           CannotRemove = true;
8210           break;
8211         }
8212         if (isa<CallInst>(BI)) {
8213           if (!isa<IntrinsicInst>(BI)) {
8214             CannotRemove = true;
8215             break;
8216           }
8217           // If there is a stackrestore below this one, remove this one.
8218           return EraseInstFromFunction(CI);
8219         }
8220       }
8221       
8222       // If the stack restore is in a return/unwind block and if there are no
8223       // allocas or calls between the restore and the return, nuke the restore.
8224       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8225         return EraseInstFromFunction(CI);
8226       break;
8227     }
8228     }
8229   }
8230
8231   return visitCallSite(II);
8232 }
8233
8234 // InvokeInst simplification
8235 //
8236 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8237   return visitCallSite(&II);
8238 }
8239
8240 // visitCallSite - Improvements for call and invoke instructions.
8241 //
8242 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8243   bool Changed = false;
8244
8245   // If the callee is a constexpr cast of a function, attempt to move the cast
8246   // to the arguments of the call/invoke.
8247   if (transformConstExprCastCall(CS)) return 0;
8248
8249   Value *Callee = CS.getCalledValue();
8250
8251   if (Function *CalleeF = dyn_cast<Function>(Callee))
8252     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8253       Instruction *OldCall = CS.getInstruction();
8254       // If the call and callee calling conventions don't match, this call must
8255       // be unreachable, as the call is undefined.
8256       new StoreInst(ConstantInt::getTrue(),
8257                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8258                                     OldCall);
8259       if (!OldCall->use_empty())
8260         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8261       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8262         return EraseInstFromFunction(*OldCall);
8263       return 0;
8264     }
8265
8266   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8267     // This instruction is not reachable, just remove it.  We insert a store to
8268     // undef so that we know that this code is not reachable, despite the fact
8269     // that we can't modify the CFG here.
8270     new StoreInst(ConstantInt::getTrue(),
8271                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8272                   CS.getInstruction());
8273
8274     if (!CS.getInstruction()->use_empty())
8275       CS.getInstruction()->
8276         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8277
8278     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8279       // Don't break the CFG, insert a dummy cond branch.
8280       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8281                      ConstantInt::getTrue(), II);
8282     }
8283     return EraseInstFromFunction(*CS.getInstruction());
8284   }
8285
8286   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8287     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8288       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8289         return transformCallThroughTrampoline(CS);
8290
8291   const PointerType *PTy = cast<PointerType>(Callee->getType());
8292   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8293   if (FTy->isVarArg()) {
8294     // See if we can optimize any arguments passed through the varargs area of
8295     // the call.
8296     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8297            E = CS.arg_end(); I != E; ++I)
8298       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8299         // If this cast does not effect the value passed through the varargs
8300         // area, we can eliminate the use of the cast.
8301         Value *Op = CI->getOperand(0);
8302         if (CI->isLosslessCast()) {
8303           *I = Op;
8304           Changed = true;
8305         }
8306       }
8307   }
8308
8309   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8310     // Inline asm calls cannot throw - mark them 'nounwind'.
8311     CS.setDoesNotThrow();
8312     Changed = true;
8313   }
8314
8315   return Changed ? CS.getInstruction() : 0;
8316 }
8317
8318 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8319 // attempt to move the cast to the arguments of the call/invoke.
8320 //
8321 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8322   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8323   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8324   if (CE->getOpcode() != Instruction::BitCast || 
8325       !isa<Function>(CE->getOperand(0)))
8326     return false;
8327   Function *Callee = cast<Function>(CE->getOperand(0));
8328   Instruction *Caller = CS.getInstruction();
8329   const ParamAttrsList* CallerPAL = CS.getParamAttrs();
8330
8331   // Okay, this is a cast from a function to a different type.  Unless doing so
8332   // would cause a type conversion of one of our arguments, change this call to
8333   // be a direct call with arguments casted to the appropriate types.
8334   //
8335   const FunctionType *FT = Callee->getFunctionType();
8336   const Type *OldRetTy = Caller->getType();
8337
8338   // Check to see if we are changing the return type...
8339   if (OldRetTy != FT->getReturnType()) {
8340     if (Callee->isDeclaration() && !Caller->use_empty() && 
8341         // Conversion is ok if changing from pointer to int of same size.
8342         !(isa<PointerType>(FT->getReturnType()) &&
8343           TD->getIntPtrType() == OldRetTy))
8344       return false;   // Cannot transform this return value.
8345
8346     if (!Caller->use_empty() &&
8347         // void -> non-void is handled specially
8348         FT->getReturnType() != Type::VoidTy &&
8349         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8350       return false;   // Cannot transform this return value.
8351
8352     if (CallerPAL && !Caller->use_empty()) {
8353       uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8354       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8355         return false;   // Attribute not compatible with transformed value.
8356     }
8357
8358     // If the callsite is an invoke instruction, and the return value is used by
8359     // a PHI node in a successor, we cannot change the return type of the call
8360     // because there is no place to put the cast instruction (without breaking
8361     // the critical edge).  Bail out in this case.
8362     if (!Caller->use_empty())
8363       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8364         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8365              UI != E; ++UI)
8366           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8367             if (PN->getParent() == II->getNormalDest() ||
8368                 PN->getParent() == II->getUnwindDest())
8369               return false;
8370   }
8371
8372   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8373   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8374
8375   CallSite::arg_iterator AI = CS.arg_begin();
8376   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8377     const Type *ParamTy = FT->getParamType(i);
8378     const Type *ActTy = (*AI)->getType();
8379
8380     if (!CastInst::isCastable(ActTy, ParamTy))
8381       return false;   // Cannot transform this parameter value.
8382
8383     if (CallerPAL) {
8384       uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8385       if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8386         return false;   // Attribute not compatible with transformed value.
8387     }
8388
8389     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8390     // Some conversions are safe even if we do not have a body.
8391     // Either we can cast directly, or we can upconvert the argument
8392     bool isConvertible = ActTy == ParamTy ||
8393       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8394       (ParamTy->isInteger() && ActTy->isInteger() &&
8395        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8396       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8397        && c->getValue().isStrictlyPositive());
8398     if (Callee->isDeclaration() && !isConvertible) return false;
8399   }
8400
8401   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8402       Callee->isDeclaration())
8403     return false;   // Do not delete arguments unless we have a function body...
8404
8405   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
8406     // In this case we have more arguments than the new function type, but we
8407     // won't be dropping them.  Check that these extra arguments have attributes
8408     // that are compatible with being a vararg call argument.
8409     for (unsigned i = CallerPAL->size(); i; --i) {
8410       if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8411         break;
8412       uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8413       if (PAttrs & ParamAttr::VarArgsIncompatible)
8414         return false;
8415     }
8416
8417   // Okay, we decided that this is a safe thing to do: go ahead and start
8418   // inserting cast instructions as necessary...
8419   std::vector<Value*> Args;
8420   Args.reserve(NumActualArgs);
8421   ParamAttrsVector attrVec;
8422   attrVec.reserve(NumCommonArgs);
8423
8424   // Get any return attributes.
8425   uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8426
8427   // If the return value is not being used, the type may not be compatible
8428   // with the existing attributes.  Wipe out any problematic attributes.
8429   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
8430
8431   // Add the new return attributes.
8432   if (RAttrs)
8433     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8434
8435   AI = CS.arg_begin();
8436   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8437     const Type *ParamTy = FT->getParamType(i);
8438     if ((*AI)->getType() == ParamTy) {
8439       Args.push_back(*AI);
8440     } else {
8441       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8442           false, ParamTy, false);
8443       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8444       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8445     }
8446
8447     // Add any parameter attributes.
8448     uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8449     if (PAttrs)
8450       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8451   }
8452
8453   // If the function takes more arguments than the call was taking, add them
8454   // now...
8455   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8456     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8457
8458   // If we are removing arguments to the function, emit an obnoxious warning...
8459   if (FT->getNumParams() < NumActualArgs)
8460     if (!FT->isVarArg()) {
8461       cerr << "WARNING: While resolving call to function '"
8462            << Callee->getName() << "' arguments were dropped!\n";
8463     } else {
8464       // Add all of the arguments in their promoted form to the arg list...
8465       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8466         const Type *PTy = getPromotedType((*AI)->getType());
8467         if (PTy != (*AI)->getType()) {
8468           // Must promote to pass through va_arg area!
8469           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8470                                                                 PTy, false);
8471           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8472           InsertNewInstBefore(Cast, *Caller);
8473           Args.push_back(Cast);
8474         } else {
8475           Args.push_back(*AI);
8476         }
8477
8478         // Add any parameter attributes.
8479         uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8480         if (PAttrs)
8481           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8482       }
8483     }
8484
8485   if (FT->getReturnType() == Type::VoidTy)
8486     Caller->setName("");   // Void type should not have a name.
8487
8488   const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8489
8490   Instruction *NC;
8491   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8492     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8493                         Args.begin(), Args.end(), Caller->getName(), Caller);
8494     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8495     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8496   } else {
8497     NC = new CallInst(Callee, Args.begin(), Args.end(),
8498                       Caller->getName(), Caller);
8499     CallInst *CI = cast<CallInst>(Caller);
8500     if (CI->isTailCall())
8501       cast<CallInst>(NC)->setTailCall();
8502     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8503     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8504   }
8505
8506   // Insert a cast of the return type as necessary.
8507   Value *NV = NC;
8508   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8509     if (NV->getType() != Type::VoidTy) {
8510       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8511                                                             OldRetTy, false);
8512       NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
8513
8514       // If this is an invoke instruction, we should insert it after the first
8515       // non-phi, instruction in the normal successor block.
8516       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8517         BasicBlock::iterator I = II->getNormalDest()->begin();
8518         while (isa<PHINode>(I)) ++I;
8519         InsertNewInstBefore(NC, *I);
8520       } else {
8521         // Otherwise, it's a call, just insert cast right after the call instr
8522         InsertNewInstBefore(NC, *Caller);
8523       }
8524       AddUsersToWorkList(*Caller);
8525     } else {
8526       NV = UndefValue::get(Caller->getType());
8527     }
8528   }
8529
8530   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8531     Caller->replaceAllUsesWith(NV);
8532   Caller->eraseFromParent();
8533   RemoveFromWorkList(Caller);
8534   return true;
8535 }
8536
8537 // transformCallThroughTrampoline - Turn a call to a function created by the
8538 // init_trampoline intrinsic into a direct call to the underlying function.
8539 //
8540 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8541   Value *Callee = CS.getCalledValue();
8542   const PointerType *PTy = cast<PointerType>(Callee->getType());
8543   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8544   const ParamAttrsList *Attrs = CS.getParamAttrs();
8545
8546   // If the call already has the 'nest' attribute somewhere then give up -
8547   // otherwise 'nest' would occur twice after splicing in the chain.
8548   if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8549     return 0;
8550
8551   IntrinsicInst *Tramp =
8552     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8553
8554   Function *NestF =
8555     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8556   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8557   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8558
8559   if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
8560     unsigned NestIdx = 1;
8561     const Type *NestTy = 0;
8562     uint16_t NestAttr = 0;
8563
8564     // Look for a parameter marked with the 'nest' attribute.
8565     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8566          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8567       if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8568         // Record the parameter type and any other attributes.
8569         NestTy = *I;
8570         NestAttr = NestAttrs->getParamAttrs(NestIdx);
8571         break;
8572       }
8573
8574     if (NestTy) {
8575       Instruction *Caller = CS.getInstruction();
8576       std::vector<Value*> NewArgs;
8577       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8578
8579       ParamAttrsVector NewAttrs;
8580       NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8581
8582       // Insert the nest argument into the call argument list, which may
8583       // mean appending it.  Likewise for attributes.
8584
8585       // Add any function result attributes.
8586       uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8587       if (Attr)
8588         NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8589
8590       {
8591         unsigned Idx = 1;
8592         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8593         do {
8594           if (Idx == NestIdx) {
8595             // Add the chain argument and attributes.
8596             Value *NestVal = Tramp->getOperand(3);
8597             if (NestVal->getType() != NestTy)
8598               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8599             NewArgs.push_back(NestVal);
8600             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8601           }
8602
8603           if (I == E)
8604             break;
8605
8606           // Add the original argument and attributes.
8607           NewArgs.push_back(*I);
8608           Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8609           if (Attr)
8610             NewAttrs.push_back
8611               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8612
8613           ++Idx, ++I;
8614         } while (1);
8615       }
8616
8617       // The trampoline may have been bitcast to a bogus type (FTy).
8618       // Handle this by synthesizing a new function type, equal to FTy
8619       // with the chain parameter inserted.
8620
8621       std::vector<const Type*> NewTypes;
8622       NewTypes.reserve(FTy->getNumParams()+1);
8623
8624       // Insert the chain's type into the list of parameter types, which may
8625       // mean appending it.
8626       {
8627         unsigned Idx = 1;
8628         FunctionType::param_iterator I = FTy->param_begin(),
8629           E = FTy->param_end();
8630
8631         do {
8632           if (Idx == NestIdx)
8633             // Add the chain's type.
8634             NewTypes.push_back(NestTy);
8635
8636           if (I == E)
8637             break;
8638
8639           // Add the original type.
8640           NewTypes.push_back(*I);
8641
8642           ++Idx, ++I;
8643         } while (1);
8644       }
8645
8646       // Replace the trampoline call with a direct call.  Let the generic
8647       // code sort out any function type mismatches.
8648       FunctionType *NewFTy =
8649         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8650       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8651         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8652       const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
8653
8654       Instruction *NewCaller;
8655       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8656         NewCaller = new InvokeInst(NewCallee,
8657                                    II->getNormalDest(), II->getUnwindDest(),
8658                                    NewArgs.begin(), NewArgs.end(),
8659                                    Caller->getName(), Caller);
8660         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8661         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8662       } else {
8663         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8664                                  Caller->getName(), Caller);
8665         if (cast<CallInst>(Caller)->isTailCall())
8666           cast<CallInst>(NewCaller)->setTailCall();
8667         cast<CallInst>(NewCaller)->
8668           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8669         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8670       }
8671       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8672         Caller->replaceAllUsesWith(NewCaller);
8673       Caller->eraseFromParent();
8674       RemoveFromWorkList(Caller);
8675       return 0;
8676     }
8677   }
8678
8679   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8680   // parameter, there is no need to adjust the argument list.  Let the generic
8681   // code sort out any function type mismatches.
8682   Constant *NewCallee =
8683     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8684   CS.setCalledFunction(NewCallee);
8685   return CS.getInstruction();
8686 }
8687
8688 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8689 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8690 /// and a single binop.
8691 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8692   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8693   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8694          isa<CmpInst>(FirstInst));
8695   unsigned Opc = FirstInst->getOpcode();
8696   Value *LHSVal = FirstInst->getOperand(0);
8697   Value *RHSVal = FirstInst->getOperand(1);
8698     
8699   const Type *LHSType = LHSVal->getType();
8700   const Type *RHSType = RHSVal->getType();
8701   
8702   // Scan to see if all operands are the same opcode, all have one use, and all
8703   // kill their operands (i.e. the operands have one use).
8704   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8705     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8706     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8707         // Verify type of the LHS matches so we don't fold cmp's of different
8708         // types or GEP's with different index types.
8709         I->getOperand(0)->getType() != LHSType ||
8710         I->getOperand(1)->getType() != RHSType)
8711       return 0;
8712
8713     // If they are CmpInst instructions, check their predicates
8714     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8715       if (cast<CmpInst>(I)->getPredicate() !=
8716           cast<CmpInst>(FirstInst)->getPredicate())
8717         return 0;
8718     
8719     // Keep track of which operand needs a phi node.
8720     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8721     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8722   }
8723   
8724   // Otherwise, this is safe to transform, determine if it is profitable.
8725
8726   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8727   // Indexes are often folded into load/store instructions, so we don't want to
8728   // hide them behind a phi.
8729   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8730     return 0;
8731   
8732   Value *InLHS = FirstInst->getOperand(0);
8733   Value *InRHS = FirstInst->getOperand(1);
8734   PHINode *NewLHS = 0, *NewRHS = 0;
8735   if (LHSVal == 0) {
8736     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8737     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8738     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8739     InsertNewInstBefore(NewLHS, PN);
8740     LHSVal = NewLHS;
8741   }
8742   
8743   if (RHSVal == 0) {
8744     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8745     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8746     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8747     InsertNewInstBefore(NewRHS, PN);
8748     RHSVal = NewRHS;
8749   }
8750   
8751   // Add all operands to the new PHIs.
8752   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8753     if (NewLHS) {
8754       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8755       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8756     }
8757     if (NewRHS) {
8758       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8759       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8760     }
8761   }
8762     
8763   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8764     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8765   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8766     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8767                            RHSVal);
8768   else {
8769     assert(isa<GetElementPtrInst>(FirstInst));
8770     return new GetElementPtrInst(LHSVal, RHSVal);
8771   }
8772 }
8773
8774 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8775 /// of the block that defines it.  This means that it must be obvious the value
8776 /// of the load is not changed from the point of the load to the end of the
8777 /// block it is in.
8778 ///
8779 /// Finally, it is safe, but not profitable, to sink a load targetting a
8780 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8781 /// to a register.
8782 static bool isSafeToSinkLoad(LoadInst *L) {
8783   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8784   
8785   for (++BBI; BBI != E; ++BBI)
8786     if (BBI->mayWriteToMemory())
8787       return false;
8788   
8789   // Check for non-address taken alloca.  If not address-taken already, it isn't
8790   // profitable to do this xform.
8791   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8792     bool isAddressTaken = false;
8793     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8794          UI != E; ++UI) {
8795       if (isa<LoadInst>(UI)) continue;
8796       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8797         // If storing TO the alloca, then the address isn't taken.
8798         if (SI->getOperand(1) == AI) continue;
8799       }
8800       isAddressTaken = true;
8801       break;
8802     }
8803     
8804     if (!isAddressTaken)
8805       return false;
8806   }
8807   
8808   return true;
8809 }
8810
8811
8812 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8813 // operator and they all are only used by the PHI, PHI together their
8814 // inputs, and do the operation once, to the result of the PHI.
8815 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8816   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8817
8818   // Scan the instruction, looking for input operations that can be folded away.
8819   // If all input operands to the phi are the same instruction (e.g. a cast from
8820   // the same type or "+42") we can pull the operation through the PHI, reducing
8821   // code size and simplifying code.
8822   Constant *ConstantOp = 0;
8823   const Type *CastSrcTy = 0;
8824   bool isVolatile = false;
8825   if (isa<CastInst>(FirstInst)) {
8826     CastSrcTy = FirstInst->getOperand(0)->getType();
8827   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8828     // Can fold binop, compare or shift here if the RHS is a constant, 
8829     // otherwise call FoldPHIArgBinOpIntoPHI.
8830     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8831     if (ConstantOp == 0)
8832       return FoldPHIArgBinOpIntoPHI(PN);
8833   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8834     isVolatile = LI->isVolatile();
8835     // We can't sink the load if the loaded value could be modified between the
8836     // load and the PHI.
8837     if (LI->getParent() != PN.getIncomingBlock(0) ||
8838         !isSafeToSinkLoad(LI))
8839       return 0;
8840   } else if (isa<GetElementPtrInst>(FirstInst)) {
8841     if (FirstInst->getNumOperands() == 2)
8842       return FoldPHIArgBinOpIntoPHI(PN);
8843     // Can't handle general GEPs yet.
8844     return 0;
8845   } else {
8846     return 0;  // Cannot fold this operation.
8847   }
8848
8849   // Check to see if all arguments are the same operation.
8850   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8851     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8852     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8853     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8854       return 0;
8855     if (CastSrcTy) {
8856       if (I->getOperand(0)->getType() != CastSrcTy)
8857         return 0;  // Cast operation must match.
8858     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8859       // We can't sink the load if the loaded value could be modified between 
8860       // the load and the PHI.
8861       if (LI->isVolatile() != isVolatile ||
8862           LI->getParent() != PN.getIncomingBlock(i) ||
8863           !isSafeToSinkLoad(LI))
8864         return 0;
8865     } else if (I->getOperand(1) != ConstantOp) {
8866       return 0;
8867     }
8868   }
8869
8870   // Okay, they are all the same operation.  Create a new PHI node of the
8871   // correct type, and PHI together all of the LHS's of the instructions.
8872   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8873                                PN.getName()+".in");
8874   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8875
8876   Value *InVal = FirstInst->getOperand(0);
8877   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8878
8879   // Add all operands to the new PHI.
8880   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8881     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8882     if (NewInVal != InVal)
8883       InVal = 0;
8884     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8885   }
8886
8887   Value *PhiVal;
8888   if (InVal) {
8889     // The new PHI unions all of the same values together.  This is really
8890     // common, so we handle it intelligently here for compile-time speed.
8891     PhiVal = InVal;
8892     delete NewPN;
8893   } else {
8894     InsertNewInstBefore(NewPN, PN);
8895     PhiVal = NewPN;
8896   }
8897
8898   // Insert and return the new operation.
8899   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8900     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8901   else if (isa<LoadInst>(FirstInst))
8902     return new LoadInst(PhiVal, "", isVolatile);
8903   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8904     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8905   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8906     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8907                            PhiVal, ConstantOp);
8908   else
8909     assert(0 && "Unknown operation");
8910   return 0;
8911 }
8912
8913 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8914 /// that is dead.
8915 static bool DeadPHICycle(PHINode *PN,
8916                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8917   if (PN->use_empty()) return true;
8918   if (!PN->hasOneUse()) return false;
8919
8920   // Remember this node, and if we find the cycle, return.
8921   if (!PotentiallyDeadPHIs.insert(PN))
8922     return true;
8923   
8924   // Don't scan crazily complex things.
8925   if (PotentiallyDeadPHIs.size() == 16)
8926     return false;
8927
8928   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8929     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8930
8931   return false;
8932 }
8933
8934 /// PHIsEqualValue - Return true if this phi node is always equal to
8935 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
8936 ///   z = some value; x = phi (y, z); y = phi (x, z)
8937 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
8938                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8939   // See if we already saw this PHI node.
8940   if (!ValueEqualPHIs.insert(PN))
8941     return true;
8942   
8943   // Don't scan crazily complex things.
8944   if (ValueEqualPHIs.size() == 16)
8945     return false;
8946  
8947   // Scan the operands to see if they are either phi nodes or are equal to
8948   // the value.
8949   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8950     Value *Op = PN->getIncomingValue(i);
8951     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8952       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8953         return false;
8954     } else if (Op != NonPhiInVal)
8955       return false;
8956   }
8957   
8958   return true;
8959 }
8960
8961
8962 // PHINode simplification
8963 //
8964 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8965   // If LCSSA is around, don't mess with Phi nodes
8966   if (MustPreserveLCSSA) return 0;
8967   
8968   if (Value *V = PN.hasConstantValue())
8969     return ReplaceInstUsesWith(PN, V);
8970
8971   // If all PHI operands are the same operation, pull them through the PHI,
8972   // reducing code size.
8973   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8974       PN.getIncomingValue(0)->hasOneUse())
8975     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8976       return Result;
8977
8978   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8979   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8980   // PHI)... break the cycle.
8981   if (PN.hasOneUse()) {
8982     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8983     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8984       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8985       PotentiallyDeadPHIs.insert(&PN);
8986       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8987         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8988     }
8989    
8990     // If this phi has a single use, and if that use just computes a value for
8991     // the next iteration of a loop, delete the phi.  This occurs with unused
8992     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8993     // common case here is good because the only other things that catch this
8994     // are induction variable analysis (sometimes) and ADCE, which is only run
8995     // late.
8996     if (PHIUser->hasOneUse() &&
8997         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8998         PHIUser->use_back() == &PN) {
8999       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9000     }
9001   }
9002
9003   // We sometimes end up with phi cycles that non-obviously end up being the
9004   // same value, for example:
9005   //   z = some value; x = phi (y, z); y = phi (x, z)
9006   // where the phi nodes don't necessarily need to be in the same block.  Do a
9007   // quick check to see if the PHI node only contains a single non-phi value, if
9008   // so, scan to see if the phi cycle is actually equal to that value.
9009   {
9010     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9011     // Scan for the first non-phi operand.
9012     while (InValNo != NumOperandVals && 
9013            isa<PHINode>(PN.getIncomingValue(InValNo)))
9014       ++InValNo;
9015
9016     if (InValNo != NumOperandVals) {
9017       Value *NonPhiInVal = PN.getOperand(InValNo);
9018       
9019       // Scan the rest of the operands to see if there are any conflicts, if so
9020       // there is no need to recursively scan other phis.
9021       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9022         Value *OpVal = PN.getIncomingValue(InValNo);
9023         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9024           break;
9025       }
9026       
9027       // If we scanned over all operands, then we have one unique value plus
9028       // phi values.  Scan PHI nodes to see if they all merge in each other or
9029       // the value.
9030       if (InValNo == NumOperandVals) {
9031         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9032         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9033           return ReplaceInstUsesWith(PN, NonPhiInVal);
9034       }
9035     }
9036   }
9037   return 0;
9038 }
9039
9040 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9041                                    Instruction *InsertPoint,
9042                                    InstCombiner *IC) {
9043   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9044   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9045   // We must cast correctly to the pointer type. Ensure that we
9046   // sign extend the integer value if it is smaller as this is
9047   // used for address computation.
9048   Instruction::CastOps opcode = 
9049      (VTySize < PtrSize ? Instruction::SExt :
9050       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9051   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9052 }
9053
9054
9055 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9056   Value *PtrOp = GEP.getOperand(0);
9057   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9058   // If so, eliminate the noop.
9059   if (GEP.getNumOperands() == 1)
9060     return ReplaceInstUsesWith(GEP, PtrOp);
9061
9062   if (isa<UndefValue>(GEP.getOperand(0)))
9063     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9064
9065   bool HasZeroPointerIndex = false;
9066   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9067     HasZeroPointerIndex = C->isNullValue();
9068
9069   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9070     return ReplaceInstUsesWith(GEP, PtrOp);
9071
9072   // Eliminate unneeded casts for indices.
9073   bool MadeChange = false;
9074   
9075   gep_type_iterator GTI = gep_type_begin(GEP);
9076   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9077     if (isa<SequentialType>(*GTI)) {
9078       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9079         if (CI->getOpcode() == Instruction::ZExt ||
9080             CI->getOpcode() == Instruction::SExt) {
9081           const Type *SrcTy = CI->getOperand(0)->getType();
9082           // We can eliminate a cast from i32 to i64 iff the target 
9083           // is a 32-bit pointer target.
9084           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9085             MadeChange = true;
9086             GEP.setOperand(i, CI->getOperand(0));
9087           }
9088         }
9089       }
9090       // If we are using a wider index than needed for this platform, shrink it
9091       // to what we need.  If the incoming value needs a cast instruction,
9092       // insert it.  This explicit cast can make subsequent optimizations more
9093       // obvious.
9094       Value *Op = GEP.getOperand(i);
9095       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
9096         if (Constant *C = dyn_cast<Constant>(Op)) {
9097           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9098           MadeChange = true;
9099         } else {
9100           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9101                                 GEP);
9102           GEP.setOperand(i, Op);
9103           MadeChange = true;
9104         }
9105     }
9106   }
9107   if (MadeChange) return &GEP;
9108
9109   // If this GEP instruction doesn't move the pointer, and if the input operand
9110   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9111   // real input to the dest type.
9112   if (GEP.hasAllZeroIndices()) {
9113     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9114       // If the bitcast is of an allocation, and the allocation will be
9115       // converted to match the type of the cast, don't touch this.
9116       if (isa<AllocationInst>(BCI->getOperand(0))) {
9117         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9118         if (Instruction *I = visitBitCast(*BCI)) {
9119           if (I != BCI) {
9120             I->takeName(BCI);
9121             BCI->getParent()->getInstList().insert(BCI, I);
9122             ReplaceInstUsesWith(*BCI, I);
9123           }
9124           return &GEP;
9125         }
9126       }
9127       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9128     }
9129   }
9130   
9131   // Combine Indices - If the source pointer to this getelementptr instruction
9132   // is a getelementptr instruction, combine the indices of the two
9133   // getelementptr instructions into a single instruction.
9134   //
9135   SmallVector<Value*, 8> SrcGEPOperands;
9136   if (User *Src = dyn_castGetElementPtr(PtrOp))
9137     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9138
9139   if (!SrcGEPOperands.empty()) {
9140     // Note that if our source is a gep chain itself that we wait for that
9141     // chain to be resolved before we perform this transformation.  This
9142     // avoids us creating a TON of code in some cases.
9143     //
9144     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9145         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9146       return 0;   // Wait until our source is folded to completion.
9147
9148     SmallVector<Value*, 8> Indices;
9149
9150     // Find out whether the last index in the source GEP is a sequential idx.
9151     bool EndsWithSequential = false;
9152     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9153            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9154       EndsWithSequential = !isa<StructType>(*I);
9155
9156     // Can we combine the two pointer arithmetics offsets?
9157     if (EndsWithSequential) {
9158       // Replace: gep (gep %P, long B), long A, ...
9159       // With:    T = long A+B; gep %P, T, ...
9160       //
9161       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9162       if (SO1 == Constant::getNullValue(SO1->getType())) {
9163         Sum = GO1;
9164       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9165         Sum = SO1;
9166       } else {
9167         // If they aren't the same type, convert both to an integer of the
9168         // target's pointer size.
9169         if (SO1->getType() != GO1->getType()) {
9170           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9171             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9172           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9173             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9174           } else {
9175             unsigned PS = TD->getPointerSizeInBits();
9176             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9177               // Convert GO1 to SO1's type.
9178               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9179
9180             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9181               // Convert SO1 to GO1's type.
9182               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9183             } else {
9184               const Type *PT = TD->getIntPtrType();
9185               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9186               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9187             }
9188           }
9189         }
9190         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9191           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9192         else {
9193           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9194           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9195         }
9196       }
9197
9198       // Recycle the GEP we already have if possible.
9199       if (SrcGEPOperands.size() == 2) {
9200         GEP.setOperand(0, SrcGEPOperands[0]);
9201         GEP.setOperand(1, Sum);
9202         return &GEP;
9203       } else {
9204         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9205                        SrcGEPOperands.end()-1);
9206         Indices.push_back(Sum);
9207         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9208       }
9209     } else if (isa<Constant>(*GEP.idx_begin()) &&
9210                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9211                SrcGEPOperands.size() != 1) {
9212       // Otherwise we can do the fold if the first index of the GEP is a zero
9213       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9214                      SrcGEPOperands.end());
9215       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9216     }
9217
9218     if (!Indices.empty())
9219       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9220                                    Indices.end(), GEP.getName());
9221
9222   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9223     // GEP of global variable.  If all of the indices for this GEP are
9224     // constants, we can promote this to a constexpr instead of an instruction.
9225
9226     // Scan for nonconstants...
9227     SmallVector<Constant*, 8> Indices;
9228     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9229     for (; I != E && isa<Constant>(*I); ++I)
9230       Indices.push_back(cast<Constant>(*I));
9231
9232     if (I == E) {  // If they are all constants...
9233       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9234                                                     &Indices[0],Indices.size());
9235
9236       // Replace all uses of the GEP with the new constexpr...
9237       return ReplaceInstUsesWith(GEP, CE);
9238     }
9239   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9240     if (!isa<PointerType>(X->getType())) {
9241       // Not interesting.  Source pointer must be a cast from pointer.
9242     } else if (HasZeroPointerIndex) {
9243       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9244       // into     : GEP [10 x i8]* X, i32 0, ...
9245       //
9246       // This occurs when the program declares an array extern like "int X[];"
9247       //
9248       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9249       const PointerType *XTy = cast<PointerType>(X->getType());
9250       if (const ArrayType *XATy =
9251           dyn_cast<ArrayType>(XTy->getElementType()))
9252         if (const ArrayType *CATy =
9253             dyn_cast<ArrayType>(CPTy->getElementType()))
9254           if (CATy->getElementType() == XATy->getElementType()) {
9255             // At this point, we know that the cast source type is a pointer
9256             // to an array of the same type as the destination pointer
9257             // array.  Because the array type is never stepped over (there
9258             // is a leading zero) we can fold the cast into this GEP.
9259             GEP.setOperand(0, X);
9260             return &GEP;
9261           }
9262     } else if (GEP.getNumOperands() == 2) {
9263       // Transform things like:
9264       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9265       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9266       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9267       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9268       if (isa<ArrayType>(SrcElTy) &&
9269           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9270           TD->getABITypeSize(ResElTy)) {
9271         Value *Idx[2];
9272         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9273         Idx[1] = GEP.getOperand(1);
9274         Value *V = InsertNewInstBefore(
9275                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
9276         // V and GEP are both pointer types --> BitCast
9277         return new BitCastInst(V, GEP.getType());
9278       }
9279       
9280       // Transform things like:
9281       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9282       //   (where tmp = 8*tmp2) into:
9283       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9284       
9285       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9286         uint64_t ArrayEltSize =
9287             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9288         
9289         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9290         // allow either a mul, shift, or constant here.
9291         Value *NewIdx = 0;
9292         ConstantInt *Scale = 0;
9293         if (ArrayEltSize == 1) {
9294           NewIdx = GEP.getOperand(1);
9295           Scale = ConstantInt::get(NewIdx->getType(), 1);
9296         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9297           NewIdx = ConstantInt::get(CI->getType(), 1);
9298           Scale = CI;
9299         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9300           if (Inst->getOpcode() == Instruction::Shl &&
9301               isa<ConstantInt>(Inst->getOperand(1))) {
9302             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9303             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9304             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9305             NewIdx = Inst->getOperand(0);
9306           } else if (Inst->getOpcode() == Instruction::Mul &&
9307                      isa<ConstantInt>(Inst->getOperand(1))) {
9308             Scale = cast<ConstantInt>(Inst->getOperand(1));
9309             NewIdx = Inst->getOperand(0);
9310           }
9311         }
9312         
9313         // If the index will be to exactly the right offset with the scale taken
9314         // out, perform the transformation. Note, we don't know whether Scale is
9315         // signed or not. We'll use unsigned version of division/modulo
9316         // operation after making sure Scale doesn't have the sign bit set.
9317         if (Scale && Scale->getSExtValue() >= 0LL &&
9318             Scale->getZExtValue() % ArrayEltSize == 0) {
9319           Scale = ConstantInt::get(Scale->getType(),
9320                                    Scale->getZExtValue() / ArrayEltSize);
9321           if (Scale->getZExtValue() != 1) {
9322             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9323                                                        false /*ZExt*/);
9324             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9325             NewIdx = InsertNewInstBefore(Sc, GEP);
9326           }
9327
9328           // Insert the new GEP instruction.
9329           Value *Idx[2];
9330           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9331           Idx[1] = NewIdx;
9332           Instruction *NewGEP =
9333             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9334           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9335           // The NewGEP must be pointer typed, so must the old one -> BitCast
9336           return new BitCastInst(NewGEP, GEP.getType());
9337         }
9338       }
9339     }
9340   }
9341
9342   return 0;
9343 }
9344
9345 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9346   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9347   if (AI.isArrayAllocation())    // Check C != 1
9348     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9349       const Type *NewTy = 
9350         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9351       AllocationInst *New = 0;
9352
9353       // Create and insert the replacement instruction...
9354       if (isa<MallocInst>(AI))
9355         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9356       else {
9357         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9358         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9359       }
9360
9361       InsertNewInstBefore(New, AI);
9362
9363       // Scan to the end of the allocation instructions, to skip over a block of
9364       // allocas if possible...
9365       //
9366       BasicBlock::iterator It = New;
9367       while (isa<AllocationInst>(*It)) ++It;
9368
9369       // Now that I is pointing to the first non-allocation-inst in the block,
9370       // insert our getelementptr instruction...
9371       //
9372       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9373       Value *Idx[2];
9374       Idx[0] = NullIdx;
9375       Idx[1] = NullIdx;
9376       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9377                                        New->getName()+".sub", It);
9378
9379       // Now make everything use the getelementptr instead of the original
9380       // allocation.
9381       return ReplaceInstUsesWith(AI, V);
9382     } else if (isa<UndefValue>(AI.getArraySize())) {
9383       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9384     }
9385
9386   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9387   // Note that we only do this for alloca's, because malloc should allocate and
9388   // return a unique pointer, even for a zero byte allocation.
9389   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9390       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9391     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9392
9393   return 0;
9394 }
9395
9396 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9397   Value *Op = FI.getOperand(0);
9398
9399   // free undef -> unreachable.
9400   if (isa<UndefValue>(Op)) {
9401     // Insert a new store to null because we cannot modify the CFG here.
9402     new StoreInst(ConstantInt::getTrue(),
9403                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9404     return EraseInstFromFunction(FI);
9405   }
9406   
9407   // If we have 'free null' delete the instruction.  This can happen in stl code
9408   // when lots of inlining happens.
9409   if (isa<ConstantPointerNull>(Op))
9410     return EraseInstFromFunction(FI);
9411   
9412   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9413   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9414     FI.setOperand(0, CI->getOperand(0));
9415     return &FI;
9416   }
9417   
9418   // Change free (gep X, 0,0,0,0) into free(X)
9419   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9420     if (GEPI->hasAllZeroIndices()) {
9421       AddToWorkList(GEPI);
9422       FI.setOperand(0, GEPI->getOperand(0));
9423       return &FI;
9424     }
9425   }
9426   
9427   // Change free(malloc) into nothing, if the malloc has a single use.
9428   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9429     if (MI->hasOneUse()) {
9430       EraseInstFromFunction(FI);
9431       return EraseInstFromFunction(*MI);
9432     }
9433
9434   return 0;
9435 }
9436
9437
9438 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9439 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9440                                         const TargetData *TD) {
9441   User *CI = cast<User>(LI.getOperand(0));
9442   Value *CastOp = CI->getOperand(0);
9443
9444   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9445     // Instead of loading constant c string, use corresponding integer value
9446     // directly if string length is small enough.
9447     const std::string &Str = CE->getOperand(0)->getStringValue();
9448     if (!Str.empty()) {
9449       unsigned len = Str.length();
9450       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9451       unsigned numBits = Ty->getPrimitiveSizeInBits();
9452       // Replace LI with immediate integer store.
9453       if ((numBits >> 3) == len + 1) {
9454         APInt StrVal(numBits, 0);
9455         APInt SingleChar(numBits, 0);
9456         if (TD->isLittleEndian()) {
9457           for (signed i = len-1; i >= 0; i--) {
9458             SingleChar = (uint64_t) Str[i];
9459             StrVal = (StrVal << 8) | SingleChar;
9460           }
9461         } else {
9462           for (unsigned i = 0; i < len; i++) {
9463             SingleChar = (uint64_t) Str[i];
9464                 StrVal = (StrVal << 8) | SingleChar;
9465           }
9466           // Append NULL at the end.
9467           SingleChar = 0;
9468           StrVal = (StrVal << 8) | SingleChar;
9469         }
9470         Value *NL = ConstantInt::get(StrVal);
9471         return IC.ReplaceInstUsesWith(LI, NL);
9472       }
9473     }
9474   }
9475
9476   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9477   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9478     const Type *SrcPTy = SrcTy->getElementType();
9479
9480     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9481          isa<VectorType>(DestPTy)) {
9482       // If the source is an array, the code below will not succeed.  Check to
9483       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9484       // constants.
9485       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9486         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9487           if (ASrcTy->getNumElements() != 0) {
9488             Value *Idxs[2];
9489             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9490             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9491             SrcTy = cast<PointerType>(CastOp->getType());
9492             SrcPTy = SrcTy->getElementType();
9493           }
9494
9495       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9496             isa<VectorType>(SrcPTy)) &&
9497           // Do not allow turning this into a load of an integer, which is then
9498           // casted to a pointer, this pessimizes pointer analysis a lot.
9499           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9500           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9501                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9502
9503         // Okay, we are casting from one integer or pointer type to another of
9504         // the same size.  Instead of casting the pointer before the load, cast
9505         // the result of the loaded value.
9506         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9507                                                              CI->getName(),
9508                                                          LI.isVolatile()),LI);
9509         // Now cast the result of the load.
9510         return new BitCastInst(NewLoad, LI.getType());
9511       }
9512     }
9513   }
9514   return 0;
9515 }
9516
9517 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9518 /// from this value cannot trap.  If it is not obviously safe to load from the
9519 /// specified pointer, we do a quick local scan of the basic block containing
9520 /// ScanFrom, to determine if the address is already accessed.
9521 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9522   // If it is an alloca it is always safe to load from.
9523   if (isa<AllocaInst>(V)) return true;
9524
9525   // If it is a global variable it is mostly safe to load from.
9526   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9527     // Don't try to evaluate aliases.  External weak GV can be null.
9528     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9529
9530   // Otherwise, be a little bit agressive by scanning the local block where we
9531   // want to check to see if the pointer is already being loaded or stored
9532   // from/to.  If so, the previous load or store would have already trapped,
9533   // so there is no harm doing an extra load (also, CSE will later eliminate
9534   // the load entirely).
9535   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9536
9537   while (BBI != E) {
9538     --BBI;
9539
9540     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9541       if (LI->getOperand(0) == V) return true;
9542     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9543       if (SI->getOperand(1) == V) return true;
9544
9545   }
9546   return false;
9547 }
9548
9549 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9550 /// until we find the underlying object a pointer is referring to or something
9551 /// we don't understand.  Note that the returned pointer may be offset from the
9552 /// input, because we ignore GEP indices.
9553 static Value *GetUnderlyingObject(Value *Ptr) {
9554   while (1) {
9555     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9556       if (CE->getOpcode() == Instruction::BitCast ||
9557           CE->getOpcode() == Instruction::GetElementPtr)
9558         Ptr = CE->getOperand(0);
9559       else
9560         return Ptr;
9561     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9562       Ptr = BCI->getOperand(0);
9563     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9564       Ptr = GEP->getOperand(0);
9565     } else {
9566       return Ptr;
9567     }
9568   }
9569 }
9570
9571 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9572   Value *Op = LI.getOperand(0);
9573
9574   // Attempt to improve the alignment.
9575   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9576   if (KnownAlign > LI.getAlignment())
9577     LI.setAlignment(KnownAlign);
9578
9579   // load (cast X) --> cast (load X) iff safe
9580   if (isa<CastInst>(Op))
9581     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9582       return Res;
9583
9584   // None of the following transforms are legal for volatile loads.
9585   if (LI.isVolatile()) return 0;
9586   
9587   if (&LI.getParent()->front() != &LI) {
9588     BasicBlock::iterator BBI = &LI; --BBI;
9589     // If the instruction immediately before this is a store to the same
9590     // address, do a simple form of store->load forwarding.
9591     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9592       if (SI->getOperand(1) == LI.getOperand(0))
9593         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9594     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9595       if (LIB->getOperand(0) == LI.getOperand(0))
9596         return ReplaceInstUsesWith(LI, LIB);
9597   }
9598
9599   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9600     const Value *GEPI0 = GEPI->getOperand(0);
9601     // TODO: Consider a target hook for valid address spaces for this xform.
9602     if (isa<ConstantPointerNull>(GEPI0) &&
9603         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
9604       // Insert a new store to null instruction before the load to indicate
9605       // that this code is not reachable.  We do this instead of inserting
9606       // an unreachable instruction directly because we cannot modify the
9607       // CFG.
9608       new StoreInst(UndefValue::get(LI.getType()),
9609                     Constant::getNullValue(Op->getType()), &LI);
9610       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9611     }
9612   } 
9613
9614   if (Constant *C = dyn_cast<Constant>(Op)) {
9615     // load null/undef -> undef
9616     // TODO: Consider a target hook for valid address spaces for this xform.
9617     if (isa<UndefValue>(C) || (C->isNullValue() && 
9618         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
9619       // Insert a new store to null instruction before the load to indicate that
9620       // this code is not reachable.  We do this instead of inserting an
9621       // unreachable instruction directly because we cannot modify the CFG.
9622       new StoreInst(UndefValue::get(LI.getType()),
9623                     Constant::getNullValue(Op->getType()), &LI);
9624       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9625     }
9626
9627     // Instcombine load (constant global) into the value loaded.
9628     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9629       if (GV->isConstant() && !GV->isDeclaration())
9630         return ReplaceInstUsesWith(LI, GV->getInitializer());
9631
9632     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9633     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9634       if (CE->getOpcode() == Instruction::GetElementPtr) {
9635         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9636           if (GV->isConstant() && !GV->isDeclaration())
9637             if (Constant *V = 
9638                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9639               return ReplaceInstUsesWith(LI, V);
9640         if (CE->getOperand(0)->isNullValue()) {
9641           // Insert a new store to null instruction before the load to indicate
9642           // that this code is not reachable.  We do this instead of inserting
9643           // an unreachable instruction directly because we cannot modify the
9644           // CFG.
9645           new StoreInst(UndefValue::get(LI.getType()),
9646                         Constant::getNullValue(Op->getType()), &LI);
9647           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9648         }
9649
9650       } else if (CE->isCast()) {
9651         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9652           return Res;
9653       }
9654   }
9655     
9656   // If this load comes from anywhere in a constant global, and if the global
9657   // is all undef or zero, we know what it loads.
9658   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9659     if (GV->isConstant() && GV->hasInitializer()) {
9660       if (GV->getInitializer()->isNullValue())
9661         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9662       else if (isa<UndefValue>(GV->getInitializer()))
9663         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9664     }
9665   }
9666
9667   if (Op->hasOneUse()) {
9668     // Change select and PHI nodes to select values instead of addresses: this
9669     // helps alias analysis out a lot, allows many others simplifications, and
9670     // exposes redundancy in the code.
9671     //
9672     // Note that we cannot do the transformation unless we know that the
9673     // introduced loads cannot trap!  Something like this is valid as long as
9674     // the condition is always false: load (select bool %C, int* null, int* %G),
9675     // but it would not be valid if we transformed it to load from null
9676     // unconditionally.
9677     //
9678     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9679       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9680       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9681           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9682         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9683                                      SI->getOperand(1)->getName()+".val"), LI);
9684         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9685                                      SI->getOperand(2)->getName()+".val"), LI);
9686         return new SelectInst(SI->getCondition(), V1, V2);
9687       }
9688
9689       // load (select (cond, null, P)) -> load P
9690       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9691         if (C->isNullValue()) {
9692           LI.setOperand(0, SI->getOperand(2));
9693           return &LI;
9694         }
9695
9696       // load (select (cond, P, null)) -> load P
9697       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9698         if (C->isNullValue()) {
9699           LI.setOperand(0, SI->getOperand(1));
9700           return &LI;
9701         }
9702     }
9703   }
9704   return 0;
9705 }
9706
9707 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9708 /// when possible.
9709 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9710   User *CI = cast<User>(SI.getOperand(1));
9711   Value *CastOp = CI->getOperand(0);
9712
9713   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9714   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9715     const Type *SrcPTy = SrcTy->getElementType();
9716
9717     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9718       // If the source is an array, the code below will not succeed.  Check to
9719       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9720       // constants.
9721       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9722         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9723           if (ASrcTy->getNumElements() != 0) {
9724             Value* Idxs[2];
9725             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9726             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9727             SrcTy = cast<PointerType>(CastOp->getType());
9728             SrcPTy = SrcTy->getElementType();
9729           }
9730
9731       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9732           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9733                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9734
9735         // Okay, we are casting from one integer or pointer type to another of
9736         // the same size.  Instead of casting the pointer before 
9737         // the store, cast the value to be stored.
9738         Value *NewCast;
9739         Value *SIOp0 = SI.getOperand(0);
9740         Instruction::CastOps opcode = Instruction::BitCast;
9741         const Type* CastSrcTy = SIOp0->getType();
9742         const Type* CastDstTy = SrcPTy;
9743         if (isa<PointerType>(CastDstTy)) {
9744           if (CastSrcTy->isInteger())
9745             opcode = Instruction::IntToPtr;
9746         } else if (isa<IntegerType>(CastDstTy)) {
9747           if (isa<PointerType>(SIOp0->getType()))
9748             opcode = Instruction::PtrToInt;
9749         }
9750         if (Constant *C = dyn_cast<Constant>(SIOp0))
9751           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9752         else
9753           NewCast = IC.InsertNewInstBefore(
9754             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9755             SI);
9756         return new StoreInst(NewCast, CastOp);
9757       }
9758     }
9759   }
9760   return 0;
9761 }
9762
9763 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9764   Value *Val = SI.getOperand(0);
9765   Value *Ptr = SI.getOperand(1);
9766
9767   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9768     EraseInstFromFunction(SI);
9769     ++NumCombined;
9770     return 0;
9771   }
9772   
9773   // If the RHS is an alloca with a single use, zapify the store, making the
9774   // alloca dead.
9775   if (Ptr->hasOneUse()) {
9776     if (isa<AllocaInst>(Ptr)) {
9777       EraseInstFromFunction(SI);
9778       ++NumCombined;
9779       return 0;
9780     }
9781     
9782     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9783       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9784           GEP->getOperand(0)->hasOneUse()) {
9785         EraseInstFromFunction(SI);
9786         ++NumCombined;
9787         return 0;
9788       }
9789   }
9790
9791   // Attempt to improve the alignment.
9792   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9793   if (KnownAlign > SI.getAlignment())
9794     SI.setAlignment(KnownAlign);
9795
9796   // Do really simple DSE, to catch cases where there are several consequtive
9797   // stores to the same location, separated by a few arithmetic operations. This
9798   // situation often occurs with bitfield accesses.
9799   BasicBlock::iterator BBI = &SI;
9800   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9801        --ScanInsts) {
9802     --BBI;
9803     
9804     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9805       // Prev store isn't volatile, and stores to the same location?
9806       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9807         ++NumDeadStore;
9808         ++BBI;
9809         EraseInstFromFunction(*PrevSI);
9810         continue;
9811       }
9812       break;
9813     }
9814     
9815     // If this is a load, we have to stop.  However, if the loaded value is from
9816     // the pointer we're loading and is producing the pointer we're storing,
9817     // then *this* store is dead (X = load P; store X -> P).
9818     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9819       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
9820         EraseInstFromFunction(SI);
9821         ++NumCombined;
9822         return 0;
9823       }
9824       // Otherwise, this is a load from some other location.  Stores before it
9825       // may not be dead.
9826       break;
9827     }
9828     
9829     // Don't skip over loads or things that can modify memory.
9830     if (BBI->mayWriteToMemory())
9831       break;
9832   }
9833   
9834   
9835   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9836
9837   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9838   if (isa<ConstantPointerNull>(Ptr)) {
9839     if (!isa<UndefValue>(Val)) {
9840       SI.setOperand(0, UndefValue::get(Val->getType()));
9841       if (Instruction *U = dyn_cast<Instruction>(Val))
9842         AddToWorkList(U);  // Dropped a use.
9843       ++NumCombined;
9844     }
9845     return 0;  // Do not modify these!
9846   }
9847
9848   // store undef, Ptr -> noop
9849   if (isa<UndefValue>(Val)) {
9850     EraseInstFromFunction(SI);
9851     ++NumCombined;
9852     return 0;
9853   }
9854
9855   // If the pointer destination is a cast, see if we can fold the cast into the
9856   // source instead.
9857   if (isa<CastInst>(Ptr))
9858     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9859       return Res;
9860   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9861     if (CE->isCast())
9862       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9863         return Res;
9864
9865   
9866   // If this store is the last instruction in the basic block, and if the block
9867   // ends with an unconditional branch, try to move it to the successor block.
9868   BBI = &SI; ++BBI;
9869   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9870     if (BI->isUnconditional())
9871       if (SimplifyStoreAtEndOfBlock(SI))
9872         return 0;  // xform done!
9873   
9874   return 0;
9875 }
9876
9877 /// SimplifyStoreAtEndOfBlock - Turn things like:
9878 ///   if () { *P = v1; } else { *P = v2 }
9879 /// into a phi node with a store in the successor.
9880 ///
9881 /// Simplify things like:
9882 ///   *P = v1; if () { *P = v2; }
9883 /// into a phi node with a store in the successor.
9884 ///
9885 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9886   BasicBlock *StoreBB = SI.getParent();
9887   
9888   // Check to see if the successor block has exactly two incoming edges.  If
9889   // so, see if the other predecessor contains a store to the same location.
9890   // if so, insert a PHI node (if needed) and move the stores down.
9891   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9892   
9893   // Determine whether Dest has exactly two predecessors and, if so, compute
9894   // the other predecessor.
9895   pred_iterator PI = pred_begin(DestBB);
9896   BasicBlock *OtherBB = 0;
9897   if (*PI != StoreBB)
9898     OtherBB = *PI;
9899   ++PI;
9900   if (PI == pred_end(DestBB))
9901     return false;
9902   
9903   if (*PI != StoreBB) {
9904     if (OtherBB)
9905       return false;
9906     OtherBB = *PI;
9907   }
9908   if (++PI != pred_end(DestBB))
9909     return false;
9910   
9911   
9912   // Verify that the other block ends in a branch and is not otherwise empty.
9913   BasicBlock::iterator BBI = OtherBB->getTerminator();
9914   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9915   if (!OtherBr || BBI == OtherBB->begin())
9916     return false;
9917   
9918   // If the other block ends in an unconditional branch, check for the 'if then
9919   // else' case.  there is an instruction before the branch.
9920   StoreInst *OtherStore = 0;
9921   if (OtherBr->isUnconditional()) {
9922     // If this isn't a store, or isn't a store to the same location, bail out.
9923     --BBI;
9924     OtherStore = dyn_cast<StoreInst>(BBI);
9925     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9926       return false;
9927   } else {
9928     // Otherwise, the other block ended with a conditional branch. If one of the
9929     // destinations is StoreBB, then we have the if/then case.
9930     if (OtherBr->getSuccessor(0) != StoreBB && 
9931         OtherBr->getSuccessor(1) != StoreBB)
9932       return false;
9933     
9934     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9935     // if/then triangle.  See if there is a store to the same ptr as SI that
9936     // lives in OtherBB.
9937     for (;; --BBI) {
9938       // Check to see if we find the matching store.
9939       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9940         if (OtherStore->getOperand(1) != SI.getOperand(1))
9941           return false;
9942         break;
9943       }
9944       // If we find something that may be using the stored value, or if we run
9945       // out of instructions, we can't do the xform.
9946       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9947           BBI == OtherBB->begin())
9948         return false;
9949     }
9950     
9951     // In order to eliminate the store in OtherBr, we have to
9952     // make sure nothing reads the stored value in StoreBB.
9953     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9954       // FIXME: This should really be AA driven.
9955       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9956         return false;
9957     }
9958   }
9959   
9960   // Insert a PHI node now if we need it.
9961   Value *MergedVal = OtherStore->getOperand(0);
9962   if (MergedVal != SI.getOperand(0)) {
9963     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9964     PN->reserveOperandSpace(2);
9965     PN->addIncoming(SI.getOperand(0), SI.getParent());
9966     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9967     MergedVal = InsertNewInstBefore(PN, DestBB->front());
9968   }
9969   
9970   // Advance to a place where it is safe to insert the new store and
9971   // insert it.
9972   BBI = DestBB->begin();
9973   while (isa<PHINode>(BBI)) ++BBI;
9974   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9975                                     OtherStore->isVolatile()), *BBI);
9976   
9977   // Nuke the old stores.
9978   EraseInstFromFunction(SI);
9979   EraseInstFromFunction(*OtherStore);
9980   ++NumCombined;
9981   return true;
9982 }
9983
9984
9985 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9986   // Change br (not X), label True, label False to: br X, label False, True
9987   Value *X = 0;
9988   BasicBlock *TrueDest;
9989   BasicBlock *FalseDest;
9990   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9991       !isa<Constant>(X)) {
9992     // Swap Destinations and condition...
9993     BI.setCondition(X);
9994     BI.setSuccessor(0, FalseDest);
9995     BI.setSuccessor(1, TrueDest);
9996     return &BI;
9997   }
9998
9999   // Cannonicalize fcmp_one -> fcmp_oeq
10000   FCmpInst::Predicate FPred; Value *Y;
10001   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10002                              TrueDest, FalseDest)))
10003     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10004          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10005       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10006       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10007       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10008       NewSCC->takeName(I);
10009       // Swap Destinations and condition...
10010       BI.setCondition(NewSCC);
10011       BI.setSuccessor(0, FalseDest);
10012       BI.setSuccessor(1, TrueDest);
10013       RemoveFromWorkList(I);
10014       I->eraseFromParent();
10015       AddToWorkList(NewSCC);
10016       return &BI;
10017     }
10018
10019   // Cannonicalize icmp_ne -> icmp_eq
10020   ICmpInst::Predicate IPred;
10021   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10022                       TrueDest, FalseDest)))
10023     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10024          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10025          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10026       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10027       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10028       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10029       NewSCC->takeName(I);
10030       // Swap Destinations and condition...
10031       BI.setCondition(NewSCC);
10032       BI.setSuccessor(0, FalseDest);
10033       BI.setSuccessor(1, TrueDest);
10034       RemoveFromWorkList(I);
10035       I->eraseFromParent();;
10036       AddToWorkList(NewSCC);
10037       return &BI;
10038     }
10039
10040   return 0;
10041 }
10042
10043 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10044   Value *Cond = SI.getCondition();
10045   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10046     if (I->getOpcode() == Instruction::Add)
10047       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10048         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10049         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10050           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10051                                                 AddRHS));
10052         SI.setOperand(0, I->getOperand(0));
10053         AddToWorkList(I);
10054         return &SI;
10055       }
10056   }
10057   return 0;
10058 }
10059
10060 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10061 /// is to leave as a vector operation.
10062 static bool CheapToScalarize(Value *V, bool isConstant) {
10063   if (isa<ConstantAggregateZero>(V)) 
10064     return true;
10065   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10066     if (isConstant) return true;
10067     // If all elts are the same, we can extract.
10068     Constant *Op0 = C->getOperand(0);
10069     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10070       if (C->getOperand(i) != Op0)
10071         return false;
10072     return true;
10073   }
10074   Instruction *I = dyn_cast<Instruction>(V);
10075   if (!I) return false;
10076   
10077   // Insert element gets simplified to the inserted element or is deleted if
10078   // this is constant idx extract element and its a constant idx insertelt.
10079   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10080       isa<ConstantInt>(I->getOperand(2)))
10081     return true;
10082   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10083     return true;
10084   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10085     if (BO->hasOneUse() &&
10086         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10087          CheapToScalarize(BO->getOperand(1), isConstant)))
10088       return true;
10089   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10090     if (CI->hasOneUse() &&
10091         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10092          CheapToScalarize(CI->getOperand(1), isConstant)))
10093       return true;
10094   
10095   return false;
10096 }
10097
10098 /// Read and decode a shufflevector mask.
10099 ///
10100 /// It turns undef elements into values that are larger than the number of
10101 /// elements in the input.
10102 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10103   unsigned NElts = SVI->getType()->getNumElements();
10104   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10105     return std::vector<unsigned>(NElts, 0);
10106   if (isa<UndefValue>(SVI->getOperand(2)))
10107     return std::vector<unsigned>(NElts, 2*NElts);
10108
10109   std::vector<unsigned> Result;
10110   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10111   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10112     if (isa<UndefValue>(CP->getOperand(i)))
10113       Result.push_back(NElts*2);  // undef -> 8
10114     else
10115       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10116   return Result;
10117 }
10118
10119 /// FindScalarElement - Given a vector and an element number, see if the scalar
10120 /// value is already around as a register, for example if it were inserted then
10121 /// extracted from the vector.
10122 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10123   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10124   const VectorType *PTy = cast<VectorType>(V->getType());
10125   unsigned Width = PTy->getNumElements();
10126   if (EltNo >= Width)  // Out of range access.
10127     return UndefValue::get(PTy->getElementType());
10128   
10129   if (isa<UndefValue>(V))
10130     return UndefValue::get(PTy->getElementType());
10131   else if (isa<ConstantAggregateZero>(V))
10132     return Constant::getNullValue(PTy->getElementType());
10133   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10134     return CP->getOperand(EltNo);
10135   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10136     // If this is an insert to a variable element, we don't know what it is.
10137     if (!isa<ConstantInt>(III->getOperand(2))) 
10138       return 0;
10139     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10140     
10141     // If this is an insert to the element we are looking for, return the
10142     // inserted value.
10143     if (EltNo == IIElt) 
10144       return III->getOperand(1);
10145     
10146     // Otherwise, the insertelement doesn't modify the value, recurse on its
10147     // vector input.
10148     return FindScalarElement(III->getOperand(0), EltNo);
10149   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10150     unsigned InEl = getShuffleMask(SVI)[EltNo];
10151     if (InEl < Width)
10152       return FindScalarElement(SVI->getOperand(0), InEl);
10153     else if (InEl < Width*2)
10154       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10155     else
10156       return UndefValue::get(PTy->getElementType());
10157   }
10158   
10159   // Otherwise, we don't know.
10160   return 0;
10161 }
10162
10163 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10164
10165   // If vector val is undef, replace extract with scalar undef.
10166   if (isa<UndefValue>(EI.getOperand(0)))
10167     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10168
10169   // If vector val is constant 0, replace extract with scalar 0.
10170   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10171     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10172   
10173   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10174     // If vector val is constant with uniform operands, replace EI
10175     // with that operand
10176     Constant *op0 = C->getOperand(0);
10177     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10178       if (C->getOperand(i) != op0) {
10179         op0 = 0; 
10180         break;
10181       }
10182     if (op0)
10183       return ReplaceInstUsesWith(EI, op0);
10184   }
10185   
10186   // If extracting a specified index from the vector, see if we can recursively
10187   // find a previously computed scalar that was inserted into the vector.
10188   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10189     unsigned IndexVal = IdxC->getZExtValue();
10190     unsigned VectorWidth = 
10191       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10192       
10193     // If this is extracting an invalid index, turn this into undef, to avoid
10194     // crashing the code below.
10195     if (IndexVal >= VectorWidth)
10196       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10197     
10198     // This instruction only demands the single element from the input vector.
10199     // If the input vector has a single use, simplify it based on this use
10200     // property.
10201     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10202       uint64_t UndefElts;
10203       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10204                                                 1 << IndexVal,
10205                                                 UndefElts)) {
10206         EI.setOperand(0, V);
10207         return &EI;
10208       }
10209     }
10210     
10211     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10212       return ReplaceInstUsesWith(EI, Elt);
10213     
10214     // If the this extractelement is directly using a bitcast from a vector of
10215     // the same number of elements, see if we can find the source element from
10216     // it.  In this case, we will end up needing to bitcast the scalars.
10217     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10218       if (const VectorType *VT = 
10219               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10220         if (VT->getNumElements() == VectorWidth)
10221           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10222             return new BitCastInst(Elt, EI.getType());
10223     }
10224   }
10225   
10226   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10227     if (I->hasOneUse()) {
10228       // Push extractelement into predecessor operation if legal and
10229       // profitable to do so
10230       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10231         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10232         if (CheapToScalarize(BO, isConstantElt)) {
10233           ExtractElementInst *newEI0 = 
10234             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10235                                    EI.getName()+".lhs");
10236           ExtractElementInst *newEI1 =
10237             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10238                                    EI.getName()+".rhs");
10239           InsertNewInstBefore(newEI0, EI);
10240           InsertNewInstBefore(newEI1, EI);
10241           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10242         }
10243       } else if (isa<LoadInst>(I)) {
10244         unsigned AS = 
10245           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10246         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10247                                          PointerType::get(EI.getType(), AS),EI);
10248         GetElementPtrInst *GEP = 
10249           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10250         InsertNewInstBefore(GEP, EI);
10251         return new LoadInst(GEP);
10252       }
10253     }
10254     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10255       // Extracting the inserted element?
10256       if (IE->getOperand(2) == EI.getOperand(1))
10257         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10258       // If the inserted and extracted elements are constants, they must not
10259       // be the same value, extract from the pre-inserted value instead.
10260       if (isa<Constant>(IE->getOperand(2)) &&
10261           isa<Constant>(EI.getOperand(1))) {
10262         AddUsesToWorkList(EI);
10263         EI.setOperand(0, IE->getOperand(0));
10264         return &EI;
10265       }
10266     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10267       // If this is extracting an element from a shufflevector, figure out where
10268       // it came from and extract from the appropriate input element instead.
10269       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10270         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10271         Value *Src;
10272         if (SrcIdx < SVI->getType()->getNumElements())
10273           Src = SVI->getOperand(0);
10274         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10275           SrcIdx -= SVI->getType()->getNumElements();
10276           Src = SVI->getOperand(1);
10277         } else {
10278           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10279         }
10280         return new ExtractElementInst(Src, SrcIdx);
10281       }
10282     }
10283   }
10284   return 0;
10285 }
10286
10287 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10288 /// elements from either LHS or RHS, return the shuffle mask and true. 
10289 /// Otherwise, return false.
10290 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10291                                          std::vector<Constant*> &Mask) {
10292   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10293          "Invalid CollectSingleShuffleElements");
10294   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10295
10296   if (isa<UndefValue>(V)) {
10297     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10298     return true;
10299   } else if (V == LHS) {
10300     for (unsigned i = 0; i != NumElts; ++i)
10301       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10302     return true;
10303   } else if (V == RHS) {
10304     for (unsigned i = 0; i != NumElts; ++i)
10305       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10306     return true;
10307   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10308     // If this is an insert of an extract from some other vector, include it.
10309     Value *VecOp    = IEI->getOperand(0);
10310     Value *ScalarOp = IEI->getOperand(1);
10311     Value *IdxOp    = IEI->getOperand(2);
10312     
10313     if (!isa<ConstantInt>(IdxOp))
10314       return false;
10315     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10316     
10317     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10318       // Okay, we can handle this if the vector we are insertinting into is
10319       // transitively ok.
10320       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10321         // If so, update the mask to reflect the inserted undef.
10322         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10323         return true;
10324       }      
10325     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10326       if (isa<ConstantInt>(EI->getOperand(1)) &&
10327           EI->getOperand(0)->getType() == V->getType()) {
10328         unsigned ExtractedIdx =
10329           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10330         
10331         // This must be extracting from either LHS or RHS.
10332         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10333           // Okay, we can handle this if the vector we are insertinting into is
10334           // transitively ok.
10335           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10336             // If so, update the mask to reflect the inserted value.
10337             if (EI->getOperand(0) == LHS) {
10338               Mask[InsertedIdx & (NumElts-1)] = 
10339                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10340             } else {
10341               assert(EI->getOperand(0) == RHS);
10342               Mask[InsertedIdx & (NumElts-1)] = 
10343                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10344               
10345             }
10346             return true;
10347           }
10348         }
10349       }
10350     }
10351   }
10352   // TODO: Handle shufflevector here!
10353   
10354   return false;
10355 }
10356
10357 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10358 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10359 /// that computes V and the LHS value of the shuffle.
10360 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10361                                      Value *&RHS) {
10362   assert(isa<VectorType>(V->getType()) && 
10363          (RHS == 0 || V->getType() == RHS->getType()) &&
10364          "Invalid shuffle!");
10365   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10366
10367   if (isa<UndefValue>(V)) {
10368     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10369     return V;
10370   } else if (isa<ConstantAggregateZero>(V)) {
10371     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10372     return V;
10373   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10374     // If this is an insert of an extract from some other vector, include it.
10375     Value *VecOp    = IEI->getOperand(0);
10376     Value *ScalarOp = IEI->getOperand(1);
10377     Value *IdxOp    = IEI->getOperand(2);
10378     
10379     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10380       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10381           EI->getOperand(0)->getType() == V->getType()) {
10382         unsigned ExtractedIdx =
10383           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10384         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10385         
10386         // Either the extracted from or inserted into vector must be RHSVec,
10387         // otherwise we'd end up with a shuffle of three inputs.
10388         if (EI->getOperand(0) == RHS || RHS == 0) {
10389           RHS = EI->getOperand(0);
10390           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10391           Mask[InsertedIdx & (NumElts-1)] = 
10392             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10393           return V;
10394         }
10395         
10396         if (VecOp == RHS) {
10397           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10398           // Everything but the extracted element is replaced with the RHS.
10399           for (unsigned i = 0; i != NumElts; ++i) {
10400             if (i != InsertedIdx)
10401               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10402           }
10403           return V;
10404         }
10405         
10406         // If this insertelement is a chain that comes from exactly these two
10407         // vectors, return the vector and the effective shuffle.
10408         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10409           return EI->getOperand(0);
10410         
10411       }
10412     }
10413   }
10414   // TODO: Handle shufflevector here!
10415   
10416   // Otherwise, can't do anything fancy.  Return an identity vector.
10417   for (unsigned i = 0; i != NumElts; ++i)
10418     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10419   return V;
10420 }
10421
10422 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10423   Value *VecOp    = IE.getOperand(0);
10424   Value *ScalarOp = IE.getOperand(1);
10425   Value *IdxOp    = IE.getOperand(2);
10426   
10427   // Inserting an undef or into an undefined place, remove this.
10428   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10429     ReplaceInstUsesWith(IE, VecOp);
10430   
10431   // If the inserted element was extracted from some other vector, and if the 
10432   // indexes are constant, try to turn this into a shufflevector operation.
10433   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10434     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10435         EI->getOperand(0)->getType() == IE.getType()) {
10436       unsigned NumVectorElts = IE.getType()->getNumElements();
10437       unsigned ExtractedIdx =
10438         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10439       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10440       
10441       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10442         return ReplaceInstUsesWith(IE, VecOp);
10443       
10444       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10445         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10446       
10447       // If we are extracting a value from a vector, then inserting it right
10448       // back into the same place, just use the input vector.
10449       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10450         return ReplaceInstUsesWith(IE, VecOp);      
10451       
10452       // We could theoretically do this for ANY input.  However, doing so could
10453       // turn chains of insertelement instructions into a chain of shufflevector
10454       // instructions, and right now we do not merge shufflevectors.  As such,
10455       // only do this in a situation where it is clear that there is benefit.
10456       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10457         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10458         // the values of VecOp, except then one read from EIOp0.
10459         // Build a new shuffle mask.
10460         std::vector<Constant*> Mask;
10461         if (isa<UndefValue>(VecOp))
10462           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10463         else {
10464           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10465           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10466                                                        NumVectorElts));
10467         } 
10468         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10469         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10470                                      ConstantVector::get(Mask));
10471       }
10472       
10473       // If this insertelement isn't used by some other insertelement, turn it
10474       // (and any insertelements it points to), into one big shuffle.
10475       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10476         std::vector<Constant*> Mask;
10477         Value *RHS = 0;
10478         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10479         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10480         // We now have a shuffle of LHS, RHS, Mask.
10481         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10482       }
10483     }
10484   }
10485
10486   return 0;
10487 }
10488
10489
10490 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10491   Value *LHS = SVI.getOperand(0);
10492   Value *RHS = SVI.getOperand(1);
10493   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10494
10495   bool MadeChange = false;
10496   
10497   // Undefined shuffle mask -> undefined value.
10498   if (isa<UndefValue>(SVI.getOperand(2)))
10499     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10500   
10501   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10502   // the undef, change them to undefs.
10503   if (isa<UndefValue>(SVI.getOperand(1))) {
10504     // Scan to see if there are any references to the RHS.  If so, replace them
10505     // with undef element refs and set MadeChange to true.
10506     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10507       if (Mask[i] >= e && Mask[i] != 2*e) {
10508         Mask[i] = 2*e;
10509         MadeChange = true;
10510       }
10511     }
10512     
10513     if (MadeChange) {
10514       // Remap any references to RHS to use LHS.
10515       std::vector<Constant*> Elts;
10516       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10517         if (Mask[i] == 2*e)
10518           Elts.push_back(UndefValue::get(Type::Int32Ty));
10519         else
10520           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10521       }
10522       SVI.setOperand(2, ConstantVector::get(Elts));
10523     }
10524   }
10525   
10526   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10527   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10528   if (LHS == RHS || isa<UndefValue>(LHS)) {
10529     if (isa<UndefValue>(LHS) && LHS == RHS) {
10530       // shuffle(undef,undef,mask) -> undef.
10531       return ReplaceInstUsesWith(SVI, LHS);
10532     }
10533     
10534     // Remap any references to RHS to use LHS.
10535     std::vector<Constant*> Elts;
10536     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10537       if (Mask[i] >= 2*e)
10538         Elts.push_back(UndefValue::get(Type::Int32Ty));
10539       else {
10540         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10541             (Mask[i] <  e && isa<UndefValue>(LHS)))
10542           Mask[i] = 2*e;     // Turn into undef.
10543         else
10544           Mask[i] &= (e-1);  // Force to LHS.
10545         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10546       }
10547     }
10548     SVI.setOperand(0, SVI.getOperand(1));
10549     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10550     SVI.setOperand(2, ConstantVector::get(Elts));
10551     LHS = SVI.getOperand(0);
10552     RHS = SVI.getOperand(1);
10553     MadeChange = true;
10554   }
10555   
10556   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10557   bool isLHSID = true, isRHSID = true;
10558     
10559   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10560     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10561     // Is this an identity shuffle of the LHS value?
10562     isLHSID &= (Mask[i] == i);
10563       
10564     // Is this an identity shuffle of the RHS value?
10565     isRHSID &= (Mask[i]-e == i);
10566   }
10567
10568   // Eliminate identity shuffles.
10569   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10570   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10571   
10572   // If the LHS is a shufflevector itself, see if we can combine it with this
10573   // one without producing an unusual shuffle.  Here we are really conservative:
10574   // we are absolutely afraid of producing a shuffle mask not in the input
10575   // program, because the code gen may not be smart enough to turn a merged
10576   // shuffle into two specific shuffles: it may produce worse code.  As such,
10577   // we only merge two shuffles if the result is one of the two input shuffle
10578   // masks.  In this case, merging the shuffles just removes one instruction,
10579   // which we know is safe.  This is good for things like turning:
10580   // (splat(splat)) -> splat.
10581   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10582     if (isa<UndefValue>(RHS)) {
10583       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10584
10585       std::vector<unsigned> NewMask;
10586       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10587         if (Mask[i] >= 2*e)
10588           NewMask.push_back(2*e);
10589         else
10590           NewMask.push_back(LHSMask[Mask[i]]);
10591       
10592       // If the result mask is equal to the src shuffle or this shuffle mask, do
10593       // the replacement.
10594       if (NewMask == LHSMask || NewMask == Mask) {
10595         std::vector<Constant*> Elts;
10596         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10597           if (NewMask[i] >= e*2) {
10598             Elts.push_back(UndefValue::get(Type::Int32Ty));
10599           } else {
10600             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10601           }
10602         }
10603         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10604                                      LHSSVI->getOperand(1),
10605                                      ConstantVector::get(Elts));
10606       }
10607     }
10608   }
10609
10610   return MadeChange ? &SVI : 0;
10611 }
10612
10613
10614
10615
10616 /// TryToSinkInstruction - Try to move the specified instruction from its
10617 /// current block into the beginning of DestBlock, which can only happen if it's
10618 /// safe to move the instruction past all of the instructions between it and the
10619 /// end of its block.
10620 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10621   assert(I->hasOneUse() && "Invariants didn't hold!");
10622
10623   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10624   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10625
10626   // Do not sink alloca instructions out of the entry block.
10627   if (isa<AllocaInst>(I) && I->getParent() ==
10628         &DestBlock->getParent()->getEntryBlock())
10629     return false;
10630
10631   // We can only sink load instructions if there is nothing between the load and
10632   // the end of block that could change the value.
10633   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10634     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10635          Scan != E; ++Scan)
10636       if (Scan->mayWriteToMemory())
10637         return false;
10638   }
10639
10640   BasicBlock::iterator InsertPos = DestBlock->begin();
10641   while (isa<PHINode>(InsertPos)) ++InsertPos;
10642
10643   I->moveBefore(InsertPos);
10644   ++NumSunkInst;
10645   return true;
10646 }
10647
10648
10649 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10650 /// all reachable code to the worklist.
10651 ///
10652 /// This has a couple of tricks to make the code faster and more powerful.  In
10653 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10654 /// them to the worklist (this significantly speeds up instcombine on code where
10655 /// many instructions are dead or constant).  Additionally, if we find a branch
10656 /// whose condition is a known constant, we only visit the reachable successors.
10657 ///
10658 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10659                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10660                                        InstCombiner &IC,
10661                                        const TargetData *TD) {
10662   std::vector<BasicBlock*> Worklist;
10663   Worklist.push_back(BB);
10664
10665   while (!Worklist.empty()) {
10666     BB = Worklist.back();
10667     Worklist.pop_back();
10668     
10669     // We have now visited this block!  If we've already been here, ignore it.
10670     if (!Visited.insert(BB)) continue;
10671     
10672     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10673       Instruction *Inst = BBI++;
10674       
10675       // DCE instruction if trivially dead.
10676       if (isInstructionTriviallyDead(Inst)) {
10677         ++NumDeadInst;
10678         DOUT << "IC: DCE: " << *Inst;
10679         Inst->eraseFromParent();
10680         continue;
10681       }
10682       
10683       // ConstantProp instruction if trivially constant.
10684       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10685         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10686         Inst->replaceAllUsesWith(C);
10687         ++NumConstProp;
10688         Inst->eraseFromParent();
10689         continue;
10690       }
10691      
10692       IC.AddToWorkList(Inst);
10693     }
10694
10695     // Recursively visit successors.  If this is a branch or switch on a
10696     // constant, only visit the reachable successor.
10697     TerminatorInst *TI = BB->getTerminator();
10698     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10699       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10700         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10701         Worklist.push_back(BI->getSuccessor(!CondVal));
10702         continue;
10703       }
10704     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10705       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10706         // See if this is an explicit destination.
10707         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10708           if (SI->getCaseValue(i) == Cond) {
10709             Worklist.push_back(SI->getSuccessor(i));
10710             continue;
10711           }
10712         
10713         // Otherwise it is the default destination.
10714         Worklist.push_back(SI->getSuccessor(0));
10715         continue;
10716       }
10717     }
10718     
10719     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10720       Worklist.push_back(TI->getSuccessor(i));
10721   }
10722 }
10723
10724 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10725   bool Changed = false;
10726   TD = &getAnalysis<TargetData>();
10727   
10728   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10729              << F.getNameStr() << "\n");
10730
10731   {
10732     // Do a depth-first traversal of the function, populate the worklist with
10733     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10734     // track of which blocks we visit.
10735     SmallPtrSet<BasicBlock*, 64> Visited;
10736     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10737
10738     // Do a quick scan over the function.  If we find any blocks that are
10739     // unreachable, remove any instructions inside of them.  This prevents
10740     // the instcombine code from having to deal with some bad special cases.
10741     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10742       if (!Visited.count(BB)) {
10743         Instruction *Term = BB->getTerminator();
10744         while (Term != BB->begin()) {   // Remove instrs bottom-up
10745           BasicBlock::iterator I = Term; --I;
10746
10747           DOUT << "IC: DCE: " << *I;
10748           ++NumDeadInst;
10749
10750           if (!I->use_empty())
10751             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10752           I->eraseFromParent();
10753         }
10754       }
10755   }
10756
10757   while (!Worklist.empty()) {
10758     Instruction *I = RemoveOneFromWorkList();
10759     if (I == 0) continue;  // skip null values.
10760
10761     // Check to see if we can DCE the instruction.
10762     if (isInstructionTriviallyDead(I)) {
10763       // Add operands to the worklist.
10764       if (I->getNumOperands() < 4)
10765         AddUsesToWorkList(*I);
10766       ++NumDeadInst;
10767
10768       DOUT << "IC: DCE: " << *I;
10769
10770       I->eraseFromParent();
10771       RemoveFromWorkList(I);
10772       continue;
10773     }
10774
10775     // Instruction isn't dead, see if we can constant propagate it.
10776     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10777       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10778
10779       // Add operands to the worklist.
10780       AddUsesToWorkList(*I);
10781       ReplaceInstUsesWith(*I, C);
10782
10783       ++NumConstProp;
10784       I->eraseFromParent();
10785       RemoveFromWorkList(I);
10786       continue;
10787     }
10788
10789     // See if we can trivially sink this instruction to a successor basic block.
10790     if (I->hasOneUse()) {
10791       BasicBlock *BB = I->getParent();
10792       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10793       if (UserParent != BB) {
10794         bool UserIsSuccessor = false;
10795         // See if the user is one of our successors.
10796         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10797           if (*SI == UserParent) {
10798             UserIsSuccessor = true;
10799             break;
10800           }
10801
10802         // If the user is one of our immediate successors, and if that successor
10803         // only has us as a predecessors (we'd have to split the critical edge
10804         // otherwise), we can keep going.
10805         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10806             next(pred_begin(UserParent)) == pred_end(UserParent))
10807           // Okay, the CFG is simple enough, try to sink this instruction.
10808           Changed |= TryToSinkInstruction(I, UserParent);
10809       }
10810     }
10811
10812     // Now that we have an instruction, try combining it to simplify it...
10813 #ifndef NDEBUG
10814     std::string OrigI;
10815 #endif
10816     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10817     if (Instruction *Result = visit(*I)) {
10818       ++NumCombined;
10819       // Should we replace the old instruction with a new one?
10820       if (Result != I) {
10821         DOUT << "IC: Old = " << *I
10822              << "    New = " << *Result;
10823
10824         // Everything uses the new instruction now.
10825         I->replaceAllUsesWith(Result);
10826
10827         // Push the new instruction and any users onto the worklist.
10828         AddToWorkList(Result);
10829         AddUsersToWorkList(*Result);
10830
10831         // Move the name to the new instruction first.
10832         Result->takeName(I);
10833
10834         // Insert the new instruction into the basic block...
10835         BasicBlock *InstParent = I->getParent();
10836         BasicBlock::iterator InsertPos = I;
10837
10838         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10839           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10840             ++InsertPos;
10841
10842         InstParent->getInstList().insert(InsertPos, Result);
10843
10844         // Make sure that we reprocess all operands now that we reduced their
10845         // use counts.
10846         AddUsesToWorkList(*I);
10847
10848         // Instructions can end up on the worklist more than once.  Make sure
10849         // we do not process an instruction that has been deleted.
10850         RemoveFromWorkList(I);
10851
10852         // Erase the old instruction.
10853         InstParent->getInstList().erase(I);
10854       } else {
10855 #ifndef NDEBUG
10856         DOUT << "IC: Mod = " << OrigI
10857              << "    New = " << *I;
10858 #endif
10859
10860         // If the instruction was modified, it's possible that it is now dead.
10861         // if so, remove it.
10862         if (isInstructionTriviallyDead(I)) {
10863           // Make sure we process all operands now that we are reducing their
10864           // use counts.
10865           AddUsesToWorkList(*I);
10866
10867           // Instructions may end up in the worklist more than once.  Erase all
10868           // occurrences of this instruction.
10869           RemoveFromWorkList(I);
10870           I->eraseFromParent();
10871         } else {
10872           AddToWorkList(I);
10873           AddUsersToWorkList(*I);
10874         }
10875       }
10876       Changed = true;
10877     }
10878   }
10879
10880   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10881     
10882   // Do an explicit clear, this shrinks the map if needed.
10883   WorklistMap.clear();
10884   return Changed;
10885 }
10886
10887
10888 bool InstCombiner::runOnFunction(Function &F) {
10889   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10890   
10891   bool EverMadeChange = false;
10892
10893   // Iterate while there is work to do.
10894   unsigned Iteration = 0;
10895   while (DoOneIteration(F, Iteration++)) 
10896     EverMadeChange = true;
10897   return EverMadeChange;
10898 }
10899
10900 FunctionPass *llvm::createInstructionCombiningPass() {
10901   return new InstCombiner();
10902 }
10903