Fix comment.
[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
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.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 <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184     Instruction *visitAnd(BinaryOperator &I);
185     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187                                      Value *A, Value *B, Value *C);
188     Instruction *visitOr (BinaryOperator &I);
189     Instruction *visitXor(BinaryOperator &I);
190     Instruction *visitShl(BinaryOperator &I);
191     Instruction *visitAShr(BinaryOperator &I);
192     Instruction *visitLShr(BinaryOperator &I);
193     Instruction *commonShiftTransforms(BinaryOperator &I);
194     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195                                       Constant *RHSC);
196     Instruction *visitFCmpInst(FCmpInst &I);
197     Instruction *visitICmpInst(ICmpInst &I);
198     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200                                                 Instruction *LHS,
201                                                 ConstantInt *RHS);
202     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203                                 ConstantInt *DivRHS);
204
205     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206                              ICmpInst::Predicate Cond, Instruction &I);
207     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208                                      BinaryOperator &I);
209     Instruction *commonCastTransforms(CastInst &CI);
210     Instruction *commonIntCastTransforms(CastInst &CI);
211     Instruction *commonPointerCastTransforms(CastInst &CI);
212     Instruction *visitTrunc(TruncInst &CI);
213     Instruction *visitZExt(ZExtInst &CI);
214     Instruction *visitSExt(SExtInst &CI);
215     Instruction *visitFPTrunc(FPTruncInst &CI);
216     Instruction *visitFPExt(CastInst &CI);
217     Instruction *visitFPToUI(FPToUIInst &FI);
218     Instruction *visitFPToSI(FPToSIInst &FI);
219     Instruction *visitUIToFP(CastInst &CI);
220     Instruction *visitSIToFP(CastInst &CI);
221     Instruction *visitPtrToInt(CastInst &CI);
222     Instruction *visitIntToPtr(IntToPtrInst &CI);
223     Instruction *visitBitCast(BitCastInst &CI);
224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225                                 Instruction *FI);
226     Instruction *visitSelectInst(SelectInst &SI);
227     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228     Instruction *visitCallInst(CallInst &CI);
229     Instruction *visitInvokeInst(InvokeInst &II);
230     Instruction *visitPHINode(PHINode &PN);
231     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232     Instruction *visitAllocationInst(AllocationInst &AI);
233     Instruction *visitFreeInst(FreeInst &FI);
234     Instruction *visitLoadInst(LoadInst &LI);
235     Instruction *visitStoreInst(StoreInst &SI);
236     Instruction *visitBranchInst(BranchInst &BI);
237     Instruction *visitSwitchInst(SwitchInst &SI);
238     Instruction *visitInsertElementInst(InsertElementInst &IE);
239     Instruction *visitExtractElementInst(ExtractElementInst &EI);
240     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241     Instruction *visitExtractValueInst(ExtractValueInst &EV);
242
243     // visitInstruction - Specify what to return for unhandled instructions...
244     Instruction *visitInstruction(Instruction &I) { return 0; }
245
246   private:
247     Instruction *visitCallSite(CallSite CS);
248     bool transformConstExprCastCall(CallSite CS);
249     Instruction *transformCallThroughTrampoline(CallSite CS);
250     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251                                    bool DoXform = true);
252     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
253
254   public:
255     // InsertNewInstBefore - insert an instruction New before instruction Old
256     // in the program.  Add the new instruction to the worklist.
257     //
258     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259       assert(New && New->getParent() == 0 &&
260              "New instruction already inserted into a basic block!");
261       BasicBlock *BB = Old.getParent();
262       BB->getInstList().insert(&Old, New);  // Insert inst
263       AddToWorkList(New);
264       return New;
265     }
266
267     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268     /// This also adds the cast to the worklist.  Finally, this returns the
269     /// cast.
270     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271                             Instruction &Pos) {
272       if (V->getType() == Ty) return V;
273
274       if (Constant *CV = dyn_cast<Constant>(V))
275         return ConstantExpr::getCast(opc, CV, Ty);
276       
277       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
278       AddToWorkList(C);
279       return C;
280     }
281         
282     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284     }
285
286
287     // ReplaceInstUsesWith - This method is to be used when an instruction is
288     // found to be dead, replacable with another preexisting expression.  Here
289     // we add all uses of I to the worklist, replace all uses of I with the new
290     // value, then return I, so that the inst combiner will know that I was
291     // modified.
292     //
293     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294       AddUsersToWorkList(I);         // Add all modified instrs to worklist
295       if (&I != V) {
296         I.replaceAllUsesWith(V);
297         return &I;
298       } else {
299         // If we are replacing the instruction with itself, this must be in a
300         // segment of unreachable code, so just clobber the instruction.
301         I.replaceAllUsesWith(UndefValue::get(I.getType()));
302         return &I;
303       }
304     }
305
306     // UpdateValueUsesWith - This method is to be used when an value is
307     // found to be replacable with another preexisting expression or was
308     // updated.  Here we add all uses of I to the worklist, replace all uses of
309     // I with the new value (unless the instruction was just updated), then
310     // return true, so that the inst combiner will know that I was modified.
311     //
312     bool UpdateValueUsesWith(Value *Old, Value *New) {
313       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
314       if (Old != New)
315         Old->replaceAllUsesWith(New);
316       if (Instruction *I = dyn_cast<Instruction>(Old))
317         AddToWorkList(I);
318       if (Instruction *I = dyn_cast<Instruction>(New))
319         AddToWorkList(I);
320       return true;
321     }
322     
323     // EraseInstFromFunction - When dealing with an instruction that has side
324     // effects or produces a void value, we can't rely on DCE to delete the
325     // instruction.  Instead, visit methods should return the value returned by
326     // this function.
327     Instruction *EraseInstFromFunction(Instruction &I) {
328       assert(I.use_empty() && "Cannot erase instruction that is used!");
329       AddUsesToWorkList(I);
330       RemoveFromWorkList(&I);
331       I.eraseFromParent();
332       return 0;  // Don't do anything with FI
333     }
334         
335     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
336                            APInt &KnownOne, unsigned Depth = 0) const {
337       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
338     }
339     
340     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
341                            unsigned Depth = 0) const {
342       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
343     }
344     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
345       return llvm::ComputeNumSignBits(Op, TD, Depth);
346     }
347
348   private:
349
350     /// SimplifyCommutative - This performs a few simplifications for 
351     /// commutative operators.
352     bool SimplifyCommutative(BinaryOperator &I);
353
354     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355     /// most-complex to least-complex order.
356     bool SimplifyCompare(CmpInst &I);
357
358     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359     /// on the demanded bits.
360     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
361                               APInt& KnownZero, APInt& KnownOne,
362                               unsigned Depth = 0);
363
364     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365                                       uint64_t &UndefElts, unsigned Depth = 0);
366       
367     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368     // PHI node as operand #0, see if we can fold the instruction into the PHI
369     // (which is only possible if all operands to the PHI are constants).
370     Instruction *FoldOpIntoPhi(Instruction &I);
371
372     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373     // operator and they all are only used by the PHI, PHI together their
374     // inputs, and do the operation once, to the result of the PHI.
375     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
378
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397                                     unsigned CastOpc,
398                                     int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414       return 3;
415     return 4;
416   }
417   if (isa<Argument>(V)) return 3;
418   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419 }
420
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 // it.
423 static bool isOnlyUse(Value *V) {
424   return V->hasOneUse() || isa<Constant>(V);
425 }
426
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431     if (ITy->getBitWidth() < 32)
432       return Type::Int32Ty;
433   }
434   return Ty;
435 }
436
437 /// getBitCastOperand - If the specified operand is a CastInst, a constant
438 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
439 /// operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442     // BitCastInst?
443     return I->getOperand(0);
444   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
445     // GetElementPtrInst?
446     if (GEP->hasAllZeroIndices())
447       return GEP->getOperand(0);
448   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
449     if (CE->getOpcode() == Instruction::BitCast)
450       // BitCast ConstantExp?
451       return CE->getOperand(0);
452     else if (CE->getOpcode() == Instruction::GetElementPtr) {
453       // GetElementPtr ConstantExp?
454       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
455            I != E; ++I) {
456         ConstantInt *CI = dyn_cast<ConstantInt>(I);
457         if (!CI || !CI->isZero())
458           // Any non-zero indices? Not cast-like.
459           return 0;
460       }
461       // All-zero indices? This is just like casting.
462       return CE->getOperand(0);
463     }
464   }
465   return 0;
466 }
467
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps 
471 isEliminableCastPair(
472   const CastInst *CI, ///< The first cast instruction
473   unsigned opcode,       ///< The opcode of the second cast instruction
474   const Type *DstTy,     ///< The target type for the second cast instruction
475   TargetData *TD         ///< The target data for pointer size
476 ) {
477   
478   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
479   const Type *MidTy = CI->getType();                  // B from above
480
481   // Get the opcodes of the two Cast instructions
482   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
484
485   return Instruction::CastOps(
486       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487                                      DstTy, TD->getIntPtrType()));
488 }
489
490 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
491 /// in any code being generated.  It does not require codegen if V is simple
492 /// enough or if the cast can be folded into other casts.
493 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
494                               const Type *Ty, TargetData *TD) {
495   if (V->getType() == Ty || isa<Constant>(V)) return false;
496   
497   // If this is another cast that can be eliminated, it isn't codegen either.
498   if (const CastInst *CI = dyn_cast<CastInst>(V))
499     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
500       return false;
501   return true;
502 }
503
504 // SimplifyCommutative - This performs a few simplifications for commutative
505 // operators:
506 //
507 //  1. Order operands such that they are listed from right (least complex) to
508 //     left (most complex).  This puts constants before unary operators before
509 //     binary operators.
510 //
511 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
512 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
513 //
514 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
515   bool Changed = false;
516   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
517     Changed = !I.swapOperands();
518
519   if (!I.isAssociative()) return Changed;
520   Instruction::BinaryOps Opcode = I.getOpcode();
521   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523       if (isa<Constant>(I.getOperand(1))) {
524         Constant *Folded = ConstantExpr::get(I.getOpcode(),
525                                              cast<Constant>(I.getOperand(1)),
526                                              cast<Constant>(Op->getOperand(1)));
527         I.setOperand(0, Op->getOperand(0));
528         I.setOperand(1, Folded);
529         return true;
530       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532             isOnlyUse(Op) && isOnlyUse(Op1)) {
533           Constant *C1 = cast<Constant>(Op->getOperand(1));
534           Constant *C2 = cast<Constant>(Op1->getOperand(1));
535
536           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
537           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
538           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
539                                                     Op1->getOperand(0),
540                                                     Op1->getName(), &I);
541           AddToWorkList(New);
542           I.setOperand(0, New);
543           I.setOperand(1, Folded);
544           return true;
545         }
546     }
547   return Changed;
548 }
549
550 /// SimplifyCompare - For a CmpInst this function just orders the operands
551 /// so that theyare listed from right (least complex) to left (most complex).
552 /// This puts constants before unary operators before binary operators.
553 bool InstCombiner::SimplifyCompare(CmpInst &I) {
554   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
555     return false;
556   I.swapOperands();
557   // Compare instructions are not associative so there's nothing else we can do.
558   return true;
559 }
560
561 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
562 // if the LHS is a constant zero (which is the 'negate' form).
563 //
564 static inline Value *dyn_castNegVal(Value *V) {
565   if (BinaryOperator::isNeg(V))
566     return BinaryOperator::getNegArgument(V);
567
568   // Constants can be considered to be negated values if they can be folded.
569   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
570     return ConstantExpr::getNeg(C);
571
572   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
573     if (C->getType()->getElementType()->isInteger())
574       return ConstantExpr::getNeg(C);
575
576   return 0;
577 }
578
579 static inline Value *dyn_castNotVal(Value *V) {
580   if (BinaryOperator::isNot(V))
581     return BinaryOperator::getNotArgument(V);
582
583   // Constants can be considered to be not'ed values...
584   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
585     return ConstantInt::get(~C->getValue());
586   return 0;
587 }
588
589 // dyn_castFoldableMul - If this value is a multiply that can be folded into
590 // other computations (because it has a constant operand), return the
591 // non-constant operand of the multiply, and set CST to point to the multiplier.
592 // Otherwise, return null.
593 //
594 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
595   if (V->hasOneUse() && V->getType()->isInteger())
596     if (Instruction *I = dyn_cast<Instruction>(V)) {
597       if (I->getOpcode() == Instruction::Mul)
598         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
599           return I->getOperand(0);
600       if (I->getOpcode() == Instruction::Shl)
601         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
602           // The multiplier is really 1 << CST.
603           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
604           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
605           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
606           return I->getOperand(0);
607         }
608     }
609   return 0;
610 }
611
612 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
613 /// expression, return it.
614 static User *dyn_castGetElementPtr(Value *V) {
615   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
616   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
617     if (CE->getOpcode() == Instruction::GetElementPtr)
618       return cast<User>(V);
619   return false;
620 }
621
622 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
623 /// opcode value. Otherwise return UserOp1.
624 static unsigned getOpcode(const Value *V) {
625   if (const Instruction *I = dyn_cast<Instruction>(V))
626     return I->getOpcode();
627   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
628     return CE->getOpcode();
629   // Use UserOp1 to mean there's no opcode.
630   return Instruction::UserOp1;
631 }
632
633 /// AddOne - Add one to a ConstantInt
634 static ConstantInt *AddOne(ConstantInt *C) {
635   APInt Val(C->getValue());
636   return ConstantInt::get(++Val);
637 }
638 /// SubOne - Subtract one from a ConstantInt
639 static ConstantInt *SubOne(ConstantInt *C) {
640   APInt Val(C->getValue());
641   return ConstantInt::get(--Val);
642 }
643 /// Add - Add two ConstantInts together
644 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
645   return ConstantInt::get(C1->getValue() + C2->getValue());
646 }
647 /// And - Bitwise AND two ConstantInts together
648 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
649   return ConstantInt::get(C1->getValue() & C2->getValue());
650 }
651 /// Subtract - Subtract one ConstantInt from another
652 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
653   return ConstantInt::get(C1->getValue() - C2->getValue());
654 }
655 /// Multiply - Multiply two ConstantInts together
656 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
657   return ConstantInt::get(C1->getValue() * C2->getValue());
658 }
659 /// MultiplyOverflows - True if the multiply can not be expressed in an int
660 /// this size.
661 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
662   uint32_t W = C1->getBitWidth();
663   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
664   if (sign) {
665     LHSExt.sext(W * 2);
666     RHSExt.sext(W * 2);
667   } else {
668     LHSExt.zext(W * 2);
669     RHSExt.zext(W * 2);
670   }
671
672   APInt MulExt = LHSExt * RHSExt;
673
674   if (sign) {
675     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
676     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
677     return MulExt.slt(Min) || MulExt.sgt(Max);
678   } else 
679     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
680 }
681
682
683 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
684 /// specified instruction is a constant integer.  If so, check to see if there
685 /// are any bits set in the constant that are not demanded.  If so, shrink the
686 /// constant and return true.
687 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
688                                    APInt Demanded) {
689   assert(I && "No instruction?");
690   assert(OpNo < I->getNumOperands() && "Operand index too large");
691
692   // If the operand is not a constant integer, nothing to do.
693   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
694   if (!OpC) return false;
695
696   // If there are no bits set that aren't demanded, nothing to do.
697   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
698   if ((~Demanded & OpC->getValue()) == 0)
699     return false;
700
701   // This instruction is producing bits that are not demanded. Shrink the RHS.
702   Demanded &= OpC->getValue();
703   I->setOperand(OpNo, ConstantInt::get(Demanded));
704   return true;
705 }
706
707 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
708 // set of known zero and one bits, compute the maximum and minimum values that
709 // could have the specified known zero and known one bits, returning them in
710 // min/max.
711 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
712                                                    const APInt& KnownZero,
713                                                    const APInt& KnownOne,
714                                                    APInt& Min, APInt& Max) {
715   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
716   assert(KnownZero.getBitWidth() == BitWidth && 
717          KnownOne.getBitWidth() == BitWidth &&
718          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
719          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
720   APInt UnknownBits = ~(KnownZero|KnownOne);
721
722   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723   // bit if it is unknown.
724   Min = KnownOne;
725   Max = KnownOne|UnknownBits;
726   
727   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
728     Min.set(BitWidth-1);
729     Max.clear(BitWidth-1);
730   }
731 }
732
733 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734 // a set of known zero and one bits, compute the maximum and minimum values that
735 // could have the specified known zero and known one bits, returning them in
736 // min/max.
737 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
738                                                      const APInt &KnownZero,
739                                                      const APInt &KnownOne,
740                                                      APInt &Min, APInt &Max) {
741   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
742   assert(KnownZero.getBitWidth() == BitWidth && 
743          KnownOne.getBitWidth() == BitWidth &&
744          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
745          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
746   APInt UnknownBits = ~(KnownZero|KnownOne);
747   
748   // The minimum value is when the unknown bits are all zeros.
749   Min = KnownOne;
750   // The maximum value is when the unknown bits are all ones.
751   Max = KnownOne|UnknownBits;
752 }
753
754 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
755 /// value based on the demanded bits. When this function is called, it is known
756 /// that only the bits set in DemandedMask of the result of V are ever used
757 /// downstream. Consequently, depending on the mask and V, it may be possible
758 /// to replace V with a constant or one of its operands. In such cases, this
759 /// function does the replacement and returns true. In all other cases, it
760 /// returns false after analyzing the expression and setting KnownOne and known
761 /// to be one in the expression. KnownZero contains all the bits that are known
762 /// to be zero in the expression. These are provided to potentially allow the
763 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
764 /// the expression. KnownOne and KnownZero always follow the invariant that 
765 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
766 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
767 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
768 /// and KnownOne must all be the same.
769 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
770                                         APInt& KnownZero, APInt& KnownOne,
771                                         unsigned Depth) {
772   assert(V != 0 && "Null pointer of Value???");
773   assert(Depth <= 6 && "Limit Search Depth");
774   uint32_t BitWidth = DemandedMask.getBitWidth();
775   const IntegerType *VTy = cast<IntegerType>(V->getType());
776   assert(VTy->getBitWidth() == BitWidth && 
777          KnownZero.getBitWidth() == BitWidth && 
778          KnownOne.getBitWidth() == BitWidth &&
779          "Value *V, DemandedMask, KnownZero and KnownOne \
780           must have same BitWidth");
781   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
782     // We know all of the bits for a constant!
783     KnownOne = CI->getValue() & DemandedMask;
784     KnownZero = ~KnownOne & DemandedMask;
785     return false;
786   }
787   
788   KnownZero.clear(); 
789   KnownOne.clear();
790   if (!V->hasOneUse()) {    // Other users may use these bits.
791     if (Depth != 0) {       // Not at the root.
792       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
793       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
794       return false;
795     }
796     // If this is the root being simplified, allow it to have multiple uses,
797     // just set the DemandedMask to all bits.
798     DemandedMask = APInt::getAllOnesValue(BitWidth);
799   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
800     if (V != UndefValue::get(VTy))
801       return UpdateValueUsesWith(V, UndefValue::get(VTy));
802     return false;
803   } else if (Depth == 6) {        // Limit search depth.
804     return false;
805   }
806   
807   Instruction *I = dyn_cast<Instruction>(V);
808   if (!I) return false;        // Only analyze instructions.
809
810   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
811   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
812   switch (I->getOpcode()) {
813   default:
814     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
815     break;
816   case Instruction::And:
817     // If either the LHS or the RHS are Zero, the result is zero.
818     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
819                              RHSKnownZero, RHSKnownOne, Depth+1))
820       return true;
821     assert((RHSKnownZero & RHSKnownOne) == 0 && 
822            "Bits known to be one AND zero?"); 
823
824     // If something is known zero on the RHS, the bits aren't demanded on the
825     // LHS.
826     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
827                              LHSKnownZero, LHSKnownOne, Depth+1))
828       return true;
829     assert((LHSKnownZero & LHSKnownOne) == 0 && 
830            "Bits known to be one AND zero?"); 
831
832     // If all of the demanded bits are known 1 on one side, return the other.
833     // These bits cannot contribute to the result of the 'and'.
834     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
835         (DemandedMask & ~LHSKnownZero))
836       return UpdateValueUsesWith(I, I->getOperand(0));
837     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
838         (DemandedMask & ~RHSKnownZero))
839       return UpdateValueUsesWith(I, I->getOperand(1));
840     
841     // If all of the demanded bits in the inputs are known zeros, return zero.
842     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
843       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
844       
845     // If the RHS is a constant, see if we can simplify it.
846     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
847       return UpdateValueUsesWith(I, I);
848       
849     // Output known-1 bits are only known if set in both the LHS & RHS.
850     RHSKnownOne &= LHSKnownOne;
851     // Output known-0 are known to be clear if zero in either the LHS | RHS.
852     RHSKnownZero |= LHSKnownZero;
853     break;
854   case Instruction::Or:
855     // If either the LHS or the RHS are One, the result is One.
856     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
857                              RHSKnownZero, RHSKnownOne, Depth+1))
858       return true;
859     assert((RHSKnownZero & RHSKnownOne) == 0 && 
860            "Bits known to be one AND zero?"); 
861     // If something is known one on the RHS, the bits aren't demanded on the
862     // LHS.
863     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
864                              LHSKnownZero, LHSKnownOne, Depth+1))
865       return true;
866     assert((LHSKnownZero & LHSKnownOne) == 0 && 
867            "Bits known to be one AND zero?"); 
868     
869     // If all of the demanded bits are known zero on one side, return the other.
870     // These bits cannot contribute to the result of the 'or'.
871     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
872         (DemandedMask & ~LHSKnownOne))
873       return UpdateValueUsesWith(I, I->getOperand(0));
874     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
875         (DemandedMask & ~RHSKnownOne))
876       return UpdateValueUsesWith(I, I->getOperand(1));
877
878     // If all of the potentially set bits on one side are known to be set on
879     // the other side, just use the 'other' side.
880     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
881         (DemandedMask & (~RHSKnownZero)))
882       return UpdateValueUsesWith(I, I->getOperand(0));
883     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
884         (DemandedMask & (~LHSKnownZero)))
885       return UpdateValueUsesWith(I, I->getOperand(1));
886         
887     // If the RHS is a constant, see if we can simplify it.
888     if (ShrinkDemandedConstant(I, 1, DemandedMask))
889       return UpdateValueUsesWith(I, I);
890           
891     // Output known-0 bits are only known if clear in both the LHS & RHS.
892     RHSKnownZero &= LHSKnownZero;
893     // Output known-1 are known to be set if set in either the LHS | RHS.
894     RHSKnownOne |= LHSKnownOne;
895     break;
896   case Instruction::Xor: {
897     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
898                              RHSKnownZero, RHSKnownOne, Depth+1))
899       return true;
900     assert((RHSKnownZero & RHSKnownOne) == 0 && 
901            "Bits known to be one AND zero?"); 
902     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
903                              LHSKnownZero, LHSKnownOne, Depth+1))
904       return true;
905     assert((LHSKnownZero & LHSKnownOne) == 0 && 
906            "Bits known to be one AND zero?"); 
907     
908     // If all of the demanded bits are known zero on one side, return the other.
909     // These bits cannot contribute to the result of the 'xor'.
910     if ((DemandedMask & RHSKnownZero) == DemandedMask)
911       return UpdateValueUsesWith(I, I->getOperand(0));
912     if ((DemandedMask & LHSKnownZero) == DemandedMask)
913       return UpdateValueUsesWith(I, I->getOperand(1));
914     
915     // Output known-0 bits are known if clear or set in both the LHS & RHS.
916     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
917                          (RHSKnownOne & LHSKnownOne);
918     // Output known-1 are known to be set if set in only one of the LHS, RHS.
919     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
920                         (RHSKnownOne & LHSKnownZero);
921     
922     // If all of the demanded bits are known to be zero on one side or the
923     // other, turn this into an *inclusive* or.
924     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
925     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
926       Instruction *Or =
927         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
928                                  I->getName());
929       InsertNewInstBefore(Or, *I);
930       return UpdateValueUsesWith(I, Or);
931     }
932     
933     // If all of the demanded bits on one side are known, and all of the set
934     // bits on that side are also known to be set on the other side, turn this
935     // into an AND, as we know the bits will be cleared.
936     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
937     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
938       // all known
939       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
940         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
941         Instruction *And = 
942           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
943         InsertNewInstBefore(And, *I);
944         return UpdateValueUsesWith(I, And);
945       }
946     }
947     
948     // If the RHS is a constant, see if we can simplify it.
949     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
950     if (ShrinkDemandedConstant(I, 1, DemandedMask))
951       return UpdateValueUsesWith(I, I);
952     
953     RHSKnownZero = KnownZeroOut;
954     RHSKnownOne  = KnownOneOut;
955     break;
956   }
957   case Instruction::Select:
958     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
959                              RHSKnownZero, RHSKnownOne, Depth+1))
960       return true;
961     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
962                              LHSKnownZero, LHSKnownOne, Depth+1))
963       return true;
964     assert((RHSKnownZero & RHSKnownOne) == 0 && 
965            "Bits known to be one AND zero?"); 
966     assert((LHSKnownZero & LHSKnownOne) == 0 && 
967            "Bits known to be one AND zero?"); 
968     
969     // If the operands are constants, see if we can simplify them.
970     if (ShrinkDemandedConstant(I, 1, DemandedMask))
971       return UpdateValueUsesWith(I, I);
972     if (ShrinkDemandedConstant(I, 2, DemandedMask))
973       return UpdateValueUsesWith(I, I);
974     
975     // Only known if known in both the LHS and RHS.
976     RHSKnownOne &= LHSKnownOne;
977     RHSKnownZero &= LHSKnownZero;
978     break;
979   case Instruction::Trunc: {
980     uint32_t truncBf = 
981       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
982     DemandedMask.zext(truncBf);
983     RHSKnownZero.zext(truncBf);
984     RHSKnownOne.zext(truncBf);
985     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
986                              RHSKnownZero, RHSKnownOne, Depth+1))
987       return true;
988     DemandedMask.trunc(BitWidth);
989     RHSKnownZero.trunc(BitWidth);
990     RHSKnownOne.trunc(BitWidth);
991     assert((RHSKnownZero & RHSKnownOne) == 0 && 
992            "Bits known to be one AND zero?"); 
993     break;
994   }
995   case Instruction::BitCast:
996     if (!I->getOperand(0)->getType()->isInteger())
997       return false;
998       
999     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1000                              RHSKnownZero, RHSKnownOne, Depth+1))
1001       return true;
1002     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1003            "Bits known to be one AND zero?"); 
1004     break;
1005   case Instruction::ZExt: {
1006     // Compute the bits in the result that are not present in the input.
1007     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1008     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1009     
1010     DemandedMask.trunc(SrcBitWidth);
1011     RHSKnownZero.trunc(SrcBitWidth);
1012     RHSKnownOne.trunc(SrcBitWidth);
1013     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1014                              RHSKnownZero, RHSKnownOne, Depth+1))
1015       return true;
1016     DemandedMask.zext(BitWidth);
1017     RHSKnownZero.zext(BitWidth);
1018     RHSKnownOne.zext(BitWidth);
1019     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1020            "Bits known to be one AND zero?"); 
1021     // The top bits are known to be zero.
1022     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1023     break;
1024   }
1025   case Instruction::SExt: {
1026     // Compute the bits in the result that are not present in the input.
1027     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1028     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1029     
1030     APInt InputDemandedBits = DemandedMask & 
1031                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1032
1033     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1034     // If any of the sign extended bits are demanded, we know that the sign
1035     // bit is demanded.
1036     if ((NewBits & DemandedMask) != 0)
1037       InputDemandedBits.set(SrcBitWidth-1);
1038       
1039     InputDemandedBits.trunc(SrcBitWidth);
1040     RHSKnownZero.trunc(SrcBitWidth);
1041     RHSKnownOne.trunc(SrcBitWidth);
1042     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043                              RHSKnownZero, RHSKnownOne, Depth+1))
1044       return true;
1045     InputDemandedBits.zext(BitWidth);
1046     RHSKnownZero.zext(BitWidth);
1047     RHSKnownOne.zext(BitWidth);
1048     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1049            "Bits known to be one AND zero?"); 
1050       
1051     // If the sign bit of the input is known set or clear, then we know the
1052     // top bits of the result.
1053
1054     // If the input sign bit is known zero, or if the NewBits are not demanded
1055     // convert this into a zero extension.
1056     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1057     {
1058       // Convert to ZExt cast
1059       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1060       return UpdateValueUsesWith(I, NewCast);
1061     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1062       RHSKnownOne |= NewBits;
1063     }
1064     break;
1065   }
1066   case Instruction::Add: {
1067     // Figure out what the input bits are.  If the top bits of the and result
1068     // are not demanded, then the add doesn't demand them from its input
1069     // either.
1070     uint32_t NLZ = DemandedMask.countLeadingZeros();
1071       
1072     // If there is a constant on the RHS, there are a variety of xformations
1073     // we can do.
1074     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1075       // If null, this should be simplified elsewhere.  Some of the xforms here
1076       // won't work if the RHS is zero.
1077       if (RHS->isZero())
1078         break;
1079       
1080       // If the top bit of the output is demanded, demand everything from the
1081       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1082       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1083
1084       // Find information about known zero/one bits in the input.
1085       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1086                                LHSKnownZero, LHSKnownOne, Depth+1))
1087         return true;
1088
1089       // If the RHS of the add has bits set that can't affect the input, reduce
1090       // the constant.
1091       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1092         return UpdateValueUsesWith(I, I);
1093       
1094       // Avoid excess work.
1095       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1096         break;
1097       
1098       // Turn it into OR if input bits are zero.
1099       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1100         Instruction *Or =
1101           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1102                                    I->getName());
1103         InsertNewInstBefore(Or, *I);
1104         return UpdateValueUsesWith(I, Or);
1105       }
1106       
1107       // We can say something about the output known-zero and known-one bits,
1108       // depending on potential carries from the input constant and the
1109       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1110       // bits set and the RHS constant is 0x01001, then we know we have a known
1111       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1112       
1113       // To compute this, we first compute the potential carry bits.  These are
1114       // the bits which may be modified.  I'm not aware of a better way to do
1115       // this scan.
1116       const APInt& RHSVal = RHS->getValue();
1117       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1118       
1119       // Now that we know which bits have carries, compute the known-1/0 sets.
1120       
1121       // Bits are known one if they are known zero in one operand and one in the
1122       // other, and there is no input carry.
1123       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1124                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1125       
1126       // Bits are known zero if they are known zero in both operands and there
1127       // is no input carry.
1128       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1129     } else {
1130       // If the high-bits of this ADD are not demanded, then it does not demand
1131       // the high bits of its LHS or RHS.
1132       if (DemandedMask[BitWidth-1] == 0) {
1133         // Right fill the mask of bits for this ADD to demand the most
1134         // significant bit and all those below it.
1135         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1136         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1137                                  LHSKnownZero, LHSKnownOne, Depth+1))
1138           return true;
1139         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1140                                  LHSKnownZero, LHSKnownOne, Depth+1))
1141           return true;
1142       }
1143     }
1144     break;
1145   }
1146   case Instruction::Sub:
1147     // If the high-bits of this SUB are not demanded, then it does not demand
1148     // the high bits of its LHS or RHS.
1149     if (DemandedMask[BitWidth-1] == 0) {
1150       // Right fill the mask of bits for this SUB to demand the most
1151       // significant bit and all those below it.
1152       uint32_t NLZ = DemandedMask.countLeadingZeros();
1153       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1154       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1155                                LHSKnownZero, LHSKnownOne, Depth+1))
1156         return true;
1157       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1158                                LHSKnownZero, LHSKnownOne, Depth+1))
1159         return true;
1160     }
1161     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1162     // the known zeros and ones.
1163     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1164     break;
1165   case Instruction::Shl:
1166     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1167       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1168       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1169       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1170                                RHSKnownZero, RHSKnownOne, Depth+1))
1171         return true;
1172       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1173              "Bits known to be one AND zero?"); 
1174       RHSKnownZero <<= ShiftAmt;
1175       RHSKnownOne  <<= ShiftAmt;
1176       // low bits known zero.
1177       if (ShiftAmt)
1178         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1179     }
1180     break;
1181   case Instruction::LShr:
1182     // For a logical shift right
1183     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1184       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1185       
1186       // Unsigned shift right.
1187       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1188       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1189                                RHSKnownZero, RHSKnownOne, Depth+1))
1190         return true;
1191       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1192              "Bits known to be one AND zero?"); 
1193       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1194       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1195       if (ShiftAmt) {
1196         // Compute the new bits that are at the top now.
1197         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1198         RHSKnownZero |= HighBits;  // high bits known zero.
1199       }
1200     }
1201     break;
1202   case Instruction::AShr:
1203     // If this is an arithmetic shift right and only the low-bit is set, we can
1204     // always convert this into a logical shr, even if the shift amount is
1205     // variable.  The low bit of the shift cannot be an input sign bit unless
1206     // the shift amount is >= the size of the datatype, which is undefined.
1207     if (DemandedMask == 1) {
1208       // Perform the logical shift right.
1209       Value *NewVal = BinaryOperator::CreateLShr(
1210                         I->getOperand(0), I->getOperand(1), I->getName());
1211       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1212       return UpdateValueUsesWith(I, NewVal);
1213     }    
1214
1215     // If the sign bit is the only bit demanded by this ashr, then there is no
1216     // need to do it, the shift doesn't change the high bit.
1217     if (DemandedMask.isSignBit())
1218       return UpdateValueUsesWith(I, I->getOperand(0));
1219     
1220     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1221       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1222       
1223       // Signed shift right.
1224       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1225       // If any of the "high bits" are demanded, we should set the sign bit as
1226       // demanded.
1227       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1228         DemandedMaskIn.set(BitWidth-1);
1229       if (SimplifyDemandedBits(I->getOperand(0),
1230                                DemandedMaskIn,
1231                                RHSKnownZero, RHSKnownOne, Depth+1))
1232         return true;
1233       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1234              "Bits known to be one AND zero?"); 
1235       // Compute the new bits that are at the top now.
1236       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1237       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1238       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1239         
1240       // Handle the sign bits.
1241       APInt SignBit(APInt::getSignBit(BitWidth));
1242       // Adjust to where it is now in the mask.
1243       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1244         
1245       // If the input sign bit is known to be zero, or if none of the top bits
1246       // are demanded, turn this into an unsigned shift right.
1247       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1248           (HighBits & ~DemandedMask) == HighBits) {
1249         // Perform the logical shift right.
1250         Value *NewVal = BinaryOperator::CreateLShr(
1251                           I->getOperand(0), SA, I->getName());
1252         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1253         return UpdateValueUsesWith(I, NewVal);
1254       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1255         RHSKnownOne |= HighBits;
1256       }
1257     }
1258     break;
1259   case Instruction::SRem:
1260     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1261       APInt RA = Rem->getValue().abs();
1262       if (RA.isPowerOf2()) {
1263         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1264           return UpdateValueUsesWith(I, I->getOperand(0));
1265
1266         APInt LowBits = RA - 1;
1267         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1268         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1269                                  LHSKnownZero, LHSKnownOne, Depth+1))
1270           return true;
1271
1272         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1273           LHSKnownZero |= ~LowBits;
1274
1275         KnownZero |= LHSKnownZero & DemandedMask;
1276
1277         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1278       }
1279     }
1280     break;
1281   case Instruction::URem: {
1282     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1283     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1284     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1285                              KnownZero2, KnownOne2, Depth+1))
1286       return true;
1287
1288     uint32_t Leaders = KnownZero2.countLeadingOnes();
1289     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1290                              KnownZero2, KnownOne2, Depth+1))
1291       return true;
1292
1293     Leaders = std::max(Leaders,
1294                        KnownZero2.countLeadingOnes());
1295     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1296     break;
1297   }
1298   case Instruction::Call:
1299     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1300       switch (II->getIntrinsicID()) {
1301       default: break;
1302       case Intrinsic::bswap: {
1303         // If the only bits demanded come from one byte of the bswap result,
1304         // just shift the input byte into position to eliminate the bswap.
1305         unsigned NLZ = DemandedMask.countLeadingZeros();
1306         unsigned NTZ = DemandedMask.countTrailingZeros();
1307           
1308         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1309         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1310         // have 14 leading zeros, round to 8.
1311         NLZ &= ~7;
1312         NTZ &= ~7;
1313         // If we need exactly one byte, we can do this transformation.
1314         if (BitWidth-NLZ-NTZ == 8) {
1315           unsigned ResultBit = NTZ;
1316           unsigned InputBit = BitWidth-NTZ-8;
1317           
1318           // Replace this with either a left or right shift to get the byte into
1319           // the right place.
1320           Instruction *NewVal;
1321           if (InputBit > ResultBit)
1322             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1323                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1324           else
1325             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1326                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1327           NewVal->takeName(I);
1328           InsertNewInstBefore(NewVal, *I);
1329           return UpdateValueUsesWith(I, NewVal);
1330         }
1331           
1332         // TODO: Could compute known zero/one bits based on the input.
1333         break;
1334       }
1335       }
1336     }
1337     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1338     break;
1339   }
1340   
1341   // If the client is only demanding bits that we know, return the known
1342   // constant.
1343   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1344     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1345   return false;
1346 }
1347
1348
1349 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1350 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1351 /// actually used by the caller.  This method analyzes which elements of the
1352 /// operand are undef and returns that information in UndefElts.
1353 ///
1354 /// If the information about demanded elements can be used to simplify the
1355 /// operation, the operation is simplified, then the resultant value is
1356 /// returned.  This returns null if no change was made.
1357 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1358                                                 uint64_t &UndefElts,
1359                                                 unsigned Depth) {
1360   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1361   assert(VWidth <= 64 && "Vector too wide to analyze!");
1362   uint64_t EltMask = ~0ULL >> (64-VWidth);
1363   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1364
1365   if (isa<UndefValue>(V)) {
1366     // If the entire vector is undefined, just return this info.
1367     UndefElts = EltMask;
1368     return 0;
1369   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1370     UndefElts = EltMask;
1371     return UndefValue::get(V->getType());
1372   }
1373
1374   UndefElts = 0;
1375   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1376     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1377     Constant *Undef = UndefValue::get(EltTy);
1378
1379     std::vector<Constant*> Elts;
1380     for (unsigned i = 0; i != VWidth; ++i)
1381       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1382         Elts.push_back(Undef);
1383         UndefElts |= (1ULL << i);
1384       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1385         Elts.push_back(Undef);
1386         UndefElts |= (1ULL << i);
1387       } else {                               // Otherwise, defined.
1388         Elts.push_back(CP->getOperand(i));
1389       }
1390
1391     // If we changed the constant, return it.
1392     Constant *NewCP = ConstantVector::get(Elts);
1393     return NewCP != CP ? NewCP : 0;
1394   } else if (isa<ConstantAggregateZero>(V)) {
1395     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1396     // set to undef.
1397     
1398     // Check if this is identity. If so, return 0 since we are not simplifying
1399     // anything.
1400     if (DemandedElts == ((1ULL << VWidth) -1))
1401       return 0;
1402     
1403     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1404     Constant *Zero = Constant::getNullValue(EltTy);
1405     Constant *Undef = UndefValue::get(EltTy);
1406     std::vector<Constant*> Elts;
1407     for (unsigned i = 0; i != VWidth; ++i)
1408       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1409     UndefElts = DemandedElts ^ EltMask;
1410     return ConstantVector::get(Elts);
1411   }
1412   
1413   // Limit search depth.
1414   if (Depth == 10)
1415     return false;
1416
1417   // If multiple users are using the root value, procede with
1418   // simplification conservatively assuming that all elements
1419   // are needed.
1420   if (!V->hasOneUse()) {
1421     // Quit if we find multiple users of a non-root value though.
1422     // They'll be handled when it's their turn to be visited by
1423     // the main instcombine process.
1424     if (Depth != 0)
1425       // TODO: Just compute the UndefElts information recursively.
1426       return false;
1427
1428     // Conservatively assume that all elements are needed.
1429     DemandedElts = EltMask;
1430   }
1431   
1432   Instruction *I = dyn_cast<Instruction>(V);
1433   if (!I) return false;        // Only analyze instructions.
1434   
1435   bool MadeChange = false;
1436   uint64_t UndefElts2;
1437   Value *TmpV;
1438   switch (I->getOpcode()) {
1439   default: break;
1440     
1441   case Instruction::InsertElement: {
1442     // If this is a variable index, we don't know which element it overwrites.
1443     // demand exactly the same input as we produce.
1444     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1445     if (Idx == 0) {
1446       // Note that we can't propagate undef elt info, because we don't know
1447       // which elt is getting updated.
1448       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1449                                         UndefElts2, Depth+1);
1450       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1451       break;
1452     }
1453     
1454     // If this is inserting an element that isn't demanded, remove this
1455     // insertelement.
1456     unsigned IdxNo = Idx->getZExtValue();
1457     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1458       return AddSoonDeadInstToWorklist(*I, 0);
1459     
1460     // Otherwise, the element inserted overwrites whatever was there, so the
1461     // input demanded set is simpler than the output set.
1462     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1463                                       DemandedElts & ~(1ULL << IdxNo),
1464                                       UndefElts, Depth+1);
1465     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1466
1467     // The inserted element is defined.
1468     UndefElts &= ~(1ULL << IdxNo);
1469     break;
1470   }
1471   case Instruction::ShuffleVector: {
1472     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1473     uint64_t LHSVWidth =
1474       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1475     uint64_t LeftDemanded = 0, RightDemanded = 0;
1476     for (unsigned i = 0; i < VWidth; i++) {
1477       if (DemandedElts & (1ULL << i)) {
1478         unsigned MaskVal = Shuffle->getMaskValue(i);
1479         if (MaskVal != -1u) {
1480           assert(MaskVal < LHSVWidth * 2 &&
1481                  "shufflevector mask index out of range!");
1482           if (MaskVal < LHSVWidth)
1483             LeftDemanded |= 1ULL << MaskVal;
1484           else
1485             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1486         }
1487       }
1488     }
1489
1490     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1491                                       UndefElts2, Depth+1);
1492     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1493
1494     uint64_t UndefElts3;
1495     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1496                                       UndefElts3, Depth+1);
1497     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1498
1499     bool NewUndefElts = false;
1500     for (unsigned i = 0; i < VWidth; i++) {
1501       unsigned MaskVal = Shuffle->getMaskValue(i);
1502       if (MaskVal == -1u) {
1503         uint64_t NewBit = 1ULL << i;
1504         UndefElts |= NewBit;
1505       } else if (MaskVal < LHSVWidth) {
1506         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1507         NewUndefElts |= NewBit;
1508         UndefElts |= NewBit;
1509       } else {
1510         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1511         NewUndefElts |= NewBit;
1512         UndefElts |= NewBit;
1513       }
1514     }
1515
1516     if (NewUndefElts) {
1517       // Add additional discovered undefs.
1518       std::vector<Constant*> Elts;
1519       for (unsigned i = 0; i < VWidth; ++i) {
1520         if (UndefElts & (1ULL << i))
1521           Elts.push_back(UndefValue::get(Type::Int32Ty));
1522         else
1523           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1524                                           Shuffle->getMaskValue(i)));
1525       }
1526       I->setOperand(2, ConstantVector::get(Elts));
1527       MadeChange = true;
1528     }
1529     break;
1530   }
1531   case Instruction::BitCast: {
1532     // Vector->vector casts only.
1533     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1534     if (!VTy) break;
1535     unsigned InVWidth = VTy->getNumElements();
1536     uint64_t InputDemandedElts = 0;
1537     unsigned Ratio;
1538
1539     if (VWidth == InVWidth) {
1540       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1541       // elements as are demanded of us.
1542       Ratio = 1;
1543       InputDemandedElts = DemandedElts;
1544     } else if (VWidth > InVWidth) {
1545       // Untested so far.
1546       break;
1547       
1548       // If there are more elements in the result than there are in the source,
1549       // then an input element is live if any of the corresponding output
1550       // elements are live.
1551       Ratio = VWidth/InVWidth;
1552       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1553         if (DemandedElts & (1ULL << OutIdx))
1554           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1555       }
1556     } else {
1557       // Untested so far.
1558       break;
1559       
1560       // If there are more elements in the source than there are in the result,
1561       // then an input element is live if the corresponding output element is
1562       // live.
1563       Ratio = InVWidth/VWidth;
1564       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1565         if (DemandedElts & (1ULL << InIdx/Ratio))
1566           InputDemandedElts |= 1ULL << InIdx;
1567     }
1568     
1569     // div/rem demand all inputs, because they don't want divide by zero.
1570     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1571                                       UndefElts2, Depth+1);
1572     if (TmpV) {
1573       I->setOperand(0, TmpV);
1574       MadeChange = true;
1575     }
1576     
1577     UndefElts = UndefElts2;
1578     if (VWidth > InVWidth) {
1579       assert(0 && "Unimp");
1580       // If there are more elements in the result than there are in the source,
1581       // then an output element is undef if the corresponding input element is
1582       // undef.
1583       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1584         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1585           UndefElts |= 1ULL << OutIdx;
1586     } else if (VWidth < InVWidth) {
1587       assert(0 && "Unimp");
1588       // If there are more elements in the source than there are in the result,
1589       // then a result element is undef if all of the corresponding input
1590       // elements are undef.
1591       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1592       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1593         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1594           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1595     }
1596     break;
1597   }
1598   case Instruction::And:
1599   case Instruction::Or:
1600   case Instruction::Xor:
1601   case Instruction::Add:
1602   case Instruction::Sub:
1603   case Instruction::Mul:
1604     // div/rem demand all inputs, because they don't want divide by zero.
1605     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1606                                       UndefElts, Depth+1);
1607     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1608     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1609                                       UndefElts2, Depth+1);
1610     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1611       
1612     // Output elements are undefined if both are undefined.  Consider things
1613     // like undef&0.  The result is known zero, not undef.
1614     UndefElts &= UndefElts2;
1615     break;
1616     
1617   case Instruction::Call: {
1618     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1619     if (!II) break;
1620     switch (II->getIntrinsicID()) {
1621     default: break;
1622       
1623     // Binary vector operations that work column-wise.  A dest element is a
1624     // function of the corresponding input elements from the two inputs.
1625     case Intrinsic::x86_sse_sub_ss:
1626     case Intrinsic::x86_sse_mul_ss:
1627     case Intrinsic::x86_sse_min_ss:
1628     case Intrinsic::x86_sse_max_ss:
1629     case Intrinsic::x86_sse2_sub_sd:
1630     case Intrinsic::x86_sse2_mul_sd:
1631     case Intrinsic::x86_sse2_min_sd:
1632     case Intrinsic::x86_sse2_max_sd:
1633       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1634                                         UndefElts, Depth+1);
1635       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1636       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1637                                         UndefElts2, Depth+1);
1638       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1639
1640       // If only the low elt is demanded and this is a scalarizable intrinsic,
1641       // scalarize it now.
1642       if (DemandedElts == 1) {
1643         switch (II->getIntrinsicID()) {
1644         default: break;
1645         case Intrinsic::x86_sse_sub_ss:
1646         case Intrinsic::x86_sse_mul_ss:
1647         case Intrinsic::x86_sse2_sub_sd:
1648         case Intrinsic::x86_sse2_mul_sd:
1649           // TODO: Lower MIN/MAX/ABS/etc
1650           Value *LHS = II->getOperand(1);
1651           Value *RHS = II->getOperand(2);
1652           // Extract the element as scalars.
1653           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1654           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1655           
1656           switch (II->getIntrinsicID()) {
1657           default: assert(0 && "Case stmts out of sync!");
1658           case Intrinsic::x86_sse_sub_ss:
1659           case Intrinsic::x86_sse2_sub_sd:
1660             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1661                                                         II->getName()), *II);
1662             break;
1663           case Intrinsic::x86_sse_mul_ss:
1664           case Intrinsic::x86_sse2_mul_sd:
1665             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1666                                                          II->getName()), *II);
1667             break;
1668           }
1669           
1670           Instruction *New =
1671             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1672                                       II->getName());
1673           InsertNewInstBefore(New, *II);
1674           AddSoonDeadInstToWorklist(*II, 0);
1675           return New;
1676         }            
1677       }
1678         
1679       // Output elements are undefined if both are undefined.  Consider things
1680       // like undef&0.  The result is known zero, not undef.
1681       UndefElts &= UndefElts2;
1682       break;
1683     }
1684     break;
1685   }
1686   }
1687   return MadeChange ? I : 0;
1688 }
1689
1690
1691 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1692 /// function is designed to check a chain of associative operators for a
1693 /// potential to apply a certain optimization.  Since the optimization may be
1694 /// applicable if the expression was reassociated, this checks the chain, then
1695 /// reassociates the expression as necessary to expose the optimization
1696 /// opportunity.  This makes use of a special Functor, which must define
1697 /// 'shouldApply' and 'apply' methods.
1698 ///
1699 template<typename Functor>
1700 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1701   unsigned Opcode = Root.getOpcode();
1702   Value *LHS = Root.getOperand(0);
1703
1704   // Quick check, see if the immediate LHS matches...
1705   if (F.shouldApply(LHS))
1706     return F.apply(Root);
1707
1708   // Otherwise, if the LHS is not of the same opcode as the root, return.
1709   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1710   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1711     // Should we apply this transform to the RHS?
1712     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1713
1714     // If not to the RHS, check to see if we should apply to the LHS...
1715     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1716       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1717       ShouldApply = true;
1718     }
1719
1720     // If the functor wants to apply the optimization to the RHS of LHSI,
1721     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1722     if (ShouldApply) {
1723       // Now all of the instructions are in the current basic block, go ahead
1724       // and perform the reassociation.
1725       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1726
1727       // First move the selected RHS to the LHS of the root...
1728       Root.setOperand(0, LHSI->getOperand(1));
1729
1730       // Make what used to be the LHS of the root be the user of the root...
1731       Value *ExtraOperand = TmpLHSI->getOperand(1);
1732       if (&Root == TmpLHSI) {
1733         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1734         return 0;
1735       }
1736       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1737       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1738       BasicBlock::iterator ARI = &Root; ++ARI;
1739       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1740       ARI = Root;
1741
1742       // Now propagate the ExtraOperand down the chain of instructions until we
1743       // get to LHSI.
1744       while (TmpLHSI != LHSI) {
1745         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1746         // Move the instruction to immediately before the chain we are
1747         // constructing to avoid breaking dominance properties.
1748         NextLHSI->moveBefore(ARI);
1749         ARI = NextLHSI;
1750
1751         Value *NextOp = NextLHSI->getOperand(1);
1752         NextLHSI->setOperand(1, ExtraOperand);
1753         TmpLHSI = NextLHSI;
1754         ExtraOperand = NextOp;
1755       }
1756
1757       // Now that the instructions are reassociated, have the functor perform
1758       // the transformation...
1759       return F.apply(Root);
1760     }
1761
1762     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1763   }
1764   return 0;
1765 }
1766
1767 namespace {
1768
1769 // AddRHS - Implements: X + X --> X << 1
1770 struct AddRHS {
1771   Value *RHS;
1772   AddRHS(Value *rhs) : RHS(rhs) {}
1773   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1774   Instruction *apply(BinaryOperator &Add) const {
1775     return BinaryOperator::CreateShl(Add.getOperand(0),
1776                                      ConstantInt::get(Add.getType(), 1));
1777   }
1778 };
1779
1780 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1781 //                 iff C1&C2 == 0
1782 struct AddMaskingAnd {
1783   Constant *C2;
1784   AddMaskingAnd(Constant *c) : C2(c) {}
1785   bool shouldApply(Value *LHS) const {
1786     ConstantInt *C1;
1787     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1788            ConstantExpr::getAnd(C1, C2)->isNullValue();
1789   }
1790   Instruction *apply(BinaryOperator &Add) const {
1791     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1792   }
1793 };
1794
1795 }
1796
1797 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1798                                              InstCombiner *IC) {
1799   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1800     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1801   }
1802
1803   // Figure out if the constant is the left or the right argument.
1804   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1805   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1806
1807   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1808     if (ConstIsRHS)
1809       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1810     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1811   }
1812
1813   Value *Op0 = SO, *Op1 = ConstOperand;
1814   if (!ConstIsRHS)
1815     std::swap(Op0, Op1);
1816   Instruction *New;
1817   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1818     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1819   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1820     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1821                           SO->getName()+".cmp");
1822   else {
1823     assert(0 && "Unknown binary instruction type!");
1824     abort();
1825   }
1826   return IC->InsertNewInstBefore(New, I);
1827 }
1828
1829 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1830 // constant as the other operand, try to fold the binary operator into the
1831 // select arguments.  This also works for Cast instructions, which obviously do
1832 // not have a second operand.
1833 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1834                                      InstCombiner *IC) {
1835   // Don't modify shared select instructions
1836   if (!SI->hasOneUse()) return 0;
1837   Value *TV = SI->getOperand(1);
1838   Value *FV = SI->getOperand(2);
1839
1840   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1841     // Bool selects with constant operands can be folded to logical ops.
1842     if (SI->getType() == Type::Int1Ty) return 0;
1843
1844     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1845     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1846
1847     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1848                               SelectFalseVal);
1849   }
1850   return 0;
1851 }
1852
1853
1854 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1855 /// node as operand #0, see if we can fold the instruction into the PHI (which
1856 /// is only possible if all operands to the PHI are constants).
1857 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1858   PHINode *PN = cast<PHINode>(I.getOperand(0));
1859   unsigned NumPHIValues = PN->getNumIncomingValues();
1860   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1861
1862   // Check to see if all of the operands of the PHI are constants.  If there is
1863   // one non-constant value, remember the BB it is.  If there is more than one
1864   // or if *it* is a PHI, bail out.
1865   BasicBlock *NonConstBB = 0;
1866   for (unsigned i = 0; i != NumPHIValues; ++i)
1867     if (!isa<Constant>(PN->getIncomingValue(i))) {
1868       if (NonConstBB) return 0;  // More than one non-const value.
1869       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1870       NonConstBB = PN->getIncomingBlock(i);
1871       
1872       // If the incoming non-constant value is in I's block, we have an infinite
1873       // loop.
1874       if (NonConstBB == I.getParent())
1875         return 0;
1876     }
1877   
1878   // If there is exactly one non-constant value, we can insert a copy of the
1879   // operation in that block.  However, if this is a critical edge, we would be
1880   // inserting the computation one some other paths (e.g. inside a loop).  Only
1881   // do this if the pred block is unconditionally branching into the phi block.
1882   if (NonConstBB) {
1883     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1884     if (!BI || !BI->isUnconditional()) return 0;
1885   }
1886
1887   // Okay, we can do the transformation: create the new PHI node.
1888   PHINode *NewPN = PHINode::Create(I.getType(), "");
1889   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1890   InsertNewInstBefore(NewPN, *PN);
1891   NewPN->takeName(PN);
1892
1893   // Next, add all of the operands to the PHI.
1894   if (I.getNumOperands() == 2) {
1895     Constant *C = cast<Constant>(I.getOperand(1));
1896     for (unsigned i = 0; i != NumPHIValues; ++i) {
1897       Value *InV = 0;
1898       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1899         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1900           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1901         else
1902           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1903       } else {
1904         assert(PN->getIncomingBlock(i) == NonConstBB);
1905         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1906           InV = BinaryOperator::Create(BO->getOpcode(),
1907                                        PN->getIncomingValue(i), C, "phitmp",
1908                                        NonConstBB->getTerminator());
1909         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1910           InV = CmpInst::Create(CI->getOpcode(), 
1911                                 CI->getPredicate(),
1912                                 PN->getIncomingValue(i), C, "phitmp",
1913                                 NonConstBB->getTerminator());
1914         else
1915           assert(0 && "Unknown binop!");
1916         
1917         AddToWorkList(cast<Instruction>(InV));
1918       }
1919       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1920     }
1921   } else { 
1922     CastInst *CI = cast<CastInst>(&I);
1923     const Type *RetTy = CI->getType();
1924     for (unsigned i = 0; i != NumPHIValues; ++i) {
1925       Value *InV;
1926       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1927         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1928       } else {
1929         assert(PN->getIncomingBlock(i) == NonConstBB);
1930         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1931                                I.getType(), "phitmp", 
1932                                NonConstBB->getTerminator());
1933         AddToWorkList(cast<Instruction>(InV));
1934       }
1935       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1936     }
1937   }
1938   return ReplaceInstUsesWith(I, NewPN);
1939 }
1940
1941
1942 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1943 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1944 /// This basically requires proving that the add in the original type would not
1945 /// overflow to change the sign bit or have a carry out.
1946 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1947   // There are different heuristics we can use for this.  Here are some simple
1948   // ones.
1949   
1950   // Add has the property that adding any two 2's complement numbers can only 
1951   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1952   // have at least two sign bits, we know that the addition of the two values will
1953   // sign extend fine.
1954   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1955     return true;
1956   
1957   
1958   // If one of the operands only has one non-zero bit, and if the other operand
1959   // has a known-zero bit in a more significant place than it (not including the
1960   // sign bit) the ripple may go up to and fill the zero, but won't change the
1961   // sign.  For example, (X & ~4) + 1.
1962   
1963   // TODO: Implement.
1964   
1965   return false;
1966 }
1967
1968
1969 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1970   bool Changed = SimplifyCommutative(I);
1971   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1972
1973   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1974     // X + undef -> undef
1975     if (isa<UndefValue>(RHS))
1976       return ReplaceInstUsesWith(I, RHS);
1977
1978     // X + 0 --> X
1979     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1980       if (RHSC->isNullValue())
1981         return ReplaceInstUsesWith(I, LHS);
1982     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1983       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1984                               (I.getType())->getValueAPF()))
1985         return ReplaceInstUsesWith(I, LHS);
1986     }
1987
1988     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1989       // X + (signbit) --> X ^ signbit
1990       const APInt& Val = CI->getValue();
1991       uint32_t BitWidth = Val.getBitWidth();
1992       if (Val == APInt::getSignBit(BitWidth))
1993         return BinaryOperator::CreateXor(LHS, RHS);
1994       
1995       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1996       // (X & 254)+1 -> (X&254)|1
1997       if (!isa<VectorType>(I.getType())) {
1998         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1999         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2000                                  KnownZero, KnownOne))
2001           return &I;
2002       }
2003
2004       // zext(i1) - 1  ->  select i1, 0, -1
2005       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2006         if (CI->isAllOnesValue() &&
2007             ZI->getOperand(0)->getType() == Type::Int1Ty)
2008           return SelectInst::Create(ZI->getOperand(0),
2009                                     Constant::getNullValue(I.getType()),
2010                                     ConstantInt::getAllOnesValue(I.getType()));
2011     }
2012
2013     if (isa<PHINode>(LHS))
2014       if (Instruction *NV = FoldOpIntoPhi(I))
2015         return NV;
2016     
2017     ConstantInt *XorRHS = 0;
2018     Value *XorLHS = 0;
2019     if (isa<ConstantInt>(RHSC) &&
2020         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2021       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2022       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2023       
2024       uint32_t Size = TySizeBits / 2;
2025       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2026       APInt CFF80Val(-C0080Val);
2027       do {
2028         if (TySizeBits > Size) {
2029           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2030           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2031           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2032               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2033             // This is a sign extend if the top bits are known zero.
2034             if (!MaskedValueIsZero(XorLHS, 
2035                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2036               Size = 0;  // Not a sign ext, but can't be any others either.
2037             break;
2038           }
2039         }
2040         Size >>= 1;
2041         C0080Val = APIntOps::lshr(C0080Val, Size);
2042         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2043       } while (Size >= 1);
2044       
2045       // FIXME: This shouldn't be necessary. When the backends can handle types
2046       // with funny bit widths then this switch statement should be removed. It
2047       // is just here to get the size of the "middle" type back up to something
2048       // that the back ends can handle.
2049       const Type *MiddleType = 0;
2050       switch (Size) {
2051         default: break;
2052         case 32: MiddleType = Type::Int32Ty; break;
2053         case 16: MiddleType = Type::Int16Ty; break;
2054         case  8: MiddleType = Type::Int8Ty; break;
2055       }
2056       if (MiddleType) {
2057         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2058         InsertNewInstBefore(NewTrunc, I);
2059         return new SExtInst(NewTrunc, I.getType(), I.getName());
2060       }
2061     }
2062   }
2063
2064   if (I.getType() == Type::Int1Ty)
2065     return BinaryOperator::CreateXor(LHS, RHS);
2066
2067   // X + X --> X << 1
2068   if (I.getType()->isInteger()) {
2069     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2070
2071     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2072       if (RHSI->getOpcode() == Instruction::Sub)
2073         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2074           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2075     }
2076     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2077       if (LHSI->getOpcode() == Instruction::Sub)
2078         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2079           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2080     }
2081   }
2082
2083   // -A + B  -->  B - A
2084   // -A + -B  -->  -(A + B)
2085   if (Value *LHSV = dyn_castNegVal(LHS)) {
2086     if (LHS->getType()->isIntOrIntVector()) {
2087       if (Value *RHSV = dyn_castNegVal(RHS)) {
2088         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2089         InsertNewInstBefore(NewAdd, I);
2090         return BinaryOperator::CreateNeg(NewAdd);
2091       }
2092     }
2093     
2094     return BinaryOperator::CreateSub(RHS, LHSV);
2095   }
2096
2097   // A + -B  -->  A - B
2098   if (!isa<Constant>(RHS))
2099     if (Value *V = dyn_castNegVal(RHS))
2100       return BinaryOperator::CreateSub(LHS, V);
2101
2102
2103   ConstantInt *C2;
2104   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2105     if (X == RHS)   // X*C + X --> X * (C+1)
2106       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2107
2108     // X*C1 + X*C2 --> X * (C1+C2)
2109     ConstantInt *C1;
2110     if (X == dyn_castFoldableMul(RHS, C1))
2111       return BinaryOperator::CreateMul(X, Add(C1, C2));
2112   }
2113
2114   // X + X*C --> X * (C+1)
2115   if (dyn_castFoldableMul(RHS, C2) == LHS)
2116     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2117
2118   // X + ~X --> -1   since   ~X = -X-1
2119   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2120     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2121   
2122
2123   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2124   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2125     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2126       return R;
2127   
2128   // A+B --> A|B iff A and B have no bits set in common.
2129   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2130     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2131     APInt LHSKnownOne(IT->getBitWidth(), 0);
2132     APInt LHSKnownZero(IT->getBitWidth(), 0);
2133     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2134     if (LHSKnownZero != 0) {
2135       APInt RHSKnownOne(IT->getBitWidth(), 0);
2136       APInt RHSKnownZero(IT->getBitWidth(), 0);
2137       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2138       
2139       // No bits in common -> bitwise or.
2140       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2141         return BinaryOperator::CreateOr(LHS, RHS);
2142     }
2143   }
2144
2145   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2146   if (I.getType()->isIntOrIntVector()) {
2147     Value *W, *X, *Y, *Z;
2148     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2149         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2150       if (W != Y) {
2151         if (W == Z) {
2152           std::swap(Y, Z);
2153         } else if (Y == X) {
2154           std::swap(W, X);
2155         } else if (X == Z) {
2156           std::swap(Y, Z);
2157           std::swap(W, X);
2158         }
2159       }
2160
2161       if (W == Y) {
2162         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2163                                                             LHS->getName()), I);
2164         return BinaryOperator::CreateMul(W, NewAdd);
2165       }
2166     }
2167   }
2168
2169   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2170     Value *X = 0;
2171     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2172       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2173
2174     // (X & FF00) + xx00  -> (X+xx00) & FF00
2175     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2176       Constant *Anded = And(CRHS, C2);
2177       if (Anded == CRHS) {
2178         // See if all bits from the first bit set in the Add RHS up are included
2179         // in the mask.  First, get the rightmost bit.
2180         const APInt& AddRHSV = CRHS->getValue();
2181
2182         // Form a mask of all bits from the lowest bit added through the top.
2183         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2184
2185         // See if the and mask includes all of these bits.
2186         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2187
2188         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2189           // Okay, the xform is safe.  Insert the new add pronto.
2190           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2191                                                             LHS->getName()), I);
2192           return BinaryOperator::CreateAnd(NewAdd, C2);
2193         }
2194       }
2195     }
2196
2197     // Try to fold constant add into select arguments.
2198     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2199       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2200         return R;
2201   }
2202
2203   // add (cast *A to intptrtype) B -> 
2204   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2205   {
2206     CastInst *CI = dyn_cast<CastInst>(LHS);
2207     Value *Other = RHS;
2208     if (!CI) {
2209       CI = dyn_cast<CastInst>(RHS);
2210       Other = LHS;
2211     }
2212     if (CI && CI->getType()->isSized() && 
2213         (CI->getType()->getPrimitiveSizeInBits() == 
2214          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2215         && isa<PointerType>(CI->getOperand(0)->getType())) {
2216       unsigned AS =
2217         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2218       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2219                                       PointerType::get(Type::Int8Ty, AS), I);
2220       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2221       return new PtrToIntInst(I2, CI->getType());
2222     }
2223   }
2224   
2225   // add (select X 0 (sub n A)) A  -->  select X A n
2226   {
2227     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2228     Value *A = RHS;
2229     if (!SI) {
2230       SI = dyn_cast<SelectInst>(RHS);
2231       A = LHS;
2232     }
2233     if (SI && SI->hasOneUse()) {
2234       Value *TV = SI->getTrueValue();
2235       Value *FV = SI->getFalseValue();
2236       Value *N;
2237
2238       // Can we fold the add into the argument of the select?
2239       // We check both true and false select arguments for a matching subtract.
2240       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2241         // Fold the add into the true select value.
2242         return SelectInst::Create(SI->getCondition(), N, A);
2243       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2244         // Fold the add into the false select value.
2245         return SelectInst::Create(SI->getCondition(), A, N);
2246     }
2247   }
2248   
2249   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2250   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2251     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2252       return ReplaceInstUsesWith(I, LHS);
2253
2254   // Check for (add (sext x), y), see if we can merge this into an
2255   // integer add followed by a sext.
2256   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2257     // (add (sext x), cst) --> (sext (add x, cst'))
2258     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2259       Constant *CI = 
2260         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2261       if (LHSConv->hasOneUse() &&
2262           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2263           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2264         // Insert the new, smaller add.
2265         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2266                                                         CI, "addconv");
2267         InsertNewInstBefore(NewAdd, I);
2268         return new SExtInst(NewAdd, I.getType());
2269       }
2270     }
2271     
2272     // (add (sext x), (sext y)) --> (sext (add int x, y))
2273     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2274       // Only do this if x/y have the same type, if at last one of them has a
2275       // single use (so we don't increase the number of sexts), and if the
2276       // integer add will not overflow.
2277       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2278           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2279           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2280                                    RHSConv->getOperand(0))) {
2281         // Insert the new integer add.
2282         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2283                                                         RHSConv->getOperand(0),
2284                                                         "addconv");
2285         InsertNewInstBefore(NewAdd, I);
2286         return new SExtInst(NewAdd, I.getType());
2287       }
2288     }
2289   }
2290   
2291   // Check for (add double (sitofp x), y), see if we can merge this into an
2292   // integer add followed by a promotion.
2293   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2294     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2295     // ... if the constant fits in the integer value.  This is useful for things
2296     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2297     // requires a constant pool load, and generally allows the add to be better
2298     // instcombined.
2299     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2300       Constant *CI = 
2301       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2302       if (LHSConv->hasOneUse() &&
2303           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2304           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2305         // Insert the new integer add.
2306         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2307                                                         CI, "addconv");
2308         InsertNewInstBefore(NewAdd, I);
2309         return new SIToFPInst(NewAdd, I.getType());
2310       }
2311     }
2312     
2313     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2314     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2315       // Only do this if x/y have the same type, if at last one of them has a
2316       // single use (so we don't increase the number of int->fp conversions),
2317       // and if the integer add will not overflow.
2318       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2319           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2320           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2321                                    RHSConv->getOperand(0))) {
2322         // Insert the new integer add.
2323         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2324                                                         RHSConv->getOperand(0),
2325                                                         "addconv");
2326         InsertNewInstBefore(NewAdd, I);
2327         return new SIToFPInst(NewAdd, I.getType());
2328       }
2329     }
2330   }
2331   
2332   return Changed ? &I : 0;
2333 }
2334
2335 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2336   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2337
2338   if (Op0 == Op1 &&                        // sub X, X  -> 0
2339       !I.getType()->isFPOrFPVector())
2340     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2341
2342   // If this is a 'B = x-(-A)', change to B = x+A...
2343   if (Value *V = dyn_castNegVal(Op1))
2344     return BinaryOperator::CreateAdd(Op0, V);
2345
2346   if (isa<UndefValue>(Op0))
2347     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2348   if (isa<UndefValue>(Op1))
2349     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2350
2351   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2352     // Replace (-1 - A) with (~A)...
2353     if (C->isAllOnesValue())
2354       return BinaryOperator::CreateNot(Op1);
2355
2356     // C - ~X == X + (1+C)
2357     Value *X = 0;
2358     if (match(Op1, m_Not(m_Value(X))))
2359       return BinaryOperator::CreateAdd(X, AddOne(C));
2360
2361     // -(X >>u 31) -> (X >>s 31)
2362     // -(X >>s 31) -> (X >>u 31)
2363     if (C->isZero()) {
2364       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2365         if (SI->getOpcode() == Instruction::LShr) {
2366           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2367             // Check to see if we are shifting out everything but the sign bit.
2368             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2369                 SI->getType()->getPrimitiveSizeInBits()-1) {
2370               // Ok, the transformation is safe.  Insert AShr.
2371               return BinaryOperator::Create(Instruction::AShr, 
2372                                           SI->getOperand(0), CU, SI->getName());
2373             }
2374           }
2375         }
2376         else if (SI->getOpcode() == Instruction::AShr) {
2377           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2378             // Check to see if we are shifting out everything but the sign bit.
2379             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2380                 SI->getType()->getPrimitiveSizeInBits()-1) {
2381               // Ok, the transformation is safe.  Insert LShr. 
2382               return BinaryOperator::CreateLShr(
2383                                           SI->getOperand(0), CU, SI->getName());
2384             }
2385           }
2386         }
2387       }
2388     }
2389
2390     // Try to fold constant sub into select arguments.
2391     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2392       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2393         return R;
2394   }
2395
2396   if (I.getType() == Type::Int1Ty)
2397     return BinaryOperator::CreateXor(Op0, Op1);
2398
2399   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2400     if (Op1I->getOpcode() == Instruction::Add &&
2401         !Op0->getType()->isFPOrFPVector()) {
2402       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2403         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2404       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2405         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2406       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2407         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2408           // C1-(X+C2) --> (C1-C2)-X
2409           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2410                                            Op1I->getOperand(0));
2411       }
2412     }
2413
2414     if (Op1I->hasOneUse()) {
2415       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2416       // is not used by anyone else...
2417       //
2418       if (Op1I->getOpcode() == Instruction::Sub &&
2419           !Op1I->getType()->isFPOrFPVector()) {
2420         // Swap the two operands of the subexpr...
2421         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2422         Op1I->setOperand(0, IIOp1);
2423         Op1I->setOperand(1, IIOp0);
2424
2425         // Create the new top level add instruction...
2426         return BinaryOperator::CreateAdd(Op0, Op1);
2427       }
2428
2429       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2430       //
2431       if (Op1I->getOpcode() == Instruction::And &&
2432           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2433         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2434
2435         Value *NewNot =
2436           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2437         return BinaryOperator::CreateAnd(Op0, NewNot);
2438       }
2439
2440       // 0 - (X sdiv C)  -> (X sdiv -C)
2441       if (Op1I->getOpcode() == Instruction::SDiv)
2442         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2443           if (CSI->isZero())
2444             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2445               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2446                                                ConstantExpr::getNeg(DivRHS));
2447
2448       // X - X*C --> X * (1-C)
2449       ConstantInt *C2 = 0;
2450       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2451         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2452         return BinaryOperator::CreateMul(Op0, CP1);
2453       }
2454     }
2455   }
2456
2457   if (!Op0->getType()->isFPOrFPVector())
2458     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2459       if (Op0I->getOpcode() == Instruction::Add) {
2460         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2461           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2462         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2463           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2464       } else if (Op0I->getOpcode() == Instruction::Sub) {
2465         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2466           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2467       }
2468     }
2469
2470   ConstantInt *C1;
2471   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2472     if (X == Op1)  // X*C - X --> X * (C-1)
2473       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2474
2475     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2476     if (X == dyn_castFoldableMul(Op1, C2))
2477       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2478   }
2479   return 0;
2480 }
2481
2482 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2483 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2484 /// TrueIfSigned if the result of the comparison is true when the input value is
2485 /// signed.
2486 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2487                            bool &TrueIfSigned) {
2488   switch (pred) {
2489   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2490     TrueIfSigned = true;
2491     return RHS->isZero();
2492   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2493     TrueIfSigned = true;
2494     return RHS->isAllOnesValue();
2495   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2496     TrueIfSigned = false;
2497     return RHS->isAllOnesValue();
2498   case ICmpInst::ICMP_UGT:
2499     // True if LHS u> RHS and RHS == high-bit-mask - 1
2500     TrueIfSigned = true;
2501     return RHS->getValue() ==
2502       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2503   case ICmpInst::ICMP_UGE: 
2504     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2505     TrueIfSigned = true;
2506     return RHS->getValue().isSignBit();
2507   default:
2508     return false;
2509   }
2510 }
2511
2512 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2513   bool Changed = SimplifyCommutative(I);
2514   Value *Op0 = I.getOperand(0);
2515
2516   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2517     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518
2519   // Simplify mul instructions with a constant RHS...
2520   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2521     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2522
2523       // ((X << C1)*C2) == (X * (C2 << C1))
2524       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2525         if (SI->getOpcode() == Instruction::Shl)
2526           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2527             return BinaryOperator::CreateMul(SI->getOperand(0),
2528                                              ConstantExpr::getShl(CI, ShOp));
2529
2530       if (CI->isZero())
2531         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2532       if (CI->equalsInt(1))                  // X * 1  == X
2533         return ReplaceInstUsesWith(I, Op0);
2534       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2535         return BinaryOperator::CreateNeg(Op0, I.getName());
2536
2537       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2538       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2539         return BinaryOperator::CreateShl(Op0,
2540                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2541       }
2542     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2543       if (Op1F->isNullValue())
2544         return ReplaceInstUsesWith(I, Op1);
2545
2546       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2547       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2548       if (Op1F->isExactlyValue(1.0))
2549         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2550     } else if (isa<VectorType>(Op1->getType())) {
2551       if (isa<ConstantAggregateZero>(Op1))
2552         return ReplaceInstUsesWith(I, Op1);
2553
2554       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2555         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2556           return BinaryOperator::CreateNeg(Op0, I.getName());
2557
2558         // As above, vector X*splat(1.0) -> X in all defined cases.
2559         if (Constant *Splat = Op1V->getSplatValue()) {
2560           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2561             if (F->isExactlyValue(1.0))
2562               return ReplaceInstUsesWith(I, Op0);
2563           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2564             if (CI->equalsInt(1))
2565               return ReplaceInstUsesWith(I, Op0);
2566         }
2567       }
2568     }
2569     
2570     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2571       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2572           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2573         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2574         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2575                                                      Op1, "tmp");
2576         InsertNewInstBefore(Add, I);
2577         Value *C1C2 = ConstantExpr::getMul(Op1, 
2578                                            cast<Constant>(Op0I->getOperand(1)));
2579         return BinaryOperator::CreateAdd(Add, C1C2);
2580         
2581       }
2582
2583     // Try to fold constant mul into select arguments.
2584     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2585       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2586         return R;
2587
2588     if (isa<PHINode>(Op0))
2589       if (Instruction *NV = FoldOpIntoPhi(I))
2590         return NV;
2591   }
2592
2593   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2594     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2595       return BinaryOperator::CreateMul(Op0v, Op1v);
2596
2597   // (X / Y) *  Y = X - (X % Y)
2598   // (X / Y) * -Y = (X % Y) - X
2599   {
2600     Value *Op1 = I.getOperand(1);
2601     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2602     if (!BO ||
2603         (BO->getOpcode() != Instruction::UDiv && 
2604          BO->getOpcode() != Instruction::SDiv)) {
2605       Op1 = Op0;
2606       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2607     }
2608     Value *Neg = dyn_castNegVal(Op1);
2609     if (BO && BO->hasOneUse() &&
2610         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2611         (BO->getOpcode() == Instruction::UDiv ||
2612          BO->getOpcode() == Instruction::SDiv)) {
2613       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2614
2615       Instruction *Rem;
2616       if (BO->getOpcode() == Instruction::UDiv)
2617         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2618       else
2619         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2620
2621       InsertNewInstBefore(Rem, I);
2622       Rem->takeName(BO);
2623
2624       if (Op1BO == Op1)
2625         return BinaryOperator::CreateSub(Op0BO, Rem);
2626       else
2627         return BinaryOperator::CreateSub(Rem, Op0BO);
2628     }
2629   }
2630
2631   if (I.getType() == Type::Int1Ty)
2632     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2633
2634   // If one of the operands of the multiply is a cast from a boolean value, then
2635   // we know the bool is either zero or one, so this is a 'masking' multiply.
2636   // See if we can simplify things based on how the boolean was originally
2637   // formed.
2638   CastInst *BoolCast = 0;
2639   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2640     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2641       BoolCast = CI;
2642   if (!BoolCast)
2643     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2644       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2645         BoolCast = CI;
2646   if (BoolCast) {
2647     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2648       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2649       const Type *SCOpTy = SCIOp0->getType();
2650       bool TIS = false;
2651       
2652       // If the icmp is true iff the sign bit of X is set, then convert this
2653       // multiply into a shift/and combination.
2654       if (isa<ConstantInt>(SCIOp1) &&
2655           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2656           TIS) {
2657         // Shift the X value right to turn it into "all signbits".
2658         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2659                                           SCOpTy->getPrimitiveSizeInBits()-1);
2660         Value *V =
2661           InsertNewInstBefore(
2662             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2663                                             BoolCast->getOperand(0)->getName()+
2664                                             ".mask"), I);
2665
2666         // If the multiply type is not the same as the source type, sign extend
2667         // or truncate to the multiply type.
2668         if (I.getType() != V->getType()) {
2669           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2670           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2671           Instruction::CastOps opcode = 
2672             (SrcBits == DstBits ? Instruction::BitCast : 
2673              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2674           V = InsertCastBefore(opcode, V, I.getType(), I);
2675         }
2676
2677         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2678         return BinaryOperator::CreateAnd(V, OtherOp);
2679       }
2680     }
2681   }
2682
2683   return Changed ? &I : 0;
2684 }
2685
2686 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2687 /// instruction.
2688 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2689   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2690   
2691   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2692   int NonNullOperand = -1;
2693   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2694     if (ST->isNullValue())
2695       NonNullOperand = 2;
2696   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2697   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2698     if (ST->isNullValue())
2699       NonNullOperand = 1;
2700   
2701   if (NonNullOperand == -1)
2702     return false;
2703   
2704   Value *SelectCond = SI->getOperand(0);
2705   
2706   // Change the div/rem to use 'Y' instead of the select.
2707   I.setOperand(1, SI->getOperand(NonNullOperand));
2708   
2709   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2710   // problem.  However, the select, or the condition of the select may have
2711   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2712   // propagate the known value for the select into other uses of it, and
2713   // propagate a known value of the condition into its other users.
2714   
2715   // If the select and condition only have a single use, don't bother with this,
2716   // early exit.
2717   if (SI->use_empty() && SelectCond->hasOneUse())
2718     return true;
2719   
2720   // Scan the current block backward, looking for other uses of SI.
2721   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2722   
2723   while (BBI != BBFront) {
2724     --BBI;
2725     // If we found a call to a function, we can't assume it will return, so
2726     // information from below it cannot be propagated above it.
2727     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2728       break;
2729     
2730     // Replace uses of the select or its condition with the known values.
2731     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2732          I != E; ++I) {
2733       if (*I == SI) {
2734         *I = SI->getOperand(NonNullOperand);
2735         AddToWorkList(BBI);
2736       } else if (*I == SelectCond) {
2737         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2738                                    ConstantInt::getFalse();
2739         AddToWorkList(BBI);
2740       }
2741     }
2742     
2743     // If we past the instruction, quit looking for it.
2744     if (&*BBI == SI)
2745       SI = 0;
2746     if (&*BBI == SelectCond)
2747       SelectCond = 0;
2748     
2749     // If we ran out of things to eliminate, break out of the loop.
2750     if (SelectCond == 0 && SI == 0)
2751       break;
2752     
2753   }
2754   return true;
2755 }
2756
2757
2758 /// This function implements the transforms on div instructions that work
2759 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2760 /// used by the visitors to those instructions.
2761 /// @brief Transforms common to all three div instructions
2762 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2763   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2764
2765   // undef / X -> 0        for integer.
2766   // undef / X -> undef    for FP (the undef could be a snan).
2767   if (isa<UndefValue>(Op0)) {
2768     if (Op0->getType()->isFPOrFPVector())
2769       return ReplaceInstUsesWith(I, Op0);
2770     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2771   }
2772
2773   // X / undef -> undef
2774   if (isa<UndefValue>(Op1))
2775     return ReplaceInstUsesWith(I, Op1);
2776
2777   return 0;
2778 }
2779
2780 /// This function implements the transforms common to both integer division
2781 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2782 /// division instructions.
2783 /// @brief Common integer divide transforms
2784 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2785   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2786
2787   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2788   if (Op0 == Op1) {
2789     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2790       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2791       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2792       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2793     }
2794
2795     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2796     return ReplaceInstUsesWith(I, CI);
2797   }
2798   
2799   if (Instruction *Common = commonDivTransforms(I))
2800     return Common;
2801   
2802   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2803   // This does not apply for fdiv.
2804   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2805     return &I;
2806
2807   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2808     // div X, 1 == X
2809     if (RHS->equalsInt(1))
2810       return ReplaceInstUsesWith(I, Op0);
2811
2812     // (X / C1) / C2  -> X / (C1*C2)
2813     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2814       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2815         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2816           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2817             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2818           else 
2819             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2820                                           Multiply(RHS, LHSRHS));
2821         }
2822
2823     if (!RHS->isZero()) { // avoid X udiv 0
2824       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2825         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2826           return R;
2827       if (isa<PHINode>(Op0))
2828         if (Instruction *NV = FoldOpIntoPhi(I))
2829           return NV;
2830     }
2831   }
2832
2833   // 0 / X == 0, we don't need to preserve faults!
2834   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2835     if (LHS->equalsInt(0))
2836       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2837
2838   // It can't be division by zero, hence it must be division by one.
2839   if (I.getType() == Type::Int1Ty)
2840     return ReplaceInstUsesWith(I, Op0);
2841
2842   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2843     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2844       // div X, 1 == X
2845       if (X->isOne())
2846         return ReplaceInstUsesWith(I, Op0);
2847   }
2848
2849   return 0;
2850 }
2851
2852 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2853   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2854
2855   // Handle the integer div common cases
2856   if (Instruction *Common = commonIDivTransforms(I))
2857     return Common;
2858
2859   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2860     // X udiv C^2 -> X >> C
2861     // Check to see if this is an unsigned division with an exact power of 2,
2862     // if so, convert to a right shift.
2863     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2864       return BinaryOperator::CreateLShr(Op0, 
2865                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2866
2867     // X udiv C, where C >= signbit
2868     if (C->getValue().isNegative()) {
2869       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2870                                       I);
2871       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2872                                 ConstantInt::get(I.getType(), 1));
2873     }
2874   }
2875
2876   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2877   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2878     if (RHSI->getOpcode() == Instruction::Shl &&
2879         isa<ConstantInt>(RHSI->getOperand(0))) {
2880       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2881       if (C1.isPowerOf2()) {
2882         Value *N = RHSI->getOperand(1);
2883         const Type *NTy = N->getType();
2884         if (uint32_t C2 = C1.logBase2()) {
2885           Constant *C2V = ConstantInt::get(NTy, C2);
2886           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2887         }
2888         return BinaryOperator::CreateLShr(Op0, N);
2889       }
2890     }
2891   }
2892   
2893   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2894   // where C1&C2 are powers of two.
2895   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2896     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2897       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2898         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2899         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2900           // Compute the shift amounts
2901           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2902           // Construct the "on true" case of the select
2903           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2904           Instruction *TSI = BinaryOperator::CreateLShr(
2905                                                  Op0, TC, SI->getName()+".t");
2906           TSI = InsertNewInstBefore(TSI, I);
2907   
2908           // Construct the "on false" case of the select
2909           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2910           Instruction *FSI = BinaryOperator::CreateLShr(
2911                                                  Op0, FC, SI->getName()+".f");
2912           FSI = InsertNewInstBefore(FSI, I);
2913
2914           // construct the select instruction and return it.
2915           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2916         }
2917       }
2918   return 0;
2919 }
2920
2921 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2922   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2923
2924   // Handle the integer div common cases
2925   if (Instruction *Common = commonIDivTransforms(I))
2926     return Common;
2927
2928   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2929     // sdiv X, -1 == -X
2930     if (RHS->isAllOnesValue())
2931       return BinaryOperator::CreateNeg(Op0);
2932   }
2933
2934   // If the sign bits of both operands are zero (i.e. we can prove they are
2935   // unsigned inputs), turn this into a udiv.
2936   if (I.getType()->isInteger()) {
2937     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2938     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2939       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2940       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2941     }
2942   }      
2943   
2944   return 0;
2945 }
2946
2947 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2948   return commonDivTransforms(I);
2949 }
2950
2951 /// This function implements the transforms on rem instructions that work
2952 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2953 /// is used by the visitors to those instructions.
2954 /// @brief Transforms common to all three rem instructions
2955 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2956   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2957
2958   // 0 % X == 0 for integer, we don't need to preserve faults!
2959   if (Constant *LHS = dyn_cast<Constant>(Op0))
2960     if (LHS->isNullValue())
2961       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2962
2963   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2964     if (I.getType()->isFPOrFPVector())
2965       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2966     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2967   }
2968   if (isa<UndefValue>(Op1))
2969     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2970
2971   // Handle cases involving: rem X, (select Cond, Y, Z)
2972   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2973     return &I;
2974
2975   return 0;
2976 }
2977
2978 /// This function implements the transforms common to both integer remainder
2979 /// instructions (urem and srem). It is called by the visitors to those integer
2980 /// remainder instructions.
2981 /// @brief Common integer remainder transforms
2982 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2983   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2984
2985   if (Instruction *common = commonRemTransforms(I))
2986     return common;
2987
2988   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2989     // X % 0 == undef, we don't need to preserve faults!
2990     if (RHS->equalsInt(0))
2991       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2992     
2993     if (RHS->equalsInt(1))  // X % 1 == 0
2994       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2995
2996     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2997       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2998         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2999           return R;
3000       } else if (isa<PHINode>(Op0I)) {
3001         if (Instruction *NV = FoldOpIntoPhi(I))
3002           return NV;
3003       }
3004
3005       // See if we can fold away this rem instruction.
3006       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3007       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3008       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3009                                KnownZero, KnownOne))
3010         return &I;
3011     }
3012   }
3013
3014   return 0;
3015 }
3016
3017 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3018   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3019
3020   if (Instruction *common = commonIRemTransforms(I))
3021     return common;
3022   
3023   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3024     // X urem C^2 -> X and C
3025     // Check to see if this is an unsigned remainder with an exact power of 2,
3026     // if so, convert to a bitwise and.
3027     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3028       if (C->getValue().isPowerOf2())
3029         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3030   }
3031
3032   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3033     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3034     if (RHSI->getOpcode() == Instruction::Shl &&
3035         isa<ConstantInt>(RHSI->getOperand(0))) {
3036       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3037         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3038         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3039                                                                    "tmp"), I);
3040         return BinaryOperator::CreateAnd(Op0, Add);
3041       }
3042     }
3043   }
3044
3045   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3046   // where C1&C2 are powers of two.
3047   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3048     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3049       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3050         // STO == 0 and SFO == 0 handled above.
3051         if ((STO->getValue().isPowerOf2()) && 
3052             (SFO->getValue().isPowerOf2())) {
3053           Value *TrueAnd = InsertNewInstBefore(
3054             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3055           Value *FalseAnd = InsertNewInstBefore(
3056             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3057           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3058         }
3059       }
3060   }
3061   
3062   return 0;
3063 }
3064
3065 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3066   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068   // Handle the integer rem common cases
3069   if (Instruction *common = commonIRemTransforms(I))
3070     return common;
3071   
3072   if (Value *RHSNeg = dyn_castNegVal(Op1))
3073     if (!isa<Constant>(RHSNeg) ||
3074         (isa<ConstantInt>(RHSNeg) &&
3075          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3076       // X % -Y -> X % Y
3077       AddUsesToWorkList(I);
3078       I.setOperand(1, RHSNeg);
3079       return &I;
3080     }
3081
3082   // If the sign bits of both operands are zero (i.e. we can prove they are
3083   // unsigned inputs), turn this into a urem.
3084   if (I.getType()->isInteger()) {
3085     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3086     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3087       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3088       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3089     }
3090   }
3091
3092   // If it's a constant vector, flip any negative values positive.
3093   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3094     unsigned VWidth = RHSV->getNumOperands();
3095
3096     bool hasNegative = false;
3097     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3098       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3099         if (RHS->getValue().isNegative())
3100           hasNegative = true;
3101
3102     if (hasNegative) {
3103       std::vector<Constant *> Elts(VWidth);
3104       for (unsigned i = 0; i != VWidth; ++i) {
3105         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3106           if (RHS->getValue().isNegative())
3107             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3108           else
3109             Elts[i] = RHS;
3110         }
3111       }
3112
3113       Constant *NewRHSV = ConstantVector::get(Elts);
3114       if (NewRHSV != RHSV) {
3115         AddUsesToWorkList(I);
3116         I.setOperand(1, NewRHSV);
3117         return &I;
3118       }
3119     }
3120   }
3121
3122   return 0;
3123 }
3124
3125 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3126   return commonRemTransforms(I);
3127 }
3128
3129 // isOneBitSet - Return true if there is exactly one bit set in the specified
3130 // constant.
3131 static bool isOneBitSet(const ConstantInt *CI) {
3132   return CI->getValue().isPowerOf2();
3133 }
3134
3135 // isHighOnes - Return true if the constant is of the form 1+0+.
3136 // This is the same as lowones(~X).
3137 static bool isHighOnes(const ConstantInt *CI) {
3138   return (~CI->getValue() + 1).isPowerOf2();
3139 }
3140
3141 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3142 /// are carefully arranged to allow folding of expressions such as:
3143 ///
3144 ///      (A < B) | (A > B) --> (A != B)
3145 ///
3146 /// Note that this is only valid if the first and second predicates have the
3147 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3148 ///
3149 /// Three bits are used to represent the condition, as follows:
3150 ///   0  A > B
3151 ///   1  A == B
3152 ///   2  A < B
3153 ///
3154 /// <=>  Value  Definition
3155 /// 000     0   Always false
3156 /// 001     1   A >  B
3157 /// 010     2   A == B
3158 /// 011     3   A >= B
3159 /// 100     4   A <  B
3160 /// 101     5   A != B
3161 /// 110     6   A <= B
3162 /// 111     7   Always true
3163 ///  
3164 static unsigned getICmpCode(const ICmpInst *ICI) {
3165   switch (ICI->getPredicate()) {
3166     // False -> 0
3167   case ICmpInst::ICMP_UGT: return 1;  // 001
3168   case ICmpInst::ICMP_SGT: return 1;  // 001
3169   case ICmpInst::ICMP_EQ:  return 2;  // 010
3170   case ICmpInst::ICMP_UGE: return 3;  // 011
3171   case ICmpInst::ICMP_SGE: return 3;  // 011
3172   case ICmpInst::ICMP_ULT: return 4;  // 100
3173   case ICmpInst::ICMP_SLT: return 4;  // 100
3174   case ICmpInst::ICMP_NE:  return 5;  // 101
3175   case ICmpInst::ICMP_ULE: return 6;  // 110
3176   case ICmpInst::ICMP_SLE: return 6;  // 110
3177     // True -> 7
3178   default:
3179     assert(0 && "Invalid ICmp predicate!");
3180     return 0;
3181   }
3182 }
3183
3184 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3185 /// predicate into a three bit mask. It also returns whether it is an ordered
3186 /// predicate by reference.
3187 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3188   isOrdered = false;
3189   switch (CC) {
3190   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3191   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3192   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3193   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3194   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3195   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3196   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3197   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3198   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3199   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3200   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3201   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3202   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3203   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3204     // True -> 7
3205   default:
3206     // Not expecting FCMP_FALSE and FCMP_TRUE;
3207     assert(0 && "Unexpected FCmp predicate!");
3208     return 0;
3209   }
3210 }
3211
3212 /// getICmpValue - This is the complement of getICmpCode, which turns an
3213 /// opcode and two operands into either a constant true or false, or a brand 
3214 /// new ICmp instruction. The sign is passed in to determine which kind
3215 /// of predicate to use in the new icmp instruction.
3216 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3217   switch (code) {
3218   default: assert(0 && "Illegal ICmp code!");
3219   case  0: return ConstantInt::getFalse();
3220   case  1: 
3221     if (sign)
3222       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3223     else
3224       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3225   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3226   case  3: 
3227     if (sign)
3228       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3229     else
3230       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3231   case  4: 
3232     if (sign)
3233       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3234     else
3235       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3236   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3237   case  6: 
3238     if (sign)
3239       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3240     else
3241       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3242   case  7: return ConstantInt::getTrue();
3243   }
3244 }
3245
3246 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3247 /// opcode and two operands into either a FCmp instruction. isordered is passed
3248 /// in to determine which kind of predicate to use in the new fcmp instruction.
3249 static Value *getFCmpValue(bool isordered, unsigned code,
3250                            Value *LHS, Value *RHS) {
3251   switch (code) {
3252   default: assert(0 && "Illegal FCmp code!");
3253   case  0:
3254     if (isordered)
3255       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3256     else
3257       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3258   case  1: 
3259     if (isordered)
3260       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3261     else
3262       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3263   case  2: 
3264     if (isordered)
3265       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3266     else
3267       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3268   case  3: 
3269     if (isordered)
3270       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3271     else
3272       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3273   case  4: 
3274     if (isordered)
3275       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3276     else
3277       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3278   case  5: 
3279     if (isordered)
3280       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3281     else
3282       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3283   case  6: 
3284     if (isordered)
3285       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3286     else
3287       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3288   case  7: return ConstantInt::getTrue();
3289   }
3290 }
3291
3292 /// PredicatesFoldable - Return true if both predicates match sign or if at
3293 /// least one of them is an equality comparison (which is signless).
3294 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3295   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3296          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3297          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3298 }
3299
3300 namespace { 
3301 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3302 struct FoldICmpLogical {
3303   InstCombiner &IC;
3304   Value *LHS, *RHS;
3305   ICmpInst::Predicate pred;
3306   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3307     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3308       pred(ICI->getPredicate()) {}
3309   bool shouldApply(Value *V) const {
3310     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3311       if (PredicatesFoldable(pred, ICI->getPredicate()))
3312         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3313                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3314     return false;
3315   }
3316   Instruction *apply(Instruction &Log) const {
3317     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3318     if (ICI->getOperand(0) != LHS) {
3319       assert(ICI->getOperand(1) == LHS);
3320       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3321     }
3322
3323     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3324     unsigned LHSCode = getICmpCode(ICI);
3325     unsigned RHSCode = getICmpCode(RHSICI);
3326     unsigned Code;
3327     switch (Log.getOpcode()) {
3328     case Instruction::And: Code = LHSCode & RHSCode; break;
3329     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3330     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3331     default: assert(0 && "Illegal logical opcode!"); return 0;
3332     }
3333
3334     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3335                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3336       
3337     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3338     if (Instruction *I = dyn_cast<Instruction>(RV))
3339       return I;
3340     // Otherwise, it's a constant boolean value...
3341     return IC.ReplaceInstUsesWith(Log, RV);
3342   }
3343 };
3344 } // end anonymous namespace
3345
3346 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3347 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3348 // guaranteed to be a binary operator.
3349 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3350                                     ConstantInt *OpRHS,
3351                                     ConstantInt *AndRHS,
3352                                     BinaryOperator &TheAnd) {
3353   Value *X = Op->getOperand(0);
3354   Constant *Together = 0;
3355   if (!Op->isShift())
3356     Together = And(AndRHS, OpRHS);
3357
3358   switch (Op->getOpcode()) {
3359   case Instruction::Xor:
3360     if (Op->hasOneUse()) {
3361       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3362       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3363       InsertNewInstBefore(And, TheAnd);
3364       And->takeName(Op);
3365       return BinaryOperator::CreateXor(And, Together);
3366     }
3367     break;
3368   case Instruction::Or:
3369     if (Together == AndRHS) // (X | C) & C --> C
3370       return ReplaceInstUsesWith(TheAnd, AndRHS);
3371
3372     if (Op->hasOneUse() && Together != OpRHS) {
3373       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3374       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3375       InsertNewInstBefore(Or, TheAnd);
3376       Or->takeName(Op);
3377       return BinaryOperator::CreateAnd(Or, AndRHS);
3378     }
3379     break;
3380   case Instruction::Add:
3381     if (Op->hasOneUse()) {
3382       // Adding a one to a single bit bit-field should be turned into an XOR
3383       // of the bit.  First thing to check is to see if this AND is with a
3384       // single bit constant.
3385       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3386
3387       // If there is only one bit set...
3388       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3389         // Ok, at this point, we know that we are masking the result of the
3390         // ADD down to exactly one bit.  If the constant we are adding has
3391         // no bits set below this bit, then we can eliminate the ADD.
3392         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3393
3394         // Check to see if any bits below the one bit set in AndRHSV are set.
3395         if ((AddRHS & (AndRHSV-1)) == 0) {
3396           // If not, the only thing that can effect the output of the AND is
3397           // the bit specified by AndRHSV.  If that bit is set, the effect of
3398           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3399           // no effect.
3400           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3401             TheAnd.setOperand(0, X);
3402             return &TheAnd;
3403           } else {
3404             // Pull the XOR out of the AND.
3405             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3406             InsertNewInstBefore(NewAnd, TheAnd);
3407             NewAnd->takeName(Op);
3408             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3409           }
3410         }
3411       }
3412     }
3413     break;
3414
3415   case Instruction::Shl: {
3416     // We know that the AND will not produce any of the bits shifted in, so if
3417     // the anded constant includes them, clear them now!
3418     //
3419     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3420     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3421     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3422     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3423
3424     if (CI->getValue() == ShlMask) { 
3425     // Masking out bits that the shift already masks
3426       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3427     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3428       TheAnd.setOperand(1, CI);
3429       return &TheAnd;
3430     }
3431     break;
3432   }
3433   case Instruction::LShr:
3434   {
3435     // We know that the AND will not produce any of the bits shifted in, so if
3436     // the anded constant includes them, clear them now!  This only applies to
3437     // unsigned shifts, because a signed shr may bring in set bits!
3438     //
3439     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3440     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3441     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3442     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3443
3444     if (CI->getValue() == ShrMask) {   
3445     // Masking out bits that the shift already masks.
3446       return ReplaceInstUsesWith(TheAnd, Op);
3447     } else if (CI != AndRHS) {
3448       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3449       return &TheAnd;
3450     }
3451     break;
3452   }
3453   case Instruction::AShr:
3454     // Signed shr.
3455     // See if this is shifting in some sign extension, then masking it out
3456     // with an and.
3457     if (Op->hasOneUse()) {
3458       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3459       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3460       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3461       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3462       if (C == AndRHS) {          // Masking out bits shifted in.
3463         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3464         // Make the argument unsigned.
3465         Value *ShVal = Op->getOperand(0);
3466         ShVal = InsertNewInstBefore(
3467             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3468                                    Op->getName()), TheAnd);
3469         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3470       }
3471     }
3472     break;
3473   }
3474   return 0;
3475 }
3476
3477
3478 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3479 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3480 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3481 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3482 /// insert new instructions.
3483 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3484                                            bool isSigned, bool Inside, 
3485                                            Instruction &IB) {
3486   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3487             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3488          "Lo is not <= Hi in range emission code!");
3489     
3490   if (Inside) {
3491     if (Lo == Hi)  // Trivially false.
3492       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3493
3494     // V >= Min && V < Hi --> V < Hi
3495     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3496       ICmpInst::Predicate pred = (isSigned ? 
3497         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3498       return new ICmpInst(pred, V, Hi);
3499     }
3500
3501     // Emit V-Lo <u Hi-Lo
3502     Constant *NegLo = ConstantExpr::getNeg(Lo);
3503     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3504     InsertNewInstBefore(Add, IB);
3505     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3506     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3507   }
3508
3509   if (Lo == Hi)  // Trivially true.
3510     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3511
3512   // V < Min || V >= Hi -> V > Hi-1
3513   Hi = SubOne(cast<ConstantInt>(Hi));
3514   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3515     ICmpInst::Predicate pred = (isSigned ? 
3516         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3517     return new ICmpInst(pred, V, Hi);
3518   }
3519
3520   // Emit V-Lo >u Hi-1-Lo
3521   // Note that Hi has already had one subtracted from it, above.
3522   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3523   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3524   InsertNewInstBefore(Add, IB);
3525   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3526   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3527 }
3528
3529 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3530 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3531 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3532 // not, since all 1s are not contiguous.
3533 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3534   const APInt& V = Val->getValue();
3535   uint32_t BitWidth = Val->getType()->getBitWidth();
3536   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3537
3538   // look for the first zero bit after the run of ones
3539   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3540   // look for the first non-zero bit
3541   ME = V.getActiveBits(); 
3542   return true;
3543 }
3544
3545 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3546 /// where isSub determines whether the operator is a sub.  If we can fold one of
3547 /// the following xforms:
3548 /// 
3549 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3550 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3551 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3552 ///
3553 /// return (A +/- B).
3554 ///
3555 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3556                                         ConstantInt *Mask, bool isSub,
3557                                         Instruction &I) {
3558   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3559   if (!LHSI || LHSI->getNumOperands() != 2 ||
3560       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3561
3562   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3563
3564   switch (LHSI->getOpcode()) {
3565   default: return 0;
3566   case Instruction::And:
3567     if (And(N, Mask) == Mask) {
3568       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3569       if ((Mask->getValue().countLeadingZeros() + 
3570            Mask->getValue().countPopulation()) == 
3571           Mask->getValue().getBitWidth())
3572         break;
3573
3574       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3575       // part, we don't need any explicit masks to take them out of A.  If that
3576       // is all N is, ignore it.
3577       uint32_t MB = 0, ME = 0;
3578       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3579         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3580         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3581         if (MaskedValueIsZero(RHS, Mask))
3582           break;
3583       }
3584     }
3585     return 0;
3586   case Instruction::Or:
3587   case Instruction::Xor:
3588     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3589     if ((Mask->getValue().countLeadingZeros() + 
3590          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3591         && And(N, Mask)->isZero())
3592       break;
3593     return 0;
3594   }
3595   
3596   Instruction *New;
3597   if (isSub)
3598     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3599   else
3600     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3601   return InsertNewInstBefore(New, I);
3602 }
3603
3604 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3605 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3606                                           ICmpInst *LHS, ICmpInst *RHS) {
3607   Value *Val, *Val2;
3608   ConstantInt *LHSCst, *RHSCst;
3609   ICmpInst::Predicate LHSCC, RHSCC;
3610   
3611   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3612   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3613       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3614     return 0;
3615   
3616   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3617   // where C is a power of 2
3618   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3619       LHSCst->getValue().isPowerOf2()) {
3620     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3621     InsertNewInstBefore(NewOr, I);
3622     return new ICmpInst(LHSCC, NewOr, LHSCst);
3623   }
3624   
3625   // From here on, we only handle:
3626   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3627   if (Val != Val2) return 0;
3628   
3629   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3630   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3631       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3632       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3633       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3634     return 0;
3635   
3636   // We can't fold (ugt x, C) & (sgt x, C2).
3637   if (!PredicatesFoldable(LHSCC, RHSCC))
3638     return 0;
3639     
3640   // Ensure that the larger constant is on the RHS.
3641   bool ShouldSwap;
3642   if (ICmpInst::isSignedPredicate(LHSCC) ||
3643       (ICmpInst::isEquality(LHSCC) && 
3644        ICmpInst::isSignedPredicate(RHSCC)))
3645     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3646   else
3647     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3648     
3649   if (ShouldSwap) {
3650     std::swap(LHS, RHS);
3651     std::swap(LHSCst, RHSCst);
3652     std::swap(LHSCC, RHSCC);
3653   }
3654
3655   // At this point, we know we have have two icmp instructions
3656   // comparing a value against two constants and and'ing the result
3657   // together.  Because of the above check, we know that we only have
3658   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3659   // (from the FoldICmpLogical check above), that the two constants 
3660   // are not equal and that the larger constant is on the RHS
3661   assert(LHSCst != RHSCst && "Compares not folded above?");
3662
3663   switch (LHSCC) {
3664   default: assert(0 && "Unknown integer condition code!");
3665   case ICmpInst::ICMP_EQ:
3666     switch (RHSCC) {
3667     default: assert(0 && "Unknown integer condition code!");
3668     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3669     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3670     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3671       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3672     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3673     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3674     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3675       return ReplaceInstUsesWith(I, LHS);
3676     }
3677   case ICmpInst::ICMP_NE:
3678     switch (RHSCC) {
3679     default: assert(0 && "Unknown integer condition code!");
3680     case ICmpInst::ICMP_ULT:
3681       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3682         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3683       break;                        // (X != 13 & X u< 15) -> no change
3684     case ICmpInst::ICMP_SLT:
3685       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3686         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3687       break;                        // (X != 13 & X s< 15) -> no change
3688     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3689     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3690     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3691       return ReplaceInstUsesWith(I, RHS);
3692     case ICmpInst::ICMP_NE:
3693       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3694         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3695         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3696                                                      Val->getName()+".off");
3697         InsertNewInstBefore(Add, I);
3698         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3699                             ConstantInt::get(Add->getType(), 1));
3700       }
3701       break;                        // (X != 13 & X != 15) -> no change
3702     }
3703     break;
3704   case ICmpInst::ICMP_ULT:
3705     switch (RHSCC) {
3706     default: assert(0 && "Unknown integer condition code!");
3707     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3708     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3709       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3710     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3711       break;
3712     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3713     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3714       return ReplaceInstUsesWith(I, LHS);
3715     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3716       break;
3717     }
3718     break;
3719   case ICmpInst::ICMP_SLT:
3720     switch (RHSCC) {
3721     default: assert(0 && "Unknown integer condition code!");
3722     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3723     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3724       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3725     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3726       break;
3727     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3728     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3729       return ReplaceInstUsesWith(I, LHS);
3730     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3731       break;
3732     }
3733     break;
3734   case ICmpInst::ICMP_UGT:
3735     switch (RHSCC) {
3736     default: assert(0 && "Unknown integer condition code!");
3737     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3738     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3739       return ReplaceInstUsesWith(I, RHS);
3740     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3741       break;
3742     case ICmpInst::ICMP_NE:
3743       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3744         return new ICmpInst(LHSCC, Val, RHSCst);
3745       break;                        // (X u> 13 & X != 15) -> no change
3746     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3747       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3748     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3749       break;
3750     }
3751     break;
3752   case ICmpInst::ICMP_SGT:
3753     switch (RHSCC) {
3754     default: assert(0 && "Unknown integer condition code!");
3755     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3756     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3757       return ReplaceInstUsesWith(I, RHS);
3758     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3759       break;
3760     case ICmpInst::ICMP_NE:
3761       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3762         return new ICmpInst(LHSCC, Val, RHSCst);
3763       break;                        // (X s> 13 & X != 15) -> no change
3764     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3765       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3766     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3767       break;
3768     }
3769     break;
3770   }
3771  
3772   return 0;
3773 }
3774
3775
3776 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3777   bool Changed = SimplifyCommutative(I);
3778   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3779
3780   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3781     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3782
3783   // and X, X = X
3784   if (Op0 == Op1)
3785     return ReplaceInstUsesWith(I, Op1);
3786
3787   // See if we can simplify any instructions used by the instruction whose sole 
3788   // purpose is to compute bits we don't care about.
3789   if (!isa<VectorType>(I.getType())) {
3790     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3791     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3792     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3793                              KnownZero, KnownOne))
3794       return &I;
3795   } else {
3796     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3797       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3798         return ReplaceInstUsesWith(I, I.getOperand(0));
3799     } else if (isa<ConstantAggregateZero>(Op1)) {
3800       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3801     }
3802   }
3803   
3804   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3805     const APInt& AndRHSMask = AndRHS->getValue();
3806     APInt NotAndRHS(~AndRHSMask);
3807
3808     // Optimize a variety of ((val OP C1) & C2) combinations...
3809     if (isa<BinaryOperator>(Op0)) {
3810       Instruction *Op0I = cast<Instruction>(Op0);
3811       Value *Op0LHS = Op0I->getOperand(0);
3812       Value *Op0RHS = Op0I->getOperand(1);
3813       switch (Op0I->getOpcode()) {
3814       case Instruction::Xor:
3815       case Instruction::Or:
3816         // If the mask is only needed on one incoming arm, push it up.
3817         if (Op0I->hasOneUse()) {
3818           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3819             // Not masking anything out for the LHS, move to RHS.
3820             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3821                                                    Op0RHS->getName()+".masked");
3822             InsertNewInstBefore(NewRHS, I);
3823             return BinaryOperator::Create(
3824                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3825           }
3826           if (!isa<Constant>(Op0RHS) &&
3827               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3828             // Not masking anything out for the RHS, move to LHS.
3829             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3830                                                    Op0LHS->getName()+".masked");
3831             InsertNewInstBefore(NewLHS, I);
3832             return BinaryOperator::Create(
3833                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3834           }
3835         }
3836
3837         break;
3838       case Instruction::Add:
3839         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3840         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3841         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3842         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3843           return BinaryOperator::CreateAnd(V, AndRHS);
3844         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3845           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3846         break;
3847
3848       case Instruction::Sub:
3849         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3850         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3851         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3852         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3853           return BinaryOperator::CreateAnd(V, AndRHS);
3854
3855         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3856         // has 1's for all bits that the subtraction with A might affect.
3857         if (Op0I->hasOneUse()) {
3858           uint32_t BitWidth = AndRHSMask.getBitWidth();
3859           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3860           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3861
3862           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3863           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3864               MaskedValueIsZero(Op0LHS, Mask)) {
3865             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3866             InsertNewInstBefore(NewNeg, I);
3867             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3868           }
3869         }
3870         break;
3871
3872       case Instruction::Shl:
3873       case Instruction::LShr:
3874         // (1 << x) & 1 --> zext(x == 0)
3875         // (1 >> x) & 1 --> zext(x == 0)
3876         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3877           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3878                                            Constant::getNullValue(I.getType()));
3879           InsertNewInstBefore(NewICmp, I);
3880           return new ZExtInst(NewICmp, I.getType());
3881         }
3882         break;
3883       }
3884
3885       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3886         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3887           return Res;
3888     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3889       // If this is an integer truncation or change from signed-to-unsigned, and
3890       // if the source is an and/or with immediate, transform it.  This
3891       // frequently occurs for bitfield accesses.
3892       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3893         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3894             CastOp->getNumOperands() == 2)
3895           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3896             if (CastOp->getOpcode() == Instruction::And) {
3897               // Change: and (cast (and X, C1) to T), C2
3898               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3899               // This will fold the two constants together, which may allow 
3900               // other simplifications.
3901               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3902                 CastOp->getOperand(0), I.getType(), 
3903                 CastOp->getName()+".shrunk");
3904               NewCast = InsertNewInstBefore(NewCast, I);
3905               // trunc_or_bitcast(C1)&C2
3906               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3907               C3 = ConstantExpr::getAnd(C3, AndRHS);
3908               return BinaryOperator::CreateAnd(NewCast, C3);
3909             } else if (CastOp->getOpcode() == Instruction::Or) {
3910               // Change: and (cast (or X, C1) to T), C2
3911               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3912               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3913               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3914                 return ReplaceInstUsesWith(I, AndRHS);
3915             }
3916           }
3917       }
3918     }
3919
3920     // Try to fold constant and into select arguments.
3921     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3922       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3923         return R;
3924     if (isa<PHINode>(Op0))
3925       if (Instruction *NV = FoldOpIntoPhi(I))
3926         return NV;
3927   }
3928
3929   Value *Op0NotVal = dyn_castNotVal(Op0);
3930   Value *Op1NotVal = dyn_castNotVal(Op1);
3931
3932   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3933     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3934
3935   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3936   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3937     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3938                                                I.getName()+".demorgan");
3939     InsertNewInstBefore(Or, I);
3940     return BinaryOperator::CreateNot(Or);
3941   }
3942   
3943   {
3944     Value *A = 0, *B = 0, *C = 0, *D = 0;
3945     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3946       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3947         return ReplaceInstUsesWith(I, Op1);
3948     
3949       // (A|B) & ~(A&B) -> A^B
3950       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3951         if ((A == C && B == D) || (A == D && B == C))
3952           return BinaryOperator::CreateXor(A, B);
3953       }
3954     }
3955     
3956     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3957       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3958         return ReplaceInstUsesWith(I, Op0);
3959
3960       // ~(A&B) & (A|B) -> A^B
3961       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3962         if ((A == C && B == D) || (A == D && B == C))
3963           return BinaryOperator::CreateXor(A, B);
3964       }
3965     }
3966     
3967     if (Op0->hasOneUse() &&
3968         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3969       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3970         I.swapOperands();     // Simplify below
3971         std::swap(Op0, Op1);
3972       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3973         cast<BinaryOperator>(Op0)->swapOperands();
3974         I.swapOperands();     // Simplify below
3975         std::swap(Op0, Op1);
3976       }
3977     }
3978
3979     if (Op1->hasOneUse() &&
3980         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3981       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3982         cast<BinaryOperator>(Op1)->swapOperands();
3983         std::swap(A, B);
3984       }
3985       if (A == Op0) {                                // A&(A^B) -> A & ~B
3986         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3987         InsertNewInstBefore(NotB, I);
3988         return BinaryOperator::CreateAnd(A, NotB);
3989       }
3990     }
3991
3992     // (A&((~A)|B)) -> A&B
3993     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3994         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3995       return BinaryOperator::CreateAnd(A, Op1);
3996     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3997         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3998       return BinaryOperator::CreateAnd(A, Op0);
3999   }
4000   
4001   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4002     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4003     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4004       return R;
4005
4006     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4007       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4008         return Res;
4009   }
4010
4011   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4012   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4013     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4014       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4015         const Type *SrcTy = Op0C->getOperand(0)->getType();
4016         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4017             // Only do this if the casts both really cause code to be generated.
4018             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4019                               I.getType(), TD) &&
4020             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4021                               I.getType(), TD)) {
4022           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4023                                                          Op1C->getOperand(0),
4024                                                          I.getName());
4025           InsertNewInstBefore(NewOp, I);
4026           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4027         }
4028       }
4029     
4030   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4031   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4032     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4033       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4034           SI0->getOperand(1) == SI1->getOperand(1) &&
4035           (SI0->hasOneUse() || SI1->hasOneUse())) {
4036         Instruction *NewOp =
4037           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4038                                                         SI1->getOperand(0),
4039                                                         SI0->getName()), I);
4040         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4041                                       SI1->getOperand(1));
4042       }
4043   }
4044
4045   // If and'ing two fcmp, try combine them into one.
4046   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4047     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4048       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4049           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4050         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4051         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4052           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4053             // If either of the constants are nans, then the whole thing returns
4054             // false.
4055             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4056               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4057             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4058                                 RHS->getOperand(0));
4059           }
4060       } else {
4061         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4062         FCmpInst::Predicate Op0CC, Op1CC;
4063         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4064             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4065           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4066             // Swap RHS operands to match LHS.
4067             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4068             std::swap(Op1LHS, Op1RHS);
4069           }
4070           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4071             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4072             if (Op0CC == Op1CC)
4073               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4074             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4075                      Op1CC == FCmpInst::FCMP_FALSE)
4076               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4077             else if (Op0CC == FCmpInst::FCMP_TRUE)
4078               return ReplaceInstUsesWith(I, Op1);
4079             else if (Op1CC == FCmpInst::FCMP_TRUE)
4080               return ReplaceInstUsesWith(I, Op0);
4081             bool Op0Ordered;
4082             bool Op1Ordered;
4083             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4084             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4085             if (Op1Pred == 0) {
4086               std::swap(Op0, Op1);
4087               std::swap(Op0Pred, Op1Pred);
4088               std::swap(Op0Ordered, Op1Ordered);
4089             }
4090             if (Op0Pred == 0) {
4091               // uno && ueq -> uno && (uno || eq) -> ueq
4092               // ord && olt -> ord && (ord && lt) -> olt
4093               if (Op0Ordered == Op1Ordered)
4094                 return ReplaceInstUsesWith(I, Op1);
4095               // uno && oeq -> uno && (ord && eq) -> false
4096               // uno && ord -> false
4097               if (!Op0Ordered)
4098                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4099               // ord && ueq -> ord && (uno || eq) -> oeq
4100               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4101                                                     Op0LHS, Op0RHS));
4102             }
4103           }
4104         }
4105       }
4106     }
4107   }
4108
4109   return Changed ? &I : 0;
4110 }
4111
4112 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4113 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4114 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4115 /// the expression came from the corresponding "byte swapped" byte in some other
4116 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4117 /// we know that the expression deposits the low byte of %X into the high byte
4118 /// of the bswap result and that all other bytes are zero.  This expression is
4119 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4120 /// match.
4121 ///
4122 /// This function returns true if the match was unsuccessful and false if so.
4123 /// On entry to the function the "OverallLeftShift" is a signed integer value
4124 /// indicating the number of bytes that the subexpression is later shifted.  For
4125 /// example, if the expression is later right shifted by 16 bits, the
4126 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4127 /// byte of ByteValues is actually being set.
4128 ///
4129 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4130 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4131 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4132 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4133 /// always in the local (OverallLeftShift) coordinate space.
4134 ///
4135 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4136                               SmallVector<Value*, 8> &ByteValues) {
4137   if (Instruction *I = dyn_cast<Instruction>(V)) {
4138     // If this is an or instruction, it may be an inner node of the bswap.
4139     if (I->getOpcode() == Instruction::Or) {
4140       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4141                                ByteValues) ||
4142              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4143                                ByteValues);
4144     }
4145   
4146     // If this is a logical shift by a constant multiple of 8, recurse with
4147     // OverallLeftShift and ByteMask adjusted.
4148     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4149       unsigned ShAmt = 
4150         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4151       // Ensure the shift amount is defined and of a byte value.
4152       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4153         return true;
4154
4155       unsigned ByteShift = ShAmt >> 3;
4156       if (I->getOpcode() == Instruction::Shl) {
4157         // X << 2 -> collect(X, +2)
4158         OverallLeftShift += ByteShift;
4159         ByteMask >>= ByteShift;
4160       } else {
4161         // X >>u 2 -> collect(X, -2)
4162         OverallLeftShift -= ByteShift;
4163         ByteMask <<= ByteShift;
4164         ByteMask &= (~0U >> (32-ByteValues.size()));
4165       }
4166
4167       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4168       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4169
4170       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4171                                ByteValues);
4172     }
4173
4174     // If this is a logical 'and' with a mask that clears bytes, clear the
4175     // corresponding bytes in ByteMask.
4176     if (I->getOpcode() == Instruction::And &&
4177         isa<ConstantInt>(I->getOperand(1))) {
4178       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4179       unsigned NumBytes = ByteValues.size();
4180       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4181       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4182       
4183       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4184         // If this byte is masked out by a later operation, we don't care what
4185         // the and mask is.
4186         if ((ByteMask & (1 << i)) == 0)
4187           continue;
4188         
4189         // If the AndMask is all zeros for this byte, clear the bit.
4190         APInt MaskB = AndMask & Byte;
4191         if (MaskB == 0) {
4192           ByteMask &= ~(1U << i);
4193           continue;
4194         }
4195         
4196         // If the AndMask is not all ones for this byte, it's not a bytezap.
4197         if (MaskB != Byte)
4198           return true;
4199
4200         // Otherwise, this byte is kept.
4201       }
4202
4203       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4204                                ByteValues);
4205     }
4206   }
4207   
4208   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4209   // the input value to the bswap.  Some observations: 1) if more than one byte
4210   // is demanded from this input, then it could not be successfully assembled
4211   // into a byteswap.  At least one of the two bytes would not be aligned with
4212   // their ultimate destination.
4213   if (!isPowerOf2_32(ByteMask)) return true;
4214   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4215   
4216   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4217   // is demanded, it needs to go into byte 0 of the result.  This means that the
4218   // byte needs to be shifted until it lands in the right byte bucket.  The
4219   // shift amount depends on the position: if the byte is coming from the high
4220   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4221   // low part, it must be shifted left.
4222   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4223   if (InputByteNo < ByteValues.size()/2) {
4224     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4225       return true;
4226   } else {
4227     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4228       return true;
4229   }
4230   
4231   // If the destination byte value is already defined, the values are or'd
4232   // together, which isn't a bswap (unless it's an or of the same bits).
4233   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4234     return true;
4235   ByteValues[DestByteNo] = V;
4236   return false;
4237 }
4238
4239 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4240 /// If so, insert the new bswap intrinsic and return it.
4241 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4242   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4243   if (!ITy || ITy->getBitWidth() % 16 || 
4244       // ByteMask only allows up to 32-byte values.
4245       ITy->getBitWidth() > 32*8) 
4246     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4247   
4248   /// ByteValues - For each byte of the result, we keep track of which value
4249   /// defines each byte.
4250   SmallVector<Value*, 8> ByteValues;
4251   ByteValues.resize(ITy->getBitWidth()/8);
4252     
4253   // Try to find all the pieces corresponding to the bswap.
4254   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4255   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4256     return 0;
4257   
4258   // Check to see if all of the bytes come from the same value.
4259   Value *V = ByteValues[0];
4260   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4261   
4262   // Check to make sure that all of the bytes come from the same value.
4263   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4264     if (ByteValues[i] != V)
4265       return 0;
4266   const Type *Tys[] = { ITy };
4267   Module *M = I.getParent()->getParent()->getParent();
4268   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4269   return CallInst::Create(F, V);
4270 }
4271
4272 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4273 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4274 /// we can simplify this expression to "cond ? C : D or B".
4275 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4276                                          Value *C, Value *D) {
4277   // If A is not a select of -1/0, this cannot match.
4278   Value *Cond = 0;
4279   if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
4280     return 0;
4281
4282   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4283   if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
4284     return SelectInst::Create(Cond, C, B);
4285   if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4286     return SelectInst::Create(Cond, C, B);
4287   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4288   if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
4289     return SelectInst::Create(Cond, C, D);
4290   if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4291     return SelectInst::Create(Cond, C, D);
4292   return 0;
4293 }
4294
4295 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4296 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4297                                          ICmpInst *LHS, ICmpInst *RHS) {
4298   Value *Val, *Val2;
4299   ConstantInt *LHSCst, *RHSCst;
4300   ICmpInst::Predicate LHSCC, RHSCC;
4301   
4302   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4303   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4304       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4305     return 0;
4306   
4307   // From here on, we only handle:
4308   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4309   if (Val != Val2) return 0;
4310   
4311   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4312   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4313       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4314       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4315       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4316     return 0;
4317   
4318   // We can't fold (ugt x, C) | (sgt x, C2).
4319   if (!PredicatesFoldable(LHSCC, RHSCC))
4320     return 0;
4321   
4322   // Ensure that the larger constant is on the RHS.
4323   bool ShouldSwap;
4324   if (ICmpInst::isSignedPredicate(LHSCC) ||
4325       (ICmpInst::isEquality(LHSCC) && 
4326        ICmpInst::isSignedPredicate(RHSCC)))
4327     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4328   else
4329     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4330   
4331   if (ShouldSwap) {
4332     std::swap(LHS, RHS);
4333     std::swap(LHSCst, RHSCst);
4334     std::swap(LHSCC, RHSCC);
4335   }
4336   
4337   // At this point, we know we have have two icmp instructions
4338   // comparing a value against two constants and or'ing the result
4339   // together.  Because of the above check, we know that we only have
4340   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4341   // FoldICmpLogical check above), that the two constants are not
4342   // equal.
4343   assert(LHSCst != RHSCst && "Compares not folded above?");
4344
4345   switch (LHSCC) {
4346   default: assert(0 && "Unknown integer condition code!");
4347   case ICmpInst::ICMP_EQ:
4348     switch (RHSCC) {
4349     default: assert(0 && "Unknown integer condition code!");
4350     case ICmpInst::ICMP_EQ:
4351       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4352         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4353         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4354                                                      Val->getName()+".off");
4355         InsertNewInstBefore(Add, I);
4356         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4357         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4358       }
4359       break;                         // (X == 13 | X == 15) -> no change
4360     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4361     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4362       break;
4363     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4364     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4365     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4366       return ReplaceInstUsesWith(I, RHS);
4367     }
4368     break;
4369   case ICmpInst::ICMP_NE:
4370     switch (RHSCC) {
4371     default: assert(0 && "Unknown integer condition code!");
4372     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4373     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4374     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4375       return ReplaceInstUsesWith(I, LHS);
4376     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4377     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4378     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4379       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4380     }
4381     break;
4382   case ICmpInst::ICMP_ULT:
4383     switch (RHSCC) {
4384     default: assert(0 && "Unknown integer condition code!");
4385     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4386       break;
4387     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4388       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4389       // this can cause overflow.
4390       if (RHSCst->isMaxValue(false))
4391         return ReplaceInstUsesWith(I, LHS);
4392       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4393     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4394       break;
4395     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4396     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4397       return ReplaceInstUsesWith(I, RHS);
4398     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4399       break;
4400     }
4401     break;
4402   case ICmpInst::ICMP_SLT:
4403     switch (RHSCC) {
4404     default: assert(0 && "Unknown integer condition code!");
4405     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4406       break;
4407     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4408       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4409       // this can cause overflow.
4410       if (RHSCst->isMaxValue(true))
4411         return ReplaceInstUsesWith(I, LHS);
4412       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4413     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4414       break;
4415     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4416     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4417       return ReplaceInstUsesWith(I, RHS);
4418     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4419       break;
4420     }
4421     break;
4422   case ICmpInst::ICMP_UGT:
4423     switch (RHSCC) {
4424     default: assert(0 && "Unknown integer condition code!");
4425     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4426     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4427       return ReplaceInstUsesWith(I, LHS);
4428     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4429       break;
4430     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4431     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4432       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4433     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4434       break;
4435     }
4436     break;
4437   case ICmpInst::ICMP_SGT:
4438     switch (RHSCC) {
4439     default: assert(0 && "Unknown integer condition code!");
4440     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4441     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4442       return ReplaceInstUsesWith(I, LHS);
4443     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4444       break;
4445     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4446     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4447       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4448     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4449       break;
4450     }
4451     break;
4452   }
4453   return 0;
4454 }
4455
4456 /// FoldOrWithConstants - This helper function folds:
4457 ///
4458 ///     ((A | B) & C1) | (B & C2)
4459 ///
4460 /// into:
4461 /// 
4462 ///     (A & C1) | B
4463 ///
4464 /// when the XOR of the two constants is "all ones" (-1).
4465 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4466                                                Value *A, Value *B, Value *C) {
4467   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4468   if (!CI1) return 0;
4469
4470   Value *V1 = 0;
4471   ConstantInt *CI2 = 0;
4472   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4473
4474   APInt Xor = CI1->getValue() ^ CI2->getValue();
4475   if (!Xor.isAllOnesValue()) return 0;
4476
4477   if (V1 == A || V1 == B) {
4478     Instruction *NewOp =
4479       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4480     return BinaryOperator::CreateOr(NewOp, V1);
4481   }
4482
4483   return 0;
4484 }
4485
4486 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4487   bool Changed = SimplifyCommutative(I);
4488   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4489
4490   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4491     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4492
4493   // or X, X = X
4494   if (Op0 == Op1)
4495     return ReplaceInstUsesWith(I, Op0);
4496
4497   // See if we can simplify any instructions used by the instruction whose sole 
4498   // purpose is to compute bits we don't care about.
4499   if (!isa<VectorType>(I.getType())) {
4500     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4501     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4502     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4503                              KnownZero, KnownOne))
4504       return &I;
4505   } else if (isa<ConstantAggregateZero>(Op1)) {
4506     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4507   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4508     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4509       return ReplaceInstUsesWith(I, I.getOperand(1));
4510   }
4511     
4512
4513   
4514   // or X, -1 == -1
4515   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4516     ConstantInt *C1 = 0; Value *X = 0;
4517     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4518     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4519       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4520       InsertNewInstBefore(Or, I);
4521       Or->takeName(Op0);
4522       return BinaryOperator::CreateAnd(Or, 
4523                ConstantInt::get(RHS->getValue() | C1->getValue()));
4524     }
4525
4526     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4527     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4528       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4529       InsertNewInstBefore(Or, I);
4530       Or->takeName(Op0);
4531       return BinaryOperator::CreateXor(Or,
4532                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4533     }
4534
4535     // Try to fold constant and into select arguments.
4536     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4537       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4538         return R;
4539     if (isa<PHINode>(Op0))
4540       if (Instruction *NV = FoldOpIntoPhi(I))
4541         return NV;
4542   }
4543
4544   Value *A = 0, *B = 0;
4545   ConstantInt *C1 = 0, *C2 = 0;
4546
4547   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4548     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4549       return ReplaceInstUsesWith(I, Op1);
4550   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4551     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4552       return ReplaceInstUsesWith(I, Op0);
4553
4554   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4555   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4556   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4557       match(Op1, m_Or(m_Value(), m_Value())) ||
4558       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4559        match(Op1, m_Shift(m_Value(), m_Value())))) {
4560     if (Instruction *BSwap = MatchBSwap(I))
4561       return BSwap;
4562   }
4563   
4564   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4565   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4566       MaskedValueIsZero(Op1, C1->getValue())) {
4567     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4568     InsertNewInstBefore(NOr, I);
4569     NOr->takeName(Op0);
4570     return BinaryOperator::CreateXor(NOr, C1);
4571   }
4572
4573   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4574   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4575       MaskedValueIsZero(Op0, C1->getValue())) {
4576     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4577     InsertNewInstBefore(NOr, I);
4578     NOr->takeName(Op0);
4579     return BinaryOperator::CreateXor(NOr, C1);
4580   }
4581
4582   // (A & C)|(B & D)
4583   Value *C = 0, *D = 0;
4584   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4585       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4586     Value *V1 = 0, *V2 = 0, *V3 = 0;
4587     C1 = dyn_cast<ConstantInt>(C);
4588     C2 = dyn_cast<ConstantInt>(D);
4589     if (C1 && C2) {  // (A & C1)|(B & C2)
4590       // If we have: ((V + N) & C1) | (V & C2)
4591       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4592       // replace with V+N.
4593       if (C1->getValue() == ~C2->getValue()) {
4594         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4595             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4596           // Add commutes, try both ways.
4597           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4598             return ReplaceInstUsesWith(I, A);
4599           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4600             return ReplaceInstUsesWith(I, A);
4601         }
4602         // Or commutes, try both ways.
4603         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4604             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4605           // Add commutes, try both ways.
4606           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4607             return ReplaceInstUsesWith(I, B);
4608           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4609             return ReplaceInstUsesWith(I, B);
4610         }
4611       }
4612       V1 = 0; V2 = 0; V3 = 0;
4613     }
4614     
4615     // Check to see if we have any common things being and'ed.  If so, find the
4616     // terms for V1 & (V2|V3).
4617     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4618       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4619         V1 = A, V2 = C, V3 = D;
4620       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4621         V1 = A, V2 = B, V3 = C;
4622       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4623         V1 = C, V2 = A, V3 = D;
4624       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4625         V1 = C, V2 = A, V3 = B;
4626       
4627       if (V1) {
4628         Value *Or =
4629           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4630         return BinaryOperator::CreateAnd(V1, Or);
4631       }
4632     }
4633
4634     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4635     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4636       return Match;
4637     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4638       return Match;
4639     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4640       return Match;
4641     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4642       return Match;
4643
4644     // ((A&~B)|(~A&B)) -> A^B
4645     if ((match(C, m_Not(m_Specific(D))) &&
4646          match(B, m_Not(m_Specific(A)))))
4647       return BinaryOperator::CreateXor(A, D);
4648     // ((~B&A)|(~A&B)) -> A^B
4649     if ((match(A, m_Not(m_Specific(D))) &&
4650          match(B, m_Not(m_Specific(C)))))
4651       return BinaryOperator::CreateXor(C, D);
4652     // ((A&~B)|(B&~A)) -> A^B
4653     if ((match(C, m_Not(m_Specific(B))) &&
4654          match(D, m_Not(m_Specific(A)))))
4655       return BinaryOperator::CreateXor(A, B);
4656     // ((~B&A)|(B&~A)) -> A^B
4657     if ((match(A, m_Not(m_Specific(B))) &&
4658          match(D, m_Not(m_Specific(C)))))
4659       return BinaryOperator::CreateXor(C, B);
4660   }
4661   
4662   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4663   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4664     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4665       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4666           SI0->getOperand(1) == SI1->getOperand(1) &&
4667           (SI0->hasOneUse() || SI1->hasOneUse())) {
4668         Instruction *NewOp =
4669         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4670                                                      SI1->getOperand(0),
4671                                                      SI0->getName()), I);
4672         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4673                                       SI1->getOperand(1));
4674       }
4675   }
4676
4677   // ((A|B)&1)|(B&-2) -> (A&1) | B
4678   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4679       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4680     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4681     if (Ret) return Ret;
4682   }
4683   // (B&-2)|((A|B)&1) -> (A&1) | B
4684   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4685       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4686     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4687     if (Ret) return Ret;
4688   }
4689
4690   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4691     if (A == Op1)   // ~A | A == -1
4692       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4693   } else {
4694     A = 0;
4695   }
4696   // Note, A is still live here!
4697   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4698     if (Op0 == B)
4699       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4700
4701     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4702     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4703       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4704                                               I.getName()+".demorgan"), I);
4705       return BinaryOperator::CreateNot(And);
4706     }
4707   }
4708
4709   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4710   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4711     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4712       return R;
4713
4714     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4715       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4716         return Res;
4717   }
4718     
4719   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4720   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4721     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4722       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4723         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4724             !isa<ICmpInst>(Op1C->getOperand(0))) {
4725           const Type *SrcTy = Op0C->getOperand(0)->getType();
4726           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4727               // Only do this if the casts both really cause code to be
4728               // generated.
4729               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4730                                 I.getType(), TD) &&
4731               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4732                                 I.getType(), TD)) {
4733             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4734                                                           Op1C->getOperand(0),
4735                                                           I.getName());
4736             InsertNewInstBefore(NewOp, I);
4737             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4738           }
4739         }
4740       }
4741   }
4742   
4743     
4744   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4745   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4746     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4747       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4748           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4749           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4750         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4751           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4752             // If either of the constants are nans, then the whole thing returns
4753             // true.
4754             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4755               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4756             
4757             // Otherwise, no need to compare the two constants, compare the
4758             // rest.
4759             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4760                                 RHS->getOperand(0));
4761           }
4762       } else {
4763         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4764         FCmpInst::Predicate Op0CC, Op1CC;
4765         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4766             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4767           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4768             // Swap RHS operands to match LHS.
4769             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4770             std::swap(Op1LHS, Op1RHS);
4771           }
4772           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4773             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4774             if (Op0CC == Op1CC)
4775               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4776             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4777                      Op1CC == FCmpInst::FCMP_TRUE)
4778               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4779             else if (Op0CC == FCmpInst::FCMP_FALSE)
4780               return ReplaceInstUsesWith(I, Op1);
4781             else if (Op1CC == FCmpInst::FCMP_FALSE)
4782               return ReplaceInstUsesWith(I, Op0);
4783             bool Op0Ordered;
4784             bool Op1Ordered;
4785             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4786             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4787             if (Op0Ordered == Op1Ordered) {
4788               // If both are ordered or unordered, return a new fcmp with
4789               // or'ed predicates.
4790               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4791                                        Op0LHS, Op0RHS);
4792               if (Instruction *I = dyn_cast<Instruction>(RV))
4793                 return I;
4794               // Otherwise, it's a constant boolean value...
4795               return ReplaceInstUsesWith(I, RV);
4796             }
4797           }
4798         }
4799       }
4800     }
4801   }
4802
4803   return Changed ? &I : 0;
4804 }
4805
4806 namespace {
4807
4808 // XorSelf - Implements: X ^ X --> 0
4809 struct XorSelf {
4810   Value *RHS;
4811   XorSelf(Value *rhs) : RHS(rhs) {}
4812   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4813   Instruction *apply(BinaryOperator &Xor) const {
4814     return &Xor;
4815   }
4816 };
4817
4818 }
4819
4820 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4821   bool Changed = SimplifyCommutative(I);
4822   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4823
4824   if (isa<UndefValue>(Op1)) {
4825     if (isa<UndefValue>(Op0))
4826       // Handle undef ^ undef -> 0 special case. This is a common
4827       // idiom (misuse).
4828       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4829     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4830   }
4831
4832   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4833   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4834     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4835     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4836   }
4837   
4838   // See if we can simplify any instructions used by the instruction whose sole 
4839   // purpose is to compute bits we don't care about.
4840   if (!isa<VectorType>(I.getType())) {
4841     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4842     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4843     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4844                              KnownZero, KnownOne))
4845       return &I;
4846   } else if (isa<ConstantAggregateZero>(Op1)) {
4847     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4848   }
4849
4850   // Is this a ~ operation?
4851   if (Value *NotOp = dyn_castNotVal(&I)) {
4852     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4853     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4854     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4855       if (Op0I->getOpcode() == Instruction::And || 
4856           Op0I->getOpcode() == Instruction::Or) {
4857         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4858         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4859           Instruction *NotY =
4860             BinaryOperator::CreateNot(Op0I->getOperand(1),
4861                                       Op0I->getOperand(1)->getName()+".not");
4862           InsertNewInstBefore(NotY, I);
4863           if (Op0I->getOpcode() == Instruction::And)
4864             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4865           else
4866             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4867         }
4868       }
4869     }
4870   }
4871   
4872   
4873   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4874     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4875       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4876       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4877         return new ICmpInst(ICI->getInversePredicate(),
4878                             ICI->getOperand(0), ICI->getOperand(1));
4879
4880       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4881         return new FCmpInst(FCI->getInversePredicate(),
4882                             FCI->getOperand(0), FCI->getOperand(1));
4883
4884       // xor (or (cmp x,m),(cmp y,n)),true --> and (!cmp x,m),(!cmp y,n)
4885       //
4886       // Proof:
4887       //   Let A = (cmp x,m)
4888       //   Let B = (cmp y,n)
4889       //   Let C = (or A, B)
4890       //   C true implies that either A, B, or both are true.
4891       //
4892       //   (xor C, true) is true only if C is false. We can then apply de
4893       //   Morgan's law. QED.
4894       BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4895       if (Op0I) {
4896         Value *A, *B;
4897         if (match(Op0I, m_Or(m_Value(A), m_Value(B)))) {
4898           ICmpInst *AOp = dyn_cast<ICmpInst>(A);
4899           ICmpInst *BOp = dyn_cast<ICmpInst>(B);
4900
4901           if (AOp && BOp) {
4902             ICmpInst *NewA = new ICmpInst(AOp->getInversePredicate(),
4903                                           AOp->getOperand(0),
4904                                           AOp->getOperand(1));
4905             InsertNewInstBefore(NewA, I);
4906             ICmpInst *NewB = new ICmpInst(BOp->getInversePredicate(),
4907                                           BOp->getOperand(0),
4908                                           BOp->getOperand(1));
4909             InsertNewInstBefore(NewB, I);
4910             return BinaryOperator::CreateAnd(NewA, NewB);
4911           }
4912         }
4913       }
4914     }
4915
4916     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4917     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4918       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4919         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4920           Instruction::CastOps Opcode = Op0C->getOpcode();
4921           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4922             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4923                                              Op0C->getDestTy())) {
4924               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4925                                      CI->getOpcode(), CI->getInversePredicate(),
4926                                      CI->getOperand(0), CI->getOperand(1)), I);
4927               NewCI->takeName(CI);
4928               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4929             }
4930           }
4931         }
4932       }
4933     }
4934
4935     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4936       // ~(c-X) == X-c-1 == X+(-c-1)
4937       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4938         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4939           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4940           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4941                                               ConstantInt::get(I.getType(), 1));
4942           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4943         }
4944           
4945       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4946         if (Op0I->getOpcode() == Instruction::Add) {
4947           // ~(X-c) --> (-c-1)-X
4948           if (RHS->isAllOnesValue()) {
4949             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4950             return BinaryOperator::CreateSub(
4951                            ConstantExpr::getSub(NegOp0CI,
4952                                              ConstantInt::get(I.getType(), 1)),
4953                                           Op0I->getOperand(0));
4954           } else if (RHS->getValue().isSignBit()) {
4955             // (X + C) ^ signbit -> (X + C + signbit)
4956             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4957             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4958
4959           }
4960         } else if (Op0I->getOpcode() == Instruction::Or) {
4961           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4962           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4963             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4964             // Anything in both C1 and C2 is known to be zero, remove it from
4965             // NewRHS.
4966             Constant *CommonBits = And(Op0CI, RHS);
4967             NewRHS = ConstantExpr::getAnd(NewRHS, 
4968                                           ConstantExpr::getNot(CommonBits));
4969             AddToWorkList(Op0I);
4970             I.setOperand(0, Op0I->getOperand(0));
4971             I.setOperand(1, NewRHS);
4972             return &I;
4973           }
4974         }
4975       }
4976     }
4977
4978     // Try to fold constant and into select arguments.
4979     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4980       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4981         return R;
4982     if (isa<PHINode>(Op0))
4983       if (Instruction *NV = FoldOpIntoPhi(I))
4984         return NV;
4985   }
4986
4987   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4988     if (X == Op1)
4989       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4990
4991   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4992     if (X == Op0)
4993       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4994
4995   
4996   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4997   if (Op1I) {
4998     Value *A, *B;
4999     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5000       if (A == Op0) {              // B^(B|A) == (A|B)^B
5001         Op1I->swapOperands();
5002         I.swapOperands();
5003         std::swap(Op0, Op1);
5004       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5005         I.swapOperands();     // Simplified below.
5006         std::swap(Op0, Op1);
5007       }
5008     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5009       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5010     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5011       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5012     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5013       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5014         Op1I->swapOperands();
5015         std::swap(A, B);
5016       }
5017       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5018         I.swapOperands();     // Simplified below.
5019         std::swap(Op0, Op1);
5020       }
5021     }
5022   }
5023   
5024   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5025   if (Op0I) {
5026     Value *A, *B;
5027     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5028       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5029         std::swap(A, B);
5030       if (B == Op1) {                                // (A|B)^B == A & ~B
5031         Instruction *NotB =
5032           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5033         return BinaryOperator::CreateAnd(A, NotB);
5034       }
5035     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5036       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5037     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5038       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5039     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5040       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5041         std::swap(A, B);
5042       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5043           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5044         Instruction *N =
5045           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5046         return BinaryOperator::CreateAnd(N, Op1);
5047       }
5048     }
5049   }
5050   
5051   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5052   if (Op0I && Op1I && Op0I->isShift() && 
5053       Op0I->getOpcode() == Op1I->getOpcode() && 
5054       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5055       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5056     Instruction *NewOp =
5057       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5058                                                     Op1I->getOperand(0),
5059                                                     Op0I->getName()), I);
5060     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5061                                   Op1I->getOperand(1));
5062   }
5063     
5064   if (Op0I && Op1I) {
5065     Value *A, *B, *C, *D;
5066     // (A & B)^(A | B) -> A ^ B
5067     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5068         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5069       if ((A == C && B == D) || (A == D && B == C)) 
5070         return BinaryOperator::CreateXor(A, B);
5071     }
5072     // (A | B)^(A & B) -> A ^ B
5073     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5074         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5075       if ((A == C && B == D) || (A == D && B == C)) 
5076         return BinaryOperator::CreateXor(A, B);
5077     }
5078     
5079     // (A & B)^(C & D)
5080     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5081         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5082         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5083       // (X & Y)^(X & Y) -> (Y^Z) & X
5084       Value *X = 0, *Y = 0, *Z = 0;
5085       if (A == C)
5086         X = A, Y = B, Z = D;
5087       else if (A == D)
5088         X = A, Y = B, Z = C;
5089       else if (B == C)
5090         X = B, Y = A, Z = D;
5091       else if (B == D)
5092         X = B, Y = A, Z = C;
5093       
5094       if (X) {
5095         Instruction *NewOp =
5096         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5097         return BinaryOperator::CreateAnd(NewOp, X);
5098       }
5099     }
5100   }
5101     
5102   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5103   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5104     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5105       return R;
5106
5107   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5108   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5109     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5110       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5111         const Type *SrcTy = Op0C->getOperand(0)->getType();
5112         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5113             // Only do this if the casts both really cause code to be generated.
5114             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5115                               I.getType(), TD) &&
5116             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5117                               I.getType(), TD)) {
5118           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5119                                                          Op1C->getOperand(0),
5120                                                          I.getName());
5121           InsertNewInstBefore(NewOp, I);
5122           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5123         }
5124       }
5125   }
5126
5127   return Changed ? &I : 0;
5128 }
5129
5130 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5131 /// overflowed for this type.
5132 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5133                             ConstantInt *In2, bool IsSigned = false) {
5134   Result = cast<ConstantInt>(Add(In1, In2));
5135
5136   if (IsSigned)
5137     if (In2->getValue().isNegative())
5138       return Result->getValue().sgt(In1->getValue());
5139     else
5140       return Result->getValue().slt(In1->getValue());
5141   else
5142     return Result->getValue().ult(In1->getValue());
5143 }
5144
5145 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5146 /// overflowed for this type.
5147 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5148                             ConstantInt *In2, bool IsSigned = false) {
5149   Result = cast<ConstantInt>(Subtract(In1, In2));
5150
5151   if (IsSigned)
5152     if (In2->getValue().isNegative())
5153       return Result->getValue().slt(In1->getValue());
5154     else
5155       return Result->getValue().sgt(In1->getValue());
5156   else
5157     return Result->getValue().ugt(In1->getValue());
5158 }
5159
5160 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5161 /// code necessary to compute the offset from the base pointer (without adding
5162 /// in the base pointer).  Return the result as a signed integer of intptr size.
5163 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5164   TargetData &TD = IC.getTargetData();
5165   gep_type_iterator GTI = gep_type_begin(GEP);
5166   const Type *IntPtrTy = TD.getIntPtrType();
5167   Value *Result = Constant::getNullValue(IntPtrTy);
5168
5169   // Build a mask for high order bits.
5170   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5171   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5172
5173   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5174        ++i, ++GTI) {
5175     Value *Op = *i;
5176     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5177     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5178       if (OpC->isZero()) continue;
5179       
5180       // Handle a struct index, which adds its field offset to the pointer.
5181       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5182         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5183         
5184         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5185           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5186         else
5187           Result = IC.InsertNewInstBefore(
5188                    BinaryOperator::CreateAdd(Result,
5189                                              ConstantInt::get(IntPtrTy, Size),
5190                                              GEP->getName()+".offs"), I);
5191         continue;
5192       }
5193       
5194       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5195       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5196       Scale = ConstantExpr::getMul(OC, Scale);
5197       if (Constant *RC = dyn_cast<Constant>(Result))
5198         Result = ConstantExpr::getAdd(RC, Scale);
5199       else {
5200         // Emit an add instruction.
5201         Result = IC.InsertNewInstBefore(
5202            BinaryOperator::CreateAdd(Result, Scale,
5203                                      GEP->getName()+".offs"), I);
5204       }
5205       continue;
5206     }
5207     // Convert to correct type.
5208     if (Op->getType() != IntPtrTy) {
5209       if (Constant *OpC = dyn_cast<Constant>(Op))
5210         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5211       else
5212         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5213                                                  Op->getName()+".c"), I);
5214     }
5215     if (Size != 1) {
5216       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5217       if (Constant *OpC = dyn_cast<Constant>(Op))
5218         Op = ConstantExpr::getMul(OpC, Scale);
5219       else    // We'll let instcombine(mul) convert this to a shl if possible.
5220         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5221                                                   GEP->getName()+".idx"), I);
5222     }
5223
5224     // Emit an add instruction.
5225     if (isa<Constant>(Op) && isa<Constant>(Result))
5226       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5227                                     cast<Constant>(Result));
5228     else
5229       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5230                                                   GEP->getName()+".offs"), I);
5231   }
5232   return Result;
5233 }
5234
5235
5236 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5237 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5238 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5239 /// complex, and scales are involved.  The above expression would also be legal
5240 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5241 /// later form is less amenable to optimization though, and we are allowed to
5242 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5243 ///
5244 /// If we can't emit an optimized form for this expression, this returns null.
5245 /// 
5246 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5247                                           InstCombiner &IC) {
5248   TargetData &TD = IC.getTargetData();
5249   gep_type_iterator GTI = gep_type_begin(GEP);
5250
5251   // Check to see if this gep only has a single variable index.  If so, and if
5252   // any constant indices are a multiple of its scale, then we can compute this
5253   // in terms of the scale of the variable index.  For example, if the GEP
5254   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5255   // because the expression will cross zero at the same point.
5256   unsigned i, e = GEP->getNumOperands();
5257   int64_t Offset = 0;
5258   for (i = 1; i != e; ++i, ++GTI) {
5259     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5260       // Compute the aggregate offset of constant indices.
5261       if (CI->isZero()) continue;
5262
5263       // Handle a struct index, which adds its field offset to the pointer.
5264       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5265         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5266       } else {
5267         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5268         Offset += Size*CI->getSExtValue();
5269       }
5270     } else {
5271       // Found our variable index.
5272       break;
5273     }
5274   }
5275   
5276   // If there are no variable indices, we must have a constant offset, just
5277   // evaluate it the general way.
5278   if (i == e) return 0;
5279   
5280   Value *VariableIdx = GEP->getOperand(i);
5281   // Determine the scale factor of the variable element.  For example, this is
5282   // 4 if the variable index is into an array of i32.
5283   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5284   
5285   // Verify that there are no other variable indices.  If so, emit the hard way.
5286   for (++i, ++GTI; i != e; ++i, ++GTI) {
5287     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5288     if (!CI) return 0;
5289    
5290     // Compute the aggregate offset of constant indices.
5291     if (CI->isZero()) continue;
5292     
5293     // Handle a struct index, which adds its field offset to the pointer.
5294     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5295       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5296     } else {
5297       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5298       Offset += Size*CI->getSExtValue();
5299     }
5300   }
5301   
5302   // Okay, we know we have a single variable index, which must be a
5303   // pointer/array/vector index.  If there is no offset, life is simple, return
5304   // the index.
5305   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5306   if (Offset == 0) {
5307     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5308     // we don't need to bother extending: the extension won't affect where the
5309     // computation crosses zero.
5310     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5311       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5312                                   VariableIdx->getNameStart(), &I);
5313     return VariableIdx;
5314   }
5315   
5316   // Otherwise, there is an index.  The computation we will do will be modulo
5317   // the pointer size, so get it.
5318   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5319   
5320   Offset &= PtrSizeMask;
5321   VariableScale &= PtrSizeMask;
5322
5323   // To do this transformation, any constant index must be a multiple of the
5324   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5325   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5326   // multiple of the variable scale.
5327   int64_t NewOffs = Offset / (int64_t)VariableScale;
5328   if (Offset != NewOffs*(int64_t)VariableScale)
5329     return 0;
5330
5331   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5332   const Type *IntPtrTy = TD.getIntPtrType();
5333   if (VariableIdx->getType() != IntPtrTy)
5334     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5335                                               true /*SExt*/, 
5336                                               VariableIdx->getNameStart(), &I);
5337   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5338   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5339 }
5340
5341
5342 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5343 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5344 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5345                                        ICmpInst::Predicate Cond,
5346                                        Instruction &I) {
5347   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5348
5349   // Look through bitcasts.
5350   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5351     RHS = BCI->getOperand(0);
5352
5353   Value *PtrBase = GEPLHS->getOperand(0);
5354   if (PtrBase == RHS) {
5355     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5356     // This transformation (ignoring the base and scales) is valid because we
5357     // know pointers can't overflow.  See if we can output an optimized form.
5358     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5359     
5360     // If not, synthesize the offset the hard way.
5361     if (Offset == 0)
5362       Offset = EmitGEPOffset(GEPLHS, I, *this);
5363     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5364                         Constant::getNullValue(Offset->getType()));
5365   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5366     // If the base pointers are different, but the indices are the same, just
5367     // compare the base pointer.
5368     if (PtrBase != GEPRHS->getOperand(0)) {
5369       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5370       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5371                         GEPRHS->getOperand(0)->getType();
5372       if (IndicesTheSame)
5373         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5374           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5375             IndicesTheSame = false;
5376             break;
5377           }
5378
5379       // If all indices are the same, just compare the base pointers.
5380       if (IndicesTheSame)
5381         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5382                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5383
5384       // Otherwise, the base pointers are different and the indices are
5385       // different, bail out.
5386       return 0;
5387     }
5388
5389     // If one of the GEPs has all zero indices, recurse.
5390     bool AllZeros = true;
5391     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5392       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5393           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5394         AllZeros = false;
5395         break;
5396       }
5397     if (AllZeros)
5398       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5399                           ICmpInst::getSwappedPredicate(Cond), I);
5400
5401     // If the other GEP has all zero indices, recurse.
5402     AllZeros = true;
5403     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5404       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5405           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5406         AllZeros = false;
5407         break;
5408       }
5409     if (AllZeros)
5410       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5411
5412     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5413       // If the GEPs only differ by one index, compare it.
5414       unsigned NumDifferences = 0;  // Keep track of # differences.
5415       unsigned DiffOperand = 0;     // The operand that differs.
5416       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5417         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5418           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5419                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5420             // Irreconcilable differences.
5421             NumDifferences = 2;
5422             break;
5423           } else {
5424             if (NumDifferences++) break;
5425             DiffOperand = i;
5426           }
5427         }
5428
5429       if (NumDifferences == 0)   // SAME GEP?
5430         return ReplaceInstUsesWith(I, // No comparison is needed here.
5431                                    ConstantInt::get(Type::Int1Ty,
5432                                              ICmpInst::isTrueWhenEqual(Cond)));
5433
5434       else if (NumDifferences == 1) {
5435         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5436         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5437         // Make sure we do a signed comparison here.
5438         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5439       }
5440     }
5441
5442     // Only lower this if the icmp is the only user of the GEP or if we expect
5443     // the result to fold to a constant!
5444     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5445         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5446       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5447       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5448       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5449       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5450     }
5451   }
5452   return 0;
5453 }
5454
5455 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5456 ///
5457 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5458                                                 Instruction *LHSI,
5459                                                 Constant *RHSC) {
5460   if (!isa<ConstantFP>(RHSC)) return 0;
5461   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5462   
5463   // Get the width of the mantissa.  We don't want to hack on conversions that
5464   // might lose information from the integer, e.g. "i64 -> float"
5465   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5466   if (MantissaWidth == -1) return 0;  // Unknown.
5467   
5468   // Check to see that the input is converted from an integer type that is small
5469   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5470   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5471   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5472   
5473   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5474   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5475   if (LHSUnsigned)
5476     ++InputSize;
5477   
5478   // If the conversion would lose info, don't hack on this.
5479   if ((int)InputSize > MantissaWidth)
5480     return 0;
5481   
5482   // Otherwise, we can potentially simplify the comparison.  We know that it
5483   // will always come through as an integer value and we know the constant is
5484   // not a NAN (it would have been previously simplified).
5485   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5486   
5487   ICmpInst::Predicate Pred;
5488   switch (I.getPredicate()) {
5489   default: assert(0 && "Unexpected predicate!");
5490   case FCmpInst::FCMP_UEQ:
5491   case FCmpInst::FCMP_OEQ:
5492     Pred = ICmpInst::ICMP_EQ;
5493     break;
5494   case FCmpInst::FCMP_UGT:
5495   case FCmpInst::FCMP_OGT:
5496     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5497     break;
5498   case FCmpInst::FCMP_UGE:
5499   case FCmpInst::FCMP_OGE:
5500     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5501     break;
5502   case FCmpInst::FCMP_ULT:
5503   case FCmpInst::FCMP_OLT:
5504     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5505     break;
5506   case FCmpInst::FCMP_ULE:
5507   case FCmpInst::FCMP_OLE:
5508     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5509     break;
5510   case FCmpInst::FCMP_UNE:
5511   case FCmpInst::FCMP_ONE:
5512     Pred = ICmpInst::ICMP_NE;
5513     break;
5514   case FCmpInst::FCMP_ORD:
5515     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5516   case FCmpInst::FCMP_UNO:
5517     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5518   }
5519   
5520   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5521   
5522   // Now we know that the APFloat is a normal number, zero or inf.
5523   
5524   // See if the FP constant is too large for the integer.  For example,
5525   // comparing an i8 to 300.0.
5526   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5527   
5528   if (!LHSUnsigned) {
5529     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5530     // and large values.
5531     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5532     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5533                           APFloat::rmNearestTiesToEven);
5534     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5535       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5536           Pred == ICmpInst::ICMP_SLE)
5537         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5538       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5539     }
5540   } else {
5541     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5542     // +INF and large values.
5543     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5544     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5545                           APFloat::rmNearestTiesToEven);
5546     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5547       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5548           Pred == ICmpInst::ICMP_ULE)
5549         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5550       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5551     }
5552   }
5553   
5554   if (!LHSUnsigned) {
5555     // See if the RHS value is < SignedMin.
5556     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5557     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5558                           APFloat::rmNearestTiesToEven);
5559     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5560       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5561           Pred == ICmpInst::ICMP_SGE)
5562         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5563       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5564     }
5565   }
5566
5567   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5568   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5569   // casting the FP value to the integer value and back, checking for equality.
5570   // Don't do this for zero, because -0.0 is not fractional.
5571   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5572   if (!RHS.isZero() &&
5573       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5574     // If we had a comparison against a fractional value, we have to adjust the
5575     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5576     // at this point.
5577     switch (Pred) {
5578     default: assert(0 && "Unexpected integer comparison!");
5579     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5580       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5581     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5582       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5583     case ICmpInst::ICMP_ULE:
5584       // (float)int <= 4.4   --> int <= 4
5585       // (float)int <= -4.4  --> false
5586       if (RHS.isNegative())
5587         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5588       break;
5589     case ICmpInst::ICMP_SLE:
5590       // (float)int <= 4.4   --> int <= 4
5591       // (float)int <= -4.4  --> int < -4
5592       if (RHS.isNegative())
5593         Pred = ICmpInst::ICMP_SLT;
5594       break;
5595     case ICmpInst::ICMP_ULT:
5596       // (float)int < -4.4   --> false
5597       // (float)int < 4.4    --> int <= 4
5598       if (RHS.isNegative())
5599         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5600       Pred = ICmpInst::ICMP_ULE;
5601       break;
5602     case ICmpInst::ICMP_SLT:
5603       // (float)int < -4.4   --> int < -4
5604       // (float)int < 4.4    --> int <= 4
5605       if (!RHS.isNegative())
5606         Pred = ICmpInst::ICMP_SLE;
5607       break;
5608     case ICmpInst::ICMP_UGT:
5609       // (float)int > 4.4    --> int > 4
5610       // (float)int > -4.4   --> true
5611       if (RHS.isNegative())
5612         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5613       break;
5614     case ICmpInst::ICMP_SGT:
5615       // (float)int > 4.4    --> int > 4
5616       // (float)int > -4.4   --> int >= -4
5617       if (RHS.isNegative())
5618         Pred = ICmpInst::ICMP_SGE;
5619       break;
5620     case ICmpInst::ICMP_UGE:
5621       // (float)int >= -4.4   --> true
5622       // (float)int >= 4.4    --> int > 4
5623       if (!RHS.isNegative())
5624         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5625       Pred = ICmpInst::ICMP_UGT;
5626       break;
5627     case ICmpInst::ICMP_SGE:
5628       // (float)int >= -4.4   --> int >= -4
5629       // (float)int >= 4.4    --> int > 4
5630       if (!RHS.isNegative())
5631         Pred = ICmpInst::ICMP_SGT;
5632       break;
5633     }
5634   }
5635
5636   // Lower this FP comparison into an appropriate integer version of the
5637   // comparison.
5638   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5639 }
5640
5641 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5642   bool Changed = SimplifyCompare(I);
5643   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5644
5645   // Fold trivial predicates.
5646   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5647     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5648   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5649     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5650   
5651   // Simplify 'fcmp pred X, X'
5652   if (Op0 == Op1) {
5653     switch (I.getPredicate()) {
5654     default: assert(0 && "Unknown predicate!");
5655     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5656     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5657     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5658       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5659     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5660     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5661     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5662       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5663       
5664     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5665     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5666     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5667     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5668       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5669       I.setPredicate(FCmpInst::FCMP_UNO);
5670       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5671       return &I;
5672       
5673     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5674     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5675     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5676     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5677       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5678       I.setPredicate(FCmpInst::FCMP_ORD);
5679       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5680       return &I;
5681     }
5682   }
5683     
5684   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5685     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5686
5687   // Handle fcmp with constant RHS
5688   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5689     // If the constant is a nan, see if we can fold the comparison based on it.
5690     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5691       if (CFP->getValueAPF().isNaN()) {
5692         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5693           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5694         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5695                "Comparison must be either ordered or unordered!");
5696         // True if unordered.
5697         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5698       }
5699     }
5700     
5701     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5702       switch (LHSI->getOpcode()) {
5703       case Instruction::PHI:
5704         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5705         // block.  If in the same block, we're encouraging jump threading.  If
5706         // not, we are just pessimizing the code by making an i1 phi.
5707         if (LHSI->getParent() == I.getParent())
5708           if (Instruction *NV = FoldOpIntoPhi(I))
5709             return NV;
5710         break;
5711       case Instruction::SIToFP:
5712       case Instruction::UIToFP:
5713         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5714           return NV;
5715         break;
5716       case Instruction::Select:
5717         // If either operand of the select is a constant, we can fold the
5718         // comparison into the select arms, which will cause one to be
5719         // constant folded and the select turned into a bitwise or.
5720         Value *Op1 = 0, *Op2 = 0;
5721         if (LHSI->hasOneUse()) {
5722           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5723             // Fold the known value into the constant operand.
5724             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5725             // Insert a new FCmp of the other select operand.
5726             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5727                                                       LHSI->getOperand(2), RHSC,
5728                                                       I.getName()), I);
5729           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5730             // Fold the known value into the constant operand.
5731             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5732             // Insert a new FCmp of the other select operand.
5733             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5734                                                       LHSI->getOperand(1), RHSC,
5735                                                       I.getName()), I);
5736           }
5737         }
5738
5739         if (Op1)
5740           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5741         break;
5742       }
5743   }
5744
5745   return Changed ? &I : 0;
5746 }
5747
5748 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5749   bool Changed = SimplifyCompare(I);
5750   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5751   const Type *Ty = Op0->getType();
5752
5753   // icmp X, X
5754   if (Op0 == Op1)
5755     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5756                                                    I.isTrueWhenEqual()));
5757
5758   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5759     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5760   
5761   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5762   // addresses never equal each other!  We already know that Op0 != Op1.
5763   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5764        isa<ConstantPointerNull>(Op0)) &&
5765       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5766        isa<ConstantPointerNull>(Op1)))
5767     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5768                                                    !I.isTrueWhenEqual()));
5769
5770   // icmp's with boolean values can always be turned into bitwise operations
5771   if (Ty == Type::Int1Ty) {
5772     switch (I.getPredicate()) {
5773     default: assert(0 && "Invalid icmp instruction!");
5774     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5775       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5776       InsertNewInstBefore(Xor, I);
5777       return BinaryOperator::CreateNot(Xor);
5778     }
5779     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5780       return BinaryOperator::CreateXor(Op0, Op1);
5781
5782     case ICmpInst::ICMP_UGT:
5783       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5784       // FALL THROUGH
5785     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5786       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5787       InsertNewInstBefore(Not, I);
5788       return BinaryOperator::CreateAnd(Not, Op1);
5789     }
5790     case ICmpInst::ICMP_SGT:
5791       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5792       // FALL THROUGH
5793     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5794       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5795       InsertNewInstBefore(Not, I);
5796       return BinaryOperator::CreateAnd(Not, Op0);
5797     }
5798     case ICmpInst::ICMP_UGE:
5799       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5800       // FALL THROUGH
5801     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5802       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5803       InsertNewInstBefore(Not, I);
5804       return BinaryOperator::CreateOr(Not, Op1);
5805     }
5806     case ICmpInst::ICMP_SGE:
5807       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5808       // FALL THROUGH
5809     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5810       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5811       InsertNewInstBefore(Not, I);
5812       return BinaryOperator::CreateOr(Not, Op0);
5813     }
5814     }
5815   }
5816
5817   // See if we are doing a comparison with a constant.
5818   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5819     Value *A, *B;
5820     
5821     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5822     if (I.isEquality() && CI->isNullValue() &&
5823         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5824       // (icmp cond A B) if cond is equality
5825       return new ICmpInst(I.getPredicate(), A, B);
5826     }
5827     
5828     // If we have an icmp le or icmp ge instruction, turn it into the
5829     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5830     // them being folded in the code below.
5831     switch (I.getPredicate()) {
5832     default: break;
5833     case ICmpInst::ICMP_ULE:
5834       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5835         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5836       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5837     case ICmpInst::ICMP_SLE:
5838       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5839         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5840       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5841     case ICmpInst::ICMP_UGE:
5842       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5843         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5844       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5845     case ICmpInst::ICMP_SGE:
5846       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5847         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5848       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5849     }
5850     
5851     // See if we can fold the comparison based on range information we can get
5852     // by checking whether bits are known to be zero or one in the input.
5853     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5854     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5855     
5856     // If this comparison is a normal comparison, it demands all
5857     // bits, if it is a sign bit comparison, it only demands the sign bit.
5858     bool UnusedBit;
5859     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5860     
5861     if (SimplifyDemandedBits(Op0, 
5862                              isSignBit ? APInt::getSignBit(BitWidth)
5863                                        : APInt::getAllOnesValue(BitWidth),
5864                              KnownZero, KnownOne, 0))
5865       return &I;
5866         
5867     // Given the known and unknown bits, compute a range that the LHS could be
5868     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5869     // EQ and NE we use unsigned values.
5870     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5871     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5872       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5873     else
5874       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5875     
5876     // If Min and Max are known to be the same, then SimplifyDemandedBits
5877     // figured out that the LHS is a constant.  Just constant fold this now so
5878     // that code below can assume that Min != Max.
5879     if (Min == Max)
5880       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5881                                                           ConstantInt::get(Min),
5882                                                           CI));
5883     
5884     // Based on the range information we know about the LHS, see if we can
5885     // simplify this comparison.  For example, (x&4) < 8  is always true.
5886     const APInt &RHSVal = CI->getValue();
5887     switch (I.getPredicate()) {  // LE/GE have been folded already.
5888     default: assert(0 && "Unknown icmp opcode!");
5889     case ICmpInst::ICMP_EQ:
5890       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5891         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5892       break;
5893     case ICmpInst::ICMP_NE:
5894       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5895         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5896       break;
5897     case ICmpInst::ICMP_ULT:
5898       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5899         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5900       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5901         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5902       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5903         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5904       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5905         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5906         
5907       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5908       if (CI->isMinValue(true))
5909         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5910                             ConstantInt::getAllOnesValue(Op0->getType()));
5911       break;
5912     case ICmpInst::ICMP_UGT:
5913       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5914         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5915       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5916         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5917         
5918       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5919         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5920       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5921         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5922       
5923       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5924       if (CI->isMaxValue(true))
5925         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5926                             ConstantInt::getNullValue(Op0->getType()));
5927       break;
5928     case ICmpInst::ICMP_SLT:
5929       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5930         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5931       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5932         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5933       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5934         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5935       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5936         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5937       break;
5938     case ICmpInst::ICMP_SGT: 
5939       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5940         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5941       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5942         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5943         
5944       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5945         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5946       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5947         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5948       break;
5949     }
5950   }
5951
5952   // Test if the ICmpInst instruction is used exclusively by a select as
5953   // part of a minimum or maximum operation. If so, refrain from doing
5954   // any other folding. This helps out other analyses which understand
5955   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5956   // and CodeGen. And in this case, at least one of the comparison
5957   // operands has at least one user besides the compare (the select),
5958   // which would often largely negate the benefit of folding anyway.
5959   if (I.hasOneUse())
5960     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5961       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5962           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5963         return 0;
5964
5965   // See if we are doing a comparison between a constant and an instruction that
5966   // can be folded into the comparison.
5967   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5968     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5969     // instruction, see if that instruction also has constants so that the 
5970     // instruction can be folded into the icmp 
5971     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5972       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5973         return Res;
5974   }
5975
5976   // Handle icmp with constant (but not simple integer constant) RHS
5977   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5978     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5979       switch (LHSI->getOpcode()) {
5980       case Instruction::GetElementPtr:
5981         if (RHSC->isNullValue()) {
5982           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5983           bool isAllZeros = true;
5984           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5985             if (!isa<Constant>(LHSI->getOperand(i)) ||
5986                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5987               isAllZeros = false;
5988               break;
5989             }
5990           if (isAllZeros)
5991             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5992                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5993         }
5994         break;
5995
5996       case Instruction::PHI:
5997         // Only fold icmp into the PHI if the phi and fcmp are in the same
5998         // block.  If in the same block, we're encouraging jump threading.  If
5999         // not, we are just pessimizing the code by making an i1 phi.
6000         if (LHSI->getParent() == I.getParent())
6001           if (Instruction *NV = FoldOpIntoPhi(I))
6002             return NV;
6003         break;
6004       case Instruction::Select: {
6005         // If either operand of the select is a constant, we can fold the
6006         // comparison into the select arms, which will cause one to be
6007         // constant folded and the select turned into a bitwise or.
6008         Value *Op1 = 0, *Op2 = 0;
6009         if (LHSI->hasOneUse()) {
6010           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6011             // Fold the known value into the constant operand.
6012             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6013             // Insert a new ICmp of the other select operand.
6014             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6015                                                    LHSI->getOperand(2), RHSC,
6016                                                    I.getName()), I);
6017           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6018             // Fold the known value into the constant operand.
6019             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6020             // Insert a new ICmp of the other select operand.
6021             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6022                                                    LHSI->getOperand(1), RHSC,
6023                                                    I.getName()), I);
6024           }
6025         }
6026
6027         if (Op1)
6028           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6029         break;
6030       }
6031       case Instruction::Malloc:
6032         // If we have (malloc != null), and if the malloc has a single use, we
6033         // can assume it is successful and remove the malloc.
6034         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6035           AddToWorkList(LHSI);
6036           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6037                                                          !I.isTrueWhenEqual()));
6038         }
6039         break;
6040       }
6041   }
6042
6043   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6044   if (User *GEP = dyn_castGetElementPtr(Op0))
6045     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6046       return NI;
6047   if (User *GEP = dyn_castGetElementPtr(Op1))
6048     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6049                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6050       return NI;
6051
6052   // Test to see if the operands of the icmp are casted versions of other
6053   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6054   // now.
6055   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6056     if (isa<PointerType>(Op0->getType()) && 
6057         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6058       // We keep moving the cast from the left operand over to the right
6059       // operand, where it can often be eliminated completely.
6060       Op0 = CI->getOperand(0);
6061
6062       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6063       // so eliminate it as well.
6064       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6065         Op1 = CI2->getOperand(0);
6066
6067       // If Op1 is a constant, we can fold the cast into the constant.
6068       if (Op0->getType() != Op1->getType()) {
6069         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6070           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6071         } else {
6072           // Otherwise, cast the RHS right before the icmp
6073           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6074         }
6075       }
6076       return new ICmpInst(I.getPredicate(), Op0, Op1);
6077     }
6078   }
6079   
6080   if (isa<CastInst>(Op0)) {
6081     // Handle the special case of: icmp (cast bool to X), <cst>
6082     // This comes up when you have code like
6083     //   int X = A < B;
6084     //   if (X) ...
6085     // For generality, we handle any zero-extension of any operand comparison
6086     // with a constant or another cast from the same type.
6087     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6088       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6089         return R;
6090   }
6091   
6092   // See if it's the same type of instruction on the left and right.
6093   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6094     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6095       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6096           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6097           I.isEquality()) {
6098         switch (Op0I->getOpcode()) {
6099         default: break;
6100         case Instruction::Add:
6101         case Instruction::Sub:
6102         case Instruction::Xor:
6103           // a+x icmp eq/ne b+x --> a icmp b
6104           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6105                               Op1I->getOperand(0));
6106           break;
6107         case Instruction::Mul:
6108           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6109             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6110             // Mask = -1 >> count-trailing-zeros(Cst).
6111             if (!CI->isZero() && !CI->isOne()) {
6112               const APInt &AP = CI->getValue();
6113               ConstantInt *Mask = ConstantInt::get(
6114                                       APInt::getLowBitsSet(AP.getBitWidth(),
6115                                                            AP.getBitWidth() -
6116                                                       AP.countTrailingZeros()));
6117               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6118                                                             Mask);
6119               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6120                                                             Mask);
6121               InsertNewInstBefore(And1, I);
6122               InsertNewInstBefore(And2, I);
6123               return new ICmpInst(I.getPredicate(), And1, And2);
6124             }
6125           }
6126           break;
6127         }
6128       }
6129     }
6130   }
6131   
6132   // ~x < ~y --> y < x
6133   { Value *A, *B;
6134     if (match(Op0, m_Not(m_Value(A))) &&
6135         match(Op1, m_Not(m_Value(B))))
6136       return new ICmpInst(I.getPredicate(), B, A);
6137   }
6138   
6139   if (I.isEquality()) {
6140     Value *A, *B, *C, *D;
6141     
6142     // -x == -y --> x == y
6143     if (match(Op0, m_Neg(m_Value(A))) &&
6144         match(Op1, m_Neg(m_Value(B))))
6145       return new ICmpInst(I.getPredicate(), A, B);
6146     
6147     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6148       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6149         Value *OtherVal = A == Op1 ? B : A;
6150         return new ICmpInst(I.getPredicate(), OtherVal,
6151                             Constant::getNullValue(A->getType()));
6152       }
6153
6154       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6155         // A^c1 == C^c2 --> A == C^(c1^c2)
6156         ConstantInt *C1, *C2;
6157         if (match(B, m_ConstantInt(C1)) &&
6158             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6159           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6160           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6161           return new ICmpInst(I.getPredicate(), A,
6162                               InsertNewInstBefore(Xor, I));
6163         }
6164         
6165         // A^B == A^D -> B == D
6166         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6167         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6168         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6169         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6170       }
6171     }
6172     
6173     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6174         (A == Op0 || B == Op0)) {
6175       // A == (A^B)  ->  B == 0
6176       Value *OtherVal = A == Op0 ? B : A;
6177       return new ICmpInst(I.getPredicate(), OtherVal,
6178                           Constant::getNullValue(A->getType()));
6179     }
6180
6181     // (A-B) == A  ->  B == 0
6182     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6183       return new ICmpInst(I.getPredicate(), B, 
6184                           Constant::getNullValue(B->getType()));
6185
6186     // A == (A-B)  ->  B == 0
6187     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6188       return new ICmpInst(I.getPredicate(), B,
6189                           Constant::getNullValue(B->getType()));
6190     
6191     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6192     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6193         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6194         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6195       Value *X = 0, *Y = 0, *Z = 0;
6196       
6197       if (A == C) {
6198         X = B; Y = D; Z = A;
6199       } else if (A == D) {
6200         X = B; Y = C; Z = A;
6201       } else if (B == C) {
6202         X = A; Y = D; Z = B;
6203       } else if (B == D) {
6204         X = A; Y = C; Z = B;
6205       }
6206       
6207       if (X) {   // Build (X^Y) & Z
6208         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6209         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6210         I.setOperand(0, Op1);
6211         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6212         return &I;
6213       }
6214     }
6215   }
6216   return Changed ? &I : 0;
6217 }
6218
6219
6220 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6221 /// and CmpRHS are both known to be integer constants.
6222 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6223                                           ConstantInt *DivRHS) {
6224   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6225   const APInt &CmpRHSV = CmpRHS->getValue();
6226   
6227   // FIXME: If the operand types don't match the type of the divide 
6228   // then don't attempt this transform. The code below doesn't have the
6229   // logic to deal with a signed divide and an unsigned compare (and
6230   // vice versa). This is because (x /s C1) <s C2  produces different 
6231   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6232   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6233   // work. :(  The if statement below tests that condition and bails 
6234   // if it finds it. 
6235   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6236   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6237     return 0;
6238   if (DivRHS->isZero())
6239     return 0; // The ProdOV computation fails on divide by zero.
6240   if (DivIsSigned && DivRHS->isAllOnesValue())
6241     return 0; // The overflow computation also screws up here
6242   if (DivRHS->isOne())
6243     return 0; // Not worth bothering, and eliminates some funny cases
6244               // with INT_MIN.
6245
6246   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6247   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6248   // C2 (CI). By solving for X we can turn this into a range check 
6249   // instead of computing a divide. 
6250   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6251
6252   // Determine if the product overflows by seeing if the product is
6253   // not equal to the divide. Make sure we do the same kind of divide
6254   // as in the LHS instruction that we're folding. 
6255   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6256                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6257
6258   // Get the ICmp opcode
6259   ICmpInst::Predicate Pred = ICI.getPredicate();
6260
6261   // Figure out the interval that is being checked.  For example, a comparison
6262   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6263   // Compute this interval based on the constants involved and the signedness of
6264   // the compare/divide.  This computes a half-open interval, keeping track of
6265   // whether either value in the interval overflows.  After analysis each
6266   // overflow variable is set to 0 if it's corresponding bound variable is valid
6267   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6268   int LoOverflow = 0, HiOverflow = 0;
6269   ConstantInt *LoBound = 0, *HiBound = 0;
6270   
6271   if (!DivIsSigned) {  // udiv
6272     // e.g. X/5 op 3  --> [15, 20)
6273     LoBound = Prod;
6274     HiOverflow = LoOverflow = ProdOV;
6275     if (!HiOverflow)
6276       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6277   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6278     if (CmpRHSV == 0) {       // (X / pos) op 0
6279       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6280       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6281       HiBound = DivRHS;
6282     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6283       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6284       HiOverflow = LoOverflow = ProdOV;
6285       if (!HiOverflow)
6286         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6287     } else {                       // (X / pos) op neg
6288       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6289       HiBound = AddOne(Prod);
6290       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6291       if (!LoOverflow) {
6292         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6293         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6294                                      true) ? -1 : 0;
6295        }
6296     }
6297   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6298     if (CmpRHSV == 0) {       // (X / neg) op 0
6299       // e.g. X/-5 op 0  --> [-4, 5)
6300       LoBound = AddOne(DivRHS);
6301       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6302       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6303         HiOverflow = 1;            // [INTMIN+1, overflow)
6304         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6305       }
6306     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6307       // e.g. X/-5 op 3  --> [-19, -14)
6308       HiBound = AddOne(Prod);
6309       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6310       if (!LoOverflow)
6311         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6312     } else {                       // (X / neg) op neg
6313       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6314       LoOverflow = HiOverflow = ProdOV;
6315       if (!HiOverflow)
6316         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6317     }
6318     
6319     // Dividing by a negative swaps the condition.  LT <-> GT
6320     Pred = ICmpInst::getSwappedPredicate(Pred);
6321   }
6322
6323   Value *X = DivI->getOperand(0);
6324   switch (Pred) {
6325   default: assert(0 && "Unhandled icmp opcode!");
6326   case ICmpInst::ICMP_EQ:
6327     if (LoOverflow && HiOverflow)
6328       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6329     else if (HiOverflow)
6330       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6331                           ICmpInst::ICMP_UGE, X, LoBound);
6332     else if (LoOverflow)
6333       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6334                           ICmpInst::ICMP_ULT, X, HiBound);
6335     else
6336       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6337   case ICmpInst::ICMP_NE:
6338     if (LoOverflow && HiOverflow)
6339       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6340     else if (HiOverflow)
6341       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6342                           ICmpInst::ICMP_ULT, X, LoBound);
6343     else if (LoOverflow)
6344       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6345                           ICmpInst::ICMP_UGE, X, HiBound);
6346     else
6347       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6348   case ICmpInst::ICMP_ULT:
6349   case ICmpInst::ICMP_SLT:
6350     if (LoOverflow == +1)   // Low bound is greater than input range.
6351       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6352     if (LoOverflow == -1)   // Low bound is less than input range.
6353       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6354     return new ICmpInst(Pred, X, LoBound);
6355   case ICmpInst::ICMP_UGT:
6356   case ICmpInst::ICMP_SGT:
6357     if (HiOverflow == +1)       // High bound greater than input range.
6358       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6359     else if (HiOverflow == -1)  // High bound less than input range.
6360       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6361     if (Pred == ICmpInst::ICMP_UGT)
6362       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6363     else
6364       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6365   }
6366 }
6367
6368
6369 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6370 ///
6371 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6372                                                           Instruction *LHSI,
6373                                                           ConstantInt *RHS) {
6374   const APInt &RHSV = RHS->getValue();
6375   
6376   switch (LHSI->getOpcode()) {
6377   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6378     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6379       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6380       // fold the xor.
6381       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6382           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6383         Value *CompareVal = LHSI->getOperand(0);
6384         
6385         // If the sign bit of the XorCST is not set, there is no change to
6386         // the operation, just stop using the Xor.
6387         if (!XorCST->getValue().isNegative()) {
6388           ICI.setOperand(0, CompareVal);
6389           AddToWorkList(LHSI);
6390           return &ICI;
6391         }
6392         
6393         // Was the old condition true if the operand is positive?
6394         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6395         
6396         // If so, the new one isn't.
6397         isTrueIfPositive ^= true;
6398         
6399         if (isTrueIfPositive)
6400           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6401         else
6402           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6403       }
6404     }
6405     break;
6406   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6407     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6408         LHSI->getOperand(0)->hasOneUse()) {
6409       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6410       
6411       // If the LHS is an AND of a truncating cast, we can widen the
6412       // and/compare to be the input width without changing the value
6413       // produced, eliminating a cast.
6414       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6415         // We can do this transformation if either the AND constant does not
6416         // have its sign bit set or if it is an equality comparison. 
6417         // Extending a relational comparison when we're checking the sign
6418         // bit would not work.
6419         if (Cast->hasOneUse() &&
6420             (ICI.isEquality() ||
6421              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6422           uint32_t BitWidth = 
6423             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6424           APInt NewCST = AndCST->getValue();
6425           NewCST.zext(BitWidth);
6426           APInt NewCI = RHSV;
6427           NewCI.zext(BitWidth);
6428           Instruction *NewAnd = 
6429             BinaryOperator::CreateAnd(Cast->getOperand(0),
6430                                       ConstantInt::get(NewCST),LHSI->getName());
6431           InsertNewInstBefore(NewAnd, ICI);
6432           return new ICmpInst(ICI.getPredicate(), NewAnd,
6433                               ConstantInt::get(NewCI));
6434         }
6435       }
6436       
6437       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6438       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6439       // happens a LOT in code produced by the C front-end, for bitfield
6440       // access.
6441       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6442       if (Shift && !Shift->isShift())
6443         Shift = 0;
6444       
6445       ConstantInt *ShAmt;
6446       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6447       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6448       const Type *AndTy = AndCST->getType();          // Type of the and.
6449       
6450       // We can fold this as long as we can't shift unknown bits
6451       // into the mask.  This can only happen with signed shift
6452       // rights, as they sign-extend.
6453       if (ShAmt) {
6454         bool CanFold = Shift->isLogicalShift();
6455         if (!CanFold) {
6456           // To test for the bad case of the signed shr, see if any
6457           // of the bits shifted in could be tested after the mask.
6458           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6459           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6460           
6461           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6462           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6463                AndCST->getValue()) == 0)
6464             CanFold = true;
6465         }
6466         
6467         if (CanFold) {
6468           Constant *NewCst;
6469           if (Shift->getOpcode() == Instruction::Shl)
6470             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6471           else
6472             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6473           
6474           // Check to see if we are shifting out any of the bits being
6475           // compared.
6476           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6477             // If we shifted bits out, the fold is not going to work out.
6478             // As a special case, check to see if this means that the
6479             // result is always true or false now.
6480             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6481               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6482             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6483               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6484           } else {
6485             ICI.setOperand(1, NewCst);
6486             Constant *NewAndCST;
6487             if (Shift->getOpcode() == Instruction::Shl)
6488               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6489             else
6490               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6491             LHSI->setOperand(1, NewAndCST);
6492             LHSI->setOperand(0, Shift->getOperand(0));
6493             AddToWorkList(Shift); // Shift is dead.
6494             AddUsesToWorkList(ICI);
6495             return &ICI;
6496           }
6497         }
6498       }
6499       
6500       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6501       // preferable because it allows the C<<Y expression to be hoisted out
6502       // of a loop if Y is invariant and X is not.
6503       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6504           ICI.isEquality() && !Shift->isArithmeticShift() &&
6505           isa<Instruction>(Shift->getOperand(0))) {
6506         // Compute C << Y.
6507         Value *NS;
6508         if (Shift->getOpcode() == Instruction::LShr) {
6509           NS = BinaryOperator::CreateShl(AndCST, 
6510                                          Shift->getOperand(1), "tmp");
6511         } else {
6512           // Insert a logical shift.
6513           NS = BinaryOperator::CreateLShr(AndCST,
6514                                           Shift->getOperand(1), "tmp");
6515         }
6516         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6517         
6518         // Compute X & (C << Y).
6519         Instruction *NewAnd = 
6520           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6521         InsertNewInstBefore(NewAnd, ICI);
6522         
6523         ICI.setOperand(0, NewAnd);
6524         return &ICI;
6525       }
6526     }
6527     break;
6528     
6529   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6530     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6531     if (!ShAmt) break;
6532     
6533     uint32_t TypeBits = RHSV.getBitWidth();
6534     
6535     // Check that the shift amount is in range.  If not, don't perform
6536     // undefined shifts.  When the shift is visited it will be
6537     // simplified.
6538     if (ShAmt->uge(TypeBits))
6539       break;
6540     
6541     if (ICI.isEquality()) {
6542       // If we are comparing against bits always shifted out, the
6543       // comparison cannot succeed.
6544       Constant *Comp =
6545         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6546       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6547         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6548         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6549         return ReplaceInstUsesWith(ICI, Cst);
6550       }
6551       
6552       if (LHSI->hasOneUse()) {
6553         // Otherwise strength reduce the shift into an and.
6554         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6555         Constant *Mask =
6556           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6557         
6558         Instruction *AndI =
6559           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6560                                     Mask, LHSI->getName()+".mask");
6561         Value *And = InsertNewInstBefore(AndI, ICI);
6562         return new ICmpInst(ICI.getPredicate(), And,
6563                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6564       }
6565     }
6566     
6567     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6568     bool TrueIfSigned = false;
6569     if (LHSI->hasOneUse() &&
6570         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6571       // (X << 31) <s 0  --> (X&1) != 0
6572       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6573                                            (TypeBits-ShAmt->getZExtValue()-1));
6574       Instruction *AndI =
6575         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6576                                   Mask, LHSI->getName()+".mask");
6577       Value *And = InsertNewInstBefore(AndI, ICI);
6578       
6579       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6580                           And, Constant::getNullValue(And->getType()));
6581     }
6582     break;
6583   }
6584     
6585   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6586   case Instruction::AShr: {
6587     // Only handle equality comparisons of shift-by-constant.
6588     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6589     if (!ShAmt || !ICI.isEquality()) break;
6590
6591     // Check that the shift amount is in range.  If not, don't perform
6592     // undefined shifts.  When the shift is visited it will be
6593     // simplified.
6594     uint32_t TypeBits = RHSV.getBitWidth();
6595     if (ShAmt->uge(TypeBits))
6596       break;
6597     
6598     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6599       
6600     // If we are comparing against bits always shifted out, the
6601     // comparison cannot succeed.
6602     APInt Comp = RHSV << ShAmtVal;
6603     if (LHSI->getOpcode() == Instruction::LShr)
6604       Comp = Comp.lshr(ShAmtVal);
6605     else
6606       Comp = Comp.ashr(ShAmtVal);
6607     
6608     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6609       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6610       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6611       return ReplaceInstUsesWith(ICI, Cst);
6612     }
6613     
6614     // Otherwise, check to see if the bits shifted out are known to be zero.
6615     // If so, we can compare against the unshifted value:
6616     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6617     if (LHSI->hasOneUse() &&
6618         MaskedValueIsZero(LHSI->getOperand(0), 
6619                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6620       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6621                           ConstantExpr::getShl(RHS, ShAmt));
6622     }
6623       
6624     if (LHSI->hasOneUse()) {
6625       // Otherwise strength reduce the shift into an and.
6626       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6627       Constant *Mask = ConstantInt::get(Val);
6628       
6629       Instruction *AndI =
6630         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6631                                   Mask, LHSI->getName()+".mask");
6632       Value *And = InsertNewInstBefore(AndI, ICI);
6633       return new ICmpInst(ICI.getPredicate(), And,
6634                           ConstantExpr::getShl(RHS, ShAmt));
6635     }
6636     break;
6637   }
6638     
6639   case Instruction::SDiv:
6640   case Instruction::UDiv:
6641     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6642     // Fold this div into the comparison, producing a range check. 
6643     // Determine, based on the divide type, what the range is being 
6644     // checked.  If there is an overflow on the low or high side, remember 
6645     // it, otherwise compute the range [low, hi) bounding the new value.
6646     // See: InsertRangeTest above for the kinds of replacements possible.
6647     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6648       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6649                                           DivRHS))
6650         return R;
6651     break;
6652
6653   case Instruction::Add:
6654     // Fold: icmp pred (add, X, C1), C2
6655
6656     if (!ICI.isEquality()) {
6657       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6658       if (!LHSC) break;
6659       const APInt &LHSV = LHSC->getValue();
6660
6661       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6662                             .subtract(LHSV);
6663
6664       if (ICI.isSignedPredicate()) {
6665         if (CR.getLower().isSignBit()) {
6666           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6667                               ConstantInt::get(CR.getUpper()));
6668         } else if (CR.getUpper().isSignBit()) {
6669           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6670                               ConstantInt::get(CR.getLower()));
6671         }
6672       } else {
6673         if (CR.getLower().isMinValue()) {
6674           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6675                               ConstantInt::get(CR.getUpper()));
6676         } else if (CR.getUpper().isMinValue()) {
6677           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6678                               ConstantInt::get(CR.getLower()));
6679         }
6680       }
6681     }
6682     break;
6683   }
6684   
6685   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6686   if (ICI.isEquality()) {
6687     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6688     
6689     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6690     // the second operand is a constant, simplify a bit.
6691     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6692       switch (BO->getOpcode()) {
6693       case Instruction::SRem:
6694         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6695         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6696           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6697           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6698             Instruction *NewRem =
6699               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6700                                          BO->getName());
6701             InsertNewInstBefore(NewRem, ICI);
6702             return new ICmpInst(ICI.getPredicate(), NewRem, 
6703                                 Constant::getNullValue(BO->getType()));
6704           }
6705         }
6706         break;
6707       case Instruction::Add:
6708         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6709         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6710           if (BO->hasOneUse())
6711             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6712                                 Subtract(RHS, BOp1C));
6713         } else if (RHSV == 0) {
6714           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6715           // efficiently invertible, or if the add has just this one use.
6716           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6717           
6718           if (Value *NegVal = dyn_castNegVal(BOp1))
6719             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6720           else if (Value *NegVal = dyn_castNegVal(BOp0))
6721             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6722           else if (BO->hasOneUse()) {
6723             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6724             InsertNewInstBefore(Neg, ICI);
6725             Neg->takeName(BO);
6726             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6727           }
6728         }
6729         break;
6730       case Instruction::Xor:
6731         // For the xor case, we can xor two constants together, eliminating
6732         // the explicit xor.
6733         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6734           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6735                               ConstantExpr::getXor(RHS, BOC));
6736         
6737         // FALLTHROUGH
6738       case Instruction::Sub:
6739         // Replace (([sub|xor] A, B) != 0) with (A != B)
6740         if (RHSV == 0)
6741           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6742                               BO->getOperand(1));
6743         break;
6744         
6745       case Instruction::Or:
6746         // If bits are being or'd in that are not present in the constant we
6747         // are comparing against, then the comparison could never succeed!
6748         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6749           Constant *NotCI = ConstantExpr::getNot(RHS);
6750           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6751             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6752                                                              isICMP_NE));
6753         }
6754         break;
6755         
6756       case Instruction::And:
6757         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6758           // If bits are being compared against that are and'd out, then the
6759           // comparison can never succeed!
6760           if ((RHSV & ~BOC->getValue()) != 0)
6761             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6762                                                              isICMP_NE));
6763           
6764           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6765           if (RHS == BOC && RHSV.isPowerOf2())
6766             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6767                                 ICmpInst::ICMP_NE, LHSI,
6768                                 Constant::getNullValue(RHS->getType()));
6769           
6770           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6771           if (BOC->getValue().isSignBit()) {
6772             Value *X = BO->getOperand(0);
6773             Constant *Zero = Constant::getNullValue(X->getType());
6774             ICmpInst::Predicate pred = isICMP_NE ? 
6775               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6776             return new ICmpInst(pred, X, Zero);
6777           }
6778           
6779           // ((X & ~7) == 0) --> X < 8
6780           if (RHSV == 0 && isHighOnes(BOC)) {
6781             Value *X = BO->getOperand(0);
6782             Constant *NegX = ConstantExpr::getNeg(BOC);
6783             ICmpInst::Predicate pred = isICMP_NE ? 
6784               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6785             return new ICmpInst(pred, X, NegX);
6786           }
6787         }
6788       default: break;
6789       }
6790     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6791       // Handle icmp {eq|ne} <intrinsic>, intcst.
6792       if (II->getIntrinsicID() == Intrinsic::bswap) {
6793         AddToWorkList(II);
6794         ICI.setOperand(0, II->getOperand(1));
6795         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6796         return &ICI;
6797       }
6798     }
6799   } else {  // Not a ICMP_EQ/ICMP_NE
6800             // If the LHS is a cast from an integral value of the same size, 
6801             // then since we know the RHS is a constant, try to simlify.
6802     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6803       Value *CastOp = Cast->getOperand(0);
6804       const Type *SrcTy = CastOp->getType();
6805       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6806       if (SrcTy->isInteger() && 
6807           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6808         // If this is an unsigned comparison, try to make the comparison use
6809         // smaller constant values.
6810         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6811           // X u< 128 => X s> -1
6812           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6813                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6814         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6815                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6816           // X u> 127 => X s< 0
6817           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6818                               Constant::getNullValue(SrcTy));
6819         }
6820       }
6821     }
6822   }
6823   return 0;
6824 }
6825
6826 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6827 /// We only handle extending casts so far.
6828 ///
6829 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6830   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6831   Value *LHSCIOp        = LHSCI->getOperand(0);
6832   const Type *SrcTy     = LHSCIOp->getType();
6833   const Type *DestTy    = LHSCI->getType();
6834   Value *RHSCIOp;
6835
6836   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6837   // integer type is the same size as the pointer type.
6838   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6839       getTargetData().getPointerSizeInBits() == 
6840          cast<IntegerType>(DestTy)->getBitWidth()) {
6841     Value *RHSOp = 0;
6842     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6843       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6844     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6845       RHSOp = RHSC->getOperand(0);
6846       // If the pointer types don't match, insert a bitcast.
6847       if (LHSCIOp->getType() != RHSOp->getType())
6848         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6849     }
6850
6851     if (RHSOp)
6852       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6853   }
6854   
6855   // The code below only handles extension cast instructions, so far.
6856   // Enforce this.
6857   if (LHSCI->getOpcode() != Instruction::ZExt &&
6858       LHSCI->getOpcode() != Instruction::SExt)
6859     return 0;
6860
6861   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6862   bool isSignedCmp = ICI.isSignedPredicate();
6863
6864   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6865     // Not an extension from the same type?
6866     RHSCIOp = CI->getOperand(0);
6867     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6868       return 0;
6869     
6870     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6871     // and the other is a zext), then we can't handle this.
6872     if (CI->getOpcode() != LHSCI->getOpcode())
6873       return 0;
6874
6875     // Deal with equality cases early.
6876     if (ICI.isEquality())
6877       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6878
6879     // A signed comparison of sign extended values simplifies into a
6880     // signed comparison.
6881     if (isSignedCmp && isSignedExt)
6882       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6883
6884     // The other three cases all fold into an unsigned comparison.
6885     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6886   }
6887
6888   // If we aren't dealing with a constant on the RHS, exit early
6889   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6890   if (!CI)
6891     return 0;
6892
6893   // Compute the constant that would happen if we truncated to SrcTy then
6894   // reextended to DestTy.
6895   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6896   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6897
6898   // If the re-extended constant didn't change...
6899   if (Res2 == CI) {
6900     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6901     // For example, we might have:
6902     //    %A = sext short %X to uint
6903     //    %B = icmp ugt uint %A, 1330
6904     // It is incorrect to transform this into 
6905     //    %B = icmp ugt short %X, 1330 
6906     // because %A may have negative value. 
6907     //
6908     // However, we allow this when the compare is EQ/NE, because they are
6909     // signless.
6910     if (isSignedExt == isSignedCmp || ICI.isEquality())
6911       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6912     return 0;
6913   }
6914
6915   // The re-extended constant changed so the constant cannot be represented 
6916   // in the shorter type. Consequently, we cannot emit a simple comparison.
6917
6918   // First, handle some easy cases. We know the result cannot be equal at this
6919   // point so handle the ICI.isEquality() cases
6920   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6921     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6922   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6923     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6924
6925   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6926   // should have been folded away previously and not enter in here.
6927   Value *Result;
6928   if (isSignedCmp) {
6929     // We're performing a signed comparison.
6930     if (cast<ConstantInt>(CI)->getValue().isNegative())
6931       Result = ConstantInt::getFalse();          // X < (small) --> false
6932     else
6933       Result = ConstantInt::getTrue();           // X < (large) --> true
6934   } else {
6935     // We're performing an unsigned comparison.
6936     if (isSignedExt) {
6937       // We're performing an unsigned comp with a sign extended value.
6938       // This is true if the input is >= 0. [aka >s -1]
6939       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6940       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6941                                    NegOne, ICI.getName()), ICI);
6942     } else {
6943       // Unsigned extend & unsigned compare -> always true.
6944       Result = ConstantInt::getTrue();
6945     }
6946   }
6947
6948   // Finally, return the value computed.
6949   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6950       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6951     return ReplaceInstUsesWith(ICI, Result);
6952
6953   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6954           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6955          "ICmp should be folded!");
6956   if (Constant *CI = dyn_cast<Constant>(Result))
6957     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6958   return BinaryOperator::CreateNot(Result);
6959 }
6960
6961 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6962   return commonShiftTransforms(I);
6963 }
6964
6965 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6966   return commonShiftTransforms(I);
6967 }
6968
6969 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6970   if (Instruction *R = commonShiftTransforms(I))
6971     return R;
6972   
6973   Value *Op0 = I.getOperand(0);
6974   
6975   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6976   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6977     if (CSI->isAllOnesValue())
6978       return ReplaceInstUsesWith(I, CSI);
6979   
6980   // See if we can turn a signed shr into an unsigned shr.
6981   if (!isa<VectorType>(I.getType()) &&
6982       MaskedValueIsZero(Op0,
6983                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6984     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6985   
6986   return 0;
6987 }
6988
6989 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6990   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6991   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6992
6993   // shl X, 0 == X and shr X, 0 == X
6994   // shl 0, X == 0 and shr 0, X == 0
6995   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6996       Op0 == Constant::getNullValue(Op0->getType()))
6997     return ReplaceInstUsesWith(I, Op0);
6998   
6999   if (isa<UndefValue>(Op0)) {            
7000     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7001       return ReplaceInstUsesWith(I, Op0);
7002     else                                    // undef << X -> 0, undef >>u X -> 0
7003       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7004   }
7005   if (isa<UndefValue>(Op1)) {
7006     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7007       return ReplaceInstUsesWith(I, Op0);          
7008     else                                     // X << undef, X >>u undef -> 0
7009       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7010   }
7011
7012   // Try to fold constant and into select arguments.
7013   if (isa<Constant>(Op0))
7014     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7015       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7016         return R;
7017
7018   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7019     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7020       return Res;
7021   return 0;
7022 }
7023
7024 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7025                                                BinaryOperator &I) {
7026   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
7027
7028   // See if we can simplify any instructions used by the instruction whose sole 
7029   // purpose is to compute bits we don't care about.
7030   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7031   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
7032   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
7033                            KnownZero, KnownOne))
7034     return &I;
7035   
7036   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7037   // of a signed value.
7038   //
7039   if (Op1->uge(TypeBits)) {
7040     if (I.getOpcode() != Instruction::AShr)
7041       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7042     else {
7043       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7044       return &I;
7045     }
7046   }
7047   
7048   // ((X*C1) << C2) == (X * (C1 << C2))
7049   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7050     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7051       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7052         return BinaryOperator::CreateMul(BO->getOperand(0),
7053                                          ConstantExpr::getShl(BOOp, Op1));
7054   
7055   // Try to fold constant and into select arguments.
7056   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7057     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7058       return R;
7059   if (isa<PHINode>(Op0))
7060     if (Instruction *NV = FoldOpIntoPhi(I))
7061       return NV;
7062   
7063   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7064   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7065     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7066     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7067     // place.  Don't try to do this transformation in this case.  Also, we
7068     // require that the input operand is a shift-by-constant so that we have
7069     // confidence that the shifts will get folded together.  We could do this
7070     // xform in more cases, but it is unlikely to be profitable.
7071     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7072         isa<ConstantInt>(TrOp->getOperand(1))) {
7073       // Okay, we'll do this xform.  Make the shift of shift.
7074       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7075       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7076                                                 I.getName());
7077       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7078
7079       // For logical shifts, the truncation has the effect of making the high
7080       // part of the register be zeros.  Emulate this by inserting an AND to
7081       // clear the top bits as needed.  This 'and' will usually be zapped by
7082       // other xforms later if dead.
7083       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7084       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7085       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7086       
7087       // The mask we constructed says what the trunc would do if occurring
7088       // between the shifts.  We want to know the effect *after* the second
7089       // shift.  We know that it is a logical shift by a constant, so adjust the
7090       // mask as appropriate.
7091       if (I.getOpcode() == Instruction::Shl)
7092         MaskV <<= Op1->getZExtValue();
7093       else {
7094         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7095         MaskV = MaskV.lshr(Op1->getZExtValue());
7096       }
7097
7098       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7099                                                    TI->getName());
7100       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7101
7102       // Return the value truncated to the interesting size.
7103       return new TruncInst(And, I.getType());
7104     }
7105   }
7106   
7107   if (Op0->hasOneUse()) {
7108     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7109       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7110       Value *V1, *V2;
7111       ConstantInt *CC;
7112       switch (Op0BO->getOpcode()) {
7113         default: break;
7114         case Instruction::Add:
7115         case Instruction::And:
7116         case Instruction::Or:
7117         case Instruction::Xor: {
7118           // These operators commute.
7119           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7120           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7121               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7122             Instruction *YS = BinaryOperator::CreateShl(
7123                                             Op0BO->getOperand(0), Op1,
7124                                             Op0BO->getName());
7125             InsertNewInstBefore(YS, I); // (Y << C)
7126             Instruction *X = 
7127               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7128                                      Op0BO->getOperand(1)->getName());
7129             InsertNewInstBefore(X, I);  // (X + (Y << C))
7130             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7131             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7132                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7133           }
7134           
7135           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7136           Value *Op0BOOp1 = Op0BO->getOperand(1);
7137           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7138               match(Op0BOOp1, 
7139                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7140                           m_ConstantInt(CC))) &&
7141               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7142             Instruction *YS = BinaryOperator::CreateShl(
7143                                                      Op0BO->getOperand(0), Op1,
7144                                                      Op0BO->getName());
7145             InsertNewInstBefore(YS, I); // (Y << C)
7146             Instruction *XM =
7147               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7148                                         V1->getName()+".mask");
7149             InsertNewInstBefore(XM, I); // X & (CC << C)
7150             
7151             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7152           }
7153         }
7154           
7155         // FALL THROUGH.
7156         case Instruction::Sub: {
7157           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7158           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7159               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7160             Instruction *YS = BinaryOperator::CreateShl(
7161                                                      Op0BO->getOperand(1), Op1,
7162                                                      Op0BO->getName());
7163             InsertNewInstBefore(YS, I); // (Y << C)
7164             Instruction *X =
7165               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7166                                      Op0BO->getOperand(0)->getName());
7167             InsertNewInstBefore(X, I);  // (X + (Y << C))
7168             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7169             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7170                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7171           }
7172           
7173           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7174           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7175               match(Op0BO->getOperand(0),
7176                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7177                           m_ConstantInt(CC))) && V2 == Op1 &&
7178               cast<BinaryOperator>(Op0BO->getOperand(0))
7179                   ->getOperand(0)->hasOneUse()) {
7180             Instruction *YS = BinaryOperator::CreateShl(
7181                                                      Op0BO->getOperand(1), Op1,
7182                                                      Op0BO->getName());
7183             InsertNewInstBefore(YS, I); // (Y << C)
7184             Instruction *XM =
7185               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7186                                         V1->getName()+".mask");
7187             InsertNewInstBefore(XM, I); // X & (CC << C)
7188             
7189             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7190           }
7191           
7192           break;
7193         }
7194       }
7195       
7196       
7197       // If the operand is an bitwise operator with a constant RHS, and the
7198       // shift is the only use, we can pull it out of the shift.
7199       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7200         bool isValid = true;     // Valid only for And, Or, Xor
7201         bool highBitSet = false; // Transform if high bit of constant set?
7202         
7203         switch (Op0BO->getOpcode()) {
7204           default: isValid = false; break;   // Do not perform transform!
7205           case Instruction::Add:
7206             isValid = isLeftShift;
7207             break;
7208           case Instruction::Or:
7209           case Instruction::Xor:
7210             highBitSet = false;
7211             break;
7212           case Instruction::And:
7213             highBitSet = true;
7214             break;
7215         }
7216         
7217         // If this is a signed shift right, and the high bit is modified
7218         // by the logical operation, do not perform the transformation.
7219         // The highBitSet boolean indicates the value of the high bit of
7220         // the constant which would cause it to be modified for this
7221         // operation.
7222         //
7223         if (isValid && I.getOpcode() == Instruction::AShr)
7224           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7225         
7226         if (isValid) {
7227           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7228           
7229           Instruction *NewShift =
7230             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7231           InsertNewInstBefore(NewShift, I);
7232           NewShift->takeName(Op0BO);
7233           
7234           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7235                                         NewRHS);
7236         }
7237       }
7238     }
7239   }
7240   
7241   // Find out if this is a shift of a shift by a constant.
7242   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7243   if (ShiftOp && !ShiftOp->isShift())
7244     ShiftOp = 0;
7245   
7246   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7247     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7248     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7249     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7250     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7251     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7252     Value *X = ShiftOp->getOperand(0);
7253     
7254     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7255     if (AmtSum > TypeBits)
7256       AmtSum = TypeBits;
7257     
7258     const IntegerType *Ty = cast<IntegerType>(I.getType());
7259     
7260     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7261     if (I.getOpcode() == ShiftOp->getOpcode()) {
7262       return BinaryOperator::Create(I.getOpcode(), X,
7263                                     ConstantInt::get(Ty, AmtSum));
7264     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7265                I.getOpcode() == Instruction::AShr) {
7266       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7267       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7268     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7269                I.getOpcode() == Instruction::LShr) {
7270       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7271       Instruction *Shift =
7272         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7273       InsertNewInstBefore(Shift, I);
7274
7275       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7276       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7277     }
7278     
7279     // Okay, if we get here, one shift must be left, and the other shift must be
7280     // right.  See if the amounts are equal.
7281     if (ShiftAmt1 == ShiftAmt2) {
7282       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7283       if (I.getOpcode() == Instruction::Shl) {
7284         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7285         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7286       }
7287       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7288       if (I.getOpcode() == Instruction::LShr) {
7289         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7290         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7291       }
7292       // We can simplify ((X << C) >>s C) into a trunc + sext.
7293       // NOTE: we could do this for any C, but that would make 'unusual' integer
7294       // types.  For now, just stick to ones well-supported by the code
7295       // generators.
7296       const Type *SExtType = 0;
7297       switch (Ty->getBitWidth() - ShiftAmt1) {
7298       case 1  :
7299       case 8  :
7300       case 16 :
7301       case 32 :
7302       case 64 :
7303       case 128:
7304         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7305         break;
7306       default: break;
7307       }
7308       if (SExtType) {
7309         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7310         InsertNewInstBefore(NewTrunc, I);
7311         return new SExtInst(NewTrunc, Ty);
7312       }
7313       // Otherwise, we can't handle it yet.
7314     } else if (ShiftAmt1 < ShiftAmt2) {
7315       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7316       
7317       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7318       if (I.getOpcode() == Instruction::Shl) {
7319         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7320                ShiftOp->getOpcode() == Instruction::AShr);
7321         Instruction *Shift =
7322           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7323         InsertNewInstBefore(Shift, I);
7324         
7325         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7326         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7327       }
7328       
7329       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7330       if (I.getOpcode() == Instruction::LShr) {
7331         assert(ShiftOp->getOpcode() == Instruction::Shl);
7332         Instruction *Shift =
7333           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7334         InsertNewInstBefore(Shift, I);
7335         
7336         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7337         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7338       }
7339       
7340       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7341     } else {
7342       assert(ShiftAmt2 < ShiftAmt1);
7343       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7344
7345       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7346       if (I.getOpcode() == Instruction::Shl) {
7347         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7348                ShiftOp->getOpcode() == Instruction::AShr);
7349         Instruction *Shift =
7350           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7351                                  ConstantInt::get(Ty, ShiftDiff));
7352         InsertNewInstBefore(Shift, I);
7353         
7354         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7355         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7356       }
7357       
7358       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7359       if (I.getOpcode() == Instruction::LShr) {
7360         assert(ShiftOp->getOpcode() == Instruction::Shl);
7361         Instruction *Shift =
7362           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7363         InsertNewInstBefore(Shift, I);
7364         
7365         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7366         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7367       }
7368       
7369       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7370     }
7371   }
7372   return 0;
7373 }
7374
7375
7376 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7377 /// expression.  If so, decompose it, returning some value X, such that Val is
7378 /// X*Scale+Offset.
7379 ///
7380 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7381                                         int &Offset) {
7382   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7383   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7384     Offset = CI->getZExtValue();
7385     Scale  = 0;
7386     return ConstantInt::get(Type::Int32Ty, 0);
7387   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7388     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7389       if (I->getOpcode() == Instruction::Shl) {
7390         // This is a value scaled by '1 << the shift amt'.
7391         Scale = 1U << RHS->getZExtValue();
7392         Offset = 0;
7393         return I->getOperand(0);
7394       } else if (I->getOpcode() == Instruction::Mul) {
7395         // This value is scaled by 'RHS'.
7396         Scale = RHS->getZExtValue();
7397         Offset = 0;
7398         return I->getOperand(0);
7399       } else if (I->getOpcode() == Instruction::Add) {
7400         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7401         // where C1 is divisible by C2.
7402         unsigned SubScale;
7403         Value *SubVal = 
7404           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7405         Offset += RHS->getZExtValue();
7406         Scale = SubScale;
7407         return SubVal;
7408       }
7409     }
7410   }
7411
7412   // Otherwise, we can't look past this.
7413   Scale = 1;
7414   Offset = 0;
7415   return Val;
7416 }
7417
7418
7419 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7420 /// try to eliminate the cast by moving the type information into the alloc.
7421 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7422                                                    AllocationInst &AI) {
7423   const PointerType *PTy = cast<PointerType>(CI.getType());
7424   
7425   // Remove any uses of AI that are dead.
7426   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7427   
7428   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7429     Instruction *User = cast<Instruction>(*UI++);
7430     if (isInstructionTriviallyDead(User)) {
7431       while (UI != E && *UI == User)
7432         ++UI; // If this instruction uses AI more than once, don't break UI.
7433       
7434       ++NumDeadInst;
7435       DOUT << "IC: DCE: " << *User;
7436       EraseInstFromFunction(*User);
7437     }
7438   }
7439   
7440   // Get the type really allocated and the type casted to.
7441   const Type *AllocElTy = AI.getAllocatedType();
7442   const Type *CastElTy = PTy->getElementType();
7443   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7444
7445   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7446   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7447   if (CastElTyAlign < AllocElTyAlign) return 0;
7448
7449   // If the allocation has multiple uses, only promote it if we are strictly
7450   // increasing the alignment of the resultant allocation.  If we keep it the
7451   // same, we open the door to infinite loops of various kinds.
7452   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7453
7454   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7455   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7456   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7457
7458   // See if we can satisfy the modulus by pulling a scale out of the array
7459   // size argument.
7460   unsigned ArraySizeScale;
7461   int ArrayOffset;
7462   Value *NumElements = // See if the array size is a decomposable linear expr.
7463     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7464  
7465   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7466   // do the xform.
7467   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7468       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7469
7470   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7471   Value *Amt = 0;
7472   if (Scale == 1) {
7473     Amt = NumElements;
7474   } else {
7475     // If the allocation size is constant, form a constant mul expression
7476     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7477     if (isa<ConstantInt>(NumElements))
7478       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7479     // otherwise multiply the amount and the number of elements
7480     else if (Scale != 1) {
7481       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7482       Amt = InsertNewInstBefore(Tmp, AI);
7483     }
7484   }
7485   
7486   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7487     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7488     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7489     Amt = InsertNewInstBefore(Tmp, AI);
7490   }
7491   
7492   AllocationInst *New;
7493   if (isa<MallocInst>(AI))
7494     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7495   else
7496     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7497   InsertNewInstBefore(New, AI);
7498   New->takeName(&AI);
7499   
7500   // If the allocation has multiple uses, insert a cast and change all things
7501   // that used it to use the new cast.  This will also hack on CI, but it will
7502   // die soon.
7503   if (!AI.hasOneUse()) {
7504     AddUsesToWorkList(AI);
7505     // New is the allocation instruction, pointer typed. AI is the original
7506     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7507     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7508     InsertNewInstBefore(NewCast, AI);
7509     AI.replaceAllUsesWith(NewCast);
7510   }
7511   return ReplaceInstUsesWith(CI, New);
7512 }
7513
7514 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7515 /// and return it as type Ty without inserting any new casts and without
7516 /// changing the computed value.  This is used by code that tries to decide
7517 /// whether promoting or shrinking integer operations to wider or smaller types
7518 /// will allow us to eliminate a truncate or extend.
7519 ///
7520 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7521 /// extension operation if Ty is larger.
7522 ///
7523 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7524 /// should return true if trunc(V) can be computed by computing V in the smaller
7525 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7526 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7527 /// efficiently truncated.
7528 ///
7529 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7530 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7531 /// the final result.
7532 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7533                                               unsigned CastOpc,
7534                                               int &NumCastsRemoved) {
7535   // We can always evaluate constants in another type.
7536   if (isa<ConstantInt>(V))
7537     return true;
7538   
7539   Instruction *I = dyn_cast<Instruction>(V);
7540   if (!I) return false;
7541   
7542   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7543   
7544   // If this is an extension or truncate, we can often eliminate it.
7545   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7546     // If this is a cast from the destination type, we can trivially eliminate
7547     // it, and this will remove a cast overall.
7548     if (I->getOperand(0)->getType() == Ty) {
7549       // If the first operand is itself a cast, and is eliminable, do not count
7550       // this as an eliminable cast.  We would prefer to eliminate those two
7551       // casts first.
7552       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7553         ++NumCastsRemoved;
7554       return true;
7555     }
7556   }
7557
7558   // We can't extend or shrink something that has multiple uses: doing so would
7559   // require duplicating the instruction in general, which isn't profitable.
7560   if (!I->hasOneUse()) return false;
7561
7562   switch (I->getOpcode()) {
7563   case Instruction::Add:
7564   case Instruction::Sub:
7565   case Instruction::Mul:
7566   case Instruction::And:
7567   case Instruction::Or:
7568   case Instruction::Xor:
7569     // These operators can all arbitrarily be extended or truncated.
7570     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7571                                       NumCastsRemoved) &&
7572            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7573                                       NumCastsRemoved);
7574
7575   case Instruction::Shl:
7576     // If we are truncating the result of this SHL, and if it's a shift of a
7577     // constant amount, we can always perform a SHL in a smaller type.
7578     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7579       uint32_t BitWidth = Ty->getBitWidth();
7580       if (BitWidth < OrigTy->getBitWidth() && 
7581           CI->getLimitedValue(BitWidth) < BitWidth)
7582         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7583                                           NumCastsRemoved);
7584     }
7585     break;
7586   case Instruction::LShr:
7587     // If this is a truncate of a logical shr, we can truncate it to a smaller
7588     // lshr iff we know that the bits we would otherwise be shifting in are
7589     // already zeros.
7590     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7591       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7592       uint32_t BitWidth = Ty->getBitWidth();
7593       if (BitWidth < OrigBitWidth &&
7594           MaskedValueIsZero(I->getOperand(0),
7595             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7596           CI->getLimitedValue(BitWidth) < BitWidth) {
7597         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7598                                           NumCastsRemoved);
7599       }
7600     }
7601     break;
7602   case Instruction::ZExt:
7603   case Instruction::SExt:
7604   case Instruction::Trunc:
7605     // If this is the same kind of case as our original (e.g. zext+zext), we
7606     // can safely replace it.  Note that replacing it does not reduce the number
7607     // of casts in the input.
7608     if (I->getOpcode() == CastOpc)
7609       return true;
7610     break;
7611   case Instruction::Select: {
7612     SelectInst *SI = cast<SelectInst>(I);
7613     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7614                                       NumCastsRemoved) &&
7615            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7616                                       NumCastsRemoved);
7617   }
7618   case Instruction::PHI: {
7619     // We can change a phi if we can change all operands.
7620     PHINode *PN = cast<PHINode>(I);
7621     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7622       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7623                                       NumCastsRemoved))
7624         return false;
7625     return true;
7626   }
7627   default:
7628     // TODO: Can handle more cases here.
7629     break;
7630   }
7631   
7632   return false;
7633 }
7634
7635 /// EvaluateInDifferentType - Given an expression that 
7636 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7637 /// evaluate the expression.
7638 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7639                                              bool isSigned) {
7640   if (Constant *C = dyn_cast<Constant>(V))
7641     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7642
7643   // Otherwise, it must be an instruction.
7644   Instruction *I = cast<Instruction>(V);
7645   Instruction *Res = 0;
7646   switch (I->getOpcode()) {
7647   case Instruction::Add:
7648   case Instruction::Sub:
7649   case Instruction::Mul:
7650   case Instruction::And:
7651   case Instruction::Or:
7652   case Instruction::Xor:
7653   case Instruction::AShr:
7654   case Instruction::LShr:
7655   case Instruction::Shl: {
7656     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7657     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7658     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7659                                  LHS, RHS);
7660     break;
7661   }    
7662   case Instruction::Trunc:
7663   case Instruction::ZExt:
7664   case Instruction::SExt:
7665     // If the source type of the cast is the type we're trying for then we can
7666     // just return the source.  There's no need to insert it because it is not
7667     // new.
7668     if (I->getOperand(0)->getType() == Ty)
7669       return I->getOperand(0);
7670     
7671     // Otherwise, must be the same type of cast, so just reinsert a new one.
7672     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7673                            Ty);
7674     break;
7675   case Instruction::Select: {
7676     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7677     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7678     Res = SelectInst::Create(I->getOperand(0), True, False);
7679     break;
7680   }
7681   case Instruction::PHI: {
7682     PHINode *OPN = cast<PHINode>(I);
7683     PHINode *NPN = PHINode::Create(Ty);
7684     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7685       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7686       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7687     }
7688     Res = NPN;
7689     break;
7690   }
7691   default: 
7692     // TODO: Can handle more cases here.
7693     assert(0 && "Unreachable!");
7694     break;
7695   }
7696   
7697   Res->takeName(I);
7698   return InsertNewInstBefore(Res, *I);
7699 }
7700
7701 /// @brief Implement the transforms common to all CastInst visitors.
7702 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7703   Value *Src = CI.getOperand(0);
7704
7705   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7706   // eliminate it now.
7707   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7708     if (Instruction::CastOps opc = 
7709         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7710       // The first cast (CSrc) is eliminable so we need to fix up or replace
7711       // the second cast (CI). CSrc will then have a good chance of being dead.
7712       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7713     }
7714   }
7715
7716   // If we are casting a select then fold the cast into the select
7717   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7718     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7719       return NV;
7720
7721   // If we are casting a PHI then fold the cast into the PHI
7722   if (isa<PHINode>(Src))
7723     if (Instruction *NV = FoldOpIntoPhi(CI))
7724       return NV;
7725   
7726   return 0;
7727 }
7728
7729 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7730 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7731   Value *Src = CI.getOperand(0);
7732   
7733   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7734     // If casting the result of a getelementptr instruction with no offset, turn
7735     // this into a cast of the original pointer!
7736     if (GEP->hasAllZeroIndices()) {
7737       // Changing the cast operand is usually not a good idea but it is safe
7738       // here because the pointer operand is being replaced with another 
7739       // pointer operand so the opcode doesn't need to change.
7740       AddToWorkList(GEP);
7741       CI.setOperand(0, GEP->getOperand(0));
7742       return &CI;
7743     }
7744     
7745     // If the GEP has a single use, and the base pointer is a bitcast, and the
7746     // GEP computes a constant offset, see if we can convert these three
7747     // instructions into fewer.  This typically happens with unions and other
7748     // non-type-safe code.
7749     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7750       if (GEP->hasAllConstantIndices()) {
7751         // We are guaranteed to get a constant from EmitGEPOffset.
7752         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7753         int64_t Offset = OffsetV->getSExtValue();
7754         
7755         // Get the base pointer input of the bitcast, and the type it points to.
7756         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7757         const Type *GEPIdxTy =
7758           cast<PointerType>(OrigBase->getType())->getElementType();
7759         if (GEPIdxTy->isSized()) {
7760           SmallVector<Value*, 8> NewIndices;
7761           
7762           // Start with the index over the outer type.  Note that the type size
7763           // might be zero (even if the offset isn't zero) if the indexed type
7764           // is something like [0 x {int, int}]
7765           const Type *IntPtrTy = TD->getIntPtrType();
7766           int64_t FirstIdx = 0;
7767           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7768             FirstIdx = Offset/TySize;
7769             Offset %= TySize;
7770           
7771             // Handle silly modulus not returning values values [0..TySize).
7772             if (Offset < 0) {
7773               --FirstIdx;
7774               Offset += TySize;
7775               assert(Offset >= 0);
7776             }
7777             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7778           }
7779           
7780           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7781
7782           // Index into the types.  If we fail, set OrigBase to null.
7783           while (Offset) {
7784             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7785               const StructLayout *SL = TD->getStructLayout(STy);
7786               if (Offset < (int64_t)SL->getSizeInBytes()) {
7787                 unsigned Elt = SL->getElementContainingOffset(Offset);
7788                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7789               
7790                 Offset -= SL->getElementOffset(Elt);
7791                 GEPIdxTy = STy->getElementType(Elt);
7792               } else {
7793                 // Otherwise, we can't index into this, bail out.
7794                 Offset = 0;
7795                 OrigBase = 0;
7796               }
7797             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7798               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7799               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7800                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7801                 Offset %= EltSize;
7802               } else {
7803                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7804               }
7805               GEPIdxTy = STy->getElementType();
7806             } else {
7807               // Otherwise, we can't index into this, bail out.
7808               Offset = 0;
7809               OrigBase = 0;
7810             }
7811           }
7812           if (OrigBase) {
7813             // If we were able to index down into an element, create the GEP
7814             // and bitcast the result.  This eliminates one bitcast, potentially
7815             // two.
7816             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7817                                                           NewIndices.begin(),
7818                                                           NewIndices.end(), "");
7819             InsertNewInstBefore(NGEP, CI);
7820             NGEP->takeName(GEP);
7821             
7822             if (isa<BitCastInst>(CI))
7823               return new BitCastInst(NGEP, CI.getType());
7824             assert(isa<PtrToIntInst>(CI));
7825             return new PtrToIntInst(NGEP, CI.getType());
7826           }
7827         }
7828       }      
7829     }
7830   }
7831     
7832   return commonCastTransforms(CI);
7833 }
7834
7835
7836
7837 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7838 /// integer types. This function implements the common transforms for all those
7839 /// cases.
7840 /// @brief Implement the transforms common to CastInst with integer operands
7841 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7842   if (Instruction *Result = commonCastTransforms(CI))
7843     return Result;
7844
7845   Value *Src = CI.getOperand(0);
7846   const Type *SrcTy = Src->getType();
7847   const Type *DestTy = CI.getType();
7848   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7849   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7850
7851   // See if we can simplify any instructions used by the LHS whose sole 
7852   // purpose is to compute bits we don't care about.
7853   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7854   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7855                            KnownZero, KnownOne))
7856     return &CI;
7857
7858   // If the source isn't an instruction or has more than one use then we
7859   // can't do anything more. 
7860   Instruction *SrcI = dyn_cast<Instruction>(Src);
7861   if (!SrcI || !Src->hasOneUse())
7862     return 0;
7863
7864   // Attempt to propagate the cast into the instruction for int->int casts.
7865   int NumCastsRemoved = 0;
7866   if (!isa<BitCastInst>(CI) &&
7867       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7868                                  CI.getOpcode(), NumCastsRemoved)) {
7869     // If this cast is a truncate, evaluting in a different type always
7870     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7871     // we need to do an AND to maintain the clear top-part of the computation,
7872     // so we require that the input have eliminated at least one cast.  If this
7873     // is a sign extension, we insert two new casts (to do the extension) so we
7874     // require that two casts have been eliminated.
7875     bool DoXForm;
7876     switch (CI.getOpcode()) {
7877     default:
7878       // All the others use floating point so we shouldn't actually 
7879       // get here because of the check above.
7880       assert(0 && "Unknown cast type");
7881     case Instruction::Trunc:
7882       DoXForm = true;
7883       break;
7884     case Instruction::ZExt:
7885       DoXForm = NumCastsRemoved >= 1;
7886       break;
7887     case Instruction::SExt:
7888       DoXForm = NumCastsRemoved >= 2;
7889       break;
7890     }
7891     
7892     if (DoXForm) {
7893       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7894                                            CI.getOpcode() == Instruction::SExt);
7895       assert(Res->getType() == DestTy);
7896       switch (CI.getOpcode()) {
7897       default: assert(0 && "Unknown cast type!");
7898       case Instruction::Trunc:
7899       case Instruction::BitCast:
7900         // Just replace this cast with the result.
7901         return ReplaceInstUsesWith(CI, Res);
7902       case Instruction::ZExt: {
7903         // We need to emit an AND to clear the high bits.
7904         assert(SrcBitSize < DestBitSize && "Not a zext?");
7905         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7906                                                             SrcBitSize));
7907         return BinaryOperator::CreateAnd(Res, C);
7908       }
7909       case Instruction::SExt:
7910         // We need to emit a cast to truncate, then a cast to sext.
7911         return CastInst::Create(Instruction::SExt,
7912             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7913                              CI), DestTy);
7914       }
7915     }
7916   }
7917   
7918   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7919   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7920
7921   switch (SrcI->getOpcode()) {
7922   case Instruction::Add:
7923   case Instruction::Mul:
7924   case Instruction::And:
7925   case Instruction::Or:
7926   case Instruction::Xor:
7927     // If we are discarding information, rewrite.
7928     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7929       // Don't insert two casts if they cannot be eliminated.  We allow 
7930       // two casts to be inserted if the sizes are the same.  This could 
7931       // only be converting signedness, which is a noop.
7932       if (DestBitSize == SrcBitSize || 
7933           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7934           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7935         Instruction::CastOps opcode = CI.getOpcode();
7936         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7937         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7938         return BinaryOperator::Create(
7939             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7940       }
7941     }
7942
7943     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7944     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7945         SrcI->getOpcode() == Instruction::Xor &&
7946         Op1 == ConstantInt::getTrue() &&
7947         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7948       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
7949       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7950     }
7951     break;
7952   case Instruction::SDiv:
7953   case Instruction::UDiv:
7954   case Instruction::SRem:
7955   case Instruction::URem:
7956     // If we are just changing the sign, rewrite.
7957     if (DestBitSize == SrcBitSize) {
7958       // Don't insert two casts if they cannot be eliminated.  We allow 
7959       // two casts to be inserted if the sizes are the same.  This could 
7960       // only be converting signedness, which is a noop.
7961       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7962           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7963         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
7964                                        Op0, DestTy, *SrcI);
7965         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
7966                                        Op1, DestTy, *SrcI);
7967         return BinaryOperator::Create(
7968           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7969       }
7970     }
7971     break;
7972
7973   case Instruction::Shl:
7974     // Allow changing the sign of the source operand.  Do not allow 
7975     // changing the size of the shift, UNLESS the shift amount is a 
7976     // constant.  We must not change variable sized shifts to a smaller 
7977     // size, because it is undefined to shift more bits out than exist 
7978     // in the value.
7979     if (DestBitSize == SrcBitSize ||
7980         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7981       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7982           Instruction::BitCast : Instruction::Trunc);
7983       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7984       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7985       return BinaryOperator::CreateShl(Op0c, Op1c);
7986     }
7987     break;
7988   case Instruction::AShr:
7989     // If this is a signed shr, and if all bits shifted in are about to be
7990     // truncated off, turn it into an unsigned shr to allow greater
7991     // simplifications.
7992     if (DestBitSize < SrcBitSize &&
7993         isa<ConstantInt>(Op1)) {
7994       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7995       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7996         // Insert the new logical shift right.
7997         return BinaryOperator::CreateLShr(Op0, Op1);
7998       }
7999     }
8000     break;
8001   }
8002   return 0;
8003 }
8004
8005 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8006   if (Instruction *Result = commonIntCastTransforms(CI))
8007     return Result;
8008   
8009   Value *Src = CI.getOperand(0);
8010   const Type *Ty = CI.getType();
8011   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8012   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8013   
8014   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8015     switch (SrcI->getOpcode()) {
8016     default: break;
8017     case Instruction::LShr:
8018       // We can shrink lshr to something smaller if we know the bits shifted in
8019       // are already zeros.
8020       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8021         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8022         
8023         // Get a mask for the bits shifting in.
8024         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8025         Value* SrcIOp0 = SrcI->getOperand(0);
8026         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8027           if (ShAmt >= DestBitWidth)        // All zeros.
8028             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8029
8030           // Okay, we can shrink this.  Truncate the input, then return a new
8031           // shift.
8032           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8033           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8034                                        Ty, CI);
8035           return BinaryOperator::CreateLShr(V1, V2);
8036         }
8037       } else {     // This is a variable shr.
8038         
8039         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
8040         // more LLVM instructions, but allows '1 << Y' to be hoisted if
8041         // loop-invariant and CSE'd.
8042         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8043           Value *One = ConstantInt::get(SrcI->getType(), 1);
8044
8045           Value *V = InsertNewInstBefore(
8046               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8047                                      "tmp"), CI);
8048           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8049                                                             SrcI->getOperand(0),
8050                                                             "tmp"), CI);
8051           Value *Zero = Constant::getNullValue(V->getType());
8052           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8053         }
8054       }
8055       break;
8056     }
8057   }
8058   
8059   return 0;
8060 }
8061
8062 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8063 /// in order to eliminate the icmp.
8064 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8065                                              bool DoXform) {
8066   // If we are just checking for a icmp eq of a single bit and zext'ing it
8067   // to an integer, then shift the bit to the appropriate place and then
8068   // cast to integer to avoid the comparison.
8069   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8070     const APInt &Op1CV = Op1C->getValue();
8071       
8072     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8073     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8074     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8075         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8076       if (!DoXform) return ICI;
8077
8078       Value *In = ICI->getOperand(0);
8079       Value *Sh = ConstantInt::get(In->getType(),
8080                                    In->getType()->getPrimitiveSizeInBits()-1);
8081       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8082                                                         In->getName()+".lobit"),
8083                                CI);
8084       if (In->getType() != CI.getType())
8085         In = CastInst::CreateIntegerCast(In, CI.getType(),
8086                                          false/*ZExt*/, "tmp", &CI);
8087
8088       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8089         Constant *One = ConstantInt::get(In->getType(), 1);
8090         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8091                                                          In->getName()+".not"),
8092                                  CI);
8093       }
8094
8095       return ReplaceInstUsesWith(CI, In);
8096     }
8097       
8098       
8099       
8100     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8101     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8102     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8103     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8104     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8105     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8106     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8107     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8108     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8109         // This only works for EQ and NE
8110         ICI->isEquality()) {
8111       // If Op1C some other power of two, convert:
8112       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8113       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8114       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8115       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8116         
8117       APInt KnownZeroMask(~KnownZero);
8118       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8119         if (!DoXform) return ICI;
8120
8121         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8122         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8123           // (X&4) == 2 --> false
8124           // (X&4) != 2 --> true
8125           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8126           Res = ConstantExpr::getZExt(Res, CI.getType());
8127           return ReplaceInstUsesWith(CI, Res);
8128         }
8129           
8130         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8131         Value *In = ICI->getOperand(0);
8132         if (ShiftAmt) {
8133           // Perform a logical shr by shiftamt.
8134           // Insert the shift to put the result in the low bit.
8135           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8136                                   ConstantInt::get(In->getType(), ShiftAmt),
8137                                                    In->getName()+".lobit"), CI);
8138         }
8139           
8140         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8141           Constant *One = ConstantInt::get(In->getType(), 1);
8142           In = BinaryOperator::CreateXor(In, One, "tmp");
8143           InsertNewInstBefore(cast<Instruction>(In), CI);
8144         }
8145           
8146         if (CI.getType() == In->getType())
8147           return ReplaceInstUsesWith(CI, In);
8148         else
8149           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8150       }
8151     }
8152   }
8153
8154   return 0;
8155 }
8156
8157 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8158   // If one of the common conversion will work ..
8159   if (Instruction *Result = commonIntCastTransforms(CI))
8160     return Result;
8161
8162   Value *Src = CI.getOperand(0);
8163
8164   // If this is a cast of a cast
8165   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8166     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8167     // types and if the sizes are just right we can convert this into a logical
8168     // 'and' which will be much cheaper than the pair of casts.
8169     if (isa<TruncInst>(CSrc)) {
8170       // Get the sizes of the types involved
8171       Value *A = CSrc->getOperand(0);
8172       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8173       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8174       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8175       // If we're actually extending zero bits and the trunc is a no-op
8176       if (MidSize < DstSize && SrcSize == DstSize) {
8177         // Replace both of the casts with an And of the type mask.
8178         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8179         Constant *AndConst = ConstantInt::get(AndValue);
8180         Instruction *And = 
8181           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8182         // Unfortunately, if the type changed, we need to cast it back.
8183         if (And->getType() != CI.getType()) {
8184           And->setName(CSrc->getName()+".mask");
8185           InsertNewInstBefore(And, CI);
8186           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8187         }
8188         return And;
8189       }
8190     }
8191   }
8192
8193   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8194     return transformZExtICmp(ICI, CI);
8195
8196   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8197   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8198     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8199     // of the (zext icmp) will be transformed.
8200     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8201     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8202     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8203         (transformZExtICmp(LHS, CI, false) ||
8204          transformZExtICmp(RHS, CI, false))) {
8205       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8206       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8207       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8208     }
8209   }
8210
8211   return 0;
8212 }
8213
8214 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8215   if (Instruction *I = commonIntCastTransforms(CI))
8216     return I;
8217   
8218   Value *Src = CI.getOperand(0);
8219   
8220   // Canonicalize sign-extend from i1 to a select.
8221   if (Src->getType() == Type::Int1Ty)
8222     return SelectInst::Create(Src,
8223                               ConstantInt::getAllOnesValue(CI.getType()),
8224                               Constant::getNullValue(CI.getType()));
8225
8226   // See if the value being truncated is already sign extended.  If so, just
8227   // eliminate the trunc/sext pair.
8228   if (getOpcode(Src) == Instruction::Trunc) {
8229     Value *Op = cast<User>(Src)->getOperand(0);
8230     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8231     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8232     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8233     unsigned NumSignBits = ComputeNumSignBits(Op);
8234
8235     if (OpBits == DestBits) {
8236       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8237       // bits, it is already ready.
8238       if (NumSignBits > DestBits-MidBits)
8239         return ReplaceInstUsesWith(CI, Op);
8240     } else if (OpBits < DestBits) {
8241       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8242       // bits, just sext from i32.
8243       if (NumSignBits > OpBits-MidBits)
8244         return new SExtInst(Op, CI.getType(), "tmp");
8245     } else {
8246       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8247       // bits, just truncate to i32.
8248       if (NumSignBits > OpBits-MidBits)
8249         return new TruncInst(Op, CI.getType(), "tmp");
8250     }
8251   }
8252
8253   // If the input is a shl/ashr pair of a same constant, then this is a sign
8254   // extension from a smaller value.  If we could trust arbitrary bitwidth
8255   // integers, we could turn this into a truncate to the smaller bit and then
8256   // use a sext for the whole extension.  Since we don't, look deeper and check
8257   // for a truncate.  If the source and dest are the same type, eliminate the
8258   // trunc and extend and just do shifts.  For example, turn:
8259   //   %a = trunc i32 %i to i8
8260   //   %b = shl i8 %a, 6
8261   //   %c = ashr i8 %b, 6
8262   //   %d = sext i8 %c to i32
8263   // into:
8264   //   %a = shl i32 %i, 30
8265   //   %d = ashr i32 %a, 30
8266   Value *A = 0;
8267   ConstantInt *BA = 0, *CA = 0;
8268   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8269                         m_ConstantInt(CA))) &&
8270       BA == CA && isa<TruncInst>(A)) {
8271     Value *I = cast<TruncInst>(A)->getOperand(0);
8272     if (I->getType() == CI.getType()) {
8273       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8274       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8275       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8276       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8277       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8278                                                         CI.getName()), CI);
8279       return BinaryOperator::CreateAShr(I, ShAmtV);
8280     }
8281   }
8282   
8283   return 0;
8284 }
8285
8286 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8287 /// in the specified FP type without changing its value.
8288 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8289   bool losesInfo;
8290   APFloat F = CFP->getValueAPF();
8291   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8292   if (!losesInfo)
8293     return ConstantFP::get(F);
8294   return 0;
8295 }
8296
8297 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8298 /// through it until we get the source value.
8299 static Value *LookThroughFPExtensions(Value *V) {
8300   if (Instruction *I = dyn_cast<Instruction>(V))
8301     if (I->getOpcode() == Instruction::FPExt)
8302       return LookThroughFPExtensions(I->getOperand(0));
8303   
8304   // If this value is a constant, return the constant in the smallest FP type
8305   // that can accurately represent it.  This allows us to turn
8306   // (float)((double)X+2.0) into x+2.0f.
8307   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8308     if (CFP->getType() == Type::PPC_FP128Ty)
8309       return V;  // No constant folding of this.
8310     // See if the value can be truncated to float and then reextended.
8311     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8312       return V;
8313     if (CFP->getType() == Type::DoubleTy)
8314       return V;  // Won't shrink.
8315     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8316       return V;
8317     // Don't try to shrink to various long double types.
8318   }
8319   
8320   return V;
8321 }
8322
8323 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8324   if (Instruction *I = commonCastTransforms(CI))
8325     return I;
8326   
8327   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8328   // smaller than the destination type, we can eliminate the truncate by doing
8329   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8330   // many builtins (sqrt, etc).
8331   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8332   if (OpI && OpI->hasOneUse()) {
8333     switch (OpI->getOpcode()) {
8334     default: break;
8335     case Instruction::Add:
8336     case Instruction::Sub:
8337     case Instruction::Mul:
8338     case Instruction::FDiv:
8339     case Instruction::FRem:
8340       const Type *SrcTy = OpI->getType();
8341       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8342       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8343       if (LHSTrunc->getType() != SrcTy && 
8344           RHSTrunc->getType() != SrcTy) {
8345         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8346         // If the source types were both smaller than the destination type of
8347         // the cast, do this xform.
8348         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8349             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8350           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8351                                       CI.getType(), CI);
8352           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8353                                       CI.getType(), CI);
8354           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8355         }
8356       }
8357       break;  
8358     }
8359   }
8360   return 0;
8361 }
8362
8363 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8364   return commonCastTransforms(CI);
8365 }
8366
8367 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8368   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8369   if (OpI == 0)
8370     return commonCastTransforms(FI);
8371
8372   // fptoui(uitofp(X)) --> X
8373   // fptoui(sitofp(X)) --> X
8374   // This is safe if the intermediate type has enough bits in its mantissa to
8375   // accurately represent all values of X.  For example, do not do this with
8376   // i64->float->i64.  This is also safe for sitofp case, because any negative
8377   // 'X' value would cause an undefined result for the fptoui. 
8378   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8379       OpI->getOperand(0)->getType() == FI.getType() &&
8380       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8381                     OpI->getType()->getFPMantissaWidth())
8382     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8383
8384   return commonCastTransforms(FI);
8385 }
8386
8387 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8388   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8389   if (OpI == 0)
8390     return commonCastTransforms(FI);
8391   
8392   // fptosi(sitofp(X)) --> X
8393   // fptosi(uitofp(X)) --> X
8394   // This is safe if the intermediate type has enough bits in its mantissa to
8395   // accurately represent all values of X.  For example, do not do this with
8396   // i64->float->i64.  This is also safe for sitofp case, because any negative
8397   // 'X' value would cause an undefined result for the fptoui. 
8398   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8399       OpI->getOperand(0)->getType() == FI.getType() &&
8400       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8401                     OpI->getType()->getFPMantissaWidth())
8402     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8403   
8404   return commonCastTransforms(FI);
8405 }
8406
8407 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8408   return commonCastTransforms(CI);
8409 }
8410
8411 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8412   return commonCastTransforms(CI);
8413 }
8414
8415 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8416   return commonPointerCastTransforms(CI);
8417 }
8418
8419 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8420   if (Instruction *I = commonCastTransforms(CI))
8421     return I;
8422   
8423   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8424   if (!DestPointee->isSized()) return 0;
8425
8426   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8427   ConstantInt *Cst;
8428   Value *X;
8429   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8430                                     m_ConstantInt(Cst)))) {
8431     // If the source and destination operands have the same type, see if this
8432     // is a single-index GEP.
8433     if (X->getType() == CI.getType()) {
8434       // Get the size of the pointee type.
8435       uint64_t Size = TD->getABITypeSize(DestPointee);
8436
8437       // Convert the constant to intptr type.
8438       APInt Offset = Cst->getValue();
8439       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8440
8441       // If Offset is evenly divisible by Size, we can do this xform.
8442       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8443         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8444         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8445       }
8446     }
8447     // TODO: Could handle other cases, e.g. where add is indexing into field of
8448     // struct etc.
8449   } else if (CI.getOperand(0)->hasOneUse() &&
8450              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8451     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8452     // "inttoptr+GEP" instead of "add+intptr".
8453     
8454     // Get the size of the pointee type.
8455     uint64_t Size = TD->getABITypeSize(DestPointee);
8456     
8457     // Convert the constant to intptr type.
8458     APInt Offset = Cst->getValue();
8459     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8460     
8461     // If Offset is evenly divisible by Size, we can do this xform.
8462     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8463       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8464       
8465       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8466                                                             "tmp"), CI);
8467       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8468     }
8469   }
8470   return 0;
8471 }
8472
8473 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8474   // If the operands are integer typed then apply the integer transforms,
8475   // otherwise just apply the common ones.
8476   Value *Src = CI.getOperand(0);
8477   const Type *SrcTy = Src->getType();
8478   const Type *DestTy = CI.getType();
8479
8480   if (SrcTy->isInteger() && DestTy->isInteger()) {
8481     if (Instruction *Result = commonIntCastTransforms(CI))
8482       return Result;
8483   } else if (isa<PointerType>(SrcTy)) {
8484     if (Instruction *I = commonPointerCastTransforms(CI))
8485       return I;
8486   } else {
8487     if (Instruction *Result = commonCastTransforms(CI))
8488       return Result;
8489   }
8490
8491
8492   // Get rid of casts from one type to the same type. These are useless and can
8493   // be replaced by the operand.
8494   if (DestTy == Src->getType())
8495     return ReplaceInstUsesWith(CI, Src);
8496
8497   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8498     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8499     const Type *DstElTy = DstPTy->getElementType();
8500     const Type *SrcElTy = SrcPTy->getElementType();
8501     
8502     // If the address spaces don't match, don't eliminate the bitcast, which is
8503     // required for changing types.
8504     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8505       return 0;
8506     
8507     // If we are casting a malloc or alloca to a pointer to a type of the same
8508     // size, rewrite the allocation instruction to allocate the "right" type.
8509     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8510       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8511         return V;
8512     
8513     // If the source and destination are pointers, and this cast is equivalent
8514     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8515     // This can enhance SROA and other transforms that want type-safe pointers.
8516     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8517     unsigned NumZeros = 0;
8518     while (SrcElTy != DstElTy && 
8519            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8520            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8521       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8522       ++NumZeros;
8523     }
8524
8525     // If we found a path from the src to dest, create the getelementptr now.
8526     if (SrcElTy == DstElTy) {
8527       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8528       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8529                                        ((Instruction*) NULL));
8530     }
8531   }
8532
8533   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8534     if (SVI->hasOneUse()) {
8535       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8536       // a bitconvert to a vector with the same # elts.
8537       if (isa<VectorType>(DestTy) && 
8538           cast<VectorType>(DestTy)->getNumElements() ==
8539                 SVI->getType()->getNumElements() &&
8540           SVI->getType()->getNumElements() ==
8541             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8542         CastInst *Tmp;
8543         // If either of the operands is a cast from CI.getType(), then
8544         // evaluating the shuffle in the casted destination's type will allow
8545         // us to eliminate at least one cast.
8546         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8547              Tmp->getOperand(0)->getType() == DestTy) ||
8548             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8549              Tmp->getOperand(0)->getType() == DestTy)) {
8550           Value *LHS = InsertCastBefore(Instruction::BitCast,
8551                                         SVI->getOperand(0), DestTy, CI);
8552           Value *RHS = InsertCastBefore(Instruction::BitCast,
8553                                         SVI->getOperand(1), DestTy, CI);
8554           // Return a new shuffle vector.  Use the same element ID's, as we
8555           // know the vector types match #elts.
8556           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8557         }
8558       }
8559     }
8560   }
8561   return 0;
8562 }
8563
8564 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8565 ///   %C = or %A, %B
8566 ///   %D = select %cond, %C, %A
8567 /// into:
8568 ///   %C = select %cond, %B, 0
8569 ///   %D = or %A, %C
8570 ///
8571 /// Assuming that the specified instruction is an operand to the select, return
8572 /// a bitmask indicating which operands of this instruction are foldable if they
8573 /// equal the other incoming value of the select.
8574 ///
8575 static unsigned GetSelectFoldableOperands(Instruction *I) {
8576   switch (I->getOpcode()) {
8577   case Instruction::Add:
8578   case Instruction::Mul:
8579   case Instruction::And:
8580   case Instruction::Or:
8581   case Instruction::Xor:
8582     return 3;              // Can fold through either operand.
8583   case Instruction::Sub:   // Can only fold on the amount subtracted.
8584   case Instruction::Shl:   // Can only fold on the shift amount.
8585   case Instruction::LShr:
8586   case Instruction::AShr:
8587     return 1;
8588   default:
8589     return 0;              // Cannot fold
8590   }
8591 }
8592
8593 /// GetSelectFoldableConstant - For the same transformation as the previous
8594 /// function, return the identity constant that goes into the select.
8595 static Constant *GetSelectFoldableConstant(Instruction *I) {
8596   switch (I->getOpcode()) {
8597   default: assert(0 && "This cannot happen!"); abort();
8598   case Instruction::Add:
8599   case Instruction::Sub:
8600   case Instruction::Or:
8601   case Instruction::Xor:
8602   case Instruction::Shl:
8603   case Instruction::LShr:
8604   case Instruction::AShr:
8605     return Constant::getNullValue(I->getType());
8606   case Instruction::And:
8607     return Constant::getAllOnesValue(I->getType());
8608   case Instruction::Mul:
8609     return ConstantInt::get(I->getType(), 1);
8610   }
8611 }
8612
8613 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8614 /// have the same opcode and only one use each.  Try to simplify this.
8615 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8616                                           Instruction *FI) {
8617   if (TI->getNumOperands() == 1) {
8618     // If this is a non-volatile load or a cast from the same type,
8619     // merge.
8620     if (TI->isCast()) {
8621       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8622         return 0;
8623     } else {
8624       return 0;  // unknown unary op.
8625     }
8626
8627     // Fold this by inserting a select from the input values.
8628     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8629                                            FI->getOperand(0), SI.getName()+".v");
8630     InsertNewInstBefore(NewSI, SI);
8631     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8632                             TI->getType());
8633   }
8634
8635   // Only handle binary operators here.
8636   if (!isa<BinaryOperator>(TI))
8637     return 0;
8638
8639   // Figure out if the operations have any operands in common.
8640   Value *MatchOp, *OtherOpT, *OtherOpF;
8641   bool MatchIsOpZero;
8642   if (TI->getOperand(0) == FI->getOperand(0)) {
8643     MatchOp  = TI->getOperand(0);
8644     OtherOpT = TI->getOperand(1);
8645     OtherOpF = FI->getOperand(1);
8646     MatchIsOpZero = true;
8647   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8648     MatchOp  = TI->getOperand(1);
8649     OtherOpT = TI->getOperand(0);
8650     OtherOpF = FI->getOperand(0);
8651     MatchIsOpZero = false;
8652   } else if (!TI->isCommutative()) {
8653     return 0;
8654   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8655     MatchOp  = TI->getOperand(0);
8656     OtherOpT = TI->getOperand(1);
8657     OtherOpF = FI->getOperand(0);
8658     MatchIsOpZero = true;
8659   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8660     MatchOp  = TI->getOperand(1);
8661     OtherOpT = TI->getOperand(0);
8662     OtherOpF = FI->getOperand(1);
8663     MatchIsOpZero = true;
8664   } else {
8665     return 0;
8666   }
8667
8668   // If we reach here, they do have operations in common.
8669   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8670                                          OtherOpF, SI.getName()+".v");
8671   InsertNewInstBefore(NewSI, SI);
8672
8673   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8674     if (MatchIsOpZero)
8675       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8676     else
8677       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8678   }
8679   assert(0 && "Shouldn't get here");
8680   return 0;
8681 }
8682
8683 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8684 /// ICmpInst as its first operand.
8685 ///
8686 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8687                                                    ICmpInst *ICI) {
8688   bool Changed = false;
8689   ICmpInst::Predicate Pred = ICI->getPredicate();
8690   Value *CmpLHS = ICI->getOperand(0);
8691   Value *CmpRHS = ICI->getOperand(1);
8692   Value *TrueVal = SI.getTrueValue();
8693   Value *FalseVal = SI.getFalseValue();
8694
8695   // Check cases where the comparison is with a constant that
8696   // can be adjusted to fit the min/max idiom. We may edit ICI in
8697   // place here, so make sure the select is the only user.
8698   if (ICI->hasOneUse())
8699     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8700       switch (Pred) {
8701       default: break;
8702       case ICmpInst::ICMP_ULT:
8703       case ICmpInst::ICMP_SLT: {
8704         // X < MIN ? T : F  -->  F
8705         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8706           return ReplaceInstUsesWith(SI, FalseVal);
8707         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8708         Constant *AdjustedRHS = SubOne(CI);
8709         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8710             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8711           Pred = ICmpInst::getSwappedPredicate(Pred);
8712           CmpRHS = AdjustedRHS;
8713           std::swap(FalseVal, TrueVal);
8714           ICI->setPredicate(Pred);
8715           ICI->setOperand(1, CmpRHS);
8716           SI.setOperand(1, TrueVal);
8717           SI.setOperand(2, FalseVal);
8718           Changed = true;
8719         }
8720         break;
8721       }
8722       case ICmpInst::ICMP_UGT:
8723       case ICmpInst::ICMP_SGT: {
8724         // X > MAX ? T : F  -->  F
8725         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8726           return ReplaceInstUsesWith(SI, FalseVal);
8727         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8728         Constant *AdjustedRHS = AddOne(CI);
8729         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8730             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8731           Pred = ICmpInst::getSwappedPredicate(Pred);
8732           CmpRHS = AdjustedRHS;
8733           std::swap(FalseVal, TrueVal);
8734           ICI->setPredicate(Pred);
8735           ICI->setOperand(1, CmpRHS);
8736           SI.setOperand(1, TrueVal);
8737           SI.setOperand(2, FalseVal);
8738           Changed = true;
8739         }
8740         break;
8741       }
8742       }
8743
8744       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8745       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8746       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8747       if (match(TrueVal, m_ConstantInt(-1)) &&
8748           match(FalseVal, m_ConstantInt(0)))
8749         Pred = ICI->getPredicate();
8750       else if (match(TrueVal, m_ConstantInt(0)) &&
8751                match(FalseVal, m_ConstantInt(-1)))
8752         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8753       
8754       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8755         // If we are just checking for a icmp eq of a single bit and zext'ing it
8756         // to an integer, then shift the bit to the appropriate place and then
8757         // cast to integer to avoid the comparison.
8758         const APInt &Op1CV = CI->getValue();
8759     
8760         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8761         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8762         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8763             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8764           Value *In = ICI->getOperand(0);
8765           Value *Sh = ConstantInt::get(In->getType(),
8766                                        In->getType()->getPrimitiveSizeInBits()-1);
8767           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8768                                                           In->getName()+".lobit"),
8769                                    *ICI);
8770           if (In->getType() != SI.getType())
8771             In = CastInst::CreateIntegerCast(In, SI.getType(),
8772                                              true/*SExt*/, "tmp", ICI);
8773     
8774           if (Pred == ICmpInst::ICMP_SGT)
8775             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8776                                        In->getName()+".not"), *ICI);
8777     
8778           return ReplaceInstUsesWith(SI, In);
8779         }
8780       }
8781     }
8782
8783   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8784     // Transform (X == Y) ? X : Y  -> Y
8785     if (Pred == ICmpInst::ICMP_EQ)
8786       return ReplaceInstUsesWith(SI, FalseVal);
8787     // Transform (X != Y) ? X : Y  -> X
8788     if (Pred == ICmpInst::ICMP_NE)
8789       return ReplaceInstUsesWith(SI, TrueVal);
8790     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8791
8792   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8793     // Transform (X == Y) ? Y : X  -> X
8794     if (Pred == ICmpInst::ICMP_EQ)
8795       return ReplaceInstUsesWith(SI, FalseVal);
8796     // Transform (X != Y) ? Y : X  -> Y
8797     if (Pred == ICmpInst::ICMP_NE)
8798       return ReplaceInstUsesWith(SI, TrueVal);
8799     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8800   }
8801
8802   /// NOTE: if we wanted to, this is where to detect integer ABS
8803
8804   return Changed ? &SI : 0;
8805 }
8806
8807 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8808   Value *CondVal = SI.getCondition();
8809   Value *TrueVal = SI.getTrueValue();
8810   Value *FalseVal = SI.getFalseValue();
8811
8812   // select true, X, Y  -> X
8813   // select false, X, Y -> Y
8814   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8815     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8816
8817   // select C, X, X -> X
8818   if (TrueVal == FalseVal)
8819     return ReplaceInstUsesWith(SI, TrueVal);
8820
8821   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8822     return ReplaceInstUsesWith(SI, FalseVal);
8823   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8824     return ReplaceInstUsesWith(SI, TrueVal);
8825   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8826     if (isa<Constant>(TrueVal))
8827       return ReplaceInstUsesWith(SI, TrueVal);
8828     else
8829       return ReplaceInstUsesWith(SI, FalseVal);
8830   }
8831
8832   if (SI.getType() == Type::Int1Ty) {
8833     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8834       if (C->getZExtValue()) {
8835         // Change: A = select B, true, C --> A = or B, C
8836         return BinaryOperator::CreateOr(CondVal, FalseVal);
8837       } else {
8838         // Change: A = select B, false, C --> A = and !B, C
8839         Value *NotCond =
8840           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8841                                              "not."+CondVal->getName()), SI);
8842         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8843       }
8844     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8845       if (C->getZExtValue() == false) {
8846         // Change: A = select B, C, false --> A = and B, C
8847         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8848       } else {
8849         // Change: A = select B, C, true --> A = or !B, C
8850         Value *NotCond =
8851           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8852                                              "not."+CondVal->getName()), SI);
8853         return BinaryOperator::CreateOr(NotCond, TrueVal);
8854       }
8855     }
8856     
8857     // select a, b, a  -> a&b
8858     // select a, a, b  -> a|b
8859     if (CondVal == TrueVal)
8860       return BinaryOperator::CreateOr(CondVal, FalseVal);
8861     else if (CondVal == FalseVal)
8862       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8863   }
8864
8865   // Selecting between two integer constants?
8866   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8867     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8868       // select C, 1, 0 -> zext C to int
8869       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8870         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8871       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8872         // select C, 0, 1 -> zext !C to int
8873         Value *NotCond =
8874           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8875                                                "not."+CondVal->getName()), SI);
8876         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8877       }
8878
8879       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8880
8881         // (x <s 0) ? -1 : 0 -> ashr x, 31
8882         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8883           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8884             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8885               // The comparison constant and the result are not neccessarily the
8886               // same width. Make an all-ones value by inserting a AShr.
8887               Value *X = IC->getOperand(0);
8888               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8889               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8890               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8891                                                         ShAmt, "ones");
8892               InsertNewInstBefore(SRA, SI);
8893
8894               // Then cast to the appropriate width.
8895               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
8896             }
8897           }
8898
8899
8900         // If one of the constants is zero (we know they can't both be) and we
8901         // have an icmp instruction with zero, and we have an 'and' with the
8902         // non-constant value, eliminate this whole mess.  This corresponds to
8903         // cases like this: ((X & 27) ? 27 : 0)
8904         if (TrueValC->isZero() || FalseValC->isZero())
8905           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8906               cast<Constant>(IC->getOperand(1))->isNullValue())
8907             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8908               if (ICA->getOpcode() == Instruction::And &&
8909                   isa<ConstantInt>(ICA->getOperand(1)) &&
8910                   (ICA->getOperand(1) == TrueValC ||
8911                    ICA->getOperand(1) == FalseValC) &&
8912                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8913                 // Okay, now we know that everything is set up, we just don't
8914                 // know whether we have a icmp_ne or icmp_eq and whether the 
8915                 // true or false val is the zero.
8916                 bool ShouldNotVal = !TrueValC->isZero();
8917                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8918                 Value *V = ICA;
8919                 if (ShouldNotVal)
8920                   V = InsertNewInstBefore(BinaryOperator::Create(
8921                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8922                 return ReplaceInstUsesWith(SI, V);
8923               }
8924       }
8925     }
8926
8927   // See if we are selecting two values based on a comparison of the two values.
8928   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8929     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8930       // Transform (X == Y) ? X : Y  -> Y
8931       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8932         // This is not safe in general for floating point:  
8933         // consider X== -0, Y== +0.
8934         // It becomes safe if either operand is a nonzero constant.
8935         ConstantFP *CFPt, *CFPf;
8936         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8937               !CFPt->getValueAPF().isZero()) ||
8938             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8939              !CFPf->getValueAPF().isZero()))
8940         return ReplaceInstUsesWith(SI, FalseVal);
8941       }
8942       // Transform (X != Y) ? X : Y  -> X
8943       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8944         return ReplaceInstUsesWith(SI, TrueVal);
8945       // NOTE: if we wanted to, this is where to detect MIN/MAX
8946
8947     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8948       // Transform (X == Y) ? Y : X  -> X
8949       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8950         // This is not safe in general for floating point:  
8951         // consider X== -0, Y== +0.
8952         // It becomes safe if either operand is a nonzero constant.
8953         ConstantFP *CFPt, *CFPf;
8954         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8955               !CFPt->getValueAPF().isZero()) ||
8956             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8957              !CFPf->getValueAPF().isZero()))
8958           return ReplaceInstUsesWith(SI, FalseVal);
8959       }
8960       // Transform (X != Y) ? Y : X  -> Y
8961       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8962         return ReplaceInstUsesWith(SI, TrueVal);
8963       // NOTE: if we wanted to, this is where to detect MIN/MAX
8964     }
8965     // NOTE: if we wanted to, this is where to detect ABS
8966   }
8967
8968   // See if we are selecting two values based on a comparison of the two values.
8969   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8970     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8971       return Result;
8972
8973   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8974     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8975       if (TI->hasOneUse() && FI->hasOneUse()) {
8976         Instruction *AddOp = 0, *SubOp = 0;
8977
8978         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8979         if (TI->getOpcode() == FI->getOpcode())
8980           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8981             return IV;
8982
8983         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8984         // even legal for FP.
8985         if (TI->getOpcode() == Instruction::Sub &&
8986             FI->getOpcode() == Instruction::Add) {
8987           AddOp = FI; SubOp = TI;
8988         } else if (FI->getOpcode() == Instruction::Sub &&
8989                    TI->getOpcode() == Instruction::Add) {
8990           AddOp = TI; SubOp = FI;
8991         }
8992
8993         if (AddOp) {
8994           Value *OtherAddOp = 0;
8995           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8996             OtherAddOp = AddOp->getOperand(1);
8997           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8998             OtherAddOp = AddOp->getOperand(0);
8999           }
9000
9001           if (OtherAddOp) {
9002             // So at this point we know we have (Y -> OtherAddOp):
9003             //        select C, (add X, Y), (sub X, Z)
9004             Value *NegVal;  // Compute -Z
9005             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9006               NegVal = ConstantExpr::getNeg(C);
9007             } else {
9008               NegVal = InsertNewInstBefore(
9009                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9010             }
9011
9012             Value *NewTrueOp = OtherAddOp;
9013             Value *NewFalseOp = NegVal;
9014             if (AddOp != TI)
9015               std::swap(NewTrueOp, NewFalseOp);
9016             Instruction *NewSel =
9017               SelectInst::Create(CondVal, NewTrueOp,
9018                                  NewFalseOp, SI.getName() + ".p");
9019
9020             NewSel = InsertNewInstBefore(NewSel, SI);
9021             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9022           }
9023         }
9024       }
9025
9026   // See if we can fold the select into one of our operands.
9027   if (SI.getType()->isInteger()) {
9028     // See the comment above GetSelectFoldableOperands for a description of the
9029     // transformation we are doing here.
9030     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9031       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9032           !isa<Constant>(FalseVal))
9033         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9034           unsigned OpToFold = 0;
9035           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9036             OpToFold = 1;
9037           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9038             OpToFold = 2;
9039           }
9040
9041           if (OpToFold) {
9042             Constant *C = GetSelectFoldableConstant(TVI);
9043             Instruction *NewSel =
9044               SelectInst::Create(SI.getCondition(),
9045                                  TVI->getOperand(2-OpToFold), C);
9046             InsertNewInstBefore(NewSel, SI);
9047             NewSel->takeName(TVI);
9048             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9049               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9050             else {
9051               assert(0 && "Unknown instruction!!");
9052             }
9053           }
9054         }
9055
9056     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9057       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9058           !isa<Constant>(TrueVal))
9059         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9060           unsigned OpToFold = 0;
9061           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9062             OpToFold = 1;
9063           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9064             OpToFold = 2;
9065           }
9066
9067           if (OpToFold) {
9068             Constant *C = GetSelectFoldableConstant(FVI);
9069             Instruction *NewSel =
9070               SelectInst::Create(SI.getCondition(), C,
9071                                  FVI->getOperand(2-OpToFold));
9072             InsertNewInstBefore(NewSel, SI);
9073             NewSel->takeName(FVI);
9074             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9075               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9076             else
9077               assert(0 && "Unknown instruction!!");
9078           }
9079         }
9080   }
9081
9082   if (BinaryOperator::isNot(CondVal)) {
9083     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9084     SI.setOperand(1, FalseVal);
9085     SI.setOperand(2, TrueVal);
9086     return &SI;
9087   }
9088
9089   return 0;
9090 }
9091
9092 /// EnforceKnownAlignment - If the specified pointer points to an object that
9093 /// we control, modify the object's alignment to PrefAlign. This isn't
9094 /// often possible though. If alignment is important, a more reliable approach
9095 /// is to simply align all global variables and allocation instructions to
9096 /// their preferred alignment from the beginning.
9097 ///
9098 static unsigned EnforceKnownAlignment(Value *V,
9099                                       unsigned Align, unsigned PrefAlign) {
9100
9101   User *U = dyn_cast<User>(V);
9102   if (!U) return Align;
9103
9104   switch (getOpcode(U)) {
9105   default: break;
9106   case Instruction::BitCast:
9107     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9108   case Instruction::GetElementPtr: {
9109     // If all indexes are zero, it is just the alignment of the base pointer.
9110     bool AllZeroOperands = true;
9111     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9112       if (!isa<Constant>(*i) ||
9113           !cast<Constant>(*i)->isNullValue()) {
9114         AllZeroOperands = false;
9115         break;
9116       }
9117
9118     if (AllZeroOperands) {
9119       // Treat this like a bitcast.
9120       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9121     }
9122     break;
9123   }
9124   }
9125
9126   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9127     // If there is a large requested alignment and we can, bump up the alignment
9128     // of the global.
9129     if (!GV->isDeclaration()) {
9130       GV->setAlignment(PrefAlign);
9131       Align = PrefAlign;
9132     }
9133   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9134     // If there is a requested alignment and if this is an alloca, round up.  We
9135     // don't do this for malloc, because some systems can't respect the request.
9136     if (isa<AllocaInst>(AI)) {
9137       AI->setAlignment(PrefAlign);
9138       Align = PrefAlign;
9139     }
9140   }
9141
9142   return Align;
9143 }
9144
9145 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9146 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9147 /// and it is more than the alignment of the ultimate object, see if we can
9148 /// increase the alignment of the ultimate object, making this check succeed.
9149 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9150                                                   unsigned PrefAlign) {
9151   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9152                       sizeof(PrefAlign) * CHAR_BIT;
9153   APInt Mask = APInt::getAllOnesValue(BitWidth);
9154   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9155   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9156   unsigned TrailZ = KnownZero.countTrailingOnes();
9157   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9158
9159   if (PrefAlign > Align)
9160     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9161   
9162     // We don't need to make any adjustment.
9163   return Align;
9164 }
9165
9166 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9167   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9168   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9169   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9170   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9171
9172   if (CopyAlign < MinAlign) {
9173     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9174     return MI;
9175   }
9176   
9177   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9178   // load/store.
9179   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9180   if (MemOpLength == 0) return 0;
9181   
9182   // Source and destination pointer types are always "i8*" for intrinsic.  See
9183   // if the size is something we can handle with a single primitive load/store.
9184   // A single load+store correctly handles overlapping memory in the memmove
9185   // case.
9186   unsigned Size = MemOpLength->getZExtValue();
9187   if (Size == 0) return MI;  // Delete this mem transfer.
9188   
9189   if (Size > 8 || (Size&(Size-1)))
9190     return 0;  // If not 1/2/4/8 bytes, exit.
9191   
9192   // Use an integer load+store unless we can find something better.
9193   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9194   
9195   // Memcpy forces the use of i8* for the source and destination.  That means
9196   // that if you're using memcpy to move one double around, you'll get a cast
9197   // from double* to i8*.  We'd much rather use a double load+store rather than
9198   // an i64 load+store, here because this improves the odds that the source or
9199   // dest address will be promotable.  See if we can find a better type than the
9200   // integer datatype.
9201   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9202     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9203     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9204       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9205       // down through these levels if so.
9206       while (!SrcETy->isSingleValueType()) {
9207         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9208           if (STy->getNumElements() == 1)
9209             SrcETy = STy->getElementType(0);
9210           else
9211             break;
9212         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9213           if (ATy->getNumElements() == 1)
9214             SrcETy = ATy->getElementType();
9215           else
9216             break;
9217         } else
9218           break;
9219       }
9220       
9221       if (SrcETy->isSingleValueType())
9222         NewPtrTy = PointerType::getUnqual(SrcETy);
9223     }
9224   }
9225   
9226   
9227   // If the memcpy/memmove provides better alignment info than we can
9228   // infer, use it.
9229   SrcAlign = std::max(SrcAlign, CopyAlign);
9230   DstAlign = std::max(DstAlign, CopyAlign);
9231   
9232   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9233   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9234   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9235   InsertNewInstBefore(L, *MI);
9236   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9237
9238   // Set the size of the copy to 0, it will be deleted on the next iteration.
9239   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9240   return MI;
9241 }
9242
9243 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9244   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9245   if (MI->getAlignment()->getZExtValue() < Alignment) {
9246     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9247     return MI;
9248   }
9249   
9250   // Extract the length and alignment and fill if they are constant.
9251   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9252   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9253   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9254     return 0;
9255   uint64_t Len = LenC->getZExtValue();
9256   Alignment = MI->getAlignment()->getZExtValue();
9257   
9258   // If the length is zero, this is a no-op
9259   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9260   
9261   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9262   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9263     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9264     
9265     Value *Dest = MI->getDest();
9266     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9267
9268     // Alignment 0 is identity for alignment 1 for memset, but not store.
9269     if (Alignment == 0) Alignment = 1;
9270     
9271     // Extract the fill value and store.
9272     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9273     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9274                                       Alignment), *MI);
9275     
9276     // Set the size of the copy to 0, it will be deleted on the next iteration.
9277     MI->setLength(Constant::getNullValue(LenC->getType()));
9278     return MI;
9279   }
9280
9281   return 0;
9282 }
9283
9284
9285 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9286 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9287 /// the heavy lifting.
9288 ///
9289 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9290   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9291   if (!II) return visitCallSite(&CI);
9292   
9293   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9294   // visitCallSite.
9295   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9296     bool Changed = false;
9297
9298     // memmove/cpy/set of zero bytes is a noop.
9299     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9300       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9301
9302       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9303         if (CI->getZExtValue() == 1) {
9304           // Replace the instruction with just byte operations.  We would
9305           // transform other cases to loads/stores, but we don't know if
9306           // alignment is sufficient.
9307         }
9308     }
9309
9310     // If we have a memmove and the source operation is a constant global,
9311     // then the source and dest pointers can't alias, so we can change this
9312     // into a call to memcpy.
9313     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9314       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9315         if (GVSrc->isConstant()) {
9316           Module *M = CI.getParent()->getParent()->getParent();
9317           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9318           const Type *Tys[1];
9319           Tys[0] = CI.getOperand(3)->getType();
9320           CI.setOperand(0, 
9321                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9322           Changed = true;
9323         }
9324
9325       // memmove(x,x,size) -> noop.
9326       if (MMI->getSource() == MMI->getDest())
9327         return EraseInstFromFunction(CI);
9328     }
9329
9330     // If we can determine a pointer alignment that is bigger than currently
9331     // set, update the alignment.
9332     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9333       if (Instruction *I = SimplifyMemTransfer(MI))
9334         return I;
9335     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9336       if (Instruction *I = SimplifyMemSet(MSI))
9337         return I;
9338     }
9339           
9340     if (Changed) return II;
9341   }
9342   
9343   switch (II->getIntrinsicID()) {
9344   default: break;
9345   case Intrinsic::bswap:
9346     // bswap(bswap(x)) -> x
9347     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9348       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9349         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9350     break;
9351   case Intrinsic::ppc_altivec_lvx:
9352   case Intrinsic::ppc_altivec_lvxl:
9353   case Intrinsic::x86_sse_loadu_ps:
9354   case Intrinsic::x86_sse2_loadu_pd:
9355   case Intrinsic::x86_sse2_loadu_dq:
9356     // Turn PPC lvx     -> load if the pointer is known aligned.
9357     // Turn X86 loadups -> load if the pointer is known aligned.
9358     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9359       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9360                                        PointerType::getUnqual(II->getType()),
9361                                        CI);
9362       return new LoadInst(Ptr);
9363     }
9364     break;
9365   case Intrinsic::ppc_altivec_stvx:
9366   case Intrinsic::ppc_altivec_stvxl:
9367     // Turn stvx -> store if the pointer is known aligned.
9368     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9369       const Type *OpPtrTy = 
9370         PointerType::getUnqual(II->getOperand(1)->getType());
9371       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9372       return new StoreInst(II->getOperand(1), Ptr);
9373     }
9374     break;
9375   case Intrinsic::x86_sse_storeu_ps:
9376   case Intrinsic::x86_sse2_storeu_pd:
9377   case Intrinsic::x86_sse2_storeu_dq:
9378     // Turn X86 storeu -> store if the pointer is known aligned.
9379     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9380       const Type *OpPtrTy = 
9381         PointerType::getUnqual(II->getOperand(2)->getType());
9382       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9383       return new StoreInst(II->getOperand(2), Ptr);
9384     }
9385     break;
9386     
9387   case Intrinsic::x86_sse_cvttss2si: {
9388     // These intrinsics only demands the 0th element of its input vector.  If
9389     // we can simplify the input based on that, do so now.
9390     uint64_t UndefElts;
9391     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9392                                               UndefElts)) {
9393       II->setOperand(1, V);
9394       return II;
9395     }
9396     break;
9397   }
9398     
9399   case Intrinsic::ppc_altivec_vperm:
9400     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9401     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9402       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9403       
9404       // Check that all of the elements are integer constants or undefs.
9405       bool AllEltsOk = true;
9406       for (unsigned i = 0; i != 16; ++i) {
9407         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9408             !isa<UndefValue>(Mask->getOperand(i))) {
9409           AllEltsOk = false;
9410           break;
9411         }
9412       }
9413       
9414       if (AllEltsOk) {
9415         // Cast the input vectors to byte vectors.
9416         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9417         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9418         Value *Result = UndefValue::get(Op0->getType());
9419         
9420         // Only extract each element once.
9421         Value *ExtractedElts[32];
9422         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9423         
9424         for (unsigned i = 0; i != 16; ++i) {
9425           if (isa<UndefValue>(Mask->getOperand(i)))
9426             continue;
9427           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9428           Idx &= 31;  // Match the hardware behavior.
9429           
9430           if (ExtractedElts[Idx] == 0) {
9431             Instruction *Elt = 
9432               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9433             InsertNewInstBefore(Elt, CI);
9434             ExtractedElts[Idx] = Elt;
9435           }
9436         
9437           // Insert this value into the result vector.
9438           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9439                                              i, "tmp");
9440           InsertNewInstBefore(cast<Instruction>(Result), CI);
9441         }
9442         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9443       }
9444     }
9445     break;
9446
9447   case Intrinsic::stackrestore: {
9448     // If the save is right next to the restore, remove the restore.  This can
9449     // happen when variable allocas are DCE'd.
9450     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9451       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9452         BasicBlock::iterator BI = SS;
9453         if (&*++BI == II)
9454           return EraseInstFromFunction(CI);
9455       }
9456     }
9457     
9458     // Scan down this block to see if there is another stack restore in the
9459     // same block without an intervening call/alloca.
9460     BasicBlock::iterator BI = II;
9461     TerminatorInst *TI = II->getParent()->getTerminator();
9462     bool CannotRemove = false;
9463     for (++BI; &*BI != TI; ++BI) {
9464       if (isa<AllocaInst>(BI)) {
9465         CannotRemove = true;
9466         break;
9467       }
9468       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9469         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9470           // If there is a stackrestore below this one, remove this one.
9471           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9472             return EraseInstFromFunction(CI);
9473           // Otherwise, ignore the intrinsic.
9474         } else {
9475           // If we found a non-intrinsic call, we can't remove the stack
9476           // restore.
9477           CannotRemove = true;
9478           break;
9479         }
9480       }
9481     }
9482     
9483     // If the stack restore is in a return/unwind block and if there are no
9484     // allocas or calls between the restore and the return, nuke the restore.
9485     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9486       return EraseInstFromFunction(CI);
9487     break;
9488   }
9489   }
9490
9491   return visitCallSite(II);
9492 }
9493
9494 // InvokeInst simplification
9495 //
9496 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9497   return visitCallSite(&II);
9498 }
9499
9500 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9501 /// passed through the varargs area, we can eliminate the use of the cast.
9502 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9503                                          const CastInst * const CI,
9504                                          const TargetData * const TD,
9505                                          const int ix) {
9506   if (!CI->isLosslessCast())
9507     return false;
9508
9509   // The size of ByVal arguments is derived from the type, so we
9510   // can't change to a type with a different size.  If the size were
9511   // passed explicitly we could avoid this check.
9512   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9513     return true;
9514
9515   const Type* SrcTy = 
9516             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9517   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9518   if (!SrcTy->isSized() || !DstTy->isSized())
9519     return false;
9520   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9521     return false;
9522   return true;
9523 }
9524
9525 // visitCallSite - Improvements for call and invoke instructions.
9526 //
9527 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9528   bool Changed = false;
9529
9530   // If the callee is a constexpr cast of a function, attempt to move the cast
9531   // to the arguments of the call/invoke.
9532   if (transformConstExprCastCall(CS)) return 0;
9533
9534   Value *Callee = CS.getCalledValue();
9535
9536   if (Function *CalleeF = dyn_cast<Function>(Callee))
9537     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9538       Instruction *OldCall = CS.getInstruction();
9539       // If the call and callee calling conventions don't match, this call must
9540       // be unreachable, as the call is undefined.
9541       new StoreInst(ConstantInt::getTrue(),
9542                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9543                                     OldCall);
9544       if (!OldCall->use_empty())
9545         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9546       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9547         return EraseInstFromFunction(*OldCall);
9548       return 0;
9549     }
9550
9551   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9552     // This instruction is not reachable, just remove it.  We insert a store to
9553     // undef so that we know that this code is not reachable, despite the fact
9554     // that we can't modify the CFG here.
9555     new StoreInst(ConstantInt::getTrue(),
9556                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9557                   CS.getInstruction());
9558
9559     if (!CS.getInstruction()->use_empty())
9560       CS.getInstruction()->
9561         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9562
9563     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9564       // Don't break the CFG, insert a dummy cond branch.
9565       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9566                          ConstantInt::getTrue(), II);
9567     }
9568     return EraseInstFromFunction(*CS.getInstruction());
9569   }
9570
9571   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9572     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9573       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9574         return transformCallThroughTrampoline(CS);
9575
9576   const PointerType *PTy = cast<PointerType>(Callee->getType());
9577   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9578   if (FTy->isVarArg()) {
9579     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9580     // See if we can optimize any arguments passed through the varargs area of
9581     // the call.
9582     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9583            E = CS.arg_end(); I != E; ++I, ++ix) {
9584       CastInst *CI = dyn_cast<CastInst>(*I);
9585       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9586         *I = CI->getOperand(0);
9587         Changed = true;
9588       }
9589     }
9590   }
9591
9592   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9593     // Inline asm calls cannot throw - mark them 'nounwind'.
9594     CS.setDoesNotThrow();
9595     Changed = true;
9596   }
9597
9598   return Changed ? CS.getInstruction() : 0;
9599 }
9600
9601 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9602 // attempt to move the cast to the arguments of the call/invoke.
9603 //
9604 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9605   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9606   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9607   if (CE->getOpcode() != Instruction::BitCast || 
9608       !isa<Function>(CE->getOperand(0)))
9609     return false;
9610   Function *Callee = cast<Function>(CE->getOperand(0));
9611   Instruction *Caller = CS.getInstruction();
9612   const AttrListPtr &CallerPAL = CS.getAttributes();
9613
9614   // Okay, this is a cast from a function to a different type.  Unless doing so
9615   // would cause a type conversion of one of our arguments, change this call to
9616   // be a direct call with arguments casted to the appropriate types.
9617   //
9618   const FunctionType *FT = Callee->getFunctionType();
9619   const Type *OldRetTy = Caller->getType();
9620   const Type *NewRetTy = FT->getReturnType();
9621
9622   if (isa<StructType>(NewRetTy))
9623     return false; // TODO: Handle multiple return values.
9624
9625   // Check to see if we are changing the return type...
9626   if (OldRetTy != NewRetTy) {
9627     if (Callee->isDeclaration() &&
9628         // Conversion is ok if changing from one pointer type to another or from
9629         // a pointer to an integer of the same size.
9630         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9631           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9632       return false;   // Cannot transform this return value.
9633
9634     if (!Caller->use_empty() &&
9635         // void -> non-void is handled specially
9636         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9637       return false;   // Cannot transform this return value.
9638
9639     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9640       Attributes RAttrs = CallerPAL.getRetAttributes();
9641       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9642         return false;   // Attribute not compatible with transformed value.
9643     }
9644
9645     // If the callsite is an invoke instruction, and the return value is used by
9646     // a PHI node in a successor, we cannot change the return type of the call
9647     // because there is no place to put the cast instruction (without breaking
9648     // the critical edge).  Bail out in this case.
9649     if (!Caller->use_empty())
9650       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9651         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9652              UI != E; ++UI)
9653           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9654             if (PN->getParent() == II->getNormalDest() ||
9655                 PN->getParent() == II->getUnwindDest())
9656               return false;
9657   }
9658
9659   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9660   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9661
9662   CallSite::arg_iterator AI = CS.arg_begin();
9663   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9664     const Type *ParamTy = FT->getParamType(i);
9665     const Type *ActTy = (*AI)->getType();
9666
9667     if (!CastInst::isCastable(ActTy, ParamTy))
9668       return false;   // Cannot transform this parameter value.
9669
9670     if (CallerPAL.getParamAttributes(i + 1) 
9671         & Attribute::typeIncompatible(ParamTy))
9672       return false;   // Attribute not compatible with transformed value.
9673
9674     // Converting from one pointer type to another or between a pointer and an
9675     // integer of the same size is safe even if we do not have a body.
9676     bool isConvertible = ActTy == ParamTy ||
9677       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9678        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9679     if (Callee->isDeclaration() && !isConvertible) return false;
9680   }
9681
9682   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9683       Callee->isDeclaration())
9684     return false;   // Do not delete arguments unless we have a function body.
9685
9686   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9687       !CallerPAL.isEmpty())
9688     // In this case we have more arguments than the new function type, but we
9689     // won't be dropping them.  Check that these extra arguments have attributes
9690     // that are compatible with being a vararg call argument.
9691     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9692       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9693         break;
9694       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9695       if (PAttrs & Attribute::VarArgsIncompatible)
9696         return false;
9697     }
9698
9699   // Okay, we decided that this is a safe thing to do: go ahead and start
9700   // inserting cast instructions as necessary...
9701   std::vector<Value*> Args;
9702   Args.reserve(NumActualArgs);
9703   SmallVector<AttributeWithIndex, 8> attrVec;
9704   attrVec.reserve(NumCommonArgs);
9705
9706   // Get any return attributes.
9707   Attributes RAttrs = CallerPAL.getRetAttributes();
9708
9709   // If the return value is not being used, the type may not be compatible
9710   // with the existing attributes.  Wipe out any problematic attributes.
9711   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9712
9713   // Add the new return attributes.
9714   if (RAttrs)
9715     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9716
9717   AI = CS.arg_begin();
9718   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9719     const Type *ParamTy = FT->getParamType(i);
9720     if ((*AI)->getType() == ParamTy) {
9721       Args.push_back(*AI);
9722     } else {
9723       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9724           false, ParamTy, false);
9725       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9726       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9727     }
9728
9729     // Add any parameter attributes.
9730     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9731       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9732   }
9733
9734   // If the function takes more arguments than the call was taking, add them
9735   // now...
9736   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9737     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9738
9739   // If we are removing arguments to the function, emit an obnoxious warning...
9740   if (FT->getNumParams() < NumActualArgs) {
9741     if (!FT->isVarArg()) {
9742       cerr << "WARNING: While resolving call to function '"
9743            << Callee->getName() << "' arguments were dropped!\n";
9744     } else {
9745       // Add all of the arguments in their promoted form to the arg list...
9746       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9747         const Type *PTy = getPromotedType((*AI)->getType());
9748         if (PTy != (*AI)->getType()) {
9749           // Must promote to pass through va_arg area!
9750           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9751                                                                 PTy, false);
9752           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9753           InsertNewInstBefore(Cast, *Caller);
9754           Args.push_back(Cast);
9755         } else {
9756           Args.push_back(*AI);
9757         }
9758
9759         // Add any parameter attributes.
9760         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9761           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9762       }
9763     }
9764   }
9765
9766   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9767     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9768
9769   if (NewRetTy == Type::VoidTy)
9770     Caller->setName("");   // Void type should not have a name.
9771
9772   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9773
9774   Instruction *NC;
9775   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9776     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9777                             Args.begin(), Args.end(),
9778                             Caller->getName(), Caller);
9779     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9780     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9781   } else {
9782     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9783                           Caller->getName(), Caller);
9784     CallInst *CI = cast<CallInst>(Caller);
9785     if (CI->isTailCall())
9786       cast<CallInst>(NC)->setTailCall();
9787     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9788     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9789   }
9790
9791   // Insert a cast of the return type as necessary.
9792   Value *NV = NC;
9793   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9794     if (NV->getType() != Type::VoidTy) {
9795       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9796                                                             OldRetTy, false);
9797       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9798
9799       // If this is an invoke instruction, we should insert it after the first
9800       // non-phi, instruction in the normal successor block.
9801       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9802         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9803         InsertNewInstBefore(NC, *I);
9804       } else {
9805         // Otherwise, it's a call, just insert cast right after the call instr
9806         InsertNewInstBefore(NC, *Caller);
9807       }
9808       AddUsersToWorkList(*Caller);
9809     } else {
9810       NV = UndefValue::get(Caller->getType());
9811     }
9812   }
9813
9814   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9815     Caller->replaceAllUsesWith(NV);
9816   Caller->eraseFromParent();
9817   RemoveFromWorkList(Caller);
9818   return true;
9819 }
9820
9821 // transformCallThroughTrampoline - Turn a call to a function created by the
9822 // init_trampoline intrinsic into a direct call to the underlying function.
9823 //
9824 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9825   Value *Callee = CS.getCalledValue();
9826   const PointerType *PTy = cast<PointerType>(Callee->getType());
9827   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9828   const AttrListPtr &Attrs = CS.getAttributes();
9829
9830   // If the call already has the 'nest' attribute somewhere then give up -
9831   // otherwise 'nest' would occur twice after splicing in the chain.
9832   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9833     return 0;
9834
9835   IntrinsicInst *Tramp =
9836     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9837
9838   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9839   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9840   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9841
9842   const AttrListPtr &NestAttrs = NestF->getAttributes();
9843   if (!NestAttrs.isEmpty()) {
9844     unsigned NestIdx = 1;
9845     const Type *NestTy = 0;
9846     Attributes NestAttr = Attribute::None;
9847
9848     // Look for a parameter marked with the 'nest' attribute.
9849     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9850          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9851       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9852         // Record the parameter type and any other attributes.
9853         NestTy = *I;
9854         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9855         break;
9856       }
9857
9858     if (NestTy) {
9859       Instruction *Caller = CS.getInstruction();
9860       std::vector<Value*> NewArgs;
9861       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9862
9863       SmallVector<AttributeWithIndex, 8> NewAttrs;
9864       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9865
9866       // Insert the nest argument into the call argument list, which may
9867       // mean appending it.  Likewise for attributes.
9868
9869       // Add any result attributes.
9870       if (Attributes Attr = Attrs.getRetAttributes())
9871         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9872
9873       {
9874         unsigned Idx = 1;
9875         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9876         do {
9877           if (Idx == NestIdx) {
9878             // Add the chain argument and attributes.
9879             Value *NestVal = Tramp->getOperand(3);
9880             if (NestVal->getType() != NestTy)
9881               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9882             NewArgs.push_back(NestVal);
9883             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9884           }
9885
9886           if (I == E)
9887             break;
9888
9889           // Add the original argument and attributes.
9890           NewArgs.push_back(*I);
9891           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9892             NewAttrs.push_back
9893               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9894
9895           ++Idx, ++I;
9896         } while (1);
9897       }
9898
9899       // Add any function attributes.
9900       if (Attributes Attr = Attrs.getFnAttributes())
9901         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9902
9903       // The trampoline may have been bitcast to a bogus type (FTy).
9904       // Handle this by synthesizing a new function type, equal to FTy
9905       // with the chain parameter inserted.
9906
9907       std::vector<const Type*> NewTypes;
9908       NewTypes.reserve(FTy->getNumParams()+1);
9909
9910       // Insert the chain's type into the list of parameter types, which may
9911       // mean appending it.
9912       {
9913         unsigned Idx = 1;
9914         FunctionType::param_iterator I = FTy->param_begin(),
9915           E = FTy->param_end();
9916
9917         do {
9918           if (Idx == NestIdx)
9919             // Add the chain's type.
9920             NewTypes.push_back(NestTy);
9921
9922           if (I == E)
9923             break;
9924
9925           // Add the original type.
9926           NewTypes.push_back(*I);
9927
9928           ++Idx, ++I;
9929         } while (1);
9930       }
9931
9932       // Replace the trampoline call with a direct call.  Let the generic
9933       // code sort out any function type mismatches.
9934       FunctionType *NewFTy =
9935         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9936       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9937         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9938       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9939
9940       Instruction *NewCaller;
9941       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9942         NewCaller = InvokeInst::Create(NewCallee,
9943                                        II->getNormalDest(), II->getUnwindDest(),
9944                                        NewArgs.begin(), NewArgs.end(),
9945                                        Caller->getName(), Caller);
9946         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9947         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9948       } else {
9949         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9950                                      Caller->getName(), Caller);
9951         if (cast<CallInst>(Caller)->isTailCall())
9952           cast<CallInst>(NewCaller)->setTailCall();
9953         cast<CallInst>(NewCaller)->
9954           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9955         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9956       }
9957       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9958         Caller->replaceAllUsesWith(NewCaller);
9959       Caller->eraseFromParent();
9960       RemoveFromWorkList(Caller);
9961       return 0;
9962     }
9963   }
9964
9965   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9966   // parameter, there is no need to adjust the argument list.  Let the generic
9967   // code sort out any function type mismatches.
9968   Constant *NewCallee =
9969     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9970   CS.setCalledFunction(NewCallee);
9971   return CS.getInstruction();
9972 }
9973
9974 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9975 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9976 /// and a single binop.
9977 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9978   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9979   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
9980   unsigned Opc = FirstInst->getOpcode();
9981   Value *LHSVal = FirstInst->getOperand(0);
9982   Value *RHSVal = FirstInst->getOperand(1);
9983     
9984   const Type *LHSType = LHSVal->getType();
9985   const Type *RHSType = RHSVal->getType();
9986   
9987   // Scan to see if all operands are the same opcode, all have one use, and all
9988   // kill their operands (i.e. the operands have one use).
9989   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
9990     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9991     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9992         // Verify type of the LHS matches so we don't fold cmp's of different
9993         // types or GEP's with different index types.
9994         I->getOperand(0)->getType() != LHSType ||
9995         I->getOperand(1)->getType() != RHSType)
9996       return 0;
9997
9998     // If they are CmpInst instructions, check their predicates
9999     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10000       if (cast<CmpInst>(I)->getPredicate() !=
10001           cast<CmpInst>(FirstInst)->getPredicate())
10002         return 0;
10003     
10004     // Keep track of which operand needs a phi node.
10005     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10006     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10007   }
10008   
10009   // Otherwise, this is safe to transform!
10010   
10011   Value *InLHS = FirstInst->getOperand(0);
10012   Value *InRHS = FirstInst->getOperand(1);
10013   PHINode *NewLHS = 0, *NewRHS = 0;
10014   if (LHSVal == 0) {
10015     NewLHS = PHINode::Create(LHSType,
10016                              FirstInst->getOperand(0)->getName() + ".pn");
10017     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10018     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10019     InsertNewInstBefore(NewLHS, PN);
10020     LHSVal = NewLHS;
10021   }
10022   
10023   if (RHSVal == 0) {
10024     NewRHS = PHINode::Create(RHSType,
10025                              FirstInst->getOperand(1)->getName() + ".pn");
10026     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10027     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10028     InsertNewInstBefore(NewRHS, PN);
10029     RHSVal = NewRHS;
10030   }
10031   
10032   // Add all operands to the new PHIs.
10033   if (NewLHS || NewRHS) {
10034     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10035       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10036       if (NewLHS) {
10037         Value *NewInLHS = InInst->getOperand(0);
10038         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10039       }
10040       if (NewRHS) {
10041         Value *NewInRHS = InInst->getOperand(1);
10042         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10043       }
10044     }
10045   }
10046     
10047   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10048     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10049   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10050   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10051                          RHSVal);
10052 }
10053
10054 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10055   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10056   
10057   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10058                                         FirstInst->op_end());
10059   
10060   // Scan to see if all operands are the same opcode, all have one use, and all
10061   // kill their operands (i.e. the operands have one use).
10062   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10063     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10064     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10065       GEP->getNumOperands() != FirstInst->getNumOperands())
10066       return 0;
10067
10068     // Compare the operand lists.
10069     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10070       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10071         continue;
10072       
10073       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10074       // if one of the PHIs has a constant for the index.  The index may be
10075       // substantially cheaper to compute for the constants, so making it a
10076       // variable index could pessimize the path.  This also handles the case
10077       // for struct indices, which must always be constant.
10078       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10079           isa<ConstantInt>(GEP->getOperand(op)))
10080         return 0;
10081       
10082       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10083         return 0;
10084       FixedOperands[op] = 0;  // Needs a PHI.
10085     }
10086   }
10087   
10088   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10089   // that is variable.
10090   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10091   
10092   bool HasAnyPHIs = false;
10093   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10094     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10095     Value *FirstOp = FirstInst->getOperand(i);
10096     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10097                                      FirstOp->getName()+".pn");
10098     InsertNewInstBefore(NewPN, PN);
10099     
10100     NewPN->reserveOperandSpace(e);
10101     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10102     OperandPhis[i] = NewPN;
10103     FixedOperands[i] = NewPN;
10104     HasAnyPHIs = true;
10105   }
10106
10107   
10108   // Add all operands to the new PHIs.
10109   if (HasAnyPHIs) {
10110     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10111       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10112       BasicBlock *InBB = PN.getIncomingBlock(i);
10113       
10114       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10115         if (PHINode *OpPhi = OperandPhis[op])
10116           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10117     }
10118   }
10119   
10120   Value *Base = FixedOperands[0];
10121   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10122                                    FixedOperands.end());
10123 }
10124
10125
10126 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10127 /// of the block that defines it.  This means that it must be obvious the value
10128 /// of the load is not changed from the point of the load to the end of the
10129 /// block it is in.
10130 ///
10131 /// Finally, it is safe, but not profitable, to sink a load targetting a
10132 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10133 /// to a register.
10134 static bool isSafeToSinkLoad(LoadInst *L) {
10135   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10136   
10137   for (++BBI; BBI != E; ++BBI)
10138     if (BBI->mayWriteToMemory())
10139       return false;
10140   
10141   // Check for non-address taken alloca.  If not address-taken already, it isn't
10142   // profitable to do this xform.
10143   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10144     bool isAddressTaken = false;
10145     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10146          UI != E; ++UI) {
10147       if (isa<LoadInst>(UI)) continue;
10148       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10149         // If storing TO the alloca, then the address isn't taken.
10150         if (SI->getOperand(1) == AI) continue;
10151       }
10152       isAddressTaken = true;
10153       break;
10154     }
10155     
10156     if (!isAddressTaken)
10157       return false;
10158   }
10159   
10160   return true;
10161 }
10162
10163
10164 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10165 // operator and they all are only used by the PHI, PHI together their
10166 // inputs, and do the operation once, to the result of the PHI.
10167 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10168   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10169
10170   // Scan the instruction, looking for input operations that can be folded away.
10171   // If all input operands to the phi are the same instruction (e.g. a cast from
10172   // the same type or "+42") we can pull the operation through the PHI, reducing
10173   // code size and simplifying code.
10174   Constant *ConstantOp = 0;
10175   const Type *CastSrcTy = 0;
10176   bool isVolatile = false;
10177   if (isa<CastInst>(FirstInst)) {
10178     CastSrcTy = FirstInst->getOperand(0)->getType();
10179   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10180     // Can fold binop, compare or shift here if the RHS is a constant, 
10181     // otherwise call FoldPHIArgBinOpIntoPHI.
10182     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10183     if (ConstantOp == 0)
10184       return FoldPHIArgBinOpIntoPHI(PN);
10185   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10186     isVolatile = LI->isVolatile();
10187     // We can't sink the load if the loaded value could be modified between the
10188     // load and the PHI.
10189     if (LI->getParent() != PN.getIncomingBlock(0) ||
10190         !isSafeToSinkLoad(LI))
10191       return 0;
10192     
10193     // If the PHI is of volatile loads and the load block has multiple
10194     // successors, sinking it would remove a load of the volatile value from
10195     // the path through the other successor.
10196     if (isVolatile &&
10197         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10198       return 0;
10199     
10200   } else if (isa<GetElementPtrInst>(FirstInst)) {
10201     return FoldPHIArgGEPIntoPHI(PN);
10202   } else {
10203     return 0;  // Cannot fold this operation.
10204   }
10205
10206   // Check to see if all arguments are the same operation.
10207   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10208     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10209     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10210     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10211       return 0;
10212     if (CastSrcTy) {
10213       if (I->getOperand(0)->getType() != CastSrcTy)
10214         return 0;  // Cast operation must match.
10215     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10216       // We can't sink the load if the loaded value could be modified between 
10217       // the load and the PHI.
10218       if (LI->isVolatile() != isVolatile ||
10219           LI->getParent() != PN.getIncomingBlock(i) ||
10220           !isSafeToSinkLoad(LI))
10221         return 0;
10222       
10223       // If the PHI is of volatile loads and the load block has multiple
10224       // successors, sinking it would remove a load of the volatile value from
10225       // the path through the other successor.
10226       if (isVolatile &&
10227           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10228         return 0;
10229
10230       
10231     } else if (I->getOperand(1) != ConstantOp) {
10232       return 0;
10233     }
10234   }
10235
10236   // Okay, they are all the same operation.  Create a new PHI node of the
10237   // correct type, and PHI together all of the LHS's of the instructions.
10238   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10239                                    PN.getName()+".in");
10240   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10241
10242   Value *InVal = FirstInst->getOperand(0);
10243   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10244
10245   // Add all operands to the new PHI.
10246   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10247     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10248     if (NewInVal != InVal)
10249       InVal = 0;
10250     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10251   }
10252
10253   Value *PhiVal;
10254   if (InVal) {
10255     // The new PHI unions all of the same values together.  This is really
10256     // common, so we handle it intelligently here for compile-time speed.
10257     PhiVal = InVal;
10258     delete NewPN;
10259   } else {
10260     InsertNewInstBefore(NewPN, PN);
10261     PhiVal = NewPN;
10262   }
10263
10264   // Insert and return the new operation.
10265   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10266     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10267   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10268     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10269   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10270     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10271                            PhiVal, ConstantOp);
10272   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10273   
10274   // If this was a volatile load that we are merging, make sure to loop through
10275   // and mark all the input loads as non-volatile.  If we don't do this, we will
10276   // insert a new volatile load and the old ones will not be deletable.
10277   if (isVolatile)
10278     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10279       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10280   
10281   return new LoadInst(PhiVal, "", isVolatile);
10282 }
10283
10284 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10285 /// that is dead.
10286 static bool DeadPHICycle(PHINode *PN,
10287                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10288   if (PN->use_empty()) return true;
10289   if (!PN->hasOneUse()) return false;
10290
10291   // Remember this node, and if we find the cycle, return.
10292   if (!PotentiallyDeadPHIs.insert(PN))
10293     return true;
10294   
10295   // Don't scan crazily complex things.
10296   if (PotentiallyDeadPHIs.size() == 16)
10297     return false;
10298
10299   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10300     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10301
10302   return false;
10303 }
10304
10305 /// PHIsEqualValue - Return true if this phi node is always equal to
10306 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10307 ///   z = some value; x = phi (y, z); y = phi (x, z)
10308 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10309                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10310   // See if we already saw this PHI node.
10311   if (!ValueEqualPHIs.insert(PN))
10312     return true;
10313   
10314   // Don't scan crazily complex things.
10315   if (ValueEqualPHIs.size() == 16)
10316     return false;
10317  
10318   // Scan the operands to see if they are either phi nodes or are equal to
10319   // the value.
10320   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10321     Value *Op = PN->getIncomingValue(i);
10322     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10323       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10324         return false;
10325     } else if (Op != NonPhiInVal)
10326       return false;
10327   }
10328   
10329   return true;
10330 }
10331
10332
10333 // PHINode simplification
10334 //
10335 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10336   // If LCSSA is around, don't mess with Phi nodes
10337   if (MustPreserveLCSSA) return 0;
10338   
10339   if (Value *V = PN.hasConstantValue())
10340     return ReplaceInstUsesWith(PN, V);
10341
10342   // If all PHI operands are the same operation, pull them through the PHI,
10343   // reducing code size.
10344   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10345       isa<Instruction>(PN.getIncomingValue(1)) &&
10346       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10347       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10348       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10349       // than themselves more than once.
10350       PN.getIncomingValue(0)->hasOneUse())
10351     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10352       return Result;
10353
10354   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10355   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10356   // PHI)... break the cycle.
10357   if (PN.hasOneUse()) {
10358     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10359     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10360       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10361       PotentiallyDeadPHIs.insert(&PN);
10362       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10363         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10364     }
10365    
10366     // If this phi has a single use, and if that use just computes a value for
10367     // the next iteration of a loop, delete the phi.  This occurs with unused
10368     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10369     // common case here is good because the only other things that catch this
10370     // are induction variable analysis (sometimes) and ADCE, which is only run
10371     // late.
10372     if (PHIUser->hasOneUse() &&
10373         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10374         PHIUser->use_back() == &PN) {
10375       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10376     }
10377   }
10378
10379   // We sometimes end up with phi cycles that non-obviously end up being the
10380   // same value, for example:
10381   //   z = some value; x = phi (y, z); y = phi (x, z)
10382   // where the phi nodes don't necessarily need to be in the same block.  Do a
10383   // quick check to see if the PHI node only contains a single non-phi value, if
10384   // so, scan to see if the phi cycle is actually equal to that value.
10385   {
10386     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10387     // Scan for the first non-phi operand.
10388     while (InValNo != NumOperandVals && 
10389            isa<PHINode>(PN.getIncomingValue(InValNo)))
10390       ++InValNo;
10391
10392     if (InValNo != NumOperandVals) {
10393       Value *NonPhiInVal = PN.getOperand(InValNo);
10394       
10395       // Scan the rest of the operands to see if there are any conflicts, if so
10396       // there is no need to recursively scan other phis.
10397       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10398         Value *OpVal = PN.getIncomingValue(InValNo);
10399         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10400           break;
10401       }
10402       
10403       // If we scanned over all operands, then we have one unique value plus
10404       // phi values.  Scan PHI nodes to see if they all merge in each other or
10405       // the value.
10406       if (InValNo == NumOperandVals) {
10407         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10408         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10409           return ReplaceInstUsesWith(PN, NonPhiInVal);
10410       }
10411     }
10412   }
10413   return 0;
10414 }
10415
10416 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10417                                    Instruction *InsertPoint,
10418                                    InstCombiner *IC) {
10419   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10420   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10421   // We must cast correctly to the pointer type. Ensure that we
10422   // sign extend the integer value if it is smaller as this is
10423   // used for address computation.
10424   Instruction::CastOps opcode = 
10425      (VTySize < PtrSize ? Instruction::SExt :
10426       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10427   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10428 }
10429
10430
10431 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10432   Value *PtrOp = GEP.getOperand(0);
10433   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10434   // If so, eliminate the noop.
10435   if (GEP.getNumOperands() == 1)
10436     return ReplaceInstUsesWith(GEP, PtrOp);
10437
10438   if (isa<UndefValue>(GEP.getOperand(0)))
10439     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10440
10441   bool HasZeroPointerIndex = false;
10442   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10443     HasZeroPointerIndex = C->isNullValue();
10444
10445   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10446     return ReplaceInstUsesWith(GEP, PtrOp);
10447
10448   // Eliminate unneeded casts for indices.
10449   bool MadeChange = false;
10450   
10451   gep_type_iterator GTI = gep_type_begin(GEP);
10452   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10453        i != e; ++i, ++GTI) {
10454     if (isa<SequentialType>(*GTI)) {
10455       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10456         if (CI->getOpcode() == Instruction::ZExt ||
10457             CI->getOpcode() == Instruction::SExt) {
10458           const Type *SrcTy = CI->getOperand(0)->getType();
10459           // We can eliminate a cast from i32 to i64 iff the target 
10460           // is a 32-bit pointer target.
10461           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10462             MadeChange = true;
10463             *i = CI->getOperand(0);
10464           }
10465         }
10466       }
10467       // If we are using a wider index than needed for this platform, shrink it
10468       // to what we need.  If narrower, sign-extend it to what we need.
10469       // If the incoming value needs a cast instruction,
10470       // insert it.  This explicit cast can make subsequent optimizations more
10471       // obvious.
10472       Value *Op = *i;
10473       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10474         if (Constant *C = dyn_cast<Constant>(Op)) {
10475           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10476           MadeChange = true;
10477         } else {
10478           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10479                                 GEP);
10480           *i = Op;
10481           MadeChange = true;
10482         }
10483       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10484         if (Constant *C = dyn_cast<Constant>(Op)) {
10485           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10486           MadeChange = true;
10487         } else {
10488           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10489                                 GEP);
10490           *i = Op;
10491           MadeChange = true;
10492         }
10493       }
10494     }
10495   }
10496   if (MadeChange) return &GEP;
10497
10498   // If this GEP instruction doesn't move the pointer, and if the input operand
10499   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10500   // real input to the dest type.
10501   if (GEP.hasAllZeroIndices()) {
10502     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10503       // If the bitcast is of an allocation, and the allocation will be
10504       // converted to match the type of the cast, don't touch this.
10505       if (isa<AllocationInst>(BCI->getOperand(0))) {
10506         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10507         if (Instruction *I = visitBitCast(*BCI)) {
10508           if (I != BCI) {
10509             I->takeName(BCI);
10510             BCI->getParent()->getInstList().insert(BCI, I);
10511             ReplaceInstUsesWith(*BCI, I);
10512           }
10513           return &GEP;
10514         }
10515       }
10516       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10517     }
10518   }
10519   
10520   // Combine Indices - If the source pointer to this getelementptr instruction
10521   // is a getelementptr instruction, combine the indices of the two
10522   // getelementptr instructions into a single instruction.
10523   //
10524   SmallVector<Value*, 8> SrcGEPOperands;
10525   if (User *Src = dyn_castGetElementPtr(PtrOp))
10526     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10527
10528   if (!SrcGEPOperands.empty()) {
10529     // Note that if our source is a gep chain itself that we wait for that
10530     // chain to be resolved before we perform this transformation.  This
10531     // avoids us creating a TON of code in some cases.
10532     //
10533     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10534         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10535       return 0;   // Wait until our source is folded to completion.
10536
10537     SmallVector<Value*, 8> Indices;
10538
10539     // Find out whether the last index in the source GEP is a sequential idx.
10540     bool EndsWithSequential = false;
10541     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10542            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10543       EndsWithSequential = !isa<StructType>(*I);
10544
10545     // Can we combine the two pointer arithmetics offsets?
10546     if (EndsWithSequential) {
10547       // Replace: gep (gep %P, long B), long A, ...
10548       // With:    T = long A+B; gep %P, T, ...
10549       //
10550       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10551       if (SO1 == Constant::getNullValue(SO1->getType())) {
10552         Sum = GO1;
10553       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10554         Sum = SO1;
10555       } else {
10556         // If they aren't the same type, convert both to an integer of the
10557         // target's pointer size.
10558         if (SO1->getType() != GO1->getType()) {
10559           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10560             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10561           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10562             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10563           } else {
10564             unsigned PS = TD->getPointerSizeInBits();
10565             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10566               // Convert GO1 to SO1's type.
10567               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10568
10569             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10570               // Convert SO1 to GO1's type.
10571               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10572             } else {
10573               const Type *PT = TD->getIntPtrType();
10574               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10575               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10576             }
10577           }
10578         }
10579         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10580           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10581         else {
10582           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10583           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10584         }
10585       }
10586
10587       // Recycle the GEP we already have if possible.
10588       if (SrcGEPOperands.size() == 2) {
10589         GEP.setOperand(0, SrcGEPOperands[0]);
10590         GEP.setOperand(1, Sum);
10591         return &GEP;
10592       } else {
10593         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10594                        SrcGEPOperands.end()-1);
10595         Indices.push_back(Sum);
10596         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10597       }
10598     } else if (isa<Constant>(*GEP.idx_begin()) &&
10599                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10600                SrcGEPOperands.size() != 1) {
10601       // Otherwise we can do the fold if the first index of the GEP is a zero
10602       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10603                      SrcGEPOperands.end());
10604       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10605     }
10606
10607     if (!Indices.empty())
10608       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10609                                        Indices.end(), GEP.getName());
10610
10611   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10612     // GEP of global variable.  If all of the indices for this GEP are
10613     // constants, we can promote this to a constexpr instead of an instruction.
10614
10615     // Scan for nonconstants...
10616     SmallVector<Constant*, 8> Indices;
10617     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10618     for (; I != E && isa<Constant>(*I); ++I)
10619       Indices.push_back(cast<Constant>(*I));
10620
10621     if (I == E) {  // If they are all constants...
10622       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10623                                                     &Indices[0],Indices.size());
10624
10625       // Replace all uses of the GEP with the new constexpr...
10626       return ReplaceInstUsesWith(GEP, CE);
10627     }
10628   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10629     if (!isa<PointerType>(X->getType())) {
10630       // Not interesting.  Source pointer must be a cast from pointer.
10631     } else if (HasZeroPointerIndex) {
10632       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10633       // into     : GEP [10 x i8]* X, i32 0, ...
10634       //
10635       // This occurs when the program declares an array extern like "int X[];"
10636       //
10637       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10638       const PointerType *XTy = cast<PointerType>(X->getType());
10639       if (const ArrayType *XATy =
10640           dyn_cast<ArrayType>(XTy->getElementType()))
10641         if (const ArrayType *CATy =
10642             dyn_cast<ArrayType>(CPTy->getElementType()))
10643           if (CATy->getElementType() == XATy->getElementType()) {
10644             // At this point, we know that the cast source type is a pointer
10645             // to an array of the same type as the destination pointer
10646             // array.  Because the array type is never stepped over (there
10647             // is a leading zero) we can fold the cast into this GEP.
10648             GEP.setOperand(0, X);
10649             return &GEP;
10650           }
10651     } else if (GEP.getNumOperands() == 2) {
10652       // Transform things like:
10653       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10654       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10655       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10656       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10657       if (isa<ArrayType>(SrcElTy) &&
10658           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10659           TD->getABITypeSize(ResElTy)) {
10660         Value *Idx[2];
10661         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10662         Idx[1] = GEP.getOperand(1);
10663         Value *V = InsertNewInstBefore(
10664                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10665         // V and GEP are both pointer types --> BitCast
10666         return new BitCastInst(V, GEP.getType());
10667       }
10668       
10669       // Transform things like:
10670       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10671       //   (where tmp = 8*tmp2) into:
10672       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10673       
10674       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10675         uint64_t ArrayEltSize =
10676             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10677         
10678         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10679         // allow either a mul, shift, or constant here.
10680         Value *NewIdx = 0;
10681         ConstantInt *Scale = 0;
10682         if (ArrayEltSize == 1) {
10683           NewIdx = GEP.getOperand(1);
10684           Scale = ConstantInt::get(NewIdx->getType(), 1);
10685         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10686           NewIdx = ConstantInt::get(CI->getType(), 1);
10687           Scale = CI;
10688         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10689           if (Inst->getOpcode() == Instruction::Shl &&
10690               isa<ConstantInt>(Inst->getOperand(1))) {
10691             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10692             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10693             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10694             NewIdx = Inst->getOperand(0);
10695           } else if (Inst->getOpcode() == Instruction::Mul &&
10696                      isa<ConstantInt>(Inst->getOperand(1))) {
10697             Scale = cast<ConstantInt>(Inst->getOperand(1));
10698             NewIdx = Inst->getOperand(0);
10699           }
10700         }
10701         
10702         // If the index will be to exactly the right offset with the scale taken
10703         // out, perform the transformation. Note, we don't know whether Scale is
10704         // signed or not. We'll use unsigned version of division/modulo
10705         // operation after making sure Scale doesn't have the sign bit set.
10706         if (Scale && Scale->getSExtValue() >= 0LL &&
10707             Scale->getZExtValue() % ArrayEltSize == 0) {
10708           Scale = ConstantInt::get(Scale->getType(),
10709                                    Scale->getZExtValue() / ArrayEltSize);
10710           if (Scale->getZExtValue() != 1) {
10711             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10712                                                        false /*ZExt*/);
10713             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10714             NewIdx = InsertNewInstBefore(Sc, GEP);
10715           }
10716
10717           // Insert the new GEP instruction.
10718           Value *Idx[2];
10719           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10720           Idx[1] = NewIdx;
10721           Instruction *NewGEP =
10722             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10723           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10724           // The NewGEP must be pointer typed, so must the old one -> BitCast
10725           return new BitCastInst(NewGEP, GEP.getType());
10726         }
10727       }
10728     }
10729   }
10730
10731   return 0;
10732 }
10733
10734 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10735   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10736   if (AI.isArrayAllocation()) {  // Check C != 1
10737     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10738       const Type *NewTy = 
10739         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10740       AllocationInst *New = 0;
10741
10742       // Create and insert the replacement instruction...
10743       if (isa<MallocInst>(AI))
10744         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10745       else {
10746         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10747         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10748       }
10749
10750       InsertNewInstBefore(New, AI);
10751
10752       // Scan to the end of the allocation instructions, to skip over a block of
10753       // allocas if possible...
10754       //
10755       BasicBlock::iterator It = New;
10756       while (isa<AllocationInst>(*It)) ++It;
10757
10758       // Now that I is pointing to the first non-allocation-inst in the block,
10759       // insert our getelementptr instruction...
10760       //
10761       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10762       Value *Idx[2];
10763       Idx[0] = NullIdx;
10764       Idx[1] = NullIdx;
10765       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10766                                            New->getName()+".sub", It);
10767
10768       // Now make everything use the getelementptr instead of the original
10769       // allocation.
10770       return ReplaceInstUsesWith(AI, V);
10771     } else if (isa<UndefValue>(AI.getArraySize())) {
10772       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10773     }
10774   }
10775
10776   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10777   // Note that we only do this for alloca's, because malloc should allocate and
10778   // return a unique pointer, even for a zero byte allocation.
10779   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10780       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10781     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10782
10783   return 0;
10784 }
10785
10786 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10787   Value *Op = FI.getOperand(0);
10788
10789   // free undef -> unreachable.
10790   if (isa<UndefValue>(Op)) {
10791     // Insert a new store to null because we cannot modify the CFG here.
10792     new StoreInst(ConstantInt::getTrue(),
10793                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10794     return EraseInstFromFunction(FI);
10795   }
10796   
10797   // If we have 'free null' delete the instruction.  This can happen in stl code
10798   // when lots of inlining happens.
10799   if (isa<ConstantPointerNull>(Op))
10800     return EraseInstFromFunction(FI);
10801   
10802   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10803   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10804     FI.setOperand(0, CI->getOperand(0));
10805     return &FI;
10806   }
10807   
10808   // Change free (gep X, 0,0,0,0) into free(X)
10809   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10810     if (GEPI->hasAllZeroIndices()) {
10811       AddToWorkList(GEPI);
10812       FI.setOperand(0, GEPI->getOperand(0));
10813       return &FI;
10814     }
10815   }
10816   
10817   // Change free(malloc) into nothing, if the malloc has a single use.
10818   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10819     if (MI->hasOneUse()) {
10820       EraseInstFromFunction(FI);
10821       return EraseInstFromFunction(*MI);
10822     }
10823
10824   return 0;
10825 }
10826
10827
10828 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10829 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10830                                         const TargetData *TD) {
10831   User *CI = cast<User>(LI.getOperand(0));
10832   Value *CastOp = CI->getOperand(0);
10833
10834   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10835     // Instead of loading constant c string, use corresponding integer value
10836     // directly if string length is small enough.
10837     std::string Str;
10838     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10839       unsigned len = Str.length();
10840       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10841       unsigned numBits = Ty->getPrimitiveSizeInBits();
10842       // Replace LI with immediate integer store.
10843       if ((numBits >> 3) == len + 1) {
10844         APInt StrVal(numBits, 0);
10845         APInt SingleChar(numBits, 0);
10846         if (TD->isLittleEndian()) {
10847           for (signed i = len-1; i >= 0; i--) {
10848             SingleChar = (uint64_t) Str[i];
10849             StrVal = (StrVal << 8) | SingleChar;
10850           }
10851         } else {
10852           for (unsigned i = 0; i < len; i++) {
10853             SingleChar = (uint64_t) Str[i];
10854             StrVal = (StrVal << 8) | SingleChar;
10855           }
10856           // Append NULL at the end.
10857           SingleChar = 0;
10858           StrVal = (StrVal << 8) | SingleChar;
10859         }
10860         Value *NL = ConstantInt::get(StrVal);
10861         return IC.ReplaceInstUsesWith(LI, NL);
10862       }
10863     }
10864   }
10865
10866   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10867   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10868     const Type *SrcPTy = SrcTy->getElementType();
10869
10870     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10871          isa<VectorType>(DestPTy)) {
10872       // If the source is an array, the code below will not succeed.  Check to
10873       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10874       // constants.
10875       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10876         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10877           if (ASrcTy->getNumElements() != 0) {
10878             Value *Idxs[2];
10879             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10880             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10881             SrcTy = cast<PointerType>(CastOp->getType());
10882             SrcPTy = SrcTy->getElementType();
10883           }
10884
10885       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10886             isa<VectorType>(SrcPTy)) &&
10887           // Do not allow turning this into a load of an integer, which is then
10888           // casted to a pointer, this pessimizes pointer analysis a lot.
10889           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10890           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10891                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10892
10893         // Okay, we are casting from one integer or pointer type to another of
10894         // the same size.  Instead of casting the pointer before the load, cast
10895         // the result of the loaded value.
10896         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10897                                                              CI->getName(),
10898                                                          LI.isVolatile()),LI);
10899         // Now cast the result of the load.
10900         return new BitCastInst(NewLoad, LI.getType());
10901       }
10902     }
10903   }
10904   return 0;
10905 }
10906
10907 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10908 /// from this value cannot trap.  If it is not obviously safe to load from the
10909 /// specified pointer, we do a quick local scan of the basic block containing
10910 /// ScanFrom, to determine if the address is already accessed.
10911 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10912   // If it is an alloca it is always safe to load from.
10913   if (isa<AllocaInst>(V)) return true;
10914
10915   // If it is a global variable it is mostly safe to load from.
10916   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10917     // Don't try to evaluate aliases.  External weak GV can be null.
10918     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10919
10920   // Otherwise, be a little bit agressive by scanning the local block where we
10921   // want to check to see if the pointer is already being loaded or stored
10922   // from/to.  If so, the previous load or store would have already trapped,
10923   // so there is no harm doing an extra load (also, CSE will later eliminate
10924   // the load entirely).
10925   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10926
10927   while (BBI != E) {
10928     --BBI;
10929
10930     // If we see a free or a call (which might do a free) the pointer could be
10931     // marked invalid.
10932     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10933       return false;
10934     
10935     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10936       if (LI->getOperand(0) == V) return true;
10937     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10938       if (SI->getOperand(1) == V) return true;
10939     }
10940
10941   }
10942   return false;
10943 }
10944
10945 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10946   Value *Op = LI.getOperand(0);
10947
10948   // Attempt to improve the alignment.
10949   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10950   if (KnownAlign >
10951       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10952                                 LI.getAlignment()))
10953     LI.setAlignment(KnownAlign);
10954
10955   // load (cast X) --> cast (load X) iff safe
10956   if (isa<CastInst>(Op))
10957     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10958       return Res;
10959
10960   // None of the following transforms are legal for volatile loads.
10961   if (LI.isVolatile()) return 0;
10962   
10963   // Do really simple store-to-load forwarding and load CSE, to catch cases
10964   // where there are several consequtive memory accesses to the same location,
10965   // separated by a few arithmetic operations.
10966   BasicBlock::iterator BBI = &LI;
10967   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10968     return ReplaceInstUsesWith(LI, AvailableVal);
10969
10970   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10971     const Value *GEPI0 = GEPI->getOperand(0);
10972     // TODO: Consider a target hook for valid address spaces for this xform.
10973     if (isa<ConstantPointerNull>(GEPI0) &&
10974         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10975       // Insert a new store to null instruction before the load to indicate
10976       // that this code is not reachable.  We do this instead of inserting
10977       // an unreachable instruction directly because we cannot modify the
10978       // CFG.
10979       new StoreInst(UndefValue::get(LI.getType()),
10980                     Constant::getNullValue(Op->getType()), &LI);
10981       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10982     }
10983   } 
10984
10985   if (Constant *C = dyn_cast<Constant>(Op)) {
10986     // load null/undef -> undef
10987     // TODO: Consider a target hook for valid address spaces for this xform.
10988     if (isa<UndefValue>(C) || (C->isNullValue() && 
10989         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10990       // Insert a new store to null instruction before the load to indicate that
10991       // this code is not reachable.  We do this instead of inserting an
10992       // unreachable instruction directly because we cannot modify the CFG.
10993       new StoreInst(UndefValue::get(LI.getType()),
10994                     Constant::getNullValue(Op->getType()), &LI);
10995       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10996     }
10997
10998     // Instcombine load (constant global) into the value loaded.
10999     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11000       if (GV->isConstant() && !GV->isDeclaration())
11001         return ReplaceInstUsesWith(LI, GV->getInitializer());
11002
11003     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11004     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11005       if (CE->getOpcode() == Instruction::GetElementPtr) {
11006         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11007           if (GV->isConstant() && !GV->isDeclaration())
11008             if (Constant *V = 
11009                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11010               return ReplaceInstUsesWith(LI, V);
11011         if (CE->getOperand(0)->isNullValue()) {
11012           // Insert a new store to null instruction before the load to indicate
11013           // that this code is not reachable.  We do this instead of inserting
11014           // an unreachable instruction directly because we cannot modify the
11015           // CFG.
11016           new StoreInst(UndefValue::get(LI.getType()),
11017                         Constant::getNullValue(Op->getType()), &LI);
11018           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11019         }
11020
11021       } else if (CE->isCast()) {
11022         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11023           return Res;
11024       }
11025     }
11026   }
11027     
11028   // If this load comes from anywhere in a constant global, and if the global
11029   // is all undef or zero, we know what it loads.
11030   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11031     if (GV->isConstant() && GV->hasInitializer()) {
11032       if (GV->getInitializer()->isNullValue())
11033         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11034       else if (isa<UndefValue>(GV->getInitializer()))
11035         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11036     }
11037   }
11038
11039   if (Op->hasOneUse()) {
11040     // Change select and PHI nodes to select values instead of addresses: this
11041     // helps alias analysis out a lot, allows many others simplifications, and
11042     // exposes redundancy in the code.
11043     //
11044     // Note that we cannot do the transformation unless we know that the
11045     // introduced loads cannot trap!  Something like this is valid as long as
11046     // the condition is always false: load (select bool %C, int* null, int* %G),
11047     // but it would not be valid if we transformed it to load from null
11048     // unconditionally.
11049     //
11050     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11051       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11052       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11053           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11054         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11055                                      SI->getOperand(1)->getName()+".val"), LI);
11056         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11057                                      SI->getOperand(2)->getName()+".val"), LI);
11058         return SelectInst::Create(SI->getCondition(), V1, V2);
11059       }
11060
11061       // load (select (cond, null, P)) -> load P
11062       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11063         if (C->isNullValue()) {
11064           LI.setOperand(0, SI->getOperand(2));
11065           return &LI;
11066         }
11067
11068       // load (select (cond, P, null)) -> load P
11069       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11070         if (C->isNullValue()) {
11071           LI.setOperand(0, SI->getOperand(1));
11072           return &LI;
11073         }
11074     }
11075   }
11076   return 0;
11077 }
11078
11079 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11080 /// when possible.
11081 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11082   User *CI = cast<User>(SI.getOperand(1));
11083   Value *CastOp = CI->getOperand(0);
11084
11085   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11086   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11087     const Type *SrcPTy = SrcTy->getElementType();
11088
11089     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
11090       // If the source is an array, the code below will not succeed.  Check to
11091       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11092       // constants.
11093       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11094         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11095           if (ASrcTy->getNumElements() != 0) {
11096             Value* Idxs[2];
11097             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11098             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11099             SrcTy = cast<PointerType>(CastOp->getType());
11100             SrcPTy = SrcTy->getElementType();
11101           }
11102
11103       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
11104           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11105                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11106
11107         // Okay, we are casting from one integer or pointer type to another of
11108         // the same size.  Instead of casting the pointer before 
11109         // the store, cast the value to be stored.
11110         Value *NewCast;
11111         Value *SIOp0 = SI.getOperand(0);
11112         Instruction::CastOps opcode = Instruction::BitCast;
11113         const Type* CastSrcTy = SIOp0->getType();
11114         const Type* CastDstTy = SrcPTy;
11115         if (isa<PointerType>(CastDstTy)) {
11116           if (CastSrcTy->isInteger())
11117             opcode = Instruction::IntToPtr;
11118         } else if (isa<IntegerType>(CastDstTy)) {
11119           if (isa<PointerType>(SIOp0->getType()))
11120             opcode = Instruction::PtrToInt;
11121         }
11122         if (Constant *C = dyn_cast<Constant>(SIOp0))
11123           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11124         else
11125           NewCast = IC.InsertNewInstBefore(
11126             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11127             SI);
11128         return new StoreInst(NewCast, CastOp);
11129       }
11130     }
11131   }
11132   return 0;
11133 }
11134
11135 /// equivalentAddressValues - Test if A and B will obviously have the same
11136 /// value. This includes recognizing that %t0 and %t1 will have the same
11137 /// value in code like this:
11138 ///   %t0 = getelementptr @a, 0, 3
11139 ///   store i32 0, i32* %t0
11140 ///   %t1 = getelementptr @a, 0, 3
11141 ///   %t2 = load i32* %t1
11142 ///
11143 static bool equivalentAddressValues(Value *A, Value *B) {
11144   // Test if the values are trivially equivalent.
11145   if (A == B) return true;
11146   
11147   // Test if the values come form identical arithmetic instructions.
11148   if (isa<BinaryOperator>(A) ||
11149       isa<CastInst>(A) ||
11150       isa<PHINode>(A) ||
11151       isa<GetElementPtrInst>(A))
11152     if (Instruction *BI = dyn_cast<Instruction>(B))
11153       if (cast<Instruction>(A)->isIdenticalTo(BI))
11154         return true;
11155   
11156   // Otherwise they may not be equivalent.
11157   return false;
11158 }
11159
11160 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11161   Value *Val = SI.getOperand(0);
11162   Value *Ptr = SI.getOperand(1);
11163
11164   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11165     EraseInstFromFunction(SI);
11166     ++NumCombined;
11167     return 0;
11168   }
11169   
11170   // If the RHS is an alloca with a single use, zapify the store, making the
11171   // alloca dead.
11172   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11173     if (isa<AllocaInst>(Ptr)) {
11174       EraseInstFromFunction(SI);
11175       ++NumCombined;
11176       return 0;
11177     }
11178     
11179     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11180       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11181           GEP->getOperand(0)->hasOneUse()) {
11182         EraseInstFromFunction(SI);
11183         ++NumCombined;
11184         return 0;
11185       }
11186   }
11187
11188   // Attempt to improve the alignment.
11189   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11190   if (KnownAlign >
11191       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11192                                 SI.getAlignment()))
11193     SI.setAlignment(KnownAlign);
11194
11195   // Do really simple DSE, to catch cases where there are several consequtive
11196   // stores to the same location, separated by a few arithmetic operations. This
11197   // situation often occurs with bitfield accesses.
11198   BasicBlock::iterator BBI = &SI;
11199   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11200        --ScanInsts) {
11201     --BBI;
11202     
11203     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11204       // Prev store isn't volatile, and stores to the same location?
11205       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11206                                                           SI.getOperand(1))) {
11207         ++NumDeadStore;
11208         ++BBI;
11209         EraseInstFromFunction(*PrevSI);
11210         continue;
11211       }
11212       break;
11213     }
11214     
11215     // If this is a load, we have to stop.  However, if the loaded value is from
11216     // the pointer we're loading and is producing the pointer we're storing,
11217     // then *this* store is dead (X = load P; store X -> P).
11218     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11219       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11220           !SI.isVolatile()) {
11221         EraseInstFromFunction(SI);
11222         ++NumCombined;
11223         return 0;
11224       }
11225       // Otherwise, this is a load from some other location.  Stores before it
11226       // may not be dead.
11227       break;
11228     }
11229     
11230     // Don't skip over loads or things that can modify memory.
11231     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11232       break;
11233   }
11234   
11235   
11236   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11237
11238   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11239   if (isa<ConstantPointerNull>(Ptr)) {
11240     if (!isa<UndefValue>(Val)) {
11241       SI.setOperand(0, UndefValue::get(Val->getType()));
11242       if (Instruction *U = dyn_cast<Instruction>(Val))
11243         AddToWorkList(U);  // Dropped a use.
11244       ++NumCombined;
11245     }
11246     return 0;  // Do not modify these!
11247   }
11248
11249   // store undef, Ptr -> noop
11250   if (isa<UndefValue>(Val)) {
11251     EraseInstFromFunction(SI);
11252     ++NumCombined;
11253     return 0;
11254   }
11255
11256   // If the pointer destination is a cast, see if we can fold the cast into the
11257   // source instead.
11258   if (isa<CastInst>(Ptr))
11259     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11260       return Res;
11261   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11262     if (CE->isCast())
11263       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11264         return Res;
11265
11266   
11267   // If this store is the last instruction in the basic block, and if the block
11268   // ends with an unconditional branch, try to move it to the successor block.
11269   BBI = &SI; ++BBI;
11270   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11271     if (BI->isUnconditional())
11272       if (SimplifyStoreAtEndOfBlock(SI))
11273         return 0;  // xform done!
11274   
11275   return 0;
11276 }
11277
11278 /// SimplifyStoreAtEndOfBlock - Turn things like:
11279 ///   if () { *P = v1; } else { *P = v2 }
11280 /// into a phi node with a store in the successor.
11281 ///
11282 /// Simplify things like:
11283 ///   *P = v1; if () { *P = v2; }
11284 /// into a phi node with a store in the successor.
11285 ///
11286 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11287   BasicBlock *StoreBB = SI.getParent();
11288   
11289   // Check to see if the successor block has exactly two incoming edges.  If
11290   // so, see if the other predecessor contains a store to the same location.
11291   // if so, insert a PHI node (if needed) and move the stores down.
11292   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11293   
11294   // Determine whether Dest has exactly two predecessors and, if so, compute
11295   // the other predecessor.
11296   pred_iterator PI = pred_begin(DestBB);
11297   BasicBlock *OtherBB = 0;
11298   if (*PI != StoreBB)
11299     OtherBB = *PI;
11300   ++PI;
11301   if (PI == pred_end(DestBB))
11302     return false;
11303   
11304   if (*PI != StoreBB) {
11305     if (OtherBB)
11306       return false;
11307     OtherBB = *PI;
11308   }
11309   if (++PI != pred_end(DestBB))
11310     return false;
11311
11312   // Bail out if all the relevant blocks aren't distinct (this can happen,
11313   // for example, if SI is in an infinite loop)
11314   if (StoreBB == DestBB || OtherBB == DestBB)
11315     return false;
11316
11317   // Verify that the other block ends in a branch and is not otherwise empty.
11318   BasicBlock::iterator BBI = OtherBB->getTerminator();
11319   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11320   if (!OtherBr || BBI == OtherBB->begin())
11321     return false;
11322   
11323   // If the other block ends in an unconditional branch, check for the 'if then
11324   // else' case.  there is an instruction before the branch.
11325   StoreInst *OtherStore = 0;
11326   if (OtherBr->isUnconditional()) {
11327     // If this isn't a store, or isn't a store to the same location, bail out.
11328     --BBI;
11329     OtherStore = dyn_cast<StoreInst>(BBI);
11330     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11331       return false;
11332   } else {
11333     // Otherwise, the other block ended with a conditional branch. If one of the
11334     // destinations is StoreBB, then we have the if/then case.
11335     if (OtherBr->getSuccessor(0) != StoreBB && 
11336         OtherBr->getSuccessor(1) != StoreBB)
11337       return false;
11338     
11339     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11340     // if/then triangle.  See if there is a store to the same ptr as SI that
11341     // lives in OtherBB.
11342     for (;; --BBI) {
11343       // Check to see if we find the matching store.
11344       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11345         if (OtherStore->getOperand(1) != SI.getOperand(1))
11346           return false;
11347         break;
11348       }
11349       // If we find something that may be using or overwriting the stored
11350       // value, or if we run out of instructions, we can't do the xform.
11351       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11352           BBI == OtherBB->begin())
11353         return false;
11354     }
11355     
11356     // In order to eliminate the store in OtherBr, we have to
11357     // make sure nothing reads or overwrites the stored value in
11358     // StoreBB.
11359     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11360       // FIXME: This should really be AA driven.
11361       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11362         return false;
11363     }
11364   }
11365   
11366   // Insert a PHI node now if we need it.
11367   Value *MergedVal = OtherStore->getOperand(0);
11368   if (MergedVal != SI.getOperand(0)) {
11369     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11370     PN->reserveOperandSpace(2);
11371     PN->addIncoming(SI.getOperand(0), SI.getParent());
11372     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11373     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11374   }
11375   
11376   // Advance to a place where it is safe to insert the new store and
11377   // insert it.
11378   BBI = DestBB->getFirstNonPHI();
11379   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11380                                     OtherStore->isVolatile()), *BBI);
11381   
11382   // Nuke the old stores.
11383   EraseInstFromFunction(SI);
11384   EraseInstFromFunction(*OtherStore);
11385   ++NumCombined;
11386   return true;
11387 }
11388
11389
11390 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11391   // Change br (not X), label True, label False to: br X, label False, True
11392   Value *X = 0;
11393   BasicBlock *TrueDest;
11394   BasicBlock *FalseDest;
11395   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11396       !isa<Constant>(X)) {
11397     // Swap Destinations and condition...
11398     BI.setCondition(X);
11399     BI.setSuccessor(0, FalseDest);
11400     BI.setSuccessor(1, TrueDest);
11401     return &BI;
11402   }
11403
11404   // Cannonicalize fcmp_one -> fcmp_oeq
11405   FCmpInst::Predicate FPred; Value *Y;
11406   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11407                              TrueDest, FalseDest)))
11408     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11409          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11410       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11411       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11412       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11413       NewSCC->takeName(I);
11414       // Swap Destinations and condition...
11415       BI.setCondition(NewSCC);
11416       BI.setSuccessor(0, FalseDest);
11417       BI.setSuccessor(1, TrueDest);
11418       RemoveFromWorkList(I);
11419       I->eraseFromParent();
11420       AddToWorkList(NewSCC);
11421       return &BI;
11422     }
11423
11424   // Cannonicalize icmp_ne -> icmp_eq
11425   ICmpInst::Predicate IPred;
11426   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11427                       TrueDest, FalseDest)))
11428     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11429          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11430          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11431       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11432       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11433       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11434       NewSCC->takeName(I);
11435       // Swap Destinations and condition...
11436       BI.setCondition(NewSCC);
11437       BI.setSuccessor(0, FalseDest);
11438       BI.setSuccessor(1, TrueDest);
11439       RemoveFromWorkList(I);
11440       I->eraseFromParent();;
11441       AddToWorkList(NewSCC);
11442       return &BI;
11443     }
11444
11445   return 0;
11446 }
11447
11448 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11449   Value *Cond = SI.getCondition();
11450   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11451     if (I->getOpcode() == Instruction::Add)
11452       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11453         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11454         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11455           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11456                                                 AddRHS));
11457         SI.setOperand(0, I->getOperand(0));
11458         AddToWorkList(I);
11459         return &SI;
11460       }
11461   }
11462   return 0;
11463 }
11464
11465 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11466   Value *Agg = EV.getAggregateOperand();
11467
11468   if (!EV.hasIndices())
11469     return ReplaceInstUsesWith(EV, Agg);
11470
11471   if (Constant *C = dyn_cast<Constant>(Agg)) {
11472     if (isa<UndefValue>(C))
11473       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11474       
11475     if (isa<ConstantAggregateZero>(C))
11476       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11477
11478     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11479       // Extract the element indexed by the first index out of the constant
11480       Value *V = C->getOperand(*EV.idx_begin());
11481       if (EV.getNumIndices() > 1)
11482         // Extract the remaining indices out of the constant indexed by the
11483         // first index
11484         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11485       else
11486         return ReplaceInstUsesWith(EV, V);
11487     }
11488     return 0; // Can't handle other constants
11489   } 
11490   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11491     // We're extracting from an insertvalue instruction, compare the indices
11492     const unsigned *exti, *exte, *insi, *inse;
11493     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11494          exte = EV.idx_end(), inse = IV->idx_end();
11495          exti != exte && insi != inse;
11496          ++exti, ++insi) {
11497       if (*insi != *exti)
11498         // The insert and extract both reference distinctly different elements.
11499         // This means the extract is not influenced by the insert, and we can
11500         // replace the aggregate operand of the extract with the aggregate
11501         // operand of the insert. i.e., replace
11502         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11503         // %E = extractvalue { i32, { i32 } } %I, 0
11504         // with
11505         // %E = extractvalue { i32, { i32 } } %A, 0
11506         return ExtractValueInst::Create(IV->getAggregateOperand(),
11507                                         EV.idx_begin(), EV.idx_end());
11508     }
11509     if (exti == exte && insi == inse)
11510       // Both iterators are at the end: Index lists are identical. Replace
11511       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11512       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11513       // with "i32 42"
11514       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11515     if (exti == exte) {
11516       // The extract list is a prefix of the insert list. i.e. replace
11517       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11518       // %E = extractvalue { i32, { i32 } } %I, 1
11519       // with
11520       // %X = extractvalue { i32, { i32 } } %A, 1
11521       // %E = insertvalue { i32 } %X, i32 42, 0
11522       // by switching the order of the insert and extract (though the
11523       // insertvalue should be left in, since it may have other uses).
11524       Value *NewEV = InsertNewInstBefore(
11525         ExtractValueInst::Create(IV->getAggregateOperand(),
11526                                  EV.idx_begin(), EV.idx_end()),
11527         EV);
11528       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11529                                      insi, inse);
11530     }
11531     if (insi == inse)
11532       // The insert list is a prefix of the extract list
11533       // We can simply remove the common indices from the extract and make it
11534       // operate on the inserted value instead of the insertvalue result.
11535       // i.e., replace
11536       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11537       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11538       // with
11539       // %E extractvalue { i32 } { i32 42 }, 0
11540       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11541                                       exti, exte);
11542   }
11543   // Can't simplify extracts from other values. Note that nested extracts are
11544   // already simplified implicitely by the above (extract ( extract (insert) )
11545   // will be translated into extract ( insert ( extract ) ) first and then just
11546   // the value inserted, if appropriate).
11547   return 0;
11548 }
11549
11550 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11551 /// is to leave as a vector operation.
11552 static bool CheapToScalarize(Value *V, bool isConstant) {
11553   if (isa<ConstantAggregateZero>(V)) 
11554     return true;
11555   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11556     if (isConstant) return true;
11557     // If all elts are the same, we can extract.
11558     Constant *Op0 = C->getOperand(0);
11559     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11560       if (C->getOperand(i) != Op0)
11561         return false;
11562     return true;
11563   }
11564   Instruction *I = dyn_cast<Instruction>(V);
11565   if (!I) return false;
11566   
11567   // Insert element gets simplified to the inserted element or is deleted if
11568   // this is constant idx extract element and its a constant idx insertelt.
11569   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11570       isa<ConstantInt>(I->getOperand(2)))
11571     return true;
11572   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11573     return true;
11574   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11575     if (BO->hasOneUse() &&
11576         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11577          CheapToScalarize(BO->getOperand(1), isConstant)))
11578       return true;
11579   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11580     if (CI->hasOneUse() &&
11581         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11582          CheapToScalarize(CI->getOperand(1), isConstant)))
11583       return true;
11584   
11585   return false;
11586 }
11587
11588 /// Read and decode a shufflevector mask.
11589 ///
11590 /// It turns undef elements into values that are larger than the number of
11591 /// elements in the input.
11592 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11593   unsigned NElts = SVI->getType()->getNumElements();
11594   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11595     return std::vector<unsigned>(NElts, 0);
11596   if (isa<UndefValue>(SVI->getOperand(2)))
11597     return std::vector<unsigned>(NElts, 2*NElts);
11598
11599   std::vector<unsigned> Result;
11600   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11601   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11602     if (isa<UndefValue>(*i))
11603       Result.push_back(NElts*2);  // undef -> 8
11604     else
11605       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11606   return Result;
11607 }
11608
11609 /// FindScalarElement - Given a vector and an element number, see if the scalar
11610 /// value is already around as a register, for example if it were inserted then
11611 /// extracted from the vector.
11612 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11613   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11614   const VectorType *PTy = cast<VectorType>(V->getType());
11615   unsigned Width = PTy->getNumElements();
11616   if (EltNo >= Width)  // Out of range access.
11617     return UndefValue::get(PTy->getElementType());
11618   
11619   if (isa<UndefValue>(V))
11620     return UndefValue::get(PTy->getElementType());
11621   else if (isa<ConstantAggregateZero>(V))
11622     return Constant::getNullValue(PTy->getElementType());
11623   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11624     return CP->getOperand(EltNo);
11625   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11626     // If this is an insert to a variable element, we don't know what it is.
11627     if (!isa<ConstantInt>(III->getOperand(2))) 
11628       return 0;
11629     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11630     
11631     // If this is an insert to the element we are looking for, return the
11632     // inserted value.
11633     if (EltNo == IIElt) 
11634       return III->getOperand(1);
11635     
11636     // Otherwise, the insertelement doesn't modify the value, recurse on its
11637     // vector input.
11638     return FindScalarElement(III->getOperand(0), EltNo);
11639   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11640     unsigned LHSWidth =
11641       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11642     unsigned InEl = getShuffleMask(SVI)[EltNo];
11643     if (InEl < LHSWidth)
11644       return FindScalarElement(SVI->getOperand(0), InEl);
11645     else if (InEl < LHSWidth*2)
11646       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11647     else
11648       return UndefValue::get(PTy->getElementType());
11649   }
11650   
11651   // Otherwise, we don't know.
11652   return 0;
11653 }
11654
11655 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11656   // If vector val is undef, replace extract with scalar undef.
11657   if (isa<UndefValue>(EI.getOperand(0)))
11658     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11659
11660   // If vector val is constant 0, replace extract with scalar 0.
11661   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11662     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11663   
11664   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11665     // If vector val is constant with all elements the same, replace EI with
11666     // that element. When the elements are not identical, we cannot replace yet
11667     // (we do that below, but only when the index is constant).
11668     Constant *op0 = C->getOperand(0);
11669     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11670       if (C->getOperand(i) != op0) {
11671         op0 = 0; 
11672         break;
11673       }
11674     if (op0)
11675       return ReplaceInstUsesWith(EI, op0);
11676   }
11677   
11678   // If extracting a specified index from the vector, see if we can recursively
11679   // find a previously computed scalar that was inserted into the vector.
11680   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11681     unsigned IndexVal = IdxC->getZExtValue();
11682     unsigned VectorWidth = 
11683       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11684       
11685     // If this is extracting an invalid index, turn this into undef, to avoid
11686     // crashing the code below.
11687     if (IndexVal >= VectorWidth)
11688       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11689     
11690     // This instruction only demands the single element from the input vector.
11691     // If the input vector has a single use, simplify it based on this use
11692     // property.
11693     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11694       uint64_t UndefElts;
11695       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11696                                                 1 << IndexVal,
11697                                                 UndefElts)) {
11698         EI.setOperand(0, V);
11699         return &EI;
11700       }
11701     }
11702     
11703     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11704       return ReplaceInstUsesWith(EI, Elt);
11705     
11706     // If the this extractelement is directly using a bitcast from a vector of
11707     // the same number of elements, see if we can find the source element from
11708     // it.  In this case, we will end up needing to bitcast the scalars.
11709     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11710       if (const VectorType *VT = 
11711               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11712         if (VT->getNumElements() == VectorWidth)
11713           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11714             return new BitCastInst(Elt, EI.getType());
11715     }
11716   }
11717   
11718   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11719     if (I->hasOneUse()) {
11720       // Push extractelement into predecessor operation if legal and
11721       // profitable to do so
11722       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11723         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11724         if (CheapToScalarize(BO, isConstantElt)) {
11725           ExtractElementInst *newEI0 = 
11726             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11727                                    EI.getName()+".lhs");
11728           ExtractElementInst *newEI1 =
11729             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11730                                    EI.getName()+".rhs");
11731           InsertNewInstBefore(newEI0, EI);
11732           InsertNewInstBefore(newEI1, EI);
11733           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11734         }
11735       } else if (isa<LoadInst>(I)) {
11736         unsigned AS = 
11737           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11738         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11739                                          PointerType::get(EI.getType(), AS),EI);
11740         GetElementPtrInst *GEP =
11741           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11742         InsertNewInstBefore(GEP, EI);
11743         return new LoadInst(GEP);
11744       }
11745     }
11746     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11747       // Extracting the inserted element?
11748       if (IE->getOperand(2) == EI.getOperand(1))
11749         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11750       // If the inserted and extracted elements are constants, they must not
11751       // be the same value, extract from the pre-inserted value instead.
11752       if (isa<Constant>(IE->getOperand(2)) &&
11753           isa<Constant>(EI.getOperand(1))) {
11754         AddUsesToWorkList(EI);
11755         EI.setOperand(0, IE->getOperand(0));
11756         return &EI;
11757       }
11758     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11759       // If this is extracting an element from a shufflevector, figure out where
11760       // it came from and extract from the appropriate input element instead.
11761       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11762         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11763         Value *Src;
11764         unsigned LHSWidth =
11765           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11766
11767         if (SrcIdx < LHSWidth)
11768           Src = SVI->getOperand(0);
11769         else if (SrcIdx < LHSWidth*2) {
11770           SrcIdx -= LHSWidth;
11771           Src = SVI->getOperand(1);
11772         } else {
11773           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11774         }
11775         return new ExtractElementInst(Src, SrcIdx);
11776       }
11777     }
11778   }
11779   return 0;
11780 }
11781
11782 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11783 /// elements from either LHS or RHS, return the shuffle mask and true. 
11784 /// Otherwise, return false.
11785 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11786                                          std::vector<Constant*> &Mask) {
11787   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11788          "Invalid CollectSingleShuffleElements");
11789   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11790
11791   if (isa<UndefValue>(V)) {
11792     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11793     return true;
11794   } else if (V == LHS) {
11795     for (unsigned i = 0; i != NumElts; ++i)
11796       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11797     return true;
11798   } else if (V == RHS) {
11799     for (unsigned i = 0; i != NumElts; ++i)
11800       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11801     return true;
11802   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11803     // If this is an insert of an extract from some other vector, include it.
11804     Value *VecOp    = IEI->getOperand(0);
11805     Value *ScalarOp = IEI->getOperand(1);
11806     Value *IdxOp    = IEI->getOperand(2);
11807     
11808     if (!isa<ConstantInt>(IdxOp))
11809       return false;
11810     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11811     
11812     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11813       // Okay, we can handle this if the vector we are insertinting into is
11814       // transitively ok.
11815       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11816         // If so, update the mask to reflect the inserted undef.
11817         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11818         return true;
11819       }      
11820     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11821       if (isa<ConstantInt>(EI->getOperand(1)) &&
11822           EI->getOperand(0)->getType() == V->getType()) {
11823         unsigned ExtractedIdx =
11824           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11825         
11826         // This must be extracting from either LHS or RHS.
11827         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11828           // Okay, we can handle this if the vector we are insertinting into is
11829           // transitively ok.
11830           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11831             // If so, update the mask to reflect the inserted value.
11832             if (EI->getOperand(0) == LHS) {
11833               Mask[InsertedIdx % NumElts] = 
11834                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11835             } else {
11836               assert(EI->getOperand(0) == RHS);
11837               Mask[InsertedIdx % NumElts] = 
11838                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11839               
11840             }
11841             return true;
11842           }
11843         }
11844       }
11845     }
11846   }
11847   // TODO: Handle shufflevector here!
11848   
11849   return false;
11850 }
11851
11852 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11853 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11854 /// that computes V and the LHS value of the shuffle.
11855 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11856                                      Value *&RHS) {
11857   assert(isa<VectorType>(V->getType()) && 
11858          (RHS == 0 || V->getType() == RHS->getType()) &&
11859          "Invalid shuffle!");
11860   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11861
11862   if (isa<UndefValue>(V)) {
11863     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11864     return V;
11865   } else if (isa<ConstantAggregateZero>(V)) {
11866     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11867     return V;
11868   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11869     // If this is an insert of an extract from some other vector, include it.
11870     Value *VecOp    = IEI->getOperand(0);
11871     Value *ScalarOp = IEI->getOperand(1);
11872     Value *IdxOp    = IEI->getOperand(2);
11873     
11874     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11875       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11876           EI->getOperand(0)->getType() == V->getType()) {
11877         unsigned ExtractedIdx =
11878           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11879         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11880         
11881         // Either the extracted from or inserted into vector must be RHSVec,
11882         // otherwise we'd end up with a shuffle of three inputs.
11883         if (EI->getOperand(0) == RHS || RHS == 0) {
11884           RHS = EI->getOperand(0);
11885           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11886           Mask[InsertedIdx % NumElts] = 
11887             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11888           return V;
11889         }
11890         
11891         if (VecOp == RHS) {
11892           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11893           // Everything but the extracted element is replaced with the RHS.
11894           for (unsigned i = 0; i != NumElts; ++i) {
11895             if (i != InsertedIdx)
11896               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11897           }
11898           return V;
11899         }
11900         
11901         // If this insertelement is a chain that comes from exactly these two
11902         // vectors, return the vector and the effective shuffle.
11903         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11904           return EI->getOperand(0);
11905         
11906       }
11907     }
11908   }
11909   // TODO: Handle shufflevector here!
11910   
11911   // Otherwise, can't do anything fancy.  Return an identity vector.
11912   for (unsigned i = 0; i != NumElts; ++i)
11913     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11914   return V;
11915 }
11916
11917 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11918   Value *VecOp    = IE.getOperand(0);
11919   Value *ScalarOp = IE.getOperand(1);
11920   Value *IdxOp    = IE.getOperand(2);
11921   
11922   // Inserting an undef or into an undefined place, remove this.
11923   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11924     ReplaceInstUsesWith(IE, VecOp);
11925   
11926   // If the inserted element was extracted from some other vector, and if the 
11927   // indexes are constant, try to turn this into a shufflevector operation.
11928   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11929     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11930         EI->getOperand(0)->getType() == IE.getType()) {
11931       unsigned NumVectorElts = IE.getType()->getNumElements();
11932       unsigned ExtractedIdx =
11933         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11934       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11935       
11936       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11937         return ReplaceInstUsesWith(IE, VecOp);
11938       
11939       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11940         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11941       
11942       // If we are extracting a value from a vector, then inserting it right
11943       // back into the same place, just use the input vector.
11944       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11945         return ReplaceInstUsesWith(IE, VecOp);      
11946       
11947       // We could theoretically do this for ANY input.  However, doing so could
11948       // turn chains of insertelement instructions into a chain of shufflevector
11949       // instructions, and right now we do not merge shufflevectors.  As such,
11950       // only do this in a situation where it is clear that there is benefit.
11951       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11952         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11953         // the values of VecOp, except then one read from EIOp0.
11954         // Build a new shuffle mask.
11955         std::vector<Constant*> Mask;
11956         if (isa<UndefValue>(VecOp))
11957           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11958         else {
11959           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11960           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11961                                                        NumVectorElts));
11962         } 
11963         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11964         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11965                                      ConstantVector::get(Mask));
11966       }
11967       
11968       // If this insertelement isn't used by some other insertelement, turn it
11969       // (and any insertelements it points to), into one big shuffle.
11970       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11971         std::vector<Constant*> Mask;
11972         Value *RHS = 0;
11973         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11974         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11975         // We now have a shuffle of LHS, RHS, Mask.
11976         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11977       }
11978     }
11979   }
11980
11981   return 0;
11982 }
11983
11984
11985 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11986   Value *LHS = SVI.getOperand(0);
11987   Value *RHS = SVI.getOperand(1);
11988   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11989
11990   bool MadeChange = false;
11991
11992   // Undefined shuffle mask -> undefined value.
11993   if (isa<UndefValue>(SVI.getOperand(2)))
11994     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11995
11996   uint64_t UndefElts;
11997   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11998
11999   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12000     return 0;
12001
12002   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12003   if (VWidth <= 64 &&
12004       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12005     LHS = SVI.getOperand(0);
12006     RHS = SVI.getOperand(1);
12007     MadeChange = true;
12008   }
12009   
12010   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12011   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12012   if (LHS == RHS || isa<UndefValue>(LHS)) {
12013     if (isa<UndefValue>(LHS) && LHS == RHS) {
12014       // shuffle(undef,undef,mask) -> undef.
12015       return ReplaceInstUsesWith(SVI, LHS);
12016     }
12017     
12018     // Remap any references to RHS to use LHS.
12019     std::vector<Constant*> Elts;
12020     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12021       if (Mask[i] >= 2*e)
12022         Elts.push_back(UndefValue::get(Type::Int32Ty));
12023       else {
12024         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12025             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12026           Mask[i] = 2*e;     // Turn into undef.
12027           Elts.push_back(UndefValue::get(Type::Int32Ty));
12028         } else {
12029           Mask[i] = Mask[i] % e;  // Force to LHS.
12030           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12031         }
12032       }
12033     }
12034     SVI.setOperand(0, SVI.getOperand(1));
12035     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12036     SVI.setOperand(2, ConstantVector::get(Elts));
12037     LHS = SVI.getOperand(0);
12038     RHS = SVI.getOperand(1);
12039     MadeChange = true;
12040   }
12041   
12042   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12043   bool isLHSID = true, isRHSID = true;
12044     
12045   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12046     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12047     // Is this an identity shuffle of the LHS value?
12048     isLHSID &= (Mask[i] == i);
12049       
12050     // Is this an identity shuffle of the RHS value?
12051     isRHSID &= (Mask[i]-e == i);
12052   }
12053
12054   // Eliminate identity shuffles.
12055   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12056   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12057   
12058   // If the LHS is a shufflevector itself, see if we can combine it with this
12059   // one without producing an unusual shuffle.  Here we are really conservative:
12060   // we are absolutely afraid of producing a shuffle mask not in the input
12061   // program, because the code gen may not be smart enough to turn a merged
12062   // shuffle into two specific shuffles: it may produce worse code.  As such,
12063   // we only merge two shuffles if the result is one of the two input shuffle
12064   // masks.  In this case, merging the shuffles just removes one instruction,
12065   // which we know is safe.  This is good for things like turning:
12066   // (splat(splat)) -> splat.
12067   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12068     if (isa<UndefValue>(RHS)) {
12069       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12070
12071       std::vector<unsigned> NewMask;
12072       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12073         if (Mask[i] >= 2*e)
12074           NewMask.push_back(2*e);
12075         else
12076           NewMask.push_back(LHSMask[Mask[i]]);
12077       
12078       // If the result mask is equal to the src shuffle or this shuffle mask, do
12079       // the replacement.
12080       if (NewMask == LHSMask || NewMask == Mask) {
12081         std::vector<Constant*> Elts;
12082         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12083           if (NewMask[i] >= e*2) {
12084             Elts.push_back(UndefValue::get(Type::Int32Ty));
12085           } else {
12086             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12087           }
12088         }
12089         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12090                                      LHSSVI->getOperand(1),
12091                                      ConstantVector::get(Elts));
12092       }
12093     }
12094   }
12095
12096   return MadeChange ? &SVI : 0;
12097 }
12098
12099
12100
12101
12102 /// TryToSinkInstruction - Try to move the specified instruction from its
12103 /// current block into the beginning of DestBlock, which can only happen if it's
12104 /// safe to move the instruction past all of the instructions between it and the
12105 /// end of its block.
12106 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12107   assert(I->hasOneUse() && "Invariants didn't hold!");
12108
12109   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12110   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12111     return false;
12112
12113   // Do not sink alloca instructions out of the entry block.
12114   if (isa<AllocaInst>(I) && I->getParent() ==
12115         &DestBlock->getParent()->getEntryBlock())
12116     return false;
12117
12118   // We can only sink load instructions if there is nothing between the load and
12119   // the end of block that could change the value.
12120   if (I->mayReadFromMemory()) {
12121     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12122          Scan != E; ++Scan)
12123       if (Scan->mayWriteToMemory())
12124         return false;
12125   }
12126
12127   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12128
12129   I->moveBefore(InsertPos);
12130   ++NumSunkInst;
12131   return true;
12132 }
12133
12134
12135 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12136 /// all reachable code to the worklist.
12137 ///
12138 /// This has a couple of tricks to make the code faster and more powerful.  In
12139 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12140 /// them to the worklist (this significantly speeds up instcombine on code where
12141 /// many instructions are dead or constant).  Additionally, if we find a branch
12142 /// whose condition is a known constant, we only visit the reachable successors.
12143 ///
12144 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12145                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12146                                        InstCombiner &IC,
12147                                        const TargetData *TD) {
12148   SmallVector<BasicBlock*, 256> Worklist;
12149   Worklist.push_back(BB);
12150
12151   while (!Worklist.empty()) {
12152     BB = Worklist.back();
12153     Worklist.pop_back();
12154     
12155     // We have now visited this block!  If we've already been here, ignore it.
12156     if (!Visited.insert(BB)) continue;
12157
12158     DbgInfoIntrinsic *DBI_Prev = NULL;
12159     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12160       Instruction *Inst = BBI++;
12161       
12162       // DCE instruction if trivially dead.
12163       if (isInstructionTriviallyDead(Inst)) {
12164         ++NumDeadInst;
12165         DOUT << "IC: DCE: " << *Inst;
12166         Inst->eraseFromParent();
12167         continue;
12168       }
12169       
12170       // ConstantProp instruction if trivially constant.
12171       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12172         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12173         Inst->replaceAllUsesWith(C);
12174         ++NumConstProp;
12175         Inst->eraseFromParent();
12176         continue;
12177       }
12178      
12179       // If there are two consecutive llvm.dbg.stoppoint calls then
12180       // it is likely that the optimizer deleted code in between these
12181       // two intrinsics. 
12182       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12183       if (DBI_Next) {
12184         if (DBI_Prev
12185             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12186             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12187           IC.RemoveFromWorkList(DBI_Prev);
12188           DBI_Prev->eraseFromParent();
12189         }
12190         DBI_Prev = DBI_Next;
12191       }
12192
12193       IC.AddToWorkList(Inst);
12194     }
12195
12196     // Recursively visit successors.  If this is a branch or switch on a
12197     // constant, only visit the reachable successor.
12198     TerminatorInst *TI = BB->getTerminator();
12199     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12200       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12201         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12202         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12203         Worklist.push_back(ReachableBB);
12204         continue;
12205       }
12206     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12207       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12208         // See if this is an explicit destination.
12209         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12210           if (SI->getCaseValue(i) == Cond) {
12211             BasicBlock *ReachableBB = SI->getSuccessor(i);
12212             Worklist.push_back(ReachableBB);
12213             continue;
12214           }
12215         
12216         // Otherwise it is the default destination.
12217         Worklist.push_back(SI->getSuccessor(0));
12218         continue;
12219       }
12220     }
12221     
12222     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12223       Worklist.push_back(TI->getSuccessor(i));
12224   }
12225 }
12226
12227 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12228   bool Changed = false;
12229   TD = &getAnalysis<TargetData>();
12230   
12231   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12232              << F.getNameStr() << "\n");
12233
12234   {
12235     // Do a depth-first traversal of the function, populate the worklist with
12236     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12237     // track of which blocks we visit.
12238     SmallPtrSet<BasicBlock*, 64> Visited;
12239     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12240
12241     // Do a quick scan over the function.  If we find any blocks that are
12242     // unreachable, remove any instructions inside of them.  This prevents
12243     // the instcombine code from having to deal with some bad special cases.
12244     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12245       if (!Visited.count(BB)) {
12246         Instruction *Term = BB->getTerminator();
12247         while (Term != BB->begin()) {   // Remove instrs bottom-up
12248           BasicBlock::iterator I = Term; --I;
12249
12250           DOUT << "IC: DCE: " << *I;
12251           ++NumDeadInst;
12252
12253           if (!I->use_empty())
12254             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12255           I->eraseFromParent();
12256         }
12257       }
12258   }
12259
12260   while (!Worklist.empty()) {
12261     Instruction *I = RemoveOneFromWorkList();
12262     if (I == 0) continue;  // skip null values.
12263
12264     // Check to see if we can DCE the instruction.
12265     if (isInstructionTriviallyDead(I)) {
12266       // Add operands to the worklist.
12267       if (I->getNumOperands() < 4)
12268         AddUsesToWorkList(*I);
12269       ++NumDeadInst;
12270
12271       DOUT << "IC: DCE: " << *I;
12272
12273       I->eraseFromParent();
12274       RemoveFromWorkList(I);
12275       continue;
12276     }
12277
12278     // Instruction isn't dead, see if we can constant propagate it.
12279     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12280       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12281
12282       // Add operands to the worklist.
12283       AddUsesToWorkList(*I);
12284       ReplaceInstUsesWith(*I, C);
12285
12286       ++NumConstProp;
12287       I->eraseFromParent();
12288       RemoveFromWorkList(I);
12289       continue;
12290     }
12291
12292     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12293       // See if we can constant fold its operands.
12294       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12295         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12296           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12297             i->set(NewC);
12298         }
12299       }
12300     }
12301
12302     // See if we can trivially sink this instruction to a successor basic block.
12303     if (I->hasOneUse()) {
12304       BasicBlock *BB = I->getParent();
12305       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12306       if (UserParent != BB) {
12307         bool UserIsSuccessor = false;
12308         // See if the user is one of our successors.
12309         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12310           if (*SI == UserParent) {
12311             UserIsSuccessor = true;
12312             break;
12313           }
12314
12315         // If the user is one of our immediate successors, and if that successor
12316         // only has us as a predecessors (we'd have to split the critical edge
12317         // otherwise), we can keep going.
12318         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12319             next(pred_begin(UserParent)) == pred_end(UserParent))
12320           // Okay, the CFG is simple enough, try to sink this instruction.
12321           Changed |= TryToSinkInstruction(I, UserParent);
12322       }
12323     }
12324
12325     // Now that we have an instruction, try combining it to simplify it...
12326 #ifndef NDEBUG
12327     std::string OrigI;
12328 #endif
12329     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12330     if (Instruction *Result = visit(*I)) {
12331       ++NumCombined;
12332       // Should we replace the old instruction with a new one?
12333       if (Result != I) {
12334         DOUT << "IC: Old = " << *I
12335              << "    New = " << *Result;
12336
12337         // Everything uses the new instruction now.
12338         I->replaceAllUsesWith(Result);
12339
12340         // Push the new instruction and any users onto the worklist.
12341         AddToWorkList(Result);
12342         AddUsersToWorkList(*Result);
12343
12344         // Move the name to the new instruction first.
12345         Result->takeName(I);
12346
12347         // Insert the new instruction into the basic block...
12348         BasicBlock *InstParent = I->getParent();
12349         BasicBlock::iterator InsertPos = I;
12350
12351         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12352           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12353             ++InsertPos;
12354
12355         InstParent->getInstList().insert(InsertPos, Result);
12356
12357         // Make sure that we reprocess all operands now that we reduced their
12358         // use counts.
12359         AddUsesToWorkList(*I);
12360
12361         // Instructions can end up on the worklist more than once.  Make sure
12362         // we do not process an instruction that has been deleted.
12363         RemoveFromWorkList(I);
12364
12365         // Erase the old instruction.
12366         InstParent->getInstList().erase(I);
12367       } else {
12368 #ifndef NDEBUG
12369         DOUT << "IC: Mod = " << OrigI
12370              << "    New = " << *I;
12371 #endif
12372
12373         // If the instruction was modified, it's possible that it is now dead.
12374         // if so, remove it.
12375         if (isInstructionTriviallyDead(I)) {
12376           // Make sure we process all operands now that we are reducing their
12377           // use counts.
12378           AddUsesToWorkList(*I);
12379
12380           // Instructions may end up in the worklist more than once.  Erase all
12381           // occurrences of this instruction.
12382           RemoveFromWorkList(I);
12383           I->eraseFromParent();
12384         } else {
12385           AddToWorkList(I);
12386           AddUsersToWorkList(*I);
12387         }
12388       }
12389       Changed = true;
12390     }
12391   }
12392
12393   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12394     
12395   // Do an explicit clear, this shrinks the map if needed.
12396   WorklistMap.clear();
12397   return Changed;
12398 }
12399
12400
12401 bool InstCombiner::runOnFunction(Function &F) {
12402   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12403   
12404   bool EverMadeChange = false;
12405
12406   // Iterate while there is work to do.
12407   unsigned Iteration = 0;
12408   while (DoOneIteration(F, Iteration++))
12409     EverMadeChange = true;
12410   return EverMadeChange;
12411 }
12412
12413 FunctionPass *llvm::createInstructionCombiningPass() {
12414   return new InstCombiner();
12415 }
12416
12417