Teach ValueTracking a new way to analyze PHI nodes, and and teach
[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(PtrToIntInst &CI);
222     Instruction *visitIntToPtr(IntToPtrInst &CI);
223     Instruction *visitBitCast(BitCastInst &CI);
224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225                                 Instruction *FI);
226     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
227     Instruction *visitSelectInst(SelectInst &SI);
228     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
229     Instruction *visitCallInst(CallInst &CI);
230     Instruction *visitInvokeInst(InvokeInst &II);
231     Instruction *visitPHINode(PHINode &PN);
232     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
233     Instruction *visitAllocationInst(AllocationInst &AI);
234     Instruction *visitFreeInst(FreeInst &FI);
235     Instruction *visitLoadInst(LoadInst &LI);
236     Instruction *visitStoreInst(StoreInst &SI);
237     Instruction *visitBranchInst(BranchInst &BI);
238     Instruction *visitSwitchInst(SwitchInst &SI);
239     Instruction *visitInsertElementInst(InsertElementInst &IE);
240     Instruction *visitExtractElementInst(ExtractElementInst &EI);
241     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
242     Instruction *visitExtractValueInst(ExtractValueInst &EV);
243
244     // visitInstruction - Specify what to return for unhandled instructions...
245     Instruction *visitInstruction(Instruction &I) { return 0; }
246
247   private:
248     Instruction *visitCallSite(CallSite CS);
249     bool transformConstExprCastCall(CallSite CS);
250     Instruction *transformCallThroughTrampoline(CallSite CS);
251     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
252                                    bool DoXform = true);
253     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
254     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
255
256
257   public:
258     // InsertNewInstBefore - insert an instruction New before instruction Old
259     // in the program.  Add the new instruction to the worklist.
260     //
261     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
262       assert(New && New->getParent() == 0 &&
263              "New instruction already inserted into a basic block!");
264       BasicBlock *BB = Old.getParent();
265       BB->getInstList().insert(&Old, New);  // Insert inst
266       AddToWorkList(New);
267       return New;
268     }
269
270     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
271     /// This also adds the cast to the worklist.  Finally, this returns the
272     /// cast.
273     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
274                             Instruction &Pos) {
275       if (V->getType() == Ty) return V;
276
277       if (Constant *CV = dyn_cast<Constant>(V))
278         return ConstantExpr::getCast(opc, CV, Ty);
279       
280       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
281       AddToWorkList(C);
282       return C;
283     }
284         
285     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
286       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
287     }
288
289
290     // ReplaceInstUsesWith - This method is to be used when an instruction is
291     // found to be dead, replacable with another preexisting expression.  Here
292     // we add all uses of I to the worklist, replace all uses of I with the new
293     // value, then return I, so that the inst combiner will know that I was
294     // modified.
295     //
296     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
297       AddUsersToWorkList(I);         // Add all modified instrs to worklist
298       if (&I != V) {
299         I.replaceAllUsesWith(V);
300         return &I;
301       } else {
302         // If we are replacing the instruction with itself, this must be in a
303         // segment of unreachable code, so just clobber the instruction.
304         I.replaceAllUsesWith(UndefValue::get(I.getType()));
305         return &I;
306       }
307     }
308
309     // EraseInstFromFunction - When dealing with an instruction that has side
310     // effects or produces a void value, we can't rely on DCE to delete the
311     // instruction.  Instead, visit methods should return the value returned by
312     // this function.
313     Instruction *EraseInstFromFunction(Instruction &I) {
314       assert(I.use_empty() && "Cannot erase instruction that is used!");
315       AddUsesToWorkList(I);
316       RemoveFromWorkList(&I);
317       I.eraseFromParent();
318       return 0;  // Don't do anything with FI
319     }
320         
321     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
322                            APInt &KnownOne, unsigned Depth = 0) const {
323       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
324     }
325     
326     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
327                            unsigned Depth = 0) const {
328       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
329     }
330     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
331       return llvm::ComputeNumSignBits(Op, TD, Depth);
332     }
333
334   private:
335
336     /// SimplifyCommutative - This performs a few simplifications for 
337     /// commutative operators.
338     bool SimplifyCommutative(BinaryOperator &I);
339
340     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341     /// most-complex to least-complex order.
342     bool SimplifyCompare(CmpInst &I);
343
344     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
345     /// based on the demanded bits.
346     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
347                                    APInt& KnownZero, APInt& KnownOne,
348                                    unsigned Depth);
349     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
350                               APInt& KnownZero, APInt& KnownOne,
351                               unsigned Depth=0);
352         
353     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
354     /// SimplifyDemandedBits knows about.  See if the instruction has any
355     /// properties that allow us to simplify its operands.
356     bool SimplifyDemandedInstructionBits(Instruction &Inst);
357         
358     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
359                                       APInt& UndefElts, unsigned Depth = 0);
360       
361     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
362     // PHI node as operand #0, see if we can fold the instruction into the PHI
363     // (which is only possible if all operands to the PHI are constants).
364     Instruction *FoldOpIntoPhi(Instruction &I);
365
366     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
367     // operator and they all are only used by the PHI, PHI together their
368     // inputs, and do the operation once, to the result of the PHI.
369     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
370     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
371     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
372
373     
374     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
375                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
376     
377     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
378                               bool isSub, Instruction &I);
379     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
380                                  bool isSigned, bool Inside, Instruction &IB);
381     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
382     Instruction *MatchBSwap(BinaryOperator &I);
383     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
384     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
385     Instruction *SimplifyMemSet(MemSetInst *MI);
386
387
388     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
389
390     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
391                                     unsigned CastOpc, int &NumCastsRemoved);
392     unsigned GetOrEnforceKnownAlignment(Value *V,
393                                         unsigned PrefAlign = 0);
394
395   };
396 }
397
398 char InstCombiner::ID = 0;
399 static RegisterPass<InstCombiner>
400 X("instcombine", "Combine redundant instructions");
401
402 // getComplexity:  Assign a complexity or rank value to LLVM Values...
403 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
404 static unsigned getComplexity(Value *V) {
405   if (isa<Instruction>(V)) {
406     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
407       return 3;
408     return 4;
409   }
410   if (isa<Argument>(V)) return 3;
411   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
412 }
413
414 // isOnlyUse - Return true if this instruction will be deleted if we stop using
415 // it.
416 static bool isOnlyUse(Value *V) {
417   return V->hasOneUse() || isa<Constant>(V);
418 }
419
420 // getPromotedType - Return the specified type promoted as it would be to pass
421 // though a va_arg area...
422 static const Type *getPromotedType(const Type *Ty) {
423   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
424     if (ITy->getBitWidth() < 32)
425       return Type::Int32Ty;
426   }
427   return Ty;
428 }
429
430 /// getBitCastOperand - If the specified operand is a CastInst, a constant
431 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
432 /// operand value, otherwise return null.
433 static Value *getBitCastOperand(Value *V) {
434   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
435     // BitCastInst?
436     return I->getOperand(0);
437   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
438     // GetElementPtrInst?
439     if (GEP->hasAllZeroIndices())
440       return GEP->getOperand(0);
441   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
442     if (CE->getOpcode() == Instruction::BitCast)
443       // BitCast ConstantExp?
444       return CE->getOperand(0);
445     else if (CE->getOpcode() == Instruction::GetElementPtr) {
446       // GetElementPtr ConstantExp?
447       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
448            I != E; ++I) {
449         ConstantInt *CI = dyn_cast<ConstantInt>(I);
450         if (!CI || !CI->isZero())
451           // Any non-zero indices? Not cast-like.
452           return 0;
453       }
454       // All-zero indices? This is just like casting.
455       return CE->getOperand(0);
456     }
457   }
458   return 0;
459 }
460
461 /// This function is a wrapper around CastInst::isEliminableCastPair. It
462 /// simply extracts arguments and returns what that function returns.
463 static Instruction::CastOps 
464 isEliminableCastPair(
465   const CastInst *CI, ///< The first cast instruction
466   unsigned opcode,       ///< The opcode of the second cast instruction
467   const Type *DstTy,     ///< The target type for the second cast instruction
468   TargetData *TD         ///< The target data for pointer size
469 ) {
470   
471   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
472   const Type *MidTy = CI->getType();                  // B from above
473
474   // Get the opcodes of the two Cast instructions
475   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
476   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
477
478   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
479                                                 DstTy, TD->getIntPtrType());
480   
481   // We don't want to form an inttoptr or ptrtoint that converts to an integer
482   // type that differs from the pointer size.
483   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
484       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
485     Res = 0;
486   
487   return Instruction::CastOps(Res);
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 APInt& KnownZero,
712                                                    const APInt& KnownOne,
713                                                    APInt& Min, APInt& Max) {
714   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
715          KnownZero.getBitWidth() == Min.getBitWidth() &&
716          KnownZero.getBitWidth() == Max.getBitWidth() &&
717          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
718   APInt UnknownBits = ~(KnownZero|KnownOne);
719
720   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
721   // bit if it is unknown.
722   Min = KnownOne;
723   Max = KnownOne|UnknownBits;
724   
725   if (UnknownBits.isNegative()) { // Sign bit is unknown
726     Min.set(Min.getBitWidth()-1);
727     Max.clear(Max.getBitWidth()-1);
728   }
729 }
730
731 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
732 // a set of known zero and one bits, compute the maximum and minimum values that
733 // could have the specified known zero and known one bits, returning them in
734 // min/max.
735 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
736                                                      const APInt &KnownOne,
737                                                      APInt &Min, APInt &Max) {
738   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
739          KnownZero.getBitWidth() == Min.getBitWidth() &&
740          KnownZero.getBitWidth() == Max.getBitWidth() &&
741          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
742   APInt UnknownBits = ~(KnownZero|KnownOne);
743   
744   // The minimum value is when the unknown bits are all zeros.
745   Min = KnownOne;
746   // The maximum value is when the unknown bits are all ones.
747   Max = KnownOne|UnknownBits;
748 }
749
750 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
751 /// SimplifyDemandedBits knows about.  See if the instruction has any
752 /// properties that allow us to simplify its operands.
753 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
754   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
755   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
756   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
757   
758   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
759                                      KnownZero, KnownOne, 0);
760   if (V == 0) return false;
761   if (V == &Inst) return true;
762   ReplaceInstUsesWith(Inst, V);
763   return true;
764 }
765
766 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
767 /// specified instruction operand if possible, updating it in place.  It returns
768 /// true if it made any change and false otherwise.
769 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
770                                         APInt &KnownZero, APInt &KnownOne,
771                                         unsigned Depth) {
772   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
773                                           KnownZero, KnownOne, Depth);
774   if (NewVal == 0) return false;
775   U.set(NewVal);
776   return true;
777 }
778
779
780 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
781 /// value based on the demanded bits.  When this function is called, it is known
782 /// that only the bits set in DemandedMask of the result of V are ever used
783 /// downstream. Consequently, depending on the mask and V, it may be possible
784 /// to replace V with a constant or one of its operands. In such cases, this
785 /// function does the replacement and returns true. In all other cases, it
786 /// returns false after analyzing the expression and setting KnownOne and known
787 /// to be one in the expression.  KnownZero contains all the bits that are known
788 /// to be zero in the expression. These are provided to potentially allow the
789 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
790 /// the expression. KnownOne and KnownZero always follow the invariant that 
791 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
792 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
793 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
794 /// and KnownOne must all be the same.
795 ///
796 /// This returns null if it did not change anything and it permits no
797 /// simplification.  This returns V itself if it did some simplification of V's
798 /// operands based on the information about what bits are demanded. This returns
799 /// some other non-null value if it found out that V is equal to another value
800 /// in the context where the specified bits are demanded, but not for all users.
801 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
802                                              APInt &KnownZero, APInt &KnownOne,
803                                              unsigned Depth) {
804   assert(V != 0 && "Null pointer of Value???");
805   assert(Depth <= 6 && "Limit Search Depth");
806   uint32_t BitWidth = DemandedMask.getBitWidth();
807   const Type *VTy = V->getType();
808   assert((TD || !isa<PointerType>(VTy)) &&
809          "SimplifyDemandedBits needs to know bit widths!");
810   assert((!TD || TD->getTypeSizeInBits(VTy) == BitWidth) &&
811          (!isa<IntegerType>(VTy) ||
812           VTy->getPrimitiveSizeInBits() == BitWidth) &&
813          KnownZero.getBitWidth() == BitWidth &&
814          KnownOne.getBitWidth() == BitWidth &&
815          "Value *V, DemandedMask, KnownZero and KnownOne \
816           must have same BitWidth");
817   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
818     // We know all of the bits for a constant!
819     KnownOne = CI->getValue() & DemandedMask;
820     KnownZero = ~KnownOne & DemandedMask;
821     return 0;
822   }
823   if (isa<ConstantPointerNull>(V)) {
824     // We know all of the bits for a constant!
825     KnownOne.clear();
826     KnownZero = DemandedMask;
827     return 0;
828   }
829
830   KnownZero.clear();
831   KnownOne.clear();
832   if (DemandedMask == 0) {   // Not demanding any bits from V.
833     if (isa<UndefValue>(V))
834       return 0;
835     return UndefValue::get(VTy);
836   }
837   
838   if (Depth == 6)        // Limit search depth.
839     return 0;
840   
841   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
842   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
843
844   Instruction *I = dyn_cast<Instruction>(V);
845   if (!I) {
846     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
847     return 0;        // Only analyze instructions.
848   }
849
850   // If there are multiple uses of this value and we aren't at the root, then
851   // we can't do any simplifications of the operands, because DemandedMask
852   // only reflects the bits demanded by *one* of the users.
853   if (Depth != 0 && !I->hasOneUse()) {
854     // Despite the fact that we can't simplify this instruction in all User's
855     // context, we can at least compute the knownzero/knownone bits, and we can
856     // do simplifications that apply to *just* the one user if we know that
857     // this instruction has a simpler value in that context.
858     if (I->getOpcode() == Instruction::And) {
859       // If either the LHS or the RHS are Zero, the result is zero.
860       ComputeMaskedBits(I->getOperand(1), DemandedMask,
861                         RHSKnownZero, RHSKnownOne, Depth+1);
862       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
863                         LHSKnownZero, LHSKnownOne, Depth+1);
864       
865       // If all of the demanded bits are known 1 on one side, return the other.
866       // These bits cannot contribute to the result of the 'and' in this
867       // context.
868       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
869           (DemandedMask & ~LHSKnownZero))
870         return I->getOperand(0);
871       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
872           (DemandedMask & ~RHSKnownZero))
873         return I->getOperand(1);
874       
875       // If all of the demanded bits in the inputs are known zeros, return zero.
876       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
877         return Constant::getNullValue(VTy);
878       
879     } else if (I->getOpcode() == Instruction::Or) {
880       // We can simplify (X|Y) -> X or Y in the user's context if we know that
881       // only bits from X or Y are demanded.
882       
883       // If either the LHS or the RHS are One, the result is One.
884       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
885                         RHSKnownZero, RHSKnownOne, Depth+1);
886       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
887                         LHSKnownZero, LHSKnownOne, Depth+1);
888       
889       // If all of the demanded bits are known zero on one side, return the
890       // other.  These bits cannot contribute to the result of the 'or' in this
891       // context.
892       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
893           (DemandedMask & ~LHSKnownOne))
894         return I->getOperand(0);
895       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
896           (DemandedMask & ~RHSKnownOne))
897         return I->getOperand(1);
898       
899       // If all of the potentially set bits on one side are known to be set on
900       // the other side, just use the 'other' side.
901       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
902           (DemandedMask & (~RHSKnownZero)))
903         return I->getOperand(0);
904       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
905           (DemandedMask & (~LHSKnownZero)))
906         return I->getOperand(1);
907     }
908     
909     // Compute the KnownZero/KnownOne bits to simplify things downstream.
910     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
911     return 0;
912   }
913   
914   // If this is the root being simplified, allow it to have multiple uses,
915   // just set the DemandedMask to all bits so that we can try to simplify the
916   // operands.  This allows visitTruncInst (for example) to simplify the
917   // operand of a trunc without duplicating all the logic below.
918   if (Depth == 0 && !V->hasOneUse())
919     DemandedMask = APInt::getAllOnesValue(BitWidth);
920   
921   switch (I->getOpcode()) {
922   default:
923     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
924     break;
925   case Instruction::And:
926     // If either the LHS or the RHS are Zero, the result is zero.
927     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
928                              RHSKnownZero, RHSKnownOne, Depth+1) ||
929         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
930                              LHSKnownZero, LHSKnownOne, Depth+1))
931       return I;
932     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
933     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
934
935     // If all of the demanded bits are known 1 on one side, return the other.
936     // These bits cannot contribute to the result of the 'and'.
937     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
938         (DemandedMask & ~LHSKnownZero))
939       return I->getOperand(0);
940     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
941         (DemandedMask & ~RHSKnownZero))
942       return I->getOperand(1);
943     
944     // If all of the demanded bits in the inputs are known zeros, return zero.
945     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
946       return Constant::getNullValue(VTy);
947       
948     // If the RHS is a constant, see if we can simplify it.
949     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
950       return I;
951       
952     // Output known-1 bits are only known if set in both the LHS & RHS.
953     RHSKnownOne &= LHSKnownOne;
954     // Output known-0 are known to be clear if zero in either the LHS | RHS.
955     RHSKnownZero |= LHSKnownZero;
956     break;
957   case Instruction::Or:
958     // If either the LHS or the RHS are One, the result is One.
959     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
960                              RHSKnownZero, RHSKnownOne, Depth+1) ||
961         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
962                              LHSKnownZero, LHSKnownOne, Depth+1))
963       return I;
964     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
965     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
966     
967     // If all of the demanded bits are known zero on one side, return the other.
968     // These bits cannot contribute to the result of the 'or'.
969     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
970         (DemandedMask & ~LHSKnownOne))
971       return I->getOperand(0);
972     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
973         (DemandedMask & ~RHSKnownOne))
974       return I->getOperand(1);
975
976     // If all of the potentially set bits on one side are known to be set on
977     // the other side, just use the 'other' side.
978     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
979         (DemandedMask & (~RHSKnownZero)))
980       return I->getOperand(0);
981     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
982         (DemandedMask & (~LHSKnownZero)))
983       return I->getOperand(1);
984         
985     // If the RHS is a constant, see if we can simplify it.
986     if (ShrinkDemandedConstant(I, 1, DemandedMask))
987       return I;
988           
989     // Output known-0 bits are only known if clear in both the LHS & RHS.
990     RHSKnownZero &= LHSKnownZero;
991     // Output known-1 are known to be set if set in either the LHS | RHS.
992     RHSKnownOne |= LHSKnownOne;
993     break;
994   case Instruction::Xor: {
995     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
996                              RHSKnownZero, RHSKnownOne, Depth+1) ||
997         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
998                              LHSKnownZero, LHSKnownOne, Depth+1))
999       return I;
1000     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1001     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1002     
1003     // If all of the demanded bits are known zero on one side, return the other.
1004     // These bits cannot contribute to the result of the 'xor'.
1005     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1006       return I->getOperand(0);
1007     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1008       return I->getOperand(1);
1009     
1010     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1011     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1012                          (RHSKnownOne & LHSKnownOne);
1013     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1014     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1015                         (RHSKnownOne & LHSKnownZero);
1016     
1017     // If all of the demanded bits are known to be zero on one side or the
1018     // other, turn this into an *inclusive* or.
1019     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1020     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1021       Instruction *Or =
1022         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1023                                  I->getName());
1024       return InsertNewInstBefore(Or, *I);
1025     }
1026     
1027     // If all of the demanded bits on one side are known, and all of the set
1028     // bits on that side are also known to be set on the other side, turn this
1029     // into an AND, as we know the bits will be cleared.
1030     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1031     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1032       // all known
1033       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1034         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1035         Instruction *And = 
1036           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1037         return InsertNewInstBefore(And, *I);
1038       }
1039     }
1040     
1041     // If the RHS is a constant, see if we can simplify it.
1042     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1043     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1044       return I;
1045     
1046     RHSKnownZero = KnownZeroOut;
1047     RHSKnownOne  = KnownOneOut;
1048     break;
1049   }
1050   case Instruction::Select:
1051     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1052                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1053         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1054                              LHSKnownZero, LHSKnownOne, Depth+1))
1055       return I;
1056     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1057     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1058     
1059     // If the operands are constants, see if we can simplify them.
1060     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1061         ShrinkDemandedConstant(I, 2, DemandedMask))
1062       return I;
1063     
1064     // Only known if known in both the LHS and RHS.
1065     RHSKnownOne &= LHSKnownOne;
1066     RHSKnownZero &= LHSKnownZero;
1067     break;
1068   case Instruction::Trunc: {
1069     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1070     DemandedMask.zext(truncBf);
1071     RHSKnownZero.zext(truncBf);
1072     RHSKnownOne.zext(truncBf);
1073     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1074                              RHSKnownZero, RHSKnownOne, Depth+1))
1075       return I;
1076     DemandedMask.trunc(BitWidth);
1077     RHSKnownZero.trunc(BitWidth);
1078     RHSKnownOne.trunc(BitWidth);
1079     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1080     break;
1081   }
1082   case Instruction::BitCast:
1083     if (!I->getOperand(0)->getType()->isInteger())
1084       return false;  // vector->int or fp->int?
1085     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1086                              RHSKnownZero, RHSKnownOne, Depth+1))
1087       return I;
1088     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1089     break;
1090   case Instruction::ZExt: {
1091     // Compute the bits in the result that are not present in the input.
1092     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1093     
1094     DemandedMask.trunc(SrcBitWidth);
1095     RHSKnownZero.trunc(SrcBitWidth);
1096     RHSKnownOne.trunc(SrcBitWidth);
1097     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1098                              RHSKnownZero, RHSKnownOne, Depth+1))
1099       return I;
1100     DemandedMask.zext(BitWidth);
1101     RHSKnownZero.zext(BitWidth);
1102     RHSKnownOne.zext(BitWidth);
1103     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1104     // The top bits are known to be zero.
1105     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1106     break;
1107   }
1108   case Instruction::SExt: {
1109     // Compute the bits in the result that are not present in the input.
1110     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1111     
1112     APInt InputDemandedBits = DemandedMask & 
1113                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1114
1115     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1116     // If any of the sign extended bits are demanded, we know that the sign
1117     // bit is demanded.
1118     if ((NewBits & DemandedMask) != 0)
1119       InputDemandedBits.set(SrcBitWidth-1);
1120       
1121     InputDemandedBits.trunc(SrcBitWidth);
1122     RHSKnownZero.trunc(SrcBitWidth);
1123     RHSKnownOne.trunc(SrcBitWidth);
1124     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1125                              RHSKnownZero, RHSKnownOne, Depth+1))
1126       return I;
1127     InputDemandedBits.zext(BitWidth);
1128     RHSKnownZero.zext(BitWidth);
1129     RHSKnownOne.zext(BitWidth);
1130     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1131       
1132     // If the sign bit of the input is known set or clear, then we know the
1133     // top bits of the result.
1134
1135     // If the input sign bit is known zero, or if the NewBits are not demanded
1136     // convert this into a zero extension.
1137     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1138       // Convert to ZExt cast
1139       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1140       return InsertNewInstBefore(NewCast, *I);
1141     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1142       RHSKnownOne |= NewBits;
1143     }
1144     break;
1145   }
1146   case Instruction::Add: {
1147     // Figure out what the input bits are.  If the top bits of the and result
1148     // are not demanded, then the add doesn't demand them from its input
1149     // either.
1150     unsigned NLZ = DemandedMask.countLeadingZeros();
1151       
1152     // If there is a constant on the RHS, there are a variety of xformations
1153     // we can do.
1154     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1155       // If null, this should be simplified elsewhere.  Some of the xforms here
1156       // won't work if the RHS is zero.
1157       if (RHS->isZero())
1158         break;
1159       
1160       // If the top bit of the output is demanded, demand everything from the
1161       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1162       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1163
1164       // Find information about known zero/one bits in the input.
1165       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1166                                LHSKnownZero, LHSKnownOne, Depth+1))
1167         return I;
1168
1169       // If the RHS of the add has bits set that can't affect the input, reduce
1170       // the constant.
1171       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1172         return I;
1173       
1174       // Avoid excess work.
1175       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1176         break;
1177       
1178       // Turn it into OR if input bits are zero.
1179       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1180         Instruction *Or =
1181           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1182                                    I->getName());
1183         return InsertNewInstBefore(Or, *I);
1184       }
1185       
1186       // We can say something about the output known-zero and known-one bits,
1187       // depending on potential carries from the input constant and the
1188       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1189       // bits set and the RHS constant is 0x01001, then we know we have a known
1190       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1191       
1192       // To compute this, we first compute the potential carry bits.  These are
1193       // the bits which may be modified.  I'm not aware of a better way to do
1194       // this scan.
1195       const APInt &RHSVal = RHS->getValue();
1196       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1197       
1198       // Now that we know which bits have carries, compute the known-1/0 sets.
1199       
1200       // Bits are known one if they are known zero in one operand and one in the
1201       // other, and there is no input carry.
1202       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1203                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1204       
1205       // Bits are known zero if they are known zero in both operands and there
1206       // is no input carry.
1207       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1208     } else {
1209       // If the high-bits of this ADD are not demanded, then it does not demand
1210       // the high bits of its LHS or RHS.
1211       if (DemandedMask[BitWidth-1] == 0) {
1212         // Right fill the mask of bits for this ADD to demand the most
1213         // significant bit and all those below it.
1214         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1215         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1216                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1217             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1218                                  LHSKnownZero, LHSKnownOne, Depth+1))
1219           return I;
1220       }
1221     }
1222     break;
1223   }
1224   case Instruction::Sub:
1225     // If the high-bits of this SUB are not demanded, then it does not demand
1226     // the high bits of its LHS or RHS.
1227     if (DemandedMask[BitWidth-1] == 0) {
1228       // Right fill the mask of bits for this SUB to demand the most
1229       // significant bit and all those below it.
1230       uint32_t NLZ = DemandedMask.countLeadingZeros();
1231       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1232       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1234           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1235                                LHSKnownZero, LHSKnownOne, Depth+1))
1236         return I;
1237     }
1238     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1239     // the known zeros and ones.
1240     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1241     break;
1242   case Instruction::Shl:
1243     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1244       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1245       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1246       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1247                                RHSKnownZero, RHSKnownOne, Depth+1))
1248         return I;
1249       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1250       RHSKnownZero <<= ShiftAmt;
1251       RHSKnownOne  <<= ShiftAmt;
1252       // low bits known zero.
1253       if (ShiftAmt)
1254         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1255     }
1256     break;
1257   case Instruction::LShr:
1258     // For a logical shift right
1259     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1260       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1261       
1262       // Unsigned shift right.
1263       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1264       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1265                                RHSKnownZero, RHSKnownOne, Depth+1))
1266         return I;
1267       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1268       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1269       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1270       if (ShiftAmt) {
1271         // Compute the new bits that are at the top now.
1272         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1273         RHSKnownZero |= HighBits;  // high bits known zero.
1274       }
1275     }
1276     break;
1277   case Instruction::AShr:
1278     // If this is an arithmetic shift right and only the low-bit is set, we can
1279     // always convert this into a logical shr, even if the shift amount is
1280     // variable.  The low bit of the shift cannot be an input sign bit unless
1281     // the shift amount is >= the size of the datatype, which is undefined.
1282     if (DemandedMask == 1) {
1283       // Perform the logical shift right.
1284       Instruction *NewVal = BinaryOperator::CreateLShr(
1285                         I->getOperand(0), I->getOperand(1), I->getName());
1286       return InsertNewInstBefore(NewVal, *I);
1287     }    
1288
1289     // If the sign bit is the only bit demanded by this ashr, then there is no
1290     // need to do it, the shift doesn't change the high bit.
1291     if (DemandedMask.isSignBit())
1292       return I->getOperand(0);
1293     
1294     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1295       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1296       
1297       // Signed shift right.
1298       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1299       // If any of the "high bits" are demanded, we should set the sign bit as
1300       // demanded.
1301       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1302         DemandedMaskIn.set(BitWidth-1);
1303       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1304                                RHSKnownZero, RHSKnownOne, Depth+1))
1305         return I;
1306       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1307       // Compute the new bits that are at the top now.
1308       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1309       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1310       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1311         
1312       // Handle the sign bits.
1313       APInt SignBit(APInt::getSignBit(BitWidth));
1314       // Adjust to where it is now in the mask.
1315       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1316         
1317       // If the input sign bit is known to be zero, or if none of the top bits
1318       // are demanded, turn this into an unsigned shift right.
1319       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1320           (HighBits & ~DemandedMask) == HighBits) {
1321         // Perform the logical shift right.
1322         Instruction *NewVal = BinaryOperator::CreateLShr(
1323                           I->getOperand(0), SA, I->getName());
1324         return InsertNewInstBefore(NewVal, *I);
1325       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1326         RHSKnownOne |= HighBits;
1327       }
1328     }
1329     break;
1330   case Instruction::SRem:
1331     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1332       APInt RA = Rem->getValue().abs();
1333       if (RA.isPowerOf2()) {
1334         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1335           return I->getOperand(0);
1336
1337         APInt LowBits = RA - 1;
1338         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1339         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1340                                  LHSKnownZero, LHSKnownOne, Depth+1))
1341           return I;
1342
1343         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1344           LHSKnownZero |= ~LowBits;
1345
1346         KnownZero |= LHSKnownZero & DemandedMask;
1347
1348         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1349       }
1350     }
1351     break;
1352   case Instruction::URem: {
1353     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1354     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1355     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1356                              KnownZero2, KnownOne2, Depth+1) ||
1357         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1358                              KnownZero2, KnownOne2, Depth+1))
1359       return I;
1360
1361     unsigned Leaders = KnownZero2.countLeadingOnes();
1362     Leaders = std::max(Leaders,
1363                        KnownZero2.countLeadingOnes());
1364     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1365     break;
1366   }
1367   case Instruction::Call:
1368     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1369       switch (II->getIntrinsicID()) {
1370       default: break;
1371       case Intrinsic::bswap: {
1372         // If the only bits demanded come from one byte of the bswap result,
1373         // just shift the input byte into position to eliminate the bswap.
1374         unsigned NLZ = DemandedMask.countLeadingZeros();
1375         unsigned NTZ = DemandedMask.countTrailingZeros();
1376           
1377         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1378         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1379         // have 14 leading zeros, round to 8.
1380         NLZ &= ~7;
1381         NTZ &= ~7;
1382         // If we need exactly one byte, we can do this transformation.
1383         if (BitWidth-NLZ-NTZ == 8) {
1384           unsigned ResultBit = NTZ;
1385           unsigned InputBit = BitWidth-NTZ-8;
1386           
1387           // Replace this with either a left or right shift to get the byte into
1388           // the right place.
1389           Instruction *NewVal;
1390           if (InputBit > ResultBit)
1391             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1392                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1393           else
1394             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1395                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1396           NewVal->takeName(I);
1397           return InsertNewInstBefore(NewVal, *I);
1398         }
1399           
1400         // TODO: Could compute known zero/one bits based on the input.
1401         break;
1402       }
1403       }
1404     }
1405     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1406     break;
1407   }
1408   
1409   // If the client is only demanding bits that we know, return the known
1410   // constant.
1411   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1412     Constant *C = ConstantInt::get(RHSKnownOne);
1413     if (isa<PointerType>(V->getType()))
1414       C = ConstantExpr::getIntToPtr(C, V->getType());
1415     return C;
1416   }
1417   return false;
1418 }
1419
1420
1421 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1422 /// any number of elements. DemandedElts contains the set of elements that are
1423 /// actually used by the caller.  This method analyzes which elements of the
1424 /// operand are undef and returns that information in UndefElts.
1425 ///
1426 /// If the information about demanded elements can be used to simplify the
1427 /// operation, the operation is simplified, then the resultant value is
1428 /// returned.  This returns null if no change was made.
1429 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1430                                                 APInt& UndefElts,
1431                                                 unsigned Depth) {
1432   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1433   APInt EltMask(APInt::getAllOnesValue(VWidth));
1434   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1435
1436   if (isa<UndefValue>(V)) {
1437     // If the entire vector is undefined, just return this info.
1438     UndefElts = EltMask;
1439     return 0;
1440   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1441     UndefElts = EltMask;
1442     return UndefValue::get(V->getType());
1443   }
1444
1445   UndefElts = 0;
1446   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1447     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1448     Constant *Undef = UndefValue::get(EltTy);
1449
1450     std::vector<Constant*> Elts;
1451     for (unsigned i = 0; i != VWidth; ++i)
1452       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1453         Elts.push_back(Undef);
1454         UndefElts.set(i);
1455       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1456         Elts.push_back(Undef);
1457         UndefElts.set(i);
1458       } else {                               // Otherwise, defined.
1459         Elts.push_back(CP->getOperand(i));
1460       }
1461
1462     // If we changed the constant, return it.
1463     Constant *NewCP = ConstantVector::get(Elts);
1464     return NewCP != CP ? NewCP : 0;
1465   } else if (isa<ConstantAggregateZero>(V)) {
1466     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1467     // set to undef.
1468     
1469     // Check if this is identity. If so, return 0 since we are not simplifying
1470     // anything.
1471     if (DemandedElts == ((1ULL << VWidth) -1))
1472       return 0;
1473     
1474     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1475     Constant *Zero = Constant::getNullValue(EltTy);
1476     Constant *Undef = UndefValue::get(EltTy);
1477     std::vector<Constant*> Elts;
1478     for (unsigned i = 0; i != VWidth; ++i) {
1479       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1480       Elts.push_back(Elt);
1481     }
1482     UndefElts = DemandedElts ^ EltMask;
1483     return ConstantVector::get(Elts);
1484   }
1485   
1486   // Limit search depth.
1487   if (Depth == 10)
1488     return 0;
1489
1490   // If multiple users are using the root value, procede with
1491   // simplification conservatively assuming that all elements
1492   // are needed.
1493   if (!V->hasOneUse()) {
1494     // Quit if we find multiple users of a non-root value though.
1495     // They'll be handled when it's their turn to be visited by
1496     // the main instcombine process.
1497     if (Depth != 0)
1498       // TODO: Just compute the UndefElts information recursively.
1499       return 0;
1500
1501     // Conservatively assume that all elements are needed.
1502     DemandedElts = EltMask;
1503   }
1504   
1505   Instruction *I = dyn_cast<Instruction>(V);
1506   if (!I) return 0;        // Only analyze instructions.
1507   
1508   bool MadeChange = false;
1509   APInt UndefElts2(VWidth, 0);
1510   Value *TmpV;
1511   switch (I->getOpcode()) {
1512   default: break;
1513     
1514   case Instruction::InsertElement: {
1515     // If this is a variable index, we don't know which element it overwrites.
1516     // demand exactly the same input as we produce.
1517     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1518     if (Idx == 0) {
1519       // Note that we can't propagate undef elt info, because we don't know
1520       // which elt is getting updated.
1521       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1522                                         UndefElts2, Depth+1);
1523       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1524       break;
1525     }
1526     
1527     // If this is inserting an element that isn't demanded, remove this
1528     // insertelement.
1529     unsigned IdxNo = Idx->getZExtValue();
1530     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1531       return AddSoonDeadInstToWorklist(*I, 0);
1532     
1533     // Otherwise, the element inserted overwrites whatever was there, so the
1534     // input demanded set is simpler than the output set.
1535     APInt DemandedElts2 = DemandedElts;
1536     DemandedElts2.clear(IdxNo);
1537     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1538                                       UndefElts, Depth+1);
1539     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1540
1541     // The inserted element is defined.
1542     UndefElts.clear(IdxNo);
1543     break;
1544   }
1545   case Instruction::ShuffleVector: {
1546     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1547     uint64_t LHSVWidth =
1548       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1549     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1550     for (unsigned i = 0; i < VWidth; i++) {
1551       if (DemandedElts[i]) {
1552         unsigned MaskVal = Shuffle->getMaskValue(i);
1553         if (MaskVal != -1u) {
1554           assert(MaskVal < LHSVWidth * 2 &&
1555                  "shufflevector mask index out of range!");
1556           if (MaskVal < LHSVWidth)
1557             LeftDemanded.set(MaskVal);
1558           else
1559             RightDemanded.set(MaskVal - LHSVWidth);
1560         }
1561       }
1562     }
1563
1564     APInt UndefElts4(LHSVWidth, 0);
1565     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1566                                       UndefElts4, Depth+1);
1567     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1568
1569     APInt UndefElts3(LHSVWidth, 0);
1570     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1571                                       UndefElts3, Depth+1);
1572     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1573
1574     bool NewUndefElts = false;
1575     for (unsigned i = 0; i < VWidth; i++) {
1576       unsigned MaskVal = Shuffle->getMaskValue(i);
1577       if (MaskVal == -1u) {
1578         UndefElts.set(i);
1579       } else if (MaskVal < LHSVWidth) {
1580         if (UndefElts4[MaskVal]) {
1581           NewUndefElts = true;
1582           UndefElts.set(i);
1583         }
1584       } else {
1585         if (UndefElts3[MaskVal - LHSVWidth]) {
1586           NewUndefElts = true;
1587           UndefElts.set(i);
1588         }
1589       }
1590     }
1591
1592     if (NewUndefElts) {
1593       // Add additional discovered undefs.
1594       std::vector<Constant*> Elts;
1595       for (unsigned i = 0; i < VWidth; ++i) {
1596         if (UndefElts[i])
1597           Elts.push_back(UndefValue::get(Type::Int32Ty));
1598         else
1599           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1600                                           Shuffle->getMaskValue(i)));
1601       }
1602       I->setOperand(2, ConstantVector::get(Elts));
1603       MadeChange = true;
1604     }
1605     break;
1606   }
1607   case Instruction::BitCast: {
1608     // Vector->vector casts only.
1609     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1610     if (!VTy) break;
1611     unsigned InVWidth = VTy->getNumElements();
1612     APInt InputDemandedElts(InVWidth, 0);
1613     unsigned Ratio;
1614
1615     if (VWidth == InVWidth) {
1616       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1617       // elements as are demanded of us.
1618       Ratio = 1;
1619       InputDemandedElts = DemandedElts;
1620     } else if (VWidth > InVWidth) {
1621       // Untested so far.
1622       break;
1623       
1624       // If there are more elements in the result than there are in the source,
1625       // then an input element is live if any of the corresponding output
1626       // elements are live.
1627       Ratio = VWidth/InVWidth;
1628       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1629         if (DemandedElts[OutIdx])
1630           InputDemandedElts.set(OutIdx/Ratio);
1631       }
1632     } else {
1633       // Untested so far.
1634       break;
1635       
1636       // If there are more elements in the source than there are in the result,
1637       // then an input element is live if the corresponding output element is
1638       // live.
1639       Ratio = InVWidth/VWidth;
1640       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1641         if (DemandedElts[InIdx/Ratio])
1642           InputDemandedElts.set(InIdx);
1643     }
1644     
1645     // div/rem demand all inputs, because they don't want divide by zero.
1646     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1647                                       UndefElts2, Depth+1);
1648     if (TmpV) {
1649       I->setOperand(0, TmpV);
1650       MadeChange = true;
1651     }
1652     
1653     UndefElts = UndefElts2;
1654     if (VWidth > InVWidth) {
1655       assert(0 && "Unimp");
1656       // If there are more elements in the result than there are in the source,
1657       // then an output element is undef if the corresponding input element is
1658       // undef.
1659       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1660         if (UndefElts2[OutIdx/Ratio])
1661           UndefElts.set(OutIdx);
1662     } else if (VWidth < InVWidth) {
1663       assert(0 && "Unimp");
1664       // If there are more elements in the source than there are in the result,
1665       // then a result element is undef if all of the corresponding input
1666       // elements are undef.
1667       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1668       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1669         if (!UndefElts2[InIdx])            // Not undef?
1670           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1671     }
1672     break;
1673   }
1674   case Instruction::And:
1675   case Instruction::Or:
1676   case Instruction::Xor:
1677   case Instruction::Add:
1678   case Instruction::Sub:
1679   case Instruction::Mul:
1680     // div/rem demand all inputs, because they don't want divide by zero.
1681     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1682                                       UndefElts, Depth+1);
1683     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1684     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1685                                       UndefElts2, Depth+1);
1686     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1687       
1688     // Output elements are undefined if both are undefined.  Consider things
1689     // like undef&0.  The result is known zero, not undef.
1690     UndefElts &= UndefElts2;
1691     break;
1692     
1693   case Instruction::Call: {
1694     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1695     if (!II) break;
1696     switch (II->getIntrinsicID()) {
1697     default: break;
1698       
1699     // Binary vector operations that work column-wise.  A dest element is a
1700     // function of the corresponding input elements from the two inputs.
1701     case Intrinsic::x86_sse_sub_ss:
1702     case Intrinsic::x86_sse_mul_ss:
1703     case Intrinsic::x86_sse_min_ss:
1704     case Intrinsic::x86_sse_max_ss:
1705     case Intrinsic::x86_sse2_sub_sd:
1706     case Intrinsic::x86_sse2_mul_sd:
1707     case Intrinsic::x86_sse2_min_sd:
1708     case Intrinsic::x86_sse2_max_sd:
1709       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1710                                         UndefElts, Depth+1);
1711       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1712       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1713                                         UndefElts2, Depth+1);
1714       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1715
1716       // If only the low elt is demanded and this is a scalarizable intrinsic,
1717       // scalarize it now.
1718       if (DemandedElts == 1) {
1719         switch (II->getIntrinsicID()) {
1720         default: break;
1721         case Intrinsic::x86_sse_sub_ss:
1722         case Intrinsic::x86_sse_mul_ss:
1723         case Intrinsic::x86_sse2_sub_sd:
1724         case Intrinsic::x86_sse2_mul_sd:
1725           // TODO: Lower MIN/MAX/ABS/etc
1726           Value *LHS = II->getOperand(1);
1727           Value *RHS = II->getOperand(2);
1728           // Extract the element as scalars.
1729           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1730           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1731           
1732           switch (II->getIntrinsicID()) {
1733           default: assert(0 && "Case stmts out of sync!");
1734           case Intrinsic::x86_sse_sub_ss:
1735           case Intrinsic::x86_sse2_sub_sd:
1736             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1737                                                         II->getName()), *II);
1738             break;
1739           case Intrinsic::x86_sse_mul_ss:
1740           case Intrinsic::x86_sse2_mul_sd:
1741             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1742                                                          II->getName()), *II);
1743             break;
1744           }
1745           
1746           Instruction *New =
1747             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1748                                       II->getName());
1749           InsertNewInstBefore(New, *II);
1750           AddSoonDeadInstToWorklist(*II, 0);
1751           return New;
1752         }            
1753       }
1754         
1755       // Output elements are undefined if both are undefined.  Consider things
1756       // like undef&0.  The result is known zero, not undef.
1757       UndefElts &= UndefElts2;
1758       break;
1759     }
1760     break;
1761   }
1762   }
1763   return MadeChange ? I : 0;
1764 }
1765
1766
1767 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1768 /// function is designed to check a chain of associative operators for a
1769 /// potential to apply a certain optimization.  Since the optimization may be
1770 /// applicable if the expression was reassociated, this checks the chain, then
1771 /// reassociates the expression as necessary to expose the optimization
1772 /// opportunity.  This makes use of a special Functor, which must define
1773 /// 'shouldApply' and 'apply' methods.
1774 ///
1775 template<typename Functor>
1776 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1777   unsigned Opcode = Root.getOpcode();
1778   Value *LHS = Root.getOperand(0);
1779
1780   // Quick check, see if the immediate LHS matches...
1781   if (F.shouldApply(LHS))
1782     return F.apply(Root);
1783
1784   // Otherwise, if the LHS is not of the same opcode as the root, return.
1785   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1786   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1787     // Should we apply this transform to the RHS?
1788     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1789
1790     // If not to the RHS, check to see if we should apply to the LHS...
1791     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1792       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1793       ShouldApply = true;
1794     }
1795
1796     // If the functor wants to apply the optimization to the RHS of LHSI,
1797     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1798     if (ShouldApply) {
1799       // Now all of the instructions are in the current basic block, go ahead
1800       // and perform the reassociation.
1801       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1802
1803       // First move the selected RHS to the LHS of the root...
1804       Root.setOperand(0, LHSI->getOperand(1));
1805
1806       // Make what used to be the LHS of the root be the user of the root...
1807       Value *ExtraOperand = TmpLHSI->getOperand(1);
1808       if (&Root == TmpLHSI) {
1809         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1810         return 0;
1811       }
1812       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1813       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1814       BasicBlock::iterator ARI = &Root; ++ARI;
1815       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1816       ARI = Root;
1817
1818       // Now propagate the ExtraOperand down the chain of instructions until we
1819       // get to LHSI.
1820       while (TmpLHSI != LHSI) {
1821         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1822         // Move the instruction to immediately before the chain we are
1823         // constructing to avoid breaking dominance properties.
1824         NextLHSI->moveBefore(ARI);
1825         ARI = NextLHSI;
1826
1827         Value *NextOp = NextLHSI->getOperand(1);
1828         NextLHSI->setOperand(1, ExtraOperand);
1829         TmpLHSI = NextLHSI;
1830         ExtraOperand = NextOp;
1831       }
1832
1833       // Now that the instructions are reassociated, have the functor perform
1834       // the transformation...
1835       return F.apply(Root);
1836     }
1837
1838     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1839   }
1840   return 0;
1841 }
1842
1843 namespace {
1844
1845 // AddRHS - Implements: X + X --> X << 1
1846 struct AddRHS {
1847   Value *RHS;
1848   AddRHS(Value *rhs) : RHS(rhs) {}
1849   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1850   Instruction *apply(BinaryOperator &Add) const {
1851     return BinaryOperator::CreateShl(Add.getOperand(0),
1852                                      ConstantInt::get(Add.getType(), 1));
1853   }
1854 };
1855
1856 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1857 //                 iff C1&C2 == 0
1858 struct AddMaskingAnd {
1859   Constant *C2;
1860   AddMaskingAnd(Constant *c) : C2(c) {}
1861   bool shouldApply(Value *LHS) const {
1862     ConstantInt *C1;
1863     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1864            ConstantExpr::getAnd(C1, C2)->isNullValue();
1865   }
1866   Instruction *apply(BinaryOperator &Add) const {
1867     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1868   }
1869 };
1870
1871 }
1872
1873 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1874                                              InstCombiner *IC) {
1875   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1876     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1877   }
1878
1879   // Figure out if the constant is the left or the right argument.
1880   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1881   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1882
1883   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1884     if (ConstIsRHS)
1885       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1886     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1887   }
1888
1889   Value *Op0 = SO, *Op1 = ConstOperand;
1890   if (!ConstIsRHS)
1891     std::swap(Op0, Op1);
1892   Instruction *New;
1893   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1894     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1895   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1896     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1897                           SO->getName()+".cmp");
1898   else {
1899     assert(0 && "Unknown binary instruction type!");
1900     abort();
1901   }
1902   return IC->InsertNewInstBefore(New, I);
1903 }
1904
1905 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1906 // constant as the other operand, try to fold the binary operator into the
1907 // select arguments.  This also works for Cast instructions, which obviously do
1908 // not have a second operand.
1909 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1910                                      InstCombiner *IC) {
1911   // Don't modify shared select instructions
1912   if (!SI->hasOneUse()) return 0;
1913   Value *TV = SI->getOperand(1);
1914   Value *FV = SI->getOperand(2);
1915
1916   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1917     // Bool selects with constant operands can be folded to logical ops.
1918     if (SI->getType() == Type::Int1Ty) return 0;
1919
1920     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1921     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1922
1923     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1924                               SelectFalseVal);
1925   }
1926   return 0;
1927 }
1928
1929
1930 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1931 /// node as operand #0, see if we can fold the instruction into the PHI (which
1932 /// is only possible if all operands to the PHI are constants).
1933 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1934   PHINode *PN = cast<PHINode>(I.getOperand(0));
1935   unsigned NumPHIValues = PN->getNumIncomingValues();
1936   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1937
1938   // Check to see if all of the operands of the PHI are constants.  If there is
1939   // one non-constant value, remember the BB it is.  If there is more than one
1940   // or if *it* is a PHI, bail out.
1941   BasicBlock *NonConstBB = 0;
1942   for (unsigned i = 0; i != NumPHIValues; ++i)
1943     if (!isa<Constant>(PN->getIncomingValue(i))) {
1944       if (NonConstBB) return 0;  // More than one non-const value.
1945       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1946       NonConstBB = PN->getIncomingBlock(i);
1947       
1948       // If the incoming non-constant value is in I's block, we have an infinite
1949       // loop.
1950       if (NonConstBB == I.getParent())
1951         return 0;
1952     }
1953   
1954   // If there is exactly one non-constant value, we can insert a copy of the
1955   // operation in that block.  However, if this is a critical edge, we would be
1956   // inserting the computation one some other paths (e.g. inside a loop).  Only
1957   // do this if the pred block is unconditionally branching into the phi block.
1958   if (NonConstBB) {
1959     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1960     if (!BI || !BI->isUnconditional()) return 0;
1961   }
1962
1963   // Okay, we can do the transformation: create the new PHI node.
1964   PHINode *NewPN = PHINode::Create(I.getType(), "");
1965   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1966   InsertNewInstBefore(NewPN, *PN);
1967   NewPN->takeName(PN);
1968
1969   // Next, add all of the operands to the PHI.
1970   if (I.getNumOperands() == 2) {
1971     Constant *C = cast<Constant>(I.getOperand(1));
1972     for (unsigned i = 0; i != NumPHIValues; ++i) {
1973       Value *InV = 0;
1974       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1975         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1976           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1977         else
1978           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1979       } else {
1980         assert(PN->getIncomingBlock(i) == NonConstBB);
1981         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1982           InV = BinaryOperator::Create(BO->getOpcode(),
1983                                        PN->getIncomingValue(i), C, "phitmp",
1984                                        NonConstBB->getTerminator());
1985         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1986           InV = CmpInst::Create(CI->getOpcode(), 
1987                                 CI->getPredicate(),
1988                                 PN->getIncomingValue(i), C, "phitmp",
1989                                 NonConstBB->getTerminator());
1990         else
1991           assert(0 && "Unknown binop!");
1992         
1993         AddToWorkList(cast<Instruction>(InV));
1994       }
1995       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1996     }
1997   } else { 
1998     CastInst *CI = cast<CastInst>(&I);
1999     const Type *RetTy = CI->getType();
2000     for (unsigned i = 0; i != NumPHIValues; ++i) {
2001       Value *InV;
2002       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2003         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2004       } else {
2005         assert(PN->getIncomingBlock(i) == NonConstBB);
2006         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2007                                I.getType(), "phitmp", 
2008                                NonConstBB->getTerminator());
2009         AddToWorkList(cast<Instruction>(InV));
2010       }
2011       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2012     }
2013   }
2014   return ReplaceInstUsesWith(I, NewPN);
2015 }
2016
2017
2018 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2019 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2020 /// This basically requires proving that the add in the original type would not
2021 /// overflow to change the sign bit or have a carry out.
2022 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2023   // There are different heuristics we can use for this.  Here are some simple
2024   // ones.
2025   
2026   // Add has the property that adding any two 2's complement numbers can only 
2027   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2028   // have at least two sign bits, we know that the addition of the two values will
2029   // sign extend fine.
2030   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2031     return true;
2032   
2033   
2034   // If one of the operands only has one non-zero bit, and if the other operand
2035   // has a known-zero bit in a more significant place than it (not including the
2036   // sign bit) the ripple may go up to and fill the zero, but won't change the
2037   // sign.  For example, (X & ~4) + 1.
2038   
2039   // TODO: Implement.
2040   
2041   return false;
2042 }
2043
2044
2045 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2046   bool Changed = SimplifyCommutative(I);
2047   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2048
2049   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2050     // X + undef -> undef
2051     if (isa<UndefValue>(RHS))
2052       return ReplaceInstUsesWith(I, RHS);
2053
2054     // X + 0 --> X
2055     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2056       if (RHSC->isNullValue())
2057         return ReplaceInstUsesWith(I, LHS);
2058     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2059       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2060                               (I.getType())->getValueAPF()))
2061         return ReplaceInstUsesWith(I, LHS);
2062     }
2063
2064     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2065       // X + (signbit) --> X ^ signbit
2066       const APInt& Val = CI->getValue();
2067       uint32_t BitWidth = Val.getBitWidth();
2068       if (Val == APInt::getSignBit(BitWidth))
2069         return BinaryOperator::CreateXor(LHS, RHS);
2070       
2071       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2072       // (X & 254)+1 -> (X&254)|1
2073       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2074         return &I;
2075
2076       // zext(i1) - 1  ->  select i1, 0, -1
2077       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2078         if (CI->isAllOnesValue() &&
2079             ZI->getOperand(0)->getType() == Type::Int1Ty)
2080           return SelectInst::Create(ZI->getOperand(0),
2081                                     Constant::getNullValue(I.getType()),
2082                                     ConstantInt::getAllOnesValue(I.getType()));
2083     }
2084
2085     if (isa<PHINode>(LHS))
2086       if (Instruction *NV = FoldOpIntoPhi(I))
2087         return NV;
2088     
2089     ConstantInt *XorRHS = 0;
2090     Value *XorLHS = 0;
2091     if (isa<ConstantInt>(RHSC) &&
2092         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2093       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2094       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2095       
2096       uint32_t Size = TySizeBits / 2;
2097       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2098       APInt CFF80Val(-C0080Val);
2099       do {
2100         if (TySizeBits > Size) {
2101           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2102           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2103           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2104               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2105             // This is a sign extend if the top bits are known zero.
2106             if (!MaskedValueIsZero(XorLHS, 
2107                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2108               Size = 0;  // Not a sign ext, but can't be any others either.
2109             break;
2110           }
2111         }
2112         Size >>= 1;
2113         C0080Val = APIntOps::lshr(C0080Val, Size);
2114         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2115       } while (Size >= 1);
2116       
2117       // FIXME: This shouldn't be necessary. When the backends can handle types
2118       // with funny bit widths then this switch statement should be removed. It
2119       // is just here to get the size of the "middle" type back up to something
2120       // that the back ends can handle.
2121       const Type *MiddleType = 0;
2122       switch (Size) {
2123         default: break;
2124         case 32: MiddleType = Type::Int32Ty; break;
2125         case 16: MiddleType = Type::Int16Ty; break;
2126         case  8: MiddleType = Type::Int8Ty; break;
2127       }
2128       if (MiddleType) {
2129         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2130         InsertNewInstBefore(NewTrunc, I);
2131         return new SExtInst(NewTrunc, I.getType(), I.getName());
2132       }
2133     }
2134   }
2135
2136   if (I.getType() == Type::Int1Ty)
2137     return BinaryOperator::CreateXor(LHS, RHS);
2138
2139   // X + X --> X << 1
2140   if (I.getType()->isInteger()) {
2141     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2142
2143     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2144       if (RHSI->getOpcode() == Instruction::Sub)
2145         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2146           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2147     }
2148     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2149       if (LHSI->getOpcode() == Instruction::Sub)
2150         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2151           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2152     }
2153   }
2154
2155   // -A + B  -->  B - A
2156   // -A + -B  -->  -(A + B)
2157   if (Value *LHSV = dyn_castNegVal(LHS)) {
2158     if (LHS->getType()->isIntOrIntVector()) {
2159       if (Value *RHSV = dyn_castNegVal(RHS)) {
2160         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2161         InsertNewInstBefore(NewAdd, I);
2162         return BinaryOperator::CreateNeg(NewAdd);
2163       }
2164     }
2165     
2166     return BinaryOperator::CreateSub(RHS, LHSV);
2167   }
2168
2169   // A + -B  -->  A - B
2170   if (!isa<Constant>(RHS))
2171     if (Value *V = dyn_castNegVal(RHS))
2172       return BinaryOperator::CreateSub(LHS, V);
2173
2174
2175   ConstantInt *C2;
2176   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2177     if (X == RHS)   // X*C + X --> X * (C+1)
2178       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2179
2180     // X*C1 + X*C2 --> X * (C1+C2)
2181     ConstantInt *C1;
2182     if (X == dyn_castFoldableMul(RHS, C1))
2183       return BinaryOperator::CreateMul(X, Add(C1, C2));
2184   }
2185
2186   // X + X*C --> X * (C+1)
2187   if (dyn_castFoldableMul(RHS, C2) == LHS)
2188     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2189
2190   // X + ~X --> -1   since   ~X = -X-1
2191   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2192     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2193   
2194
2195   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2196   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2197     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2198       return R;
2199   
2200   // A+B --> A|B iff A and B have no bits set in common.
2201   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2202     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2203     APInt LHSKnownOne(IT->getBitWidth(), 0);
2204     APInt LHSKnownZero(IT->getBitWidth(), 0);
2205     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2206     if (LHSKnownZero != 0) {
2207       APInt RHSKnownOne(IT->getBitWidth(), 0);
2208       APInt RHSKnownZero(IT->getBitWidth(), 0);
2209       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2210       
2211       // No bits in common -> bitwise or.
2212       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2213         return BinaryOperator::CreateOr(LHS, RHS);
2214     }
2215   }
2216
2217   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2218   if (I.getType()->isIntOrIntVector()) {
2219     Value *W, *X, *Y, *Z;
2220     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2221         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2222       if (W != Y) {
2223         if (W == Z) {
2224           std::swap(Y, Z);
2225         } else if (Y == X) {
2226           std::swap(W, X);
2227         } else if (X == Z) {
2228           std::swap(Y, Z);
2229           std::swap(W, X);
2230         }
2231       }
2232
2233       if (W == Y) {
2234         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2235                                                             LHS->getName()), I);
2236         return BinaryOperator::CreateMul(W, NewAdd);
2237       }
2238     }
2239   }
2240
2241   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2242     Value *X = 0;
2243     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2244       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2245
2246     // (X & FF00) + xx00  -> (X+xx00) & FF00
2247     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2248       Constant *Anded = And(CRHS, C2);
2249       if (Anded == CRHS) {
2250         // See if all bits from the first bit set in the Add RHS up are included
2251         // in the mask.  First, get the rightmost bit.
2252         const APInt& AddRHSV = CRHS->getValue();
2253
2254         // Form a mask of all bits from the lowest bit added through the top.
2255         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2256
2257         // See if the and mask includes all of these bits.
2258         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2259
2260         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2261           // Okay, the xform is safe.  Insert the new add pronto.
2262           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2263                                                             LHS->getName()), I);
2264           return BinaryOperator::CreateAnd(NewAdd, C2);
2265         }
2266       }
2267     }
2268
2269     // Try to fold constant add into select arguments.
2270     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2271       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2272         return R;
2273   }
2274
2275   // add (cast *A to intptrtype) B -> 
2276   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2277   {
2278     CastInst *CI = dyn_cast<CastInst>(LHS);
2279     Value *Other = RHS;
2280     if (!CI) {
2281       CI = dyn_cast<CastInst>(RHS);
2282       Other = LHS;
2283     }
2284     if (CI && CI->getType()->isSized() && 
2285         (CI->getType()->getPrimitiveSizeInBits() == 
2286          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2287         && isa<PointerType>(CI->getOperand(0)->getType())) {
2288       unsigned AS =
2289         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2290       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2291                                       PointerType::get(Type::Int8Ty, AS), I);
2292       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2293       return new PtrToIntInst(I2, CI->getType());
2294     }
2295   }
2296   
2297   // add (select X 0 (sub n A)) A  -->  select X A n
2298   {
2299     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2300     Value *A = RHS;
2301     if (!SI) {
2302       SI = dyn_cast<SelectInst>(RHS);
2303       A = LHS;
2304     }
2305     if (SI && SI->hasOneUse()) {
2306       Value *TV = SI->getTrueValue();
2307       Value *FV = SI->getFalseValue();
2308       Value *N;
2309
2310       // Can we fold the add into the argument of the select?
2311       // We check both true and false select arguments for a matching subtract.
2312       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2313         // Fold the add into the true select value.
2314         return SelectInst::Create(SI->getCondition(), N, A);
2315       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2316         // Fold the add into the false select value.
2317         return SelectInst::Create(SI->getCondition(), A, N);
2318     }
2319   }
2320   
2321   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2322   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2323     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2324       return ReplaceInstUsesWith(I, LHS);
2325
2326   // Check for (add (sext x), y), see if we can merge this into an
2327   // integer add followed by a sext.
2328   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2329     // (add (sext x), cst) --> (sext (add x, cst'))
2330     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2331       Constant *CI = 
2332         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2333       if (LHSConv->hasOneUse() &&
2334           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2335           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2336         // Insert the new, smaller add.
2337         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2338                                                         CI, "addconv");
2339         InsertNewInstBefore(NewAdd, I);
2340         return new SExtInst(NewAdd, I.getType());
2341       }
2342     }
2343     
2344     // (add (sext x), (sext y)) --> (sext (add int x, y))
2345     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2346       // Only do this if x/y have the same type, if at last one of them has a
2347       // single use (so we don't increase the number of sexts), and if the
2348       // integer add will not overflow.
2349       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2350           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2351           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2352                                    RHSConv->getOperand(0))) {
2353         // Insert the new integer add.
2354         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2355                                                         RHSConv->getOperand(0),
2356                                                         "addconv");
2357         InsertNewInstBefore(NewAdd, I);
2358         return new SExtInst(NewAdd, I.getType());
2359       }
2360     }
2361   }
2362   
2363   // Check for (add double (sitofp x), y), see if we can merge this into an
2364   // integer add followed by a promotion.
2365   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2366     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2367     // ... if the constant fits in the integer value.  This is useful for things
2368     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2369     // requires a constant pool load, and generally allows the add to be better
2370     // instcombined.
2371     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2372       Constant *CI = 
2373       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2374       if (LHSConv->hasOneUse() &&
2375           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2376           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2377         // Insert the new integer add.
2378         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2379                                                         CI, "addconv");
2380         InsertNewInstBefore(NewAdd, I);
2381         return new SIToFPInst(NewAdd, I.getType());
2382       }
2383     }
2384     
2385     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2386     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2387       // Only do this if x/y have the same type, if at last one of them has a
2388       // single use (so we don't increase the number of int->fp conversions),
2389       // and if the integer add will not overflow.
2390       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2391           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2392           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2393                                    RHSConv->getOperand(0))) {
2394         // Insert the new integer add.
2395         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2396                                                         RHSConv->getOperand(0),
2397                                                         "addconv");
2398         InsertNewInstBefore(NewAdd, I);
2399         return new SIToFPInst(NewAdd, I.getType());
2400       }
2401     }
2402   }
2403   
2404   return Changed ? &I : 0;
2405 }
2406
2407 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2408   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2409
2410   if (Op0 == Op1 &&                        // sub X, X  -> 0
2411       !I.getType()->isFPOrFPVector())
2412     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2413
2414   // If this is a 'B = x-(-A)', change to B = x+A...
2415   if (Value *V = dyn_castNegVal(Op1))
2416     return BinaryOperator::CreateAdd(Op0, V);
2417
2418   if (isa<UndefValue>(Op0))
2419     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2420   if (isa<UndefValue>(Op1))
2421     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2422
2423   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424     // Replace (-1 - A) with (~A)...
2425     if (C->isAllOnesValue())
2426       return BinaryOperator::CreateNot(Op1);
2427
2428     // C - ~X == X + (1+C)
2429     Value *X = 0;
2430     if (match(Op1, m_Not(m_Value(X))))
2431       return BinaryOperator::CreateAdd(X, AddOne(C));
2432
2433     // -(X >>u 31) -> (X >>s 31)
2434     // -(X >>s 31) -> (X >>u 31)
2435     if (C->isZero()) {
2436       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2437         if (SI->getOpcode() == Instruction::LShr) {
2438           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2439             // Check to see if we are shifting out everything but the sign bit.
2440             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2441                 SI->getType()->getPrimitiveSizeInBits()-1) {
2442               // Ok, the transformation is safe.  Insert AShr.
2443               return BinaryOperator::Create(Instruction::AShr, 
2444                                           SI->getOperand(0), CU, SI->getName());
2445             }
2446           }
2447         }
2448         else if (SI->getOpcode() == Instruction::AShr) {
2449           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450             // Check to see if we are shifting out everything but the sign bit.
2451             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452                 SI->getType()->getPrimitiveSizeInBits()-1) {
2453               // Ok, the transformation is safe.  Insert LShr. 
2454               return BinaryOperator::CreateLShr(
2455                                           SI->getOperand(0), CU, SI->getName());
2456             }
2457           }
2458         }
2459       }
2460     }
2461
2462     // Try to fold constant sub into select arguments.
2463     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2464       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2465         return R;
2466   }
2467
2468   if (I.getType() == Type::Int1Ty)
2469     return BinaryOperator::CreateXor(Op0, Op1);
2470
2471   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2472     if (Op1I->getOpcode() == Instruction::Add &&
2473         !Op0->getType()->isFPOrFPVector()) {
2474       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2475         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2476       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2477         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2478       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2479         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2480           // C1-(X+C2) --> (C1-C2)-X
2481           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2482                                            Op1I->getOperand(0));
2483       }
2484     }
2485
2486     if (Op1I->hasOneUse()) {
2487       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2488       // is not used by anyone else...
2489       //
2490       if (Op1I->getOpcode() == Instruction::Sub &&
2491           !Op1I->getType()->isFPOrFPVector()) {
2492         // Swap the two operands of the subexpr...
2493         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2494         Op1I->setOperand(0, IIOp1);
2495         Op1I->setOperand(1, IIOp0);
2496
2497         // Create the new top level add instruction...
2498         return BinaryOperator::CreateAdd(Op0, Op1);
2499       }
2500
2501       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2502       //
2503       if (Op1I->getOpcode() == Instruction::And &&
2504           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2505         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2506
2507         Value *NewNot =
2508           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2509         return BinaryOperator::CreateAnd(Op0, NewNot);
2510       }
2511
2512       // 0 - (X sdiv C)  -> (X sdiv -C)
2513       if (Op1I->getOpcode() == Instruction::SDiv)
2514         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2515           if (CSI->isZero())
2516             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2517               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2518                                                ConstantExpr::getNeg(DivRHS));
2519
2520       // X - X*C --> X * (1-C)
2521       ConstantInt *C2 = 0;
2522       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2523         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2524         return BinaryOperator::CreateMul(Op0, CP1);
2525       }
2526     }
2527   }
2528
2529   if (!Op0->getType()->isFPOrFPVector())
2530     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2531       if (Op0I->getOpcode() == Instruction::Add) {
2532         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2533           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2534         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2535           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2536       } else if (Op0I->getOpcode() == Instruction::Sub) {
2537         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2538           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2539       }
2540     }
2541
2542   ConstantInt *C1;
2543   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2544     if (X == Op1)  // X*C - X --> X * (C-1)
2545       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2546
2547     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2548     if (X == dyn_castFoldableMul(Op1, C2))
2549       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2550   }
2551   return 0;
2552 }
2553
2554 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2555 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2556 /// TrueIfSigned if the result of the comparison is true when the input value is
2557 /// signed.
2558 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2559                            bool &TrueIfSigned) {
2560   switch (pred) {
2561   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2562     TrueIfSigned = true;
2563     return RHS->isZero();
2564   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2565     TrueIfSigned = true;
2566     return RHS->isAllOnesValue();
2567   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2568     TrueIfSigned = false;
2569     return RHS->isAllOnesValue();
2570   case ICmpInst::ICMP_UGT:
2571     // True if LHS u> RHS and RHS == high-bit-mask - 1
2572     TrueIfSigned = true;
2573     return RHS->getValue() ==
2574       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2575   case ICmpInst::ICMP_UGE: 
2576     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2577     TrueIfSigned = true;
2578     return RHS->getValue().isSignBit();
2579   default:
2580     return false;
2581   }
2582 }
2583
2584 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2585   bool Changed = SimplifyCommutative(I);
2586   Value *Op0 = I.getOperand(0);
2587
2588   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2589     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2590
2591   // Simplify mul instructions with a constant RHS...
2592   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2593     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2594
2595       // ((X << C1)*C2) == (X * (C2 << C1))
2596       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2597         if (SI->getOpcode() == Instruction::Shl)
2598           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2599             return BinaryOperator::CreateMul(SI->getOperand(0),
2600                                              ConstantExpr::getShl(CI, ShOp));
2601
2602       if (CI->isZero())
2603         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2604       if (CI->equalsInt(1))                  // X * 1  == X
2605         return ReplaceInstUsesWith(I, Op0);
2606       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2607         return BinaryOperator::CreateNeg(Op0, I.getName());
2608
2609       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2610       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2611         return BinaryOperator::CreateShl(Op0,
2612                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2613       }
2614     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2615       if (Op1F->isNullValue())
2616         return ReplaceInstUsesWith(I, Op1);
2617
2618       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2619       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2620       if (Op1F->isExactlyValue(1.0))
2621         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2622     } else if (isa<VectorType>(Op1->getType())) {
2623       if (isa<ConstantAggregateZero>(Op1))
2624         return ReplaceInstUsesWith(I, Op1);
2625
2626       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2627         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2628           return BinaryOperator::CreateNeg(Op0, I.getName());
2629
2630         // As above, vector X*splat(1.0) -> X in all defined cases.
2631         if (Constant *Splat = Op1V->getSplatValue()) {
2632           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2633             if (F->isExactlyValue(1.0))
2634               return ReplaceInstUsesWith(I, Op0);
2635           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2636             if (CI->equalsInt(1))
2637               return ReplaceInstUsesWith(I, Op0);
2638         }
2639       }
2640     }
2641     
2642     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2643       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2644           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2645         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2646         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2647                                                      Op1, "tmp");
2648         InsertNewInstBefore(Add, I);
2649         Value *C1C2 = ConstantExpr::getMul(Op1, 
2650                                            cast<Constant>(Op0I->getOperand(1)));
2651         return BinaryOperator::CreateAdd(Add, C1C2);
2652         
2653       }
2654
2655     // Try to fold constant mul into select arguments.
2656     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2657       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2658         return R;
2659
2660     if (isa<PHINode>(Op0))
2661       if (Instruction *NV = FoldOpIntoPhi(I))
2662         return NV;
2663   }
2664
2665   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2666     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2667       return BinaryOperator::CreateMul(Op0v, Op1v);
2668
2669   // (X / Y) *  Y = X - (X % Y)
2670   // (X / Y) * -Y = (X % Y) - X
2671   {
2672     Value *Op1 = I.getOperand(1);
2673     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2674     if (!BO ||
2675         (BO->getOpcode() != Instruction::UDiv && 
2676          BO->getOpcode() != Instruction::SDiv)) {
2677       Op1 = Op0;
2678       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2679     }
2680     Value *Neg = dyn_castNegVal(Op1);
2681     if (BO && BO->hasOneUse() &&
2682         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2683         (BO->getOpcode() == Instruction::UDiv ||
2684          BO->getOpcode() == Instruction::SDiv)) {
2685       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2686
2687       Instruction *Rem;
2688       if (BO->getOpcode() == Instruction::UDiv)
2689         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2690       else
2691         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2692
2693       InsertNewInstBefore(Rem, I);
2694       Rem->takeName(BO);
2695
2696       if (Op1BO == Op1)
2697         return BinaryOperator::CreateSub(Op0BO, Rem);
2698       else
2699         return BinaryOperator::CreateSub(Rem, Op0BO);
2700     }
2701   }
2702
2703   if (I.getType() == Type::Int1Ty)
2704     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2705
2706   // If one of the operands of the multiply is a cast from a boolean value, then
2707   // we know the bool is either zero or one, so this is a 'masking' multiply.
2708   // See if we can simplify things based on how the boolean was originally
2709   // formed.
2710   CastInst *BoolCast = 0;
2711   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2712     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2713       BoolCast = CI;
2714   if (!BoolCast)
2715     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2716       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2717         BoolCast = CI;
2718   if (BoolCast) {
2719     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2720       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2721       const Type *SCOpTy = SCIOp0->getType();
2722       bool TIS = false;
2723       
2724       // If the icmp is true iff the sign bit of X is set, then convert this
2725       // multiply into a shift/and combination.
2726       if (isa<ConstantInt>(SCIOp1) &&
2727           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2728           TIS) {
2729         // Shift the X value right to turn it into "all signbits".
2730         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2731                                           SCOpTy->getPrimitiveSizeInBits()-1);
2732         Value *V =
2733           InsertNewInstBefore(
2734             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2735                                             BoolCast->getOperand(0)->getName()+
2736                                             ".mask"), I);
2737
2738         // If the multiply type is not the same as the source type, sign extend
2739         // or truncate to the multiply type.
2740         if (I.getType() != V->getType()) {
2741           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2742           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2743           Instruction::CastOps opcode = 
2744             (SrcBits == DstBits ? Instruction::BitCast : 
2745              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2746           V = InsertCastBefore(opcode, V, I.getType(), I);
2747         }
2748
2749         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2750         return BinaryOperator::CreateAnd(V, OtherOp);
2751       }
2752     }
2753   }
2754
2755   return Changed ? &I : 0;
2756 }
2757
2758 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2759 /// instruction.
2760 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2761   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2762   
2763   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2764   int NonNullOperand = -1;
2765   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2766     if (ST->isNullValue())
2767       NonNullOperand = 2;
2768   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2769   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2770     if (ST->isNullValue())
2771       NonNullOperand = 1;
2772   
2773   if (NonNullOperand == -1)
2774     return false;
2775   
2776   Value *SelectCond = SI->getOperand(0);
2777   
2778   // Change the div/rem to use 'Y' instead of the select.
2779   I.setOperand(1, SI->getOperand(NonNullOperand));
2780   
2781   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2782   // problem.  However, the select, or the condition of the select may have
2783   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2784   // propagate the known value for the select into other uses of it, and
2785   // propagate a known value of the condition into its other users.
2786   
2787   // If the select and condition only have a single use, don't bother with this,
2788   // early exit.
2789   if (SI->use_empty() && SelectCond->hasOneUse())
2790     return true;
2791   
2792   // Scan the current block backward, looking for other uses of SI.
2793   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2794   
2795   while (BBI != BBFront) {
2796     --BBI;
2797     // If we found a call to a function, we can't assume it will return, so
2798     // information from below it cannot be propagated above it.
2799     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2800       break;
2801     
2802     // Replace uses of the select or its condition with the known values.
2803     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2804          I != E; ++I) {
2805       if (*I == SI) {
2806         *I = SI->getOperand(NonNullOperand);
2807         AddToWorkList(BBI);
2808       } else if (*I == SelectCond) {
2809         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2810                                    ConstantInt::getFalse();
2811         AddToWorkList(BBI);
2812       }
2813     }
2814     
2815     // If we past the instruction, quit looking for it.
2816     if (&*BBI == SI)
2817       SI = 0;
2818     if (&*BBI == SelectCond)
2819       SelectCond = 0;
2820     
2821     // If we ran out of things to eliminate, break out of the loop.
2822     if (SelectCond == 0 && SI == 0)
2823       break;
2824     
2825   }
2826   return true;
2827 }
2828
2829
2830 /// This function implements the transforms on div instructions that work
2831 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2832 /// used by the visitors to those instructions.
2833 /// @brief Transforms common to all three div instructions
2834 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2835   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2836
2837   // undef / X -> 0        for integer.
2838   // undef / X -> undef    for FP (the undef could be a snan).
2839   if (isa<UndefValue>(Op0)) {
2840     if (Op0->getType()->isFPOrFPVector())
2841       return ReplaceInstUsesWith(I, Op0);
2842     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2843   }
2844
2845   // X / undef -> undef
2846   if (isa<UndefValue>(Op1))
2847     return ReplaceInstUsesWith(I, Op1);
2848
2849   return 0;
2850 }
2851
2852 /// This function implements the transforms common to both integer division
2853 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2854 /// division instructions.
2855 /// @brief Common integer divide transforms
2856 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
2859   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2860   if (Op0 == Op1) {
2861     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2862       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2863       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2864       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2865     }
2866
2867     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2868     return ReplaceInstUsesWith(I, CI);
2869   }
2870   
2871   if (Instruction *Common = commonDivTransforms(I))
2872     return Common;
2873   
2874   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2875   // This does not apply for fdiv.
2876   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2877     return &I;
2878
2879   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2880     // div X, 1 == X
2881     if (RHS->equalsInt(1))
2882       return ReplaceInstUsesWith(I, Op0);
2883
2884     // (X / C1) / C2  -> X / (C1*C2)
2885     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2886       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2887         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2888           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2889             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2890           else 
2891             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2892                                           Multiply(RHS, LHSRHS));
2893         }
2894
2895     if (!RHS->isZero()) { // avoid X udiv 0
2896       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2897         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2898           return R;
2899       if (isa<PHINode>(Op0))
2900         if (Instruction *NV = FoldOpIntoPhi(I))
2901           return NV;
2902     }
2903   }
2904
2905   // 0 / X == 0, we don't need to preserve faults!
2906   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2907     if (LHS->equalsInt(0))
2908       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2909
2910   // It can't be division by zero, hence it must be division by one.
2911   if (I.getType() == Type::Int1Ty)
2912     return ReplaceInstUsesWith(I, Op0);
2913
2914   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2915     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2916       // div X, 1 == X
2917       if (X->isOne())
2918         return ReplaceInstUsesWith(I, Op0);
2919   }
2920
2921   return 0;
2922 }
2923
2924 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2925   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2926
2927   // Handle the integer div common cases
2928   if (Instruction *Common = commonIDivTransforms(I))
2929     return Common;
2930
2931   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2932     // X udiv C^2 -> X >> C
2933     // Check to see if this is an unsigned division with an exact power of 2,
2934     // if so, convert to a right shift.
2935     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2936       return BinaryOperator::CreateLShr(Op0, 
2937                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2938
2939     // X udiv C, where C >= signbit
2940     if (C->getValue().isNegative()) {
2941       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2942                                       I);
2943       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2944                                 ConstantInt::get(I.getType(), 1));
2945     }
2946   }
2947
2948   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2949   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2950     if (RHSI->getOpcode() == Instruction::Shl &&
2951         isa<ConstantInt>(RHSI->getOperand(0))) {
2952       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2953       if (C1.isPowerOf2()) {
2954         Value *N = RHSI->getOperand(1);
2955         const Type *NTy = N->getType();
2956         if (uint32_t C2 = C1.logBase2()) {
2957           Constant *C2V = ConstantInt::get(NTy, C2);
2958           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2959         }
2960         return BinaryOperator::CreateLShr(Op0, N);
2961       }
2962     }
2963   }
2964   
2965   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2966   // where C1&C2 are powers of two.
2967   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2968     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2969       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2970         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2971         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2972           // Compute the shift amounts
2973           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2974           // Construct the "on true" case of the select
2975           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2976           Instruction *TSI = BinaryOperator::CreateLShr(
2977                                                  Op0, TC, SI->getName()+".t");
2978           TSI = InsertNewInstBefore(TSI, I);
2979   
2980           // Construct the "on false" case of the select
2981           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2982           Instruction *FSI = BinaryOperator::CreateLShr(
2983                                                  Op0, FC, SI->getName()+".f");
2984           FSI = InsertNewInstBefore(FSI, I);
2985
2986           // construct the select instruction and return it.
2987           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2988         }
2989       }
2990   return 0;
2991 }
2992
2993 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2994   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2995
2996   // Handle the integer div common cases
2997   if (Instruction *Common = commonIDivTransforms(I))
2998     return Common;
2999
3000   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3001     // sdiv X, -1 == -X
3002     if (RHS->isAllOnesValue())
3003       return BinaryOperator::CreateNeg(Op0);
3004   }
3005
3006   // If the sign bits of both operands are zero (i.e. we can prove they are
3007   // unsigned inputs), turn this into a udiv.
3008   if (I.getType()->isInteger()) {
3009     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3010     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3011       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3012       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3013     }
3014   }      
3015   
3016   return 0;
3017 }
3018
3019 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3020   return commonDivTransforms(I);
3021 }
3022
3023 /// This function implements the transforms on rem instructions that work
3024 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3025 /// is used by the visitors to those instructions.
3026 /// @brief Transforms common to all three rem instructions
3027 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3028   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3029
3030   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3031     if (I.getType()->isFPOrFPVector())
3032       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3033     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3034   }
3035   if (isa<UndefValue>(Op1))
3036     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3037
3038   // Handle cases involving: rem X, (select Cond, Y, Z)
3039   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3040     return &I;
3041
3042   return 0;
3043 }
3044
3045 /// This function implements the transforms common to both integer remainder
3046 /// instructions (urem and srem). It is called by the visitors to those integer
3047 /// remainder instructions.
3048 /// @brief Common integer remainder transforms
3049 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3050   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3051
3052   if (Instruction *common = commonRemTransforms(I))
3053     return common;
3054
3055   // 0 % X == 0 for integer, we don't need to preserve faults!
3056   if (Constant *LHS = dyn_cast<Constant>(Op0))
3057     if (LHS->isNullValue())
3058       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3059
3060   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3061     // X % 0 == undef, we don't need to preserve faults!
3062     if (RHS->equalsInt(0))
3063       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3064     
3065     if (RHS->equalsInt(1))  // X % 1 == 0
3066       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3067
3068     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3069       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3070         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3071           return R;
3072       } else if (isa<PHINode>(Op0I)) {
3073         if (Instruction *NV = FoldOpIntoPhi(I))
3074           return NV;
3075       }
3076
3077       // See if we can fold away this rem instruction.
3078       if (SimplifyDemandedInstructionBits(I))
3079         return &I;
3080     }
3081   }
3082
3083   return 0;
3084 }
3085
3086 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3087   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3088
3089   if (Instruction *common = commonIRemTransforms(I))
3090     return common;
3091   
3092   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3093     // X urem C^2 -> X and C
3094     // Check to see if this is an unsigned remainder with an exact power of 2,
3095     // if so, convert to a bitwise and.
3096     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3097       if (C->getValue().isPowerOf2())
3098         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3099   }
3100
3101   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3102     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3103     if (RHSI->getOpcode() == Instruction::Shl &&
3104         isa<ConstantInt>(RHSI->getOperand(0))) {
3105       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3106         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3107         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3108                                                                    "tmp"), I);
3109         return BinaryOperator::CreateAnd(Op0, Add);
3110       }
3111     }
3112   }
3113
3114   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3115   // where C1&C2 are powers of two.
3116   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3117     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3118       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3119         // STO == 0 and SFO == 0 handled above.
3120         if ((STO->getValue().isPowerOf2()) && 
3121             (SFO->getValue().isPowerOf2())) {
3122           Value *TrueAnd = InsertNewInstBefore(
3123             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3124           Value *FalseAnd = InsertNewInstBefore(
3125             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3126           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3127         }
3128       }
3129   }
3130   
3131   return 0;
3132 }
3133
3134 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3135   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3136
3137   // Handle the integer rem common cases
3138   if (Instruction *common = commonIRemTransforms(I))
3139     return common;
3140   
3141   if (Value *RHSNeg = dyn_castNegVal(Op1))
3142     if (!isa<Constant>(RHSNeg) ||
3143         (isa<ConstantInt>(RHSNeg) &&
3144          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3145       // X % -Y -> X % Y
3146       AddUsesToWorkList(I);
3147       I.setOperand(1, RHSNeg);
3148       return &I;
3149     }
3150
3151   // If the sign bits of both operands are zero (i.e. we can prove they are
3152   // unsigned inputs), turn this into a urem.
3153   if (I.getType()->isInteger()) {
3154     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3155     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3156       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3157       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3158     }
3159   }
3160
3161   // If it's a constant vector, flip any negative values positive.
3162   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3163     unsigned VWidth = RHSV->getNumOperands();
3164
3165     bool hasNegative = false;
3166     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3167       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3168         if (RHS->getValue().isNegative())
3169           hasNegative = true;
3170
3171     if (hasNegative) {
3172       std::vector<Constant *> Elts(VWidth);
3173       for (unsigned i = 0; i != VWidth; ++i) {
3174         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3175           if (RHS->getValue().isNegative())
3176             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3177           else
3178             Elts[i] = RHS;
3179         }
3180       }
3181
3182       Constant *NewRHSV = ConstantVector::get(Elts);
3183       if (NewRHSV != RHSV) {
3184         AddUsesToWorkList(I);
3185         I.setOperand(1, NewRHSV);
3186         return &I;
3187       }
3188     }
3189   }
3190
3191   return 0;
3192 }
3193
3194 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3195   return commonRemTransforms(I);
3196 }
3197
3198 // isOneBitSet - Return true if there is exactly one bit set in the specified
3199 // constant.
3200 static bool isOneBitSet(const ConstantInt *CI) {
3201   return CI->getValue().isPowerOf2();
3202 }
3203
3204 // isHighOnes - Return true if the constant is of the form 1+0+.
3205 // This is the same as lowones(~X).
3206 static bool isHighOnes(const ConstantInt *CI) {
3207   return (~CI->getValue() + 1).isPowerOf2();
3208 }
3209
3210 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3211 /// are carefully arranged to allow folding of expressions such as:
3212 ///
3213 ///      (A < B) | (A > B) --> (A != B)
3214 ///
3215 /// Note that this is only valid if the first and second predicates have the
3216 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3217 ///
3218 /// Three bits are used to represent the condition, as follows:
3219 ///   0  A > B
3220 ///   1  A == B
3221 ///   2  A < B
3222 ///
3223 /// <=>  Value  Definition
3224 /// 000     0   Always false
3225 /// 001     1   A >  B
3226 /// 010     2   A == B
3227 /// 011     3   A >= B
3228 /// 100     4   A <  B
3229 /// 101     5   A != B
3230 /// 110     6   A <= B
3231 /// 111     7   Always true
3232 ///  
3233 static unsigned getICmpCode(const ICmpInst *ICI) {
3234   switch (ICI->getPredicate()) {
3235     // False -> 0
3236   case ICmpInst::ICMP_UGT: return 1;  // 001
3237   case ICmpInst::ICMP_SGT: return 1;  // 001
3238   case ICmpInst::ICMP_EQ:  return 2;  // 010
3239   case ICmpInst::ICMP_UGE: return 3;  // 011
3240   case ICmpInst::ICMP_SGE: return 3;  // 011
3241   case ICmpInst::ICMP_ULT: return 4;  // 100
3242   case ICmpInst::ICMP_SLT: return 4;  // 100
3243   case ICmpInst::ICMP_NE:  return 5;  // 101
3244   case ICmpInst::ICMP_ULE: return 6;  // 110
3245   case ICmpInst::ICMP_SLE: return 6;  // 110
3246     // True -> 7
3247   default:
3248     assert(0 && "Invalid ICmp predicate!");
3249     return 0;
3250   }
3251 }
3252
3253 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3254 /// predicate into a three bit mask. It also returns whether it is an ordered
3255 /// predicate by reference.
3256 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3257   isOrdered = false;
3258   switch (CC) {
3259   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3260   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3261   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3262   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3263   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3264   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3265   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3266   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3267   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3268   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3269   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3270   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3271   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3272   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3273     // True -> 7
3274   default:
3275     // Not expecting FCMP_FALSE and FCMP_TRUE;
3276     assert(0 && "Unexpected FCmp predicate!");
3277     return 0;
3278   }
3279 }
3280
3281 /// getICmpValue - This is the complement of getICmpCode, which turns an
3282 /// opcode and two operands into either a constant true or false, or a brand 
3283 /// new ICmp instruction. The sign is passed in to determine which kind
3284 /// of predicate to use in the new icmp instruction.
3285 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3286   switch (code) {
3287   default: assert(0 && "Illegal ICmp code!");
3288   case  0: return ConstantInt::getFalse();
3289   case  1: 
3290     if (sign)
3291       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3292     else
3293       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3294   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3295   case  3: 
3296     if (sign)
3297       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3298     else
3299       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3300   case  4: 
3301     if (sign)
3302       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3303     else
3304       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3305   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3306   case  6: 
3307     if (sign)
3308       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3309     else
3310       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3311   case  7: return ConstantInt::getTrue();
3312   }
3313 }
3314
3315 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3316 /// opcode and two operands into either a FCmp instruction. isordered is passed
3317 /// in to determine which kind of predicate to use in the new fcmp instruction.
3318 static Value *getFCmpValue(bool isordered, unsigned code,
3319                            Value *LHS, Value *RHS) {
3320   switch (code) {
3321   default: assert(0 && "Illegal FCmp code!");
3322   case  0:
3323     if (isordered)
3324       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3325     else
3326       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3327   case  1: 
3328     if (isordered)
3329       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3330     else
3331       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3332   case  2: 
3333     if (isordered)
3334       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3335     else
3336       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3337   case  3: 
3338     if (isordered)
3339       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3340     else
3341       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3342   case  4: 
3343     if (isordered)
3344       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3345     else
3346       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3347   case  5: 
3348     if (isordered)
3349       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3350     else
3351       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3352   case  6: 
3353     if (isordered)
3354       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3355     else
3356       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3357   case  7: return ConstantInt::getTrue();
3358   }
3359 }
3360
3361 /// PredicatesFoldable - Return true if both predicates match sign or if at
3362 /// least one of them is an equality comparison (which is signless).
3363 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3364   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3365          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3366          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3367 }
3368
3369 namespace { 
3370 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3371 struct FoldICmpLogical {
3372   InstCombiner &IC;
3373   Value *LHS, *RHS;
3374   ICmpInst::Predicate pred;
3375   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3376     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3377       pred(ICI->getPredicate()) {}
3378   bool shouldApply(Value *V) const {
3379     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3380       if (PredicatesFoldable(pred, ICI->getPredicate()))
3381         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3382                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3383     return false;
3384   }
3385   Instruction *apply(Instruction &Log) const {
3386     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3387     if (ICI->getOperand(0) != LHS) {
3388       assert(ICI->getOperand(1) == LHS);
3389       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3390     }
3391
3392     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3393     unsigned LHSCode = getICmpCode(ICI);
3394     unsigned RHSCode = getICmpCode(RHSICI);
3395     unsigned Code;
3396     switch (Log.getOpcode()) {
3397     case Instruction::And: Code = LHSCode & RHSCode; break;
3398     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3399     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3400     default: assert(0 && "Illegal logical opcode!"); return 0;
3401     }
3402
3403     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3404                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3405       
3406     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3407     if (Instruction *I = dyn_cast<Instruction>(RV))
3408       return I;
3409     // Otherwise, it's a constant boolean value...
3410     return IC.ReplaceInstUsesWith(Log, RV);
3411   }
3412 };
3413 } // end anonymous namespace
3414
3415 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3416 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3417 // guaranteed to be a binary operator.
3418 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3419                                     ConstantInt *OpRHS,
3420                                     ConstantInt *AndRHS,
3421                                     BinaryOperator &TheAnd) {
3422   Value *X = Op->getOperand(0);
3423   Constant *Together = 0;
3424   if (!Op->isShift())
3425     Together = And(AndRHS, OpRHS);
3426
3427   switch (Op->getOpcode()) {
3428   case Instruction::Xor:
3429     if (Op->hasOneUse()) {
3430       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3431       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3432       InsertNewInstBefore(And, TheAnd);
3433       And->takeName(Op);
3434       return BinaryOperator::CreateXor(And, Together);
3435     }
3436     break;
3437   case Instruction::Or:
3438     if (Together == AndRHS) // (X | C) & C --> C
3439       return ReplaceInstUsesWith(TheAnd, AndRHS);
3440
3441     if (Op->hasOneUse() && Together != OpRHS) {
3442       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3443       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3444       InsertNewInstBefore(Or, TheAnd);
3445       Or->takeName(Op);
3446       return BinaryOperator::CreateAnd(Or, AndRHS);
3447     }
3448     break;
3449   case Instruction::Add:
3450     if (Op->hasOneUse()) {
3451       // Adding a one to a single bit bit-field should be turned into an XOR
3452       // of the bit.  First thing to check is to see if this AND is with a
3453       // single bit constant.
3454       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3455
3456       // If there is only one bit set...
3457       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3458         // Ok, at this point, we know that we are masking the result of the
3459         // ADD down to exactly one bit.  If the constant we are adding has
3460         // no bits set below this bit, then we can eliminate the ADD.
3461         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3462
3463         // Check to see if any bits below the one bit set in AndRHSV are set.
3464         if ((AddRHS & (AndRHSV-1)) == 0) {
3465           // If not, the only thing that can effect the output of the AND is
3466           // the bit specified by AndRHSV.  If that bit is set, the effect of
3467           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3468           // no effect.
3469           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3470             TheAnd.setOperand(0, X);
3471             return &TheAnd;
3472           } else {
3473             // Pull the XOR out of the AND.
3474             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3475             InsertNewInstBefore(NewAnd, TheAnd);
3476             NewAnd->takeName(Op);
3477             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3478           }
3479         }
3480       }
3481     }
3482     break;
3483
3484   case Instruction::Shl: {
3485     // We know that the AND will not produce any of the bits shifted in, so if
3486     // the anded constant includes them, clear them now!
3487     //
3488     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3489     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3490     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3491     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3492
3493     if (CI->getValue() == ShlMask) { 
3494     // Masking out bits that the shift already masks
3495       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3496     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3497       TheAnd.setOperand(1, CI);
3498       return &TheAnd;
3499     }
3500     break;
3501   }
3502   case Instruction::LShr:
3503   {
3504     // We know that the AND will not produce any of the bits shifted in, so if
3505     // the anded constant includes them, clear them now!  This only applies to
3506     // unsigned shifts, because a signed shr may bring in set bits!
3507     //
3508     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3509     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3510     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3511     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3512
3513     if (CI->getValue() == ShrMask) {   
3514     // Masking out bits that the shift already masks.
3515       return ReplaceInstUsesWith(TheAnd, Op);
3516     } else if (CI != AndRHS) {
3517       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3518       return &TheAnd;
3519     }
3520     break;
3521   }
3522   case Instruction::AShr:
3523     // Signed shr.
3524     // See if this is shifting in some sign extension, then masking it out
3525     // with an and.
3526     if (Op->hasOneUse()) {
3527       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3528       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3529       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3530       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3531       if (C == AndRHS) {          // Masking out bits shifted in.
3532         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3533         // Make the argument unsigned.
3534         Value *ShVal = Op->getOperand(0);
3535         ShVal = InsertNewInstBefore(
3536             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3537                                    Op->getName()), TheAnd);
3538         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3539       }
3540     }
3541     break;
3542   }
3543   return 0;
3544 }
3545
3546
3547 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3548 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3549 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3550 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3551 /// insert new instructions.
3552 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3553                                            bool isSigned, bool Inside, 
3554                                            Instruction &IB) {
3555   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3556             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3557          "Lo is not <= Hi in range emission code!");
3558     
3559   if (Inside) {
3560     if (Lo == Hi)  // Trivially false.
3561       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3562
3563     // V >= Min && V < Hi --> V < Hi
3564     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3565       ICmpInst::Predicate pred = (isSigned ? 
3566         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3567       return new ICmpInst(pred, V, Hi);
3568     }
3569
3570     // Emit V-Lo <u Hi-Lo
3571     Constant *NegLo = ConstantExpr::getNeg(Lo);
3572     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3573     InsertNewInstBefore(Add, IB);
3574     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3575     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3576   }
3577
3578   if (Lo == Hi)  // Trivially true.
3579     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3580
3581   // V < Min || V >= Hi -> V > Hi-1
3582   Hi = SubOne(cast<ConstantInt>(Hi));
3583   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3584     ICmpInst::Predicate pred = (isSigned ? 
3585         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3586     return new ICmpInst(pred, V, Hi);
3587   }
3588
3589   // Emit V-Lo >u Hi-1-Lo
3590   // Note that Hi has already had one subtracted from it, above.
3591   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3592   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3593   InsertNewInstBefore(Add, IB);
3594   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3595   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3596 }
3597
3598 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3599 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3600 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3601 // not, since all 1s are not contiguous.
3602 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3603   const APInt& V = Val->getValue();
3604   uint32_t BitWidth = Val->getType()->getBitWidth();
3605   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3606
3607   // look for the first zero bit after the run of ones
3608   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3609   // look for the first non-zero bit
3610   ME = V.getActiveBits(); 
3611   return true;
3612 }
3613
3614 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3615 /// where isSub determines whether the operator is a sub.  If we can fold one of
3616 /// the following xforms:
3617 /// 
3618 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3619 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3620 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3621 ///
3622 /// return (A +/- B).
3623 ///
3624 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3625                                         ConstantInt *Mask, bool isSub,
3626                                         Instruction &I) {
3627   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3628   if (!LHSI || LHSI->getNumOperands() != 2 ||
3629       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3630
3631   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3632
3633   switch (LHSI->getOpcode()) {
3634   default: return 0;
3635   case Instruction::And:
3636     if (And(N, Mask) == Mask) {
3637       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3638       if ((Mask->getValue().countLeadingZeros() + 
3639            Mask->getValue().countPopulation()) == 
3640           Mask->getValue().getBitWidth())
3641         break;
3642
3643       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3644       // part, we don't need any explicit masks to take them out of A.  If that
3645       // is all N is, ignore it.
3646       uint32_t MB = 0, ME = 0;
3647       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3648         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3649         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3650         if (MaskedValueIsZero(RHS, Mask))
3651           break;
3652       }
3653     }
3654     return 0;
3655   case Instruction::Or:
3656   case Instruction::Xor:
3657     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3658     if ((Mask->getValue().countLeadingZeros() + 
3659          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3660         && And(N, Mask)->isZero())
3661       break;
3662     return 0;
3663   }
3664   
3665   Instruction *New;
3666   if (isSub)
3667     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3668   else
3669     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3670   return InsertNewInstBefore(New, I);
3671 }
3672
3673 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3674 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3675                                           ICmpInst *LHS, ICmpInst *RHS) {
3676   Value *Val, *Val2;
3677   ConstantInt *LHSCst, *RHSCst;
3678   ICmpInst::Predicate LHSCC, RHSCC;
3679   
3680   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3681   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3682       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3683     return 0;
3684   
3685   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3686   // where C is a power of 2
3687   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3688       LHSCst->getValue().isPowerOf2()) {
3689     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3690     InsertNewInstBefore(NewOr, I);
3691     return new ICmpInst(LHSCC, NewOr, LHSCst);
3692   }
3693   
3694   // From here on, we only handle:
3695   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3696   if (Val != Val2) return 0;
3697   
3698   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3699   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3700       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3701       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3702       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3703     return 0;
3704   
3705   // We can't fold (ugt x, C) & (sgt x, C2).
3706   if (!PredicatesFoldable(LHSCC, RHSCC))
3707     return 0;
3708     
3709   // Ensure that the larger constant is on the RHS.
3710   bool ShouldSwap;
3711   if (ICmpInst::isSignedPredicate(LHSCC) ||
3712       (ICmpInst::isEquality(LHSCC) && 
3713        ICmpInst::isSignedPredicate(RHSCC)))
3714     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3715   else
3716     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3717     
3718   if (ShouldSwap) {
3719     std::swap(LHS, RHS);
3720     std::swap(LHSCst, RHSCst);
3721     std::swap(LHSCC, RHSCC);
3722   }
3723
3724   // At this point, we know we have have two icmp instructions
3725   // comparing a value against two constants and and'ing the result
3726   // together.  Because of the above check, we know that we only have
3727   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3728   // (from the FoldICmpLogical check above), that the two constants 
3729   // are not equal and that the larger constant is on the RHS
3730   assert(LHSCst != RHSCst && "Compares not folded above?");
3731
3732   switch (LHSCC) {
3733   default: assert(0 && "Unknown integer condition code!");
3734   case ICmpInst::ICMP_EQ:
3735     switch (RHSCC) {
3736     default: assert(0 && "Unknown integer condition code!");
3737     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3738     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3739     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3740       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3741     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3742     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3743     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3744       return ReplaceInstUsesWith(I, LHS);
3745     }
3746   case ICmpInst::ICMP_NE:
3747     switch (RHSCC) {
3748     default: assert(0 && "Unknown integer condition code!");
3749     case ICmpInst::ICMP_ULT:
3750       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3751         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3752       break;                        // (X != 13 & X u< 15) -> no change
3753     case ICmpInst::ICMP_SLT:
3754       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3755         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3756       break;                        // (X != 13 & X s< 15) -> no change
3757     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3758     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3759     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3760       return ReplaceInstUsesWith(I, RHS);
3761     case ICmpInst::ICMP_NE:
3762       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3763         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3764         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3765                                                      Val->getName()+".off");
3766         InsertNewInstBefore(Add, I);
3767         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3768                             ConstantInt::get(Add->getType(), 1));
3769       }
3770       break;                        // (X != 13 & X != 15) -> no change
3771     }
3772     break;
3773   case ICmpInst::ICMP_ULT:
3774     switch (RHSCC) {
3775     default: assert(0 && "Unknown integer condition code!");
3776     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3777     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3778       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3779     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3780       break;
3781     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3782     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3783       return ReplaceInstUsesWith(I, LHS);
3784     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3785       break;
3786     }
3787     break;
3788   case ICmpInst::ICMP_SLT:
3789     switch (RHSCC) {
3790     default: assert(0 && "Unknown integer condition code!");
3791     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3792     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3793       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3794     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3795       break;
3796     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3797     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3798       return ReplaceInstUsesWith(I, LHS);
3799     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3800       break;
3801     }
3802     break;
3803   case ICmpInst::ICMP_UGT:
3804     switch (RHSCC) {
3805     default: assert(0 && "Unknown integer condition code!");
3806     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3807     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3808       return ReplaceInstUsesWith(I, RHS);
3809     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3810       break;
3811     case ICmpInst::ICMP_NE:
3812       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3813         return new ICmpInst(LHSCC, Val, RHSCst);
3814       break;                        // (X u> 13 & X != 15) -> no change
3815     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3816       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3817     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3818       break;
3819     }
3820     break;
3821   case ICmpInst::ICMP_SGT:
3822     switch (RHSCC) {
3823     default: assert(0 && "Unknown integer condition code!");
3824     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3825     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3826       return ReplaceInstUsesWith(I, RHS);
3827     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3828       break;
3829     case ICmpInst::ICMP_NE:
3830       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3831         return new ICmpInst(LHSCC, Val, RHSCst);
3832       break;                        // (X s> 13 & X != 15) -> no change
3833     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3834       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3835     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3836       break;
3837     }
3838     break;
3839   }
3840  
3841   return 0;
3842 }
3843
3844
3845 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3846   bool Changed = SimplifyCommutative(I);
3847   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3848
3849   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3850     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3851
3852   // and X, X = X
3853   if (Op0 == Op1)
3854     return ReplaceInstUsesWith(I, Op1);
3855
3856   // See if we can simplify any instructions used by the instruction whose sole 
3857   // purpose is to compute bits we don't care about.
3858   if (!isa<VectorType>(I.getType())) {
3859     if (SimplifyDemandedInstructionBits(I))
3860       return &I;
3861   } else {
3862     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3863       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3864         return ReplaceInstUsesWith(I, I.getOperand(0));
3865     } else if (isa<ConstantAggregateZero>(Op1)) {
3866       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3867     }
3868   }
3869   
3870   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3871     const APInt& AndRHSMask = AndRHS->getValue();
3872     APInt NotAndRHS(~AndRHSMask);
3873
3874     // Optimize a variety of ((val OP C1) & C2) combinations...
3875     if (isa<BinaryOperator>(Op0)) {
3876       Instruction *Op0I = cast<Instruction>(Op0);
3877       Value *Op0LHS = Op0I->getOperand(0);
3878       Value *Op0RHS = Op0I->getOperand(1);
3879       switch (Op0I->getOpcode()) {
3880       case Instruction::Xor:
3881       case Instruction::Or:
3882         // If the mask is only needed on one incoming arm, push it up.
3883         if (Op0I->hasOneUse()) {
3884           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3885             // Not masking anything out for the LHS, move to RHS.
3886             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3887                                                    Op0RHS->getName()+".masked");
3888             InsertNewInstBefore(NewRHS, I);
3889             return BinaryOperator::Create(
3890                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3891           }
3892           if (!isa<Constant>(Op0RHS) &&
3893               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3894             // Not masking anything out for the RHS, move to LHS.
3895             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3896                                                    Op0LHS->getName()+".masked");
3897             InsertNewInstBefore(NewLHS, I);
3898             return BinaryOperator::Create(
3899                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3900           }
3901         }
3902
3903         break;
3904       case Instruction::Add:
3905         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3906         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3907         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3908         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3909           return BinaryOperator::CreateAnd(V, AndRHS);
3910         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3911           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3912         break;
3913
3914       case Instruction::Sub:
3915         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3916         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3917         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3918         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3919           return BinaryOperator::CreateAnd(V, AndRHS);
3920
3921         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3922         // has 1's for all bits that the subtraction with A might affect.
3923         if (Op0I->hasOneUse()) {
3924           uint32_t BitWidth = AndRHSMask.getBitWidth();
3925           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3926           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3927
3928           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3929           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3930               MaskedValueIsZero(Op0LHS, Mask)) {
3931             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3932             InsertNewInstBefore(NewNeg, I);
3933             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3934           }
3935         }
3936         break;
3937
3938       case Instruction::Shl:
3939       case Instruction::LShr:
3940         // (1 << x) & 1 --> zext(x == 0)
3941         // (1 >> x) & 1 --> zext(x == 0)
3942         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3943           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3944                                            Constant::getNullValue(I.getType()));
3945           InsertNewInstBefore(NewICmp, I);
3946           return new ZExtInst(NewICmp, I.getType());
3947         }
3948         break;
3949       }
3950
3951       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3952         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3953           return Res;
3954     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3955       // If this is an integer truncation or change from signed-to-unsigned, and
3956       // if the source is an and/or with immediate, transform it.  This
3957       // frequently occurs for bitfield accesses.
3958       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3959         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3960             CastOp->getNumOperands() == 2)
3961           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3962             if (CastOp->getOpcode() == Instruction::And) {
3963               // Change: and (cast (and X, C1) to T), C2
3964               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3965               // This will fold the two constants together, which may allow 
3966               // other simplifications.
3967               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3968                 CastOp->getOperand(0), I.getType(), 
3969                 CastOp->getName()+".shrunk");
3970               NewCast = InsertNewInstBefore(NewCast, I);
3971               // trunc_or_bitcast(C1)&C2
3972               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3973               C3 = ConstantExpr::getAnd(C3, AndRHS);
3974               return BinaryOperator::CreateAnd(NewCast, C3);
3975             } else if (CastOp->getOpcode() == Instruction::Or) {
3976               // Change: and (cast (or X, C1) to T), C2
3977               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3978               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3979               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3980                 return ReplaceInstUsesWith(I, AndRHS);
3981             }
3982           }
3983       }
3984     }
3985
3986     // Try to fold constant and into select arguments.
3987     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3988       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3989         return R;
3990     if (isa<PHINode>(Op0))
3991       if (Instruction *NV = FoldOpIntoPhi(I))
3992         return NV;
3993   }
3994
3995   Value *Op0NotVal = dyn_castNotVal(Op0);
3996   Value *Op1NotVal = dyn_castNotVal(Op1);
3997
3998   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3999     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4000
4001   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4002   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4003     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4004                                                I.getName()+".demorgan");
4005     InsertNewInstBefore(Or, I);
4006     return BinaryOperator::CreateNot(Or);
4007   }
4008   
4009   {
4010     Value *A = 0, *B = 0, *C = 0, *D = 0;
4011     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4012       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4013         return ReplaceInstUsesWith(I, Op1);
4014     
4015       // (A|B) & ~(A&B) -> A^B
4016       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4017         if ((A == C && B == D) || (A == D && B == C))
4018           return BinaryOperator::CreateXor(A, B);
4019       }
4020     }
4021     
4022     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4023       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4024         return ReplaceInstUsesWith(I, Op0);
4025
4026       // ~(A&B) & (A|B) -> A^B
4027       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4028         if ((A == C && B == D) || (A == D && B == C))
4029           return BinaryOperator::CreateXor(A, B);
4030       }
4031     }
4032     
4033     if (Op0->hasOneUse() &&
4034         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4035       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4036         I.swapOperands();     // Simplify below
4037         std::swap(Op0, Op1);
4038       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4039         cast<BinaryOperator>(Op0)->swapOperands();
4040         I.swapOperands();     // Simplify below
4041         std::swap(Op0, Op1);
4042       }
4043     }
4044
4045     if (Op1->hasOneUse() &&
4046         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4047       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4048         cast<BinaryOperator>(Op1)->swapOperands();
4049         std::swap(A, B);
4050       }
4051       if (A == Op0) {                                // A&(A^B) -> A & ~B
4052         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4053         InsertNewInstBefore(NotB, I);
4054         return BinaryOperator::CreateAnd(A, NotB);
4055       }
4056     }
4057
4058     // (A&((~A)|B)) -> A&B
4059     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4060         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4061       return BinaryOperator::CreateAnd(A, Op1);
4062     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4063         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4064       return BinaryOperator::CreateAnd(A, Op0);
4065   }
4066   
4067   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4068     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4069     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4070       return R;
4071
4072     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4073       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4074         return Res;
4075   }
4076
4077   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4078   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4079     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4080       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4081         const Type *SrcTy = Op0C->getOperand(0)->getType();
4082         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4083             // Only do this if the casts both really cause code to be generated.
4084             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4085                               I.getType(), TD) &&
4086             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4087                               I.getType(), TD)) {
4088           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4089                                                          Op1C->getOperand(0),
4090                                                          I.getName());
4091           InsertNewInstBefore(NewOp, I);
4092           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4093         }
4094       }
4095     
4096   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4097   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4098     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4099       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4100           SI0->getOperand(1) == SI1->getOperand(1) &&
4101           (SI0->hasOneUse() || SI1->hasOneUse())) {
4102         Instruction *NewOp =
4103           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4104                                                         SI1->getOperand(0),
4105                                                         SI0->getName()), I);
4106         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4107                                       SI1->getOperand(1));
4108       }
4109   }
4110
4111   // If and'ing two fcmp, try combine them into one.
4112   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4113     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4114       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4115           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4116         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4117         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4118           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4119             // If either of the constants are nans, then the whole thing returns
4120             // false.
4121             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4122               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4123             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4124                                 RHS->getOperand(0));
4125           }
4126       } else {
4127         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4128         FCmpInst::Predicate Op0CC, Op1CC;
4129         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4130             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4131           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4132             // Swap RHS operands to match LHS.
4133             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4134             std::swap(Op1LHS, Op1RHS);
4135           }
4136           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4137             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4138             if (Op0CC == Op1CC)
4139               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4140             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4141                      Op1CC == FCmpInst::FCMP_FALSE)
4142               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4143             else if (Op0CC == FCmpInst::FCMP_TRUE)
4144               return ReplaceInstUsesWith(I, Op1);
4145             else if (Op1CC == FCmpInst::FCMP_TRUE)
4146               return ReplaceInstUsesWith(I, Op0);
4147             bool Op0Ordered;
4148             bool Op1Ordered;
4149             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4150             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4151             if (Op1Pred == 0) {
4152               std::swap(Op0, Op1);
4153               std::swap(Op0Pred, Op1Pred);
4154               std::swap(Op0Ordered, Op1Ordered);
4155             }
4156             if (Op0Pred == 0) {
4157               // uno && ueq -> uno && (uno || eq) -> ueq
4158               // ord && olt -> ord && (ord && lt) -> olt
4159               if (Op0Ordered == Op1Ordered)
4160                 return ReplaceInstUsesWith(I, Op1);
4161               // uno && oeq -> uno && (ord && eq) -> false
4162               // uno && ord -> false
4163               if (!Op0Ordered)
4164                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4165               // ord && ueq -> ord && (uno || eq) -> oeq
4166               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4167                                                     Op0LHS, Op0RHS));
4168             }
4169           }
4170         }
4171       }
4172     }
4173   }
4174
4175   return Changed ? &I : 0;
4176 }
4177
4178 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4179 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4180 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4181 /// the expression came from the corresponding "byte swapped" byte in some other
4182 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4183 /// we know that the expression deposits the low byte of %X into the high byte
4184 /// of the bswap result and that all other bytes are zero.  This expression is
4185 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4186 /// match.
4187 ///
4188 /// This function returns true if the match was unsuccessful and false if so.
4189 /// On entry to the function the "OverallLeftShift" is a signed integer value
4190 /// indicating the number of bytes that the subexpression is later shifted.  For
4191 /// example, if the expression is later right shifted by 16 bits, the
4192 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4193 /// byte of ByteValues is actually being set.
4194 ///
4195 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4196 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4197 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4198 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4199 /// always in the local (OverallLeftShift) coordinate space.
4200 ///
4201 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4202                               SmallVector<Value*, 8> &ByteValues) {
4203   if (Instruction *I = dyn_cast<Instruction>(V)) {
4204     // If this is an or instruction, it may be an inner node of the bswap.
4205     if (I->getOpcode() == Instruction::Or) {
4206       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4207                                ByteValues) ||
4208              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4209                                ByteValues);
4210     }
4211   
4212     // If this is a logical shift by a constant multiple of 8, recurse with
4213     // OverallLeftShift and ByteMask adjusted.
4214     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4215       unsigned ShAmt = 
4216         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4217       // Ensure the shift amount is defined and of a byte value.
4218       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4219         return true;
4220
4221       unsigned ByteShift = ShAmt >> 3;
4222       if (I->getOpcode() == Instruction::Shl) {
4223         // X << 2 -> collect(X, +2)
4224         OverallLeftShift += ByteShift;
4225         ByteMask >>= ByteShift;
4226       } else {
4227         // X >>u 2 -> collect(X, -2)
4228         OverallLeftShift -= ByteShift;
4229         ByteMask <<= ByteShift;
4230         ByteMask &= (~0U >> (32-ByteValues.size()));
4231       }
4232
4233       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4234       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4235
4236       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4237                                ByteValues);
4238     }
4239
4240     // If this is a logical 'and' with a mask that clears bytes, clear the
4241     // corresponding bytes in ByteMask.
4242     if (I->getOpcode() == Instruction::And &&
4243         isa<ConstantInt>(I->getOperand(1))) {
4244       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4245       unsigned NumBytes = ByteValues.size();
4246       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4247       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4248       
4249       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4250         // If this byte is masked out by a later operation, we don't care what
4251         // the and mask is.
4252         if ((ByteMask & (1 << i)) == 0)
4253           continue;
4254         
4255         // If the AndMask is all zeros for this byte, clear the bit.
4256         APInt MaskB = AndMask & Byte;
4257         if (MaskB == 0) {
4258           ByteMask &= ~(1U << i);
4259           continue;
4260         }
4261         
4262         // If the AndMask is not all ones for this byte, it's not a bytezap.
4263         if (MaskB != Byte)
4264           return true;
4265
4266         // Otherwise, this byte is kept.
4267       }
4268
4269       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4270                                ByteValues);
4271     }
4272   }
4273   
4274   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4275   // the input value to the bswap.  Some observations: 1) if more than one byte
4276   // is demanded from this input, then it could not be successfully assembled
4277   // into a byteswap.  At least one of the two bytes would not be aligned with
4278   // their ultimate destination.
4279   if (!isPowerOf2_32(ByteMask)) return true;
4280   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4281   
4282   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4283   // is demanded, it needs to go into byte 0 of the result.  This means that the
4284   // byte needs to be shifted until it lands in the right byte bucket.  The
4285   // shift amount depends on the position: if the byte is coming from the high
4286   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4287   // low part, it must be shifted left.
4288   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4289   if (InputByteNo < ByteValues.size()/2) {
4290     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4291       return true;
4292   } else {
4293     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4294       return true;
4295   }
4296   
4297   // If the destination byte value is already defined, the values are or'd
4298   // together, which isn't a bswap (unless it's an or of the same bits).
4299   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4300     return true;
4301   ByteValues[DestByteNo] = V;
4302   return false;
4303 }
4304
4305 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4306 /// If so, insert the new bswap intrinsic and return it.
4307 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4308   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4309   if (!ITy || ITy->getBitWidth() % 16 || 
4310       // ByteMask only allows up to 32-byte values.
4311       ITy->getBitWidth() > 32*8) 
4312     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4313   
4314   /// ByteValues - For each byte of the result, we keep track of which value
4315   /// defines each byte.
4316   SmallVector<Value*, 8> ByteValues;
4317   ByteValues.resize(ITy->getBitWidth()/8);
4318     
4319   // Try to find all the pieces corresponding to the bswap.
4320   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4321   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4322     return 0;
4323   
4324   // Check to see if all of the bytes come from the same value.
4325   Value *V = ByteValues[0];
4326   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4327   
4328   // Check to make sure that all of the bytes come from the same value.
4329   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4330     if (ByteValues[i] != V)
4331       return 0;
4332   const Type *Tys[] = { ITy };
4333   Module *M = I.getParent()->getParent()->getParent();
4334   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4335   return CallInst::Create(F, V);
4336 }
4337
4338 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4339 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4340 /// we can simplify this expression to "cond ? C : D or B".
4341 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4342                                          Value *C, Value *D) {
4343   // If A is not a select of -1/0, this cannot match.
4344   Value *Cond = 0;
4345   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4346     return 0;
4347
4348   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4349   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4350     return SelectInst::Create(Cond, C, B);
4351   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4352     return SelectInst::Create(Cond, C, B);
4353   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4354   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4355     return SelectInst::Create(Cond, C, D);
4356   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4357     return SelectInst::Create(Cond, C, D);
4358   return 0;
4359 }
4360
4361 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4362 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4363                                          ICmpInst *LHS, ICmpInst *RHS) {
4364   Value *Val, *Val2;
4365   ConstantInt *LHSCst, *RHSCst;
4366   ICmpInst::Predicate LHSCC, RHSCC;
4367   
4368   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4369   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4370       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4371     return 0;
4372   
4373   // From here on, we only handle:
4374   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4375   if (Val != Val2) return 0;
4376   
4377   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4378   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4379       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4380       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4381       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4382     return 0;
4383   
4384   // We can't fold (ugt x, C) | (sgt x, C2).
4385   if (!PredicatesFoldable(LHSCC, RHSCC))
4386     return 0;
4387   
4388   // Ensure that the larger constant is on the RHS.
4389   bool ShouldSwap;
4390   if (ICmpInst::isSignedPredicate(LHSCC) ||
4391       (ICmpInst::isEquality(LHSCC) && 
4392        ICmpInst::isSignedPredicate(RHSCC)))
4393     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4394   else
4395     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4396   
4397   if (ShouldSwap) {
4398     std::swap(LHS, RHS);
4399     std::swap(LHSCst, RHSCst);
4400     std::swap(LHSCC, RHSCC);
4401   }
4402   
4403   // At this point, we know we have have two icmp instructions
4404   // comparing a value against two constants and or'ing the result
4405   // together.  Because of the above check, we know that we only have
4406   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4407   // FoldICmpLogical check above), that the two constants are not
4408   // equal.
4409   assert(LHSCst != RHSCst && "Compares not folded above?");
4410
4411   switch (LHSCC) {
4412   default: assert(0 && "Unknown integer condition code!");
4413   case ICmpInst::ICMP_EQ:
4414     switch (RHSCC) {
4415     default: assert(0 && "Unknown integer condition code!");
4416     case ICmpInst::ICMP_EQ:
4417       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4418         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4419         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4420                                                      Val->getName()+".off");
4421         InsertNewInstBefore(Add, I);
4422         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4423         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4424       }
4425       break;                         // (X == 13 | X == 15) -> no change
4426     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4427     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4428       break;
4429     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4430     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4431     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4432       return ReplaceInstUsesWith(I, RHS);
4433     }
4434     break;
4435   case ICmpInst::ICMP_NE:
4436     switch (RHSCC) {
4437     default: assert(0 && "Unknown integer condition code!");
4438     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4439     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4440     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4441       return ReplaceInstUsesWith(I, LHS);
4442     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4443     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4444     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4445       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4446     }
4447     break;
4448   case ICmpInst::ICMP_ULT:
4449     switch (RHSCC) {
4450     default: assert(0 && "Unknown integer condition code!");
4451     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4452       break;
4453     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4454       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4455       // this can cause overflow.
4456       if (RHSCst->isMaxValue(false))
4457         return ReplaceInstUsesWith(I, LHS);
4458       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4459     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4460       break;
4461     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4462     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4463       return ReplaceInstUsesWith(I, RHS);
4464     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4465       break;
4466     }
4467     break;
4468   case ICmpInst::ICMP_SLT:
4469     switch (RHSCC) {
4470     default: assert(0 && "Unknown integer condition code!");
4471     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4472       break;
4473     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4474       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4475       // this can cause overflow.
4476       if (RHSCst->isMaxValue(true))
4477         return ReplaceInstUsesWith(I, LHS);
4478       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4479     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4480       break;
4481     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4482     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4483       return ReplaceInstUsesWith(I, RHS);
4484     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4485       break;
4486     }
4487     break;
4488   case ICmpInst::ICMP_UGT:
4489     switch (RHSCC) {
4490     default: assert(0 && "Unknown integer condition code!");
4491     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4492     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4493       return ReplaceInstUsesWith(I, LHS);
4494     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4495       break;
4496     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4497     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4498       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4499     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4500       break;
4501     }
4502     break;
4503   case ICmpInst::ICMP_SGT:
4504     switch (RHSCC) {
4505     default: assert(0 && "Unknown integer condition code!");
4506     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4507     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4508       return ReplaceInstUsesWith(I, LHS);
4509     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4510       break;
4511     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4512     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4513       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4514     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4515       break;
4516     }
4517     break;
4518   }
4519   return 0;
4520 }
4521
4522 /// FoldOrWithConstants - This helper function folds:
4523 ///
4524 ///     ((A | B) & C1) | (B & C2)
4525 ///
4526 /// into:
4527 /// 
4528 ///     (A & C1) | B
4529 ///
4530 /// when the XOR of the two constants is "all ones" (-1).
4531 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4532                                                Value *A, Value *B, Value *C) {
4533   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4534   if (!CI1) return 0;
4535
4536   Value *V1 = 0;
4537   ConstantInt *CI2 = 0;
4538   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4539
4540   APInt Xor = CI1->getValue() ^ CI2->getValue();
4541   if (!Xor.isAllOnesValue()) return 0;
4542
4543   if (V1 == A || V1 == B) {
4544     Instruction *NewOp =
4545       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4546     return BinaryOperator::CreateOr(NewOp, V1);
4547   }
4548
4549   return 0;
4550 }
4551
4552 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4553   bool Changed = SimplifyCommutative(I);
4554   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4555
4556   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4557     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4558
4559   // or X, X = X
4560   if (Op0 == Op1)
4561     return ReplaceInstUsesWith(I, Op0);
4562
4563   // See if we can simplify any instructions used by the instruction whose sole 
4564   // purpose is to compute bits we don't care about.
4565   if (!isa<VectorType>(I.getType())) {
4566     if (SimplifyDemandedInstructionBits(I))
4567       return &I;
4568   } else if (isa<ConstantAggregateZero>(Op1)) {
4569     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4570   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4571     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4572       return ReplaceInstUsesWith(I, I.getOperand(1));
4573   }
4574     
4575
4576   
4577   // or X, -1 == -1
4578   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4579     ConstantInt *C1 = 0; Value *X = 0;
4580     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4581     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4582       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4583       InsertNewInstBefore(Or, I);
4584       Or->takeName(Op0);
4585       return BinaryOperator::CreateAnd(Or, 
4586                ConstantInt::get(RHS->getValue() | C1->getValue()));
4587     }
4588
4589     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4590     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4591       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4592       InsertNewInstBefore(Or, I);
4593       Or->takeName(Op0);
4594       return BinaryOperator::CreateXor(Or,
4595                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4596     }
4597
4598     // Try to fold constant and into select arguments.
4599     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4600       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4601         return R;
4602     if (isa<PHINode>(Op0))
4603       if (Instruction *NV = FoldOpIntoPhi(I))
4604         return NV;
4605   }
4606
4607   Value *A = 0, *B = 0;
4608   ConstantInt *C1 = 0, *C2 = 0;
4609
4610   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4611     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4612       return ReplaceInstUsesWith(I, Op1);
4613   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4614     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4615       return ReplaceInstUsesWith(I, Op0);
4616
4617   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4618   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4619   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4620       match(Op1, m_Or(m_Value(), m_Value())) ||
4621       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4622        match(Op1, m_Shift(m_Value(), m_Value())))) {
4623     if (Instruction *BSwap = MatchBSwap(I))
4624       return BSwap;
4625   }
4626   
4627   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4628   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4629       MaskedValueIsZero(Op1, C1->getValue())) {
4630     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4631     InsertNewInstBefore(NOr, I);
4632     NOr->takeName(Op0);
4633     return BinaryOperator::CreateXor(NOr, C1);
4634   }
4635
4636   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4637   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4638       MaskedValueIsZero(Op0, C1->getValue())) {
4639     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4640     InsertNewInstBefore(NOr, I);
4641     NOr->takeName(Op0);
4642     return BinaryOperator::CreateXor(NOr, C1);
4643   }
4644
4645   // (A & C)|(B & D)
4646   Value *C = 0, *D = 0;
4647   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4648       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4649     Value *V1 = 0, *V2 = 0, *V3 = 0;
4650     C1 = dyn_cast<ConstantInt>(C);
4651     C2 = dyn_cast<ConstantInt>(D);
4652     if (C1 && C2) {  // (A & C1)|(B & C2)
4653       // If we have: ((V + N) & C1) | (V & C2)
4654       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4655       // replace with V+N.
4656       if (C1->getValue() == ~C2->getValue()) {
4657         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4658             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4659           // Add commutes, try both ways.
4660           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4661             return ReplaceInstUsesWith(I, A);
4662           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4663             return ReplaceInstUsesWith(I, A);
4664         }
4665         // Or commutes, try both ways.
4666         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4667             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4668           // Add commutes, try both ways.
4669           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4670             return ReplaceInstUsesWith(I, B);
4671           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4672             return ReplaceInstUsesWith(I, B);
4673         }
4674       }
4675       V1 = 0; V2 = 0; V3 = 0;
4676     }
4677     
4678     // Check to see if we have any common things being and'ed.  If so, find the
4679     // terms for V1 & (V2|V3).
4680     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4681       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4682         V1 = A, V2 = C, V3 = D;
4683       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4684         V1 = A, V2 = B, V3 = C;
4685       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4686         V1 = C, V2 = A, V3 = D;
4687       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4688         V1 = C, V2 = A, V3 = B;
4689       
4690       if (V1) {
4691         Value *Or =
4692           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4693         return BinaryOperator::CreateAnd(V1, Or);
4694       }
4695     }
4696
4697     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4698     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4699       return Match;
4700     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4701       return Match;
4702     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4703       return Match;
4704     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4705       return Match;
4706
4707     // ((A&~B)|(~A&B)) -> A^B
4708     if ((match(C, m_Not(m_Specific(D))) &&
4709          match(B, m_Not(m_Specific(A)))))
4710       return BinaryOperator::CreateXor(A, D);
4711     // ((~B&A)|(~A&B)) -> A^B
4712     if ((match(A, m_Not(m_Specific(D))) &&
4713          match(B, m_Not(m_Specific(C)))))
4714       return BinaryOperator::CreateXor(C, D);
4715     // ((A&~B)|(B&~A)) -> A^B
4716     if ((match(C, m_Not(m_Specific(B))) &&
4717          match(D, m_Not(m_Specific(A)))))
4718       return BinaryOperator::CreateXor(A, B);
4719     // ((~B&A)|(B&~A)) -> A^B
4720     if ((match(A, m_Not(m_Specific(B))) &&
4721          match(D, m_Not(m_Specific(C)))))
4722       return BinaryOperator::CreateXor(C, B);
4723   }
4724   
4725   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4726   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4727     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4728       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4729           SI0->getOperand(1) == SI1->getOperand(1) &&
4730           (SI0->hasOneUse() || SI1->hasOneUse())) {
4731         Instruction *NewOp =
4732         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4733                                                      SI1->getOperand(0),
4734                                                      SI0->getName()), I);
4735         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4736                                       SI1->getOperand(1));
4737       }
4738   }
4739
4740   // ((A|B)&1)|(B&-2) -> (A&1) | B
4741   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4742       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4743     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4744     if (Ret) return Ret;
4745   }
4746   // (B&-2)|((A|B)&1) -> (A&1) | B
4747   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4748       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4749     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4750     if (Ret) return Ret;
4751   }
4752
4753   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4754     if (A == Op1)   // ~A | A == -1
4755       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4756   } else {
4757     A = 0;
4758   }
4759   // Note, A is still live here!
4760   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4761     if (Op0 == B)
4762       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4763
4764     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4765     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4766       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4767                                               I.getName()+".demorgan"), I);
4768       return BinaryOperator::CreateNot(And);
4769     }
4770   }
4771
4772   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4773   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4774     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4775       return R;
4776
4777     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4778       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4779         return Res;
4780   }
4781     
4782   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4783   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4784     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4785       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4786         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4787             !isa<ICmpInst>(Op1C->getOperand(0))) {
4788           const Type *SrcTy = Op0C->getOperand(0)->getType();
4789           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4790               // Only do this if the casts both really cause code to be
4791               // generated.
4792               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4793                                 I.getType(), TD) &&
4794               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4795                                 I.getType(), TD)) {
4796             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4797                                                           Op1C->getOperand(0),
4798                                                           I.getName());
4799             InsertNewInstBefore(NewOp, I);
4800             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4801           }
4802         }
4803       }
4804   }
4805   
4806     
4807   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4808   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4809     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4810       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4811           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4812           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4813         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4814           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4815             // If either of the constants are nans, then the whole thing returns
4816             // true.
4817             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4818               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819             
4820             // Otherwise, no need to compare the two constants, compare the
4821             // rest.
4822             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4823                                 RHS->getOperand(0));
4824           }
4825       } else {
4826         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4827         FCmpInst::Predicate Op0CC, Op1CC;
4828         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4829             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4830           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4831             // Swap RHS operands to match LHS.
4832             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4833             std::swap(Op1LHS, Op1RHS);
4834           }
4835           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4836             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4837             if (Op0CC == Op1CC)
4838               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4839             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4840                      Op1CC == FCmpInst::FCMP_TRUE)
4841               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4842             else if (Op0CC == FCmpInst::FCMP_FALSE)
4843               return ReplaceInstUsesWith(I, Op1);
4844             else if (Op1CC == FCmpInst::FCMP_FALSE)
4845               return ReplaceInstUsesWith(I, Op0);
4846             bool Op0Ordered;
4847             bool Op1Ordered;
4848             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4849             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4850             if (Op0Ordered == Op1Ordered) {
4851               // If both are ordered or unordered, return a new fcmp with
4852               // or'ed predicates.
4853               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4854                                        Op0LHS, Op0RHS);
4855               if (Instruction *I = dyn_cast<Instruction>(RV))
4856                 return I;
4857               // Otherwise, it's a constant boolean value...
4858               return ReplaceInstUsesWith(I, RV);
4859             }
4860           }
4861         }
4862       }
4863     }
4864   }
4865
4866   return Changed ? &I : 0;
4867 }
4868
4869 namespace {
4870
4871 // XorSelf - Implements: X ^ X --> 0
4872 struct XorSelf {
4873   Value *RHS;
4874   XorSelf(Value *rhs) : RHS(rhs) {}
4875   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4876   Instruction *apply(BinaryOperator &Xor) const {
4877     return &Xor;
4878   }
4879 };
4880
4881 }
4882
4883 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4884   bool Changed = SimplifyCommutative(I);
4885   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4886
4887   if (isa<UndefValue>(Op1)) {
4888     if (isa<UndefValue>(Op0))
4889       // Handle undef ^ undef -> 0 special case. This is a common
4890       // idiom (misuse).
4891       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4892     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4893   }
4894
4895   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4896   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4897     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4898     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4899   }
4900   
4901   // See if we can simplify any instructions used by the instruction whose sole 
4902   // purpose is to compute bits we don't care about.
4903   if (!isa<VectorType>(I.getType())) {
4904     if (SimplifyDemandedInstructionBits(I))
4905       return &I;
4906   } else if (isa<ConstantAggregateZero>(Op1)) {
4907     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4908   }
4909
4910   // Is this a ~ operation?
4911   if (Value *NotOp = dyn_castNotVal(&I)) {
4912     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4913     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4914     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4915       if (Op0I->getOpcode() == Instruction::And || 
4916           Op0I->getOpcode() == Instruction::Or) {
4917         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4918         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4919           Instruction *NotY =
4920             BinaryOperator::CreateNot(Op0I->getOperand(1),
4921                                       Op0I->getOperand(1)->getName()+".not");
4922           InsertNewInstBefore(NotY, I);
4923           if (Op0I->getOpcode() == Instruction::And)
4924             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4925           else
4926             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4927         }
4928       }
4929     }
4930   }
4931   
4932   
4933   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4934     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4935       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4936       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4937         return new ICmpInst(ICI->getInversePredicate(),
4938                             ICI->getOperand(0), ICI->getOperand(1));
4939
4940       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4941         return new FCmpInst(FCI->getInversePredicate(),
4942                             FCI->getOperand(0), FCI->getOperand(1));
4943     }
4944
4945     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4946     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4947       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4948         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4949           Instruction::CastOps Opcode = Op0C->getOpcode();
4950           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4951             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4952                                              Op0C->getDestTy())) {
4953               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4954                                      CI->getOpcode(), CI->getInversePredicate(),
4955                                      CI->getOperand(0), CI->getOperand(1)), I);
4956               NewCI->takeName(CI);
4957               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4958             }
4959           }
4960         }
4961       }
4962     }
4963
4964     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4965       // ~(c-X) == X-c-1 == X+(-c-1)
4966       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4967         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4968           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4969           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4970                                               ConstantInt::get(I.getType(), 1));
4971           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4972         }
4973           
4974       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4975         if (Op0I->getOpcode() == Instruction::Add) {
4976           // ~(X-c) --> (-c-1)-X
4977           if (RHS->isAllOnesValue()) {
4978             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4979             return BinaryOperator::CreateSub(
4980                            ConstantExpr::getSub(NegOp0CI,
4981                                              ConstantInt::get(I.getType(), 1)),
4982                                           Op0I->getOperand(0));
4983           } else if (RHS->getValue().isSignBit()) {
4984             // (X + C) ^ signbit -> (X + C + signbit)
4985             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4986             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4987
4988           }
4989         } else if (Op0I->getOpcode() == Instruction::Or) {
4990           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4991           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4992             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4993             // Anything in both C1 and C2 is known to be zero, remove it from
4994             // NewRHS.
4995             Constant *CommonBits = And(Op0CI, RHS);
4996             NewRHS = ConstantExpr::getAnd(NewRHS, 
4997                                           ConstantExpr::getNot(CommonBits));
4998             AddToWorkList(Op0I);
4999             I.setOperand(0, Op0I->getOperand(0));
5000             I.setOperand(1, NewRHS);
5001             return &I;
5002           }
5003         }
5004       }
5005     }
5006
5007     // Try to fold constant and into select arguments.
5008     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5009       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5010         return R;
5011     if (isa<PHINode>(Op0))
5012       if (Instruction *NV = FoldOpIntoPhi(I))
5013         return NV;
5014   }
5015
5016   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5017     if (X == Op1)
5018       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5019
5020   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5021     if (X == Op0)
5022       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5023
5024   
5025   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5026   if (Op1I) {
5027     Value *A, *B;
5028     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5029       if (A == Op0) {              // B^(B|A) == (A|B)^B
5030         Op1I->swapOperands();
5031         I.swapOperands();
5032         std::swap(Op0, Op1);
5033       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5034         I.swapOperands();     // Simplified below.
5035         std::swap(Op0, Op1);
5036       }
5037     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5038       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5039     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5040       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5041     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5042       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5043         Op1I->swapOperands();
5044         std::swap(A, B);
5045       }
5046       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5047         I.swapOperands();     // Simplified below.
5048         std::swap(Op0, Op1);
5049       }
5050     }
5051   }
5052   
5053   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5054   if (Op0I) {
5055     Value *A, *B;
5056     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5057       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5058         std::swap(A, B);
5059       if (B == Op1) {                                // (A|B)^B == A & ~B
5060         Instruction *NotB =
5061           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5062         return BinaryOperator::CreateAnd(A, NotB);
5063       }
5064     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5065       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5066     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5067       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5068     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5069       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5070         std::swap(A, B);
5071       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5072           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5073         Instruction *N =
5074           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5075         return BinaryOperator::CreateAnd(N, Op1);
5076       }
5077     }
5078   }
5079   
5080   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5081   if (Op0I && Op1I && Op0I->isShift() && 
5082       Op0I->getOpcode() == Op1I->getOpcode() && 
5083       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5084       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5085     Instruction *NewOp =
5086       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5087                                                     Op1I->getOperand(0),
5088                                                     Op0I->getName()), I);
5089     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5090                                   Op1I->getOperand(1));
5091   }
5092     
5093   if (Op0I && Op1I) {
5094     Value *A, *B, *C, *D;
5095     // (A & B)^(A | B) -> A ^ B
5096     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5097         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5098       if ((A == C && B == D) || (A == D && B == C)) 
5099         return BinaryOperator::CreateXor(A, B);
5100     }
5101     // (A | B)^(A & B) -> A ^ B
5102     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5103         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5104       if ((A == C && B == D) || (A == D && B == C)) 
5105         return BinaryOperator::CreateXor(A, B);
5106     }
5107     
5108     // (A & B)^(C & D)
5109     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5110         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5111         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5112       // (X & Y)^(X & Y) -> (Y^Z) & X
5113       Value *X = 0, *Y = 0, *Z = 0;
5114       if (A == C)
5115         X = A, Y = B, Z = D;
5116       else if (A == D)
5117         X = A, Y = B, Z = C;
5118       else if (B == C)
5119         X = B, Y = A, Z = D;
5120       else if (B == D)
5121         X = B, Y = A, Z = C;
5122       
5123       if (X) {
5124         Instruction *NewOp =
5125         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5126         return BinaryOperator::CreateAnd(NewOp, X);
5127       }
5128     }
5129   }
5130     
5131   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5132   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5133     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5134       return R;
5135
5136   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5137   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5138     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5139       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5140         const Type *SrcTy = Op0C->getOperand(0)->getType();
5141         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5142             // Only do this if the casts both really cause code to be generated.
5143             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5144                               I.getType(), TD) &&
5145             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5146                               I.getType(), TD)) {
5147           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5148                                                          Op1C->getOperand(0),
5149                                                          I.getName());
5150           InsertNewInstBefore(NewOp, I);
5151           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5152         }
5153       }
5154   }
5155
5156   return Changed ? &I : 0;
5157 }
5158
5159 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5160 /// overflowed for this type.
5161 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5162                             ConstantInt *In2, bool IsSigned = false) {
5163   Result = cast<ConstantInt>(Add(In1, In2));
5164
5165   if (IsSigned)
5166     if (In2->getValue().isNegative())
5167       return Result->getValue().sgt(In1->getValue());
5168     else
5169       return Result->getValue().slt(In1->getValue());
5170   else
5171     return Result->getValue().ult(In1->getValue());
5172 }
5173
5174 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5175 /// overflowed for this type.
5176 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5177                             ConstantInt *In2, bool IsSigned = false) {
5178   Result = cast<ConstantInt>(Subtract(In1, In2));
5179
5180   if (IsSigned)
5181     if (In2->getValue().isNegative())
5182       return Result->getValue().slt(In1->getValue());
5183     else
5184       return Result->getValue().sgt(In1->getValue());
5185   else
5186     return Result->getValue().ugt(In1->getValue());
5187 }
5188
5189 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5190 /// code necessary to compute the offset from the base pointer (without adding
5191 /// in the base pointer).  Return the result as a signed integer of intptr size.
5192 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5193   TargetData &TD = IC.getTargetData();
5194   gep_type_iterator GTI = gep_type_begin(GEP);
5195   const Type *IntPtrTy = TD.getIntPtrType();
5196   Value *Result = Constant::getNullValue(IntPtrTy);
5197
5198   // Build a mask for high order bits.
5199   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5200   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5201
5202   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5203        ++i, ++GTI) {
5204     Value *Op = *i;
5205     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5206     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5207       if (OpC->isZero()) continue;
5208       
5209       // Handle a struct index, which adds its field offset to the pointer.
5210       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5211         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5212         
5213         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5214           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5215         else
5216           Result = IC.InsertNewInstBefore(
5217                    BinaryOperator::CreateAdd(Result,
5218                                              ConstantInt::get(IntPtrTy, Size),
5219                                              GEP->getName()+".offs"), I);
5220         continue;
5221       }
5222       
5223       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5224       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5225       Scale = ConstantExpr::getMul(OC, Scale);
5226       if (Constant *RC = dyn_cast<Constant>(Result))
5227         Result = ConstantExpr::getAdd(RC, Scale);
5228       else {
5229         // Emit an add instruction.
5230         Result = IC.InsertNewInstBefore(
5231            BinaryOperator::CreateAdd(Result, Scale,
5232                                      GEP->getName()+".offs"), I);
5233       }
5234       continue;
5235     }
5236     // Convert to correct type.
5237     if (Op->getType() != IntPtrTy) {
5238       if (Constant *OpC = dyn_cast<Constant>(Op))
5239         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5240       else
5241         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5242                                                                 true,
5243                                                       Op->getName()+".c"), I);
5244     }
5245     if (Size != 1) {
5246       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5247       if (Constant *OpC = dyn_cast<Constant>(Op))
5248         Op = ConstantExpr::getMul(OpC, Scale);
5249       else    // We'll let instcombine(mul) convert this to a shl if possible.
5250         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5251                                                   GEP->getName()+".idx"), I);
5252     }
5253
5254     // Emit an add instruction.
5255     if (isa<Constant>(Op) && isa<Constant>(Result))
5256       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5257                                     cast<Constant>(Result));
5258     else
5259       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5260                                                   GEP->getName()+".offs"), I);
5261   }
5262   return Result;
5263 }
5264
5265
5266 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5267 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5268 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5269 /// complex, and scales are involved.  The above expression would also be legal
5270 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5271 /// later form is less amenable to optimization though, and we are allowed to
5272 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5273 ///
5274 /// If we can't emit an optimized form for this expression, this returns null.
5275 /// 
5276 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5277                                           InstCombiner &IC) {
5278   TargetData &TD = IC.getTargetData();
5279   gep_type_iterator GTI = gep_type_begin(GEP);
5280
5281   // Check to see if this gep only has a single variable index.  If so, and if
5282   // any constant indices are a multiple of its scale, then we can compute this
5283   // in terms of the scale of the variable index.  For example, if the GEP
5284   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5285   // because the expression will cross zero at the same point.
5286   unsigned i, e = GEP->getNumOperands();
5287   int64_t Offset = 0;
5288   for (i = 1; i != e; ++i, ++GTI) {
5289     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
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.getTypeAllocSize(GTI.getIndexedType());
5298         Offset += Size*CI->getSExtValue();
5299       }
5300     } else {
5301       // Found our variable index.
5302       break;
5303     }
5304   }
5305   
5306   // If there are no variable indices, we must have a constant offset, just
5307   // evaluate it the general way.
5308   if (i == e) return 0;
5309   
5310   Value *VariableIdx = GEP->getOperand(i);
5311   // Determine the scale factor of the variable element.  For example, this is
5312   // 4 if the variable index is into an array of i32.
5313   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5314   
5315   // Verify that there are no other variable indices.  If so, emit the hard way.
5316   for (++i, ++GTI; i != e; ++i, ++GTI) {
5317     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5318     if (!CI) return 0;
5319    
5320     // Compute the aggregate offset of constant indices.
5321     if (CI->isZero()) continue;
5322     
5323     // Handle a struct index, which adds its field offset to the pointer.
5324     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5325       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5326     } else {
5327       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5328       Offset += Size*CI->getSExtValue();
5329     }
5330   }
5331   
5332   // Okay, we know we have a single variable index, which must be a
5333   // pointer/array/vector index.  If there is no offset, life is simple, return
5334   // the index.
5335   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5336   if (Offset == 0) {
5337     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5338     // we don't need to bother extending: the extension won't affect where the
5339     // computation crosses zero.
5340     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5341       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5342                                   VariableIdx->getNameStart(), &I);
5343     return VariableIdx;
5344   }
5345   
5346   // Otherwise, there is an index.  The computation we will do will be modulo
5347   // the pointer size, so get it.
5348   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5349   
5350   Offset &= PtrSizeMask;
5351   VariableScale &= PtrSizeMask;
5352
5353   // To do this transformation, any constant index must be a multiple of the
5354   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5355   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5356   // multiple of the variable scale.
5357   int64_t NewOffs = Offset / (int64_t)VariableScale;
5358   if (Offset != NewOffs*(int64_t)VariableScale)
5359     return 0;
5360
5361   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5362   const Type *IntPtrTy = TD.getIntPtrType();
5363   if (VariableIdx->getType() != IntPtrTy)
5364     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5365                                               true /*SExt*/, 
5366                                               VariableIdx->getNameStart(), &I);
5367   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5368   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5369 }
5370
5371
5372 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5373 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5374 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5375                                        ICmpInst::Predicate Cond,
5376                                        Instruction &I) {
5377   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5378
5379   // Look through bitcasts.
5380   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5381     RHS = BCI->getOperand(0);
5382
5383   Value *PtrBase = GEPLHS->getOperand(0);
5384   if (PtrBase == RHS) {
5385     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5386     // This transformation (ignoring the base and scales) is valid because we
5387     // know pointers can't overflow.  See if we can output an optimized form.
5388     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5389     
5390     // If not, synthesize the offset the hard way.
5391     if (Offset == 0)
5392       Offset = EmitGEPOffset(GEPLHS, I, *this);
5393     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5394                         Constant::getNullValue(Offset->getType()));
5395   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5396     // If the base pointers are different, but the indices are the same, just
5397     // compare the base pointer.
5398     if (PtrBase != GEPRHS->getOperand(0)) {
5399       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5400       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5401                         GEPRHS->getOperand(0)->getType();
5402       if (IndicesTheSame)
5403         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5404           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5405             IndicesTheSame = false;
5406             break;
5407           }
5408
5409       // If all indices are the same, just compare the base pointers.
5410       if (IndicesTheSame)
5411         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5412                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5413
5414       // Otherwise, the base pointers are different and the indices are
5415       // different, bail out.
5416       return 0;
5417     }
5418
5419     // If one of the GEPs has all zero indices, recurse.
5420     bool AllZeros = true;
5421     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5422       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5423           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5424         AllZeros = false;
5425         break;
5426       }
5427     if (AllZeros)
5428       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5429                           ICmpInst::getSwappedPredicate(Cond), I);
5430
5431     // If the other GEP has all zero indices, recurse.
5432     AllZeros = true;
5433     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5434       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5435           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5436         AllZeros = false;
5437         break;
5438       }
5439     if (AllZeros)
5440       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5441
5442     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5443       // If the GEPs only differ by one index, compare it.
5444       unsigned NumDifferences = 0;  // Keep track of # differences.
5445       unsigned DiffOperand = 0;     // The operand that differs.
5446       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5447         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5448           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5449                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5450             // Irreconcilable differences.
5451             NumDifferences = 2;
5452             break;
5453           } else {
5454             if (NumDifferences++) break;
5455             DiffOperand = i;
5456           }
5457         }
5458
5459       if (NumDifferences == 0)   // SAME GEP?
5460         return ReplaceInstUsesWith(I, // No comparison is needed here.
5461                                    ConstantInt::get(Type::Int1Ty,
5462                                              ICmpInst::isTrueWhenEqual(Cond)));
5463
5464       else if (NumDifferences == 1) {
5465         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5466         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5467         // Make sure we do a signed comparison here.
5468         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5469       }
5470     }
5471
5472     // Only lower this if the icmp is the only user of the GEP or if we expect
5473     // the result to fold to a constant!
5474     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5475         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5476       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5477       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5478       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5479       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5480     }
5481   }
5482   return 0;
5483 }
5484
5485 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5486 ///
5487 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5488                                                 Instruction *LHSI,
5489                                                 Constant *RHSC) {
5490   if (!isa<ConstantFP>(RHSC)) return 0;
5491   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5492   
5493   // Get the width of the mantissa.  We don't want to hack on conversions that
5494   // might lose information from the integer, e.g. "i64 -> float"
5495   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5496   if (MantissaWidth == -1) return 0;  // Unknown.
5497   
5498   // Check to see that the input is converted from an integer type that is small
5499   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5500   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5501   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5502   
5503   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5504   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5505   if (LHSUnsigned)
5506     ++InputSize;
5507   
5508   // If the conversion would lose info, don't hack on this.
5509   if ((int)InputSize > MantissaWidth)
5510     return 0;
5511   
5512   // Otherwise, we can potentially simplify the comparison.  We know that it
5513   // will always come through as an integer value and we know the constant is
5514   // not a NAN (it would have been previously simplified).
5515   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5516   
5517   ICmpInst::Predicate Pred;
5518   switch (I.getPredicate()) {
5519   default: assert(0 && "Unexpected predicate!");
5520   case FCmpInst::FCMP_UEQ:
5521   case FCmpInst::FCMP_OEQ:
5522     Pred = ICmpInst::ICMP_EQ;
5523     break;
5524   case FCmpInst::FCMP_UGT:
5525   case FCmpInst::FCMP_OGT:
5526     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5527     break;
5528   case FCmpInst::FCMP_UGE:
5529   case FCmpInst::FCMP_OGE:
5530     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5531     break;
5532   case FCmpInst::FCMP_ULT:
5533   case FCmpInst::FCMP_OLT:
5534     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5535     break;
5536   case FCmpInst::FCMP_ULE:
5537   case FCmpInst::FCMP_OLE:
5538     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5539     break;
5540   case FCmpInst::FCMP_UNE:
5541   case FCmpInst::FCMP_ONE:
5542     Pred = ICmpInst::ICMP_NE;
5543     break;
5544   case FCmpInst::FCMP_ORD:
5545     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5546   case FCmpInst::FCMP_UNO:
5547     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5548   }
5549   
5550   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5551   
5552   // Now we know that the APFloat is a normal number, zero or inf.
5553   
5554   // See if the FP constant is too large for the integer.  For example,
5555   // comparing an i8 to 300.0.
5556   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5557   
5558   if (!LHSUnsigned) {
5559     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5560     // and large values.
5561     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5562     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5563                           APFloat::rmNearestTiesToEven);
5564     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5565       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5566           Pred == ICmpInst::ICMP_SLE)
5567         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5568       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5569     }
5570   } else {
5571     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5572     // +INF and large values.
5573     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5574     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5575                           APFloat::rmNearestTiesToEven);
5576     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5577       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5578           Pred == ICmpInst::ICMP_ULE)
5579         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5580       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5581     }
5582   }
5583   
5584   if (!LHSUnsigned) {
5585     // See if the RHS value is < SignedMin.
5586     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5587     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5588                           APFloat::rmNearestTiesToEven);
5589     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5590       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5591           Pred == ICmpInst::ICMP_SGE)
5592         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5593       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5594     }
5595   }
5596
5597   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5598   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5599   // casting the FP value to the integer value and back, checking for equality.
5600   // Don't do this for zero, because -0.0 is not fractional.
5601   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5602   if (!RHS.isZero() &&
5603       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5604     // If we had a comparison against a fractional value, we have to adjust the
5605     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5606     // at this point.
5607     switch (Pred) {
5608     default: assert(0 && "Unexpected integer comparison!");
5609     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5610       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5611     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5612       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5613     case ICmpInst::ICMP_ULE:
5614       // (float)int <= 4.4   --> int <= 4
5615       // (float)int <= -4.4  --> false
5616       if (RHS.isNegative())
5617         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5618       break;
5619     case ICmpInst::ICMP_SLE:
5620       // (float)int <= 4.4   --> int <= 4
5621       // (float)int <= -4.4  --> int < -4
5622       if (RHS.isNegative())
5623         Pred = ICmpInst::ICMP_SLT;
5624       break;
5625     case ICmpInst::ICMP_ULT:
5626       // (float)int < -4.4   --> false
5627       // (float)int < 4.4    --> int <= 4
5628       if (RHS.isNegative())
5629         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5630       Pred = ICmpInst::ICMP_ULE;
5631       break;
5632     case ICmpInst::ICMP_SLT:
5633       // (float)int < -4.4   --> int < -4
5634       // (float)int < 4.4    --> int <= 4
5635       if (!RHS.isNegative())
5636         Pred = ICmpInst::ICMP_SLE;
5637       break;
5638     case ICmpInst::ICMP_UGT:
5639       // (float)int > 4.4    --> int > 4
5640       // (float)int > -4.4   --> true
5641       if (RHS.isNegative())
5642         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5643       break;
5644     case ICmpInst::ICMP_SGT:
5645       // (float)int > 4.4    --> int > 4
5646       // (float)int > -4.4   --> int >= -4
5647       if (RHS.isNegative())
5648         Pred = ICmpInst::ICMP_SGE;
5649       break;
5650     case ICmpInst::ICMP_UGE:
5651       // (float)int >= -4.4   --> true
5652       // (float)int >= 4.4    --> int > 4
5653       if (!RHS.isNegative())
5654         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5655       Pred = ICmpInst::ICMP_UGT;
5656       break;
5657     case ICmpInst::ICMP_SGE:
5658       // (float)int >= -4.4   --> int >= -4
5659       // (float)int >= 4.4    --> int > 4
5660       if (!RHS.isNegative())
5661         Pred = ICmpInst::ICMP_SGT;
5662       break;
5663     }
5664   }
5665
5666   // Lower this FP comparison into an appropriate integer version of the
5667   // comparison.
5668   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5669 }
5670
5671 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5672   bool Changed = SimplifyCompare(I);
5673   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5674
5675   // Fold trivial predicates.
5676   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5677     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5678   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5679     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5680   
5681   // Simplify 'fcmp pred X, X'
5682   if (Op0 == Op1) {
5683     switch (I.getPredicate()) {
5684     default: assert(0 && "Unknown predicate!");
5685     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5686     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5687     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5688       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5689     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5690     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5691     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5692       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5693       
5694     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5695     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5696     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5697     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5698       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5699       I.setPredicate(FCmpInst::FCMP_UNO);
5700       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5701       return &I;
5702       
5703     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5704     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5705     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5706     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5707       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5708       I.setPredicate(FCmpInst::FCMP_ORD);
5709       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5710       return &I;
5711     }
5712   }
5713     
5714   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5715     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5716
5717   // Handle fcmp with constant RHS
5718   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5719     // If the constant is a nan, see if we can fold the comparison based on it.
5720     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5721       if (CFP->getValueAPF().isNaN()) {
5722         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5723           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5724         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5725                "Comparison must be either ordered or unordered!");
5726         // True if unordered.
5727         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5728       }
5729     }
5730     
5731     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5732       switch (LHSI->getOpcode()) {
5733       case Instruction::PHI:
5734         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5735         // block.  If in the same block, we're encouraging jump threading.  If
5736         // not, we are just pessimizing the code by making an i1 phi.
5737         if (LHSI->getParent() == I.getParent())
5738           if (Instruction *NV = FoldOpIntoPhi(I))
5739             return NV;
5740         break;
5741       case Instruction::SIToFP:
5742       case Instruction::UIToFP:
5743         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5744           return NV;
5745         break;
5746       case Instruction::Select:
5747         // If either operand of the select is a constant, we can fold the
5748         // comparison into the select arms, which will cause one to be
5749         // constant folded and the select turned into a bitwise or.
5750         Value *Op1 = 0, *Op2 = 0;
5751         if (LHSI->hasOneUse()) {
5752           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5753             // Fold the known value into the constant operand.
5754             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5755             // Insert a new FCmp of the other select operand.
5756             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5757                                                       LHSI->getOperand(2), RHSC,
5758                                                       I.getName()), I);
5759           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5760             // Fold the known value into the constant operand.
5761             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5762             // Insert a new FCmp of the other select operand.
5763             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5764                                                       LHSI->getOperand(1), RHSC,
5765                                                       I.getName()), I);
5766           }
5767         }
5768
5769         if (Op1)
5770           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5771         break;
5772       }
5773   }
5774
5775   return Changed ? &I : 0;
5776 }
5777
5778 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5779   bool Changed = SimplifyCompare(I);
5780   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5781   const Type *Ty = Op0->getType();
5782
5783   // icmp X, X
5784   if (Op0 == Op1)
5785     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5786                                                    I.isTrueWhenEqual()));
5787
5788   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5789     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5790   
5791   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5792   // addresses never equal each other!  We already know that Op0 != Op1.
5793   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5794        isa<ConstantPointerNull>(Op0)) &&
5795       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5796        isa<ConstantPointerNull>(Op1)))
5797     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5798                                                    !I.isTrueWhenEqual()));
5799
5800   // icmp's with boolean values can always be turned into bitwise operations
5801   if (Ty == Type::Int1Ty) {
5802     switch (I.getPredicate()) {
5803     default: assert(0 && "Invalid icmp instruction!");
5804     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5805       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5806       InsertNewInstBefore(Xor, I);
5807       return BinaryOperator::CreateNot(Xor);
5808     }
5809     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5810       return BinaryOperator::CreateXor(Op0, Op1);
5811
5812     case ICmpInst::ICMP_UGT:
5813       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5814       // FALL THROUGH
5815     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5816       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5817       InsertNewInstBefore(Not, I);
5818       return BinaryOperator::CreateAnd(Not, Op1);
5819     }
5820     case ICmpInst::ICMP_SGT:
5821       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5822       // FALL THROUGH
5823     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5824       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5825       InsertNewInstBefore(Not, I);
5826       return BinaryOperator::CreateAnd(Not, Op0);
5827     }
5828     case ICmpInst::ICMP_UGE:
5829       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5830       // FALL THROUGH
5831     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5832       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5833       InsertNewInstBefore(Not, I);
5834       return BinaryOperator::CreateOr(Not, Op1);
5835     }
5836     case ICmpInst::ICMP_SGE:
5837       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5838       // FALL THROUGH
5839     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5840       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5841       InsertNewInstBefore(Not, I);
5842       return BinaryOperator::CreateOr(Not, Op0);
5843     }
5844     }
5845   }
5846
5847   unsigned BitWidth = 0;
5848   if (TD)
5849     BitWidth = TD->getTypeSizeInBits(Ty);
5850   else if (isa<IntegerType>(Ty))
5851     BitWidth = Ty->getPrimitiveSizeInBits();
5852
5853   bool isSignBit = false;
5854
5855   // See if we are doing a comparison with a constant.
5856   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5857     Value *A = 0, *B = 0;
5858     
5859     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5860     if (I.isEquality() && CI->isNullValue() &&
5861         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5862       // (icmp cond A B) if cond is equality
5863       return new ICmpInst(I.getPredicate(), A, B);
5864     }
5865     
5866     // If we have an icmp le or icmp ge instruction, turn it into the
5867     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5868     // them being folded in the code below.
5869     switch (I.getPredicate()) {
5870     default: break;
5871     case ICmpInst::ICMP_ULE:
5872       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5873         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5874       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5875     case ICmpInst::ICMP_SLE:
5876       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5877         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5878       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5879     case ICmpInst::ICMP_UGE:
5880       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5881         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5882       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5883     case ICmpInst::ICMP_SGE:
5884       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5885         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5886       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5887     }
5888     
5889     // If this comparison is a normal comparison, it demands all
5890     // bits, if it is a sign bit comparison, it only demands the sign bit.
5891     bool UnusedBit;
5892     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5893   }
5894
5895   // See if we can fold the comparison based on range information we can get
5896   // by checking whether bits are known to be zero or one in the input.
5897   if (BitWidth != 0) {
5898     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5899     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5900
5901     if (SimplifyDemandedBits(I.getOperandUse(0),
5902                              isSignBit ? APInt::getSignBit(BitWidth)
5903                                        : APInt::getAllOnesValue(BitWidth),
5904                              Op0KnownZero, Op0KnownOne, 0))
5905       return &I;
5906     if (SimplifyDemandedBits(I.getOperandUse(1),
5907                              APInt::getAllOnesValue(BitWidth),
5908                              Op1KnownZero, Op1KnownOne, 0))
5909       return &I;
5910
5911     // Given the known and unknown bits, compute a range that the LHS could be
5912     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5913     // EQ and NE we use unsigned values.
5914     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
5915     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
5916     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5917       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5918                                              Op0Min, Op0Max);
5919       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5920                                              Op1Min, Op1Max);
5921     } else {
5922       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5923                                                Op0Min, Op0Max);
5924       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5925                                                Op1Min, Op1Max);
5926     }
5927
5928     // If Min and Max are known to be the same, then SimplifyDemandedBits
5929     // figured out that the LHS is a constant.  Just constant fold this now so
5930     // that code below can assume that Min != Max.
5931     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
5932       return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
5933     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
5934       return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
5935
5936     // Based on the range information we know about the LHS, see if we can
5937     // simplify this comparison.  For example, (x&4) < 8  is always true.
5938     switch (I.getPredicate()) {
5939     default: assert(0 && "Unknown icmp opcode!");
5940     case ICmpInst::ICMP_EQ:
5941       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
5942         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5943       break;
5944     case ICmpInst::ICMP_NE:
5945       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
5946         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5947       break;
5948     case ICmpInst::ICMP_ULT:
5949       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
5950         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5951       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
5952         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5953       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
5954         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5955       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5956         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
5957           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5958
5959         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5960         if (CI->isMinValue(true))
5961           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5962                             ConstantInt::getAllOnesValue(Op0->getType()));
5963       }
5964       break;
5965     case ICmpInst::ICMP_UGT:
5966       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
5967         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5968       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
5969         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5970
5971       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
5972         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5973       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5974         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
5975           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5976
5977         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5978         if (CI->isMaxValue(true))
5979           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5980                               ConstantInt::getNullValue(Op0->getType()));
5981       }
5982       break;
5983     case ICmpInst::ICMP_SLT:
5984       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
5985         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5986       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
5987         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5988       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
5989         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5990       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5991         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
5992           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5993       }
5994       break;
5995     case ICmpInst::ICMP_SGT:
5996       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
5997         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5998       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
5999         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6000
6001       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6002         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6003       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6004         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6005           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6006       }
6007       break;
6008     case ICmpInst::ICMP_SGE:
6009       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6010       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6011         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6012       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6013         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6014       break;
6015     case ICmpInst::ICMP_SLE:
6016       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6017       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6018         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6019       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6020         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6021       break;
6022     case ICmpInst::ICMP_UGE:
6023       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6024       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6025         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6026       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6027         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6028       break;
6029     case ICmpInst::ICMP_ULE:
6030       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6031       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6032         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6033       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6034         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6035       break;
6036     }
6037
6038     // Turn a signed comparison into an unsigned one if both operands
6039     // are known to have the same sign.
6040     if (I.isSignedPredicate() &&
6041         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6042          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6043       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6044   }
6045
6046   // Test if the ICmpInst instruction is used exclusively by a select as
6047   // part of a minimum or maximum operation. If so, refrain from doing
6048   // any other folding. This helps out other analyses which understand
6049   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6050   // and CodeGen. And in this case, at least one of the comparison
6051   // operands has at least one user besides the compare (the select),
6052   // which would often largely negate the benefit of folding anyway.
6053   if (I.hasOneUse())
6054     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6055       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6056           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6057         return 0;
6058
6059   // See if we are doing a comparison between a constant and an instruction that
6060   // can be folded into the comparison.
6061   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6062     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6063     // instruction, see if that instruction also has constants so that the 
6064     // instruction can be folded into the icmp 
6065     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6066       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6067         return Res;
6068   }
6069
6070   // Handle icmp with constant (but not simple integer constant) RHS
6071   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6072     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6073       switch (LHSI->getOpcode()) {
6074       case Instruction::GetElementPtr:
6075         if (RHSC->isNullValue()) {
6076           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6077           bool isAllZeros = true;
6078           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6079             if (!isa<Constant>(LHSI->getOperand(i)) ||
6080                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6081               isAllZeros = false;
6082               break;
6083             }
6084           if (isAllZeros)
6085             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6086                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6087         }
6088         break;
6089
6090       case Instruction::PHI:
6091         // Only fold icmp into the PHI if the phi and fcmp are in the same
6092         // block.  If in the same block, we're encouraging jump threading.  If
6093         // not, we are just pessimizing the code by making an i1 phi.
6094         if (LHSI->getParent() == I.getParent())
6095           if (Instruction *NV = FoldOpIntoPhi(I))
6096             return NV;
6097         break;
6098       case Instruction::Select: {
6099         // If either operand of the select is a constant, we can fold the
6100         // comparison into the select arms, which will cause one to be
6101         // constant folded and the select turned into a bitwise or.
6102         Value *Op1 = 0, *Op2 = 0;
6103         if (LHSI->hasOneUse()) {
6104           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6105             // Fold the known value into the constant operand.
6106             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6107             // Insert a new ICmp of the other select operand.
6108             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6109                                                    LHSI->getOperand(2), RHSC,
6110                                                    I.getName()), I);
6111           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6112             // Fold the known value into the constant operand.
6113             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6114             // Insert a new ICmp of the other select operand.
6115             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6116                                                    LHSI->getOperand(1), RHSC,
6117                                                    I.getName()), I);
6118           }
6119         }
6120
6121         if (Op1)
6122           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6123         break;
6124       }
6125       case Instruction::Malloc:
6126         // If we have (malloc != null), and if the malloc has a single use, we
6127         // can assume it is successful and remove the malloc.
6128         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6129           AddToWorkList(LHSI);
6130           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6131                                                          !I.isTrueWhenEqual()));
6132         }
6133         break;
6134       }
6135   }
6136
6137   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6138   if (User *GEP = dyn_castGetElementPtr(Op0))
6139     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6140       return NI;
6141   if (User *GEP = dyn_castGetElementPtr(Op1))
6142     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6143                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6144       return NI;
6145
6146   // Test to see if the operands of the icmp are casted versions of other
6147   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6148   // now.
6149   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6150     if (isa<PointerType>(Op0->getType()) && 
6151         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6152       // We keep moving the cast from the left operand over to the right
6153       // operand, where it can often be eliminated completely.
6154       Op0 = CI->getOperand(0);
6155
6156       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6157       // so eliminate it as well.
6158       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6159         Op1 = CI2->getOperand(0);
6160
6161       // If Op1 is a constant, we can fold the cast into the constant.
6162       if (Op0->getType() != Op1->getType()) {
6163         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6164           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6165         } else {
6166           // Otherwise, cast the RHS right before the icmp
6167           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6168         }
6169       }
6170       return new ICmpInst(I.getPredicate(), Op0, Op1);
6171     }
6172   }
6173   
6174   if (isa<CastInst>(Op0)) {
6175     // Handle the special case of: icmp (cast bool to X), <cst>
6176     // This comes up when you have code like
6177     //   int X = A < B;
6178     //   if (X) ...
6179     // For generality, we handle any zero-extension of any operand comparison
6180     // with a constant or another cast from the same type.
6181     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6182       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6183         return R;
6184   }
6185   
6186   // See if it's the same type of instruction on the left and right.
6187   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6188     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6189       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6190           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6191         switch (Op0I->getOpcode()) {
6192         default: break;
6193         case Instruction::Add:
6194         case Instruction::Sub:
6195         case Instruction::Xor:
6196           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6197             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6198                                 Op1I->getOperand(0));
6199           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6200           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6201             if (CI->getValue().isSignBit()) {
6202               ICmpInst::Predicate Pred = I.isSignedPredicate()
6203                                              ? I.getUnsignedPredicate()
6204                                              : I.getSignedPredicate();
6205               return new ICmpInst(Pred, Op0I->getOperand(0),
6206                                   Op1I->getOperand(0));
6207             }
6208             
6209             if (CI->getValue().isMaxSignedValue()) {
6210               ICmpInst::Predicate Pred = I.isSignedPredicate()
6211                                              ? I.getUnsignedPredicate()
6212                                              : I.getSignedPredicate();
6213               Pred = I.getSwappedPredicate(Pred);
6214               return new ICmpInst(Pred, Op0I->getOperand(0),
6215                                   Op1I->getOperand(0));
6216             }
6217           }
6218           break;
6219         case Instruction::Mul:
6220           if (!I.isEquality())
6221             break;
6222
6223           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6224             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6225             // Mask = -1 >> count-trailing-zeros(Cst).
6226             if (!CI->isZero() && !CI->isOne()) {
6227               const APInt &AP = CI->getValue();
6228               ConstantInt *Mask = ConstantInt::get(
6229                                       APInt::getLowBitsSet(AP.getBitWidth(),
6230                                                            AP.getBitWidth() -
6231                                                       AP.countTrailingZeros()));
6232               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6233                                                             Mask);
6234               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6235                                                             Mask);
6236               InsertNewInstBefore(And1, I);
6237               InsertNewInstBefore(And2, I);
6238               return new ICmpInst(I.getPredicate(), And1, And2);
6239             }
6240           }
6241           break;
6242         }
6243       }
6244     }
6245   }
6246   
6247   // ~x < ~y --> y < x
6248   { Value *A, *B;
6249     if (match(Op0, m_Not(m_Value(A))) &&
6250         match(Op1, m_Not(m_Value(B))))
6251       return new ICmpInst(I.getPredicate(), B, A);
6252   }
6253   
6254   if (I.isEquality()) {
6255     Value *A, *B, *C, *D;
6256     
6257     // -x == -y --> x == y
6258     if (match(Op0, m_Neg(m_Value(A))) &&
6259         match(Op1, m_Neg(m_Value(B))))
6260       return new ICmpInst(I.getPredicate(), A, B);
6261     
6262     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6263       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6264         Value *OtherVal = A == Op1 ? B : A;
6265         return new ICmpInst(I.getPredicate(), OtherVal,
6266                             Constant::getNullValue(A->getType()));
6267       }
6268
6269       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6270         // A^c1 == C^c2 --> A == C^(c1^c2)
6271         ConstantInt *C1, *C2;
6272         if (match(B, m_ConstantInt(C1)) &&
6273             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6274           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6275           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6276           return new ICmpInst(I.getPredicate(), A,
6277                               InsertNewInstBefore(Xor, I));
6278         }
6279         
6280         // A^B == A^D -> B == D
6281         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6282         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6283         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6284         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6285       }
6286     }
6287     
6288     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6289         (A == Op0 || B == Op0)) {
6290       // A == (A^B)  ->  B == 0
6291       Value *OtherVal = A == Op0 ? B : A;
6292       return new ICmpInst(I.getPredicate(), OtherVal,
6293                           Constant::getNullValue(A->getType()));
6294     }
6295
6296     // (A-B) == A  ->  B == 0
6297     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6298       return new ICmpInst(I.getPredicate(), B, 
6299                           Constant::getNullValue(B->getType()));
6300
6301     // A == (A-B)  ->  B == 0
6302     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6303       return new ICmpInst(I.getPredicate(), B,
6304                           Constant::getNullValue(B->getType()));
6305     
6306     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6307     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6308         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6309         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6310       Value *X = 0, *Y = 0, *Z = 0;
6311       
6312       if (A == C) {
6313         X = B; Y = D; Z = A;
6314       } else if (A == D) {
6315         X = B; Y = C; Z = A;
6316       } else if (B == C) {
6317         X = A; Y = D; Z = B;
6318       } else if (B == D) {
6319         X = A; Y = C; Z = B;
6320       }
6321       
6322       if (X) {   // Build (X^Y) & Z
6323         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6324         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6325         I.setOperand(0, Op1);
6326         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6327         return &I;
6328       }
6329     }
6330   }
6331   return Changed ? &I : 0;
6332 }
6333
6334
6335 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6336 /// and CmpRHS are both known to be integer constants.
6337 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6338                                           ConstantInt *DivRHS) {
6339   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6340   const APInt &CmpRHSV = CmpRHS->getValue();
6341   
6342   // FIXME: If the operand types don't match the type of the divide 
6343   // then don't attempt this transform. The code below doesn't have the
6344   // logic to deal with a signed divide and an unsigned compare (and
6345   // vice versa). This is because (x /s C1) <s C2  produces different 
6346   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6347   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6348   // work. :(  The if statement below tests that condition and bails 
6349   // if it finds it. 
6350   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6351   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6352     return 0;
6353   if (DivRHS->isZero())
6354     return 0; // The ProdOV computation fails on divide by zero.
6355   if (DivIsSigned && DivRHS->isAllOnesValue())
6356     return 0; // The overflow computation also screws up here
6357   if (DivRHS->isOne())
6358     return 0; // Not worth bothering, and eliminates some funny cases
6359               // with INT_MIN.
6360
6361   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6362   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6363   // C2 (CI). By solving for X we can turn this into a range check 
6364   // instead of computing a divide. 
6365   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6366
6367   // Determine if the product overflows by seeing if the product is
6368   // not equal to the divide. Make sure we do the same kind of divide
6369   // as in the LHS instruction that we're folding. 
6370   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6371                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6372
6373   // Get the ICmp opcode
6374   ICmpInst::Predicate Pred = ICI.getPredicate();
6375
6376   // Figure out the interval that is being checked.  For example, a comparison
6377   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6378   // Compute this interval based on the constants involved and the signedness of
6379   // the compare/divide.  This computes a half-open interval, keeping track of
6380   // whether either value in the interval overflows.  After analysis each
6381   // overflow variable is set to 0 if it's corresponding bound variable is valid
6382   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6383   int LoOverflow = 0, HiOverflow = 0;
6384   ConstantInt *LoBound = 0, *HiBound = 0;
6385   
6386   if (!DivIsSigned) {  // udiv
6387     // e.g. X/5 op 3  --> [15, 20)
6388     LoBound = Prod;
6389     HiOverflow = LoOverflow = ProdOV;
6390     if (!HiOverflow)
6391       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6392   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6393     if (CmpRHSV == 0) {       // (X / pos) op 0
6394       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6395       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6396       HiBound = DivRHS;
6397     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6398       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6399       HiOverflow = LoOverflow = ProdOV;
6400       if (!HiOverflow)
6401         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6402     } else {                       // (X / pos) op neg
6403       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6404       HiBound = AddOne(Prod);
6405       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6406       if (!LoOverflow) {
6407         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6408         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6409                                      true) ? -1 : 0;
6410        }
6411     }
6412   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6413     if (CmpRHSV == 0) {       // (X / neg) op 0
6414       // e.g. X/-5 op 0  --> [-4, 5)
6415       LoBound = AddOne(DivRHS);
6416       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6417       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6418         HiOverflow = 1;            // [INTMIN+1, overflow)
6419         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6420       }
6421     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6422       // e.g. X/-5 op 3  --> [-19, -14)
6423       HiBound = AddOne(Prod);
6424       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6425       if (!LoOverflow)
6426         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6427     } else {                       // (X / neg) op neg
6428       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6429       LoOverflow = HiOverflow = ProdOV;
6430       if (!HiOverflow)
6431         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6432     }
6433     
6434     // Dividing by a negative swaps the condition.  LT <-> GT
6435     Pred = ICmpInst::getSwappedPredicate(Pred);
6436   }
6437
6438   Value *X = DivI->getOperand(0);
6439   switch (Pred) {
6440   default: assert(0 && "Unhandled icmp opcode!");
6441   case ICmpInst::ICMP_EQ:
6442     if (LoOverflow && HiOverflow)
6443       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6444     else if (HiOverflow)
6445       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6446                           ICmpInst::ICMP_UGE, X, LoBound);
6447     else if (LoOverflow)
6448       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6449                           ICmpInst::ICMP_ULT, X, HiBound);
6450     else
6451       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6452   case ICmpInst::ICMP_NE:
6453     if (LoOverflow && HiOverflow)
6454       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6455     else if (HiOverflow)
6456       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6457                           ICmpInst::ICMP_ULT, X, LoBound);
6458     else if (LoOverflow)
6459       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6460                           ICmpInst::ICMP_UGE, X, HiBound);
6461     else
6462       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6463   case ICmpInst::ICMP_ULT:
6464   case ICmpInst::ICMP_SLT:
6465     if (LoOverflow == +1)   // Low bound is greater than input range.
6466       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6467     if (LoOverflow == -1)   // Low bound is less than input range.
6468       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6469     return new ICmpInst(Pred, X, LoBound);
6470   case ICmpInst::ICMP_UGT:
6471   case ICmpInst::ICMP_SGT:
6472     if (HiOverflow == +1)       // High bound greater than input range.
6473       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6474     else if (HiOverflow == -1)  // High bound less than input range.
6475       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6476     if (Pred == ICmpInst::ICMP_UGT)
6477       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6478     else
6479       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6480   }
6481 }
6482
6483
6484 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6485 ///
6486 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6487                                                           Instruction *LHSI,
6488                                                           ConstantInt *RHS) {
6489   const APInt &RHSV = RHS->getValue();
6490   
6491   switch (LHSI->getOpcode()) {
6492   case Instruction::Trunc:
6493     if (ICI.isEquality() && LHSI->hasOneUse()) {
6494       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6495       // of the high bits truncated out of x are known.
6496       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6497              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6498       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6499       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6500       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6501       
6502       // If all the high bits are known, we can do this xform.
6503       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6504         // Pull in the high bits from known-ones set.
6505         APInt NewRHS(RHS->getValue());
6506         NewRHS.zext(SrcBits);
6507         NewRHS |= KnownOne;
6508         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6509                             ConstantInt::get(NewRHS));
6510       }
6511     }
6512     break;
6513       
6514   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6515     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6516       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6517       // fold the xor.
6518       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6519           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6520         Value *CompareVal = LHSI->getOperand(0);
6521         
6522         // If the sign bit of the XorCST is not set, there is no change to
6523         // the operation, just stop using the Xor.
6524         if (!XorCST->getValue().isNegative()) {
6525           ICI.setOperand(0, CompareVal);
6526           AddToWorkList(LHSI);
6527           return &ICI;
6528         }
6529         
6530         // Was the old condition true if the operand is positive?
6531         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6532         
6533         // If so, the new one isn't.
6534         isTrueIfPositive ^= true;
6535         
6536         if (isTrueIfPositive)
6537           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6538         else
6539           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6540       }
6541
6542       if (LHSI->hasOneUse()) {
6543         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6544         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6545           const APInt &SignBit = XorCST->getValue();
6546           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6547                                          ? ICI.getUnsignedPredicate()
6548                                          : ICI.getSignedPredicate();
6549           return new ICmpInst(Pred, LHSI->getOperand(0),
6550                               ConstantInt::get(RHSV ^ SignBit));
6551         }
6552
6553         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6554         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6555           const APInt &NotSignBit = XorCST->getValue();
6556           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6557                                          ? ICI.getUnsignedPredicate()
6558                                          : ICI.getSignedPredicate();
6559           Pred = ICI.getSwappedPredicate(Pred);
6560           return new ICmpInst(Pred, LHSI->getOperand(0),
6561                               ConstantInt::get(RHSV ^ NotSignBit));
6562         }
6563       }
6564     }
6565     break;
6566   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6567     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6568         LHSI->getOperand(0)->hasOneUse()) {
6569       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6570       
6571       // If the LHS is an AND of a truncating cast, we can widen the
6572       // and/compare to be the input width without changing the value
6573       // produced, eliminating a cast.
6574       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6575         // We can do this transformation if either the AND constant does not
6576         // have its sign bit set or if it is an equality comparison. 
6577         // Extending a relational comparison when we're checking the sign
6578         // bit would not work.
6579         if (Cast->hasOneUse() &&
6580             (ICI.isEquality() ||
6581              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6582           uint32_t BitWidth = 
6583             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6584           APInt NewCST = AndCST->getValue();
6585           NewCST.zext(BitWidth);
6586           APInt NewCI = RHSV;
6587           NewCI.zext(BitWidth);
6588           Instruction *NewAnd = 
6589             BinaryOperator::CreateAnd(Cast->getOperand(0),
6590                                       ConstantInt::get(NewCST),LHSI->getName());
6591           InsertNewInstBefore(NewAnd, ICI);
6592           return new ICmpInst(ICI.getPredicate(), NewAnd,
6593                               ConstantInt::get(NewCI));
6594         }
6595       }
6596       
6597       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6598       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6599       // happens a LOT in code produced by the C front-end, for bitfield
6600       // access.
6601       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6602       if (Shift && !Shift->isShift())
6603         Shift = 0;
6604       
6605       ConstantInt *ShAmt;
6606       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6607       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6608       const Type *AndTy = AndCST->getType();          // Type of the and.
6609       
6610       // We can fold this as long as we can't shift unknown bits
6611       // into the mask.  This can only happen with signed shift
6612       // rights, as they sign-extend.
6613       if (ShAmt) {
6614         bool CanFold = Shift->isLogicalShift();
6615         if (!CanFold) {
6616           // To test for the bad case of the signed shr, see if any
6617           // of the bits shifted in could be tested after the mask.
6618           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6619           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6620           
6621           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6622           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6623                AndCST->getValue()) == 0)
6624             CanFold = true;
6625         }
6626         
6627         if (CanFold) {
6628           Constant *NewCst;
6629           if (Shift->getOpcode() == Instruction::Shl)
6630             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6631           else
6632             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6633           
6634           // Check to see if we are shifting out any of the bits being
6635           // compared.
6636           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6637             // If we shifted bits out, the fold is not going to work out.
6638             // As a special case, check to see if this means that the
6639             // result is always true or false now.
6640             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6641               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6642             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6643               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6644           } else {
6645             ICI.setOperand(1, NewCst);
6646             Constant *NewAndCST;
6647             if (Shift->getOpcode() == Instruction::Shl)
6648               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6649             else
6650               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6651             LHSI->setOperand(1, NewAndCST);
6652             LHSI->setOperand(0, Shift->getOperand(0));
6653             AddToWorkList(Shift); // Shift is dead.
6654             AddUsesToWorkList(ICI);
6655             return &ICI;
6656           }
6657         }
6658       }
6659       
6660       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6661       // preferable because it allows the C<<Y expression to be hoisted out
6662       // of a loop if Y is invariant and X is not.
6663       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6664           ICI.isEquality() && !Shift->isArithmeticShift() &&
6665           !isa<Constant>(Shift->getOperand(0))) {
6666         // Compute C << Y.
6667         Value *NS;
6668         if (Shift->getOpcode() == Instruction::LShr) {
6669           NS = BinaryOperator::CreateShl(AndCST, 
6670                                          Shift->getOperand(1), "tmp");
6671         } else {
6672           // Insert a logical shift.
6673           NS = BinaryOperator::CreateLShr(AndCST,
6674                                           Shift->getOperand(1), "tmp");
6675         }
6676         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6677         
6678         // Compute X & (C << Y).
6679         Instruction *NewAnd = 
6680           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6681         InsertNewInstBefore(NewAnd, ICI);
6682         
6683         ICI.setOperand(0, NewAnd);
6684         return &ICI;
6685       }
6686     }
6687     break;
6688     
6689   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6690     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6691     if (!ShAmt) break;
6692     
6693     uint32_t TypeBits = RHSV.getBitWidth();
6694     
6695     // Check that the shift amount is in range.  If not, don't perform
6696     // undefined shifts.  When the shift is visited it will be
6697     // simplified.
6698     if (ShAmt->uge(TypeBits))
6699       break;
6700     
6701     if (ICI.isEquality()) {
6702       // If we are comparing against bits always shifted out, the
6703       // comparison cannot succeed.
6704       Constant *Comp =
6705         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6706       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6707         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6708         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6709         return ReplaceInstUsesWith(ICI, Cst);
6710       }
6711       
6712       if (LHSI->hasOneUse()) {
6713         // Otherwise strength reduce the shift into an and.
6714         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6715         Constant *Mask =
6716           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6717         
6718         Instruction *AndI =
6719           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6720                                     Mask, LHSI->getName()+".mask");
6721         Value *And = InsertNewInstBefore(AndI, ICI);
6722         return new ICmpInst(ICI.getPredicate(), And,
6723                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6724       }
6725     }
6726     
6727     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6728     bool TrueIfSigned = false;
6729     if (LHSI->hasOneUse() &&
6730         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6731       // (X << 31) <s 0  --> (X&1) != 0
6732       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6733                                            (TypeBits-ShAmt->getZExtValue()-1));
6734       Instruction *AndI =
6735         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6736                                   Mask, LHSI->getName()+".mask");
6737       Value *And = InsertNewInstBefore(AndI, ICI);
6738       
6739       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6740                           And, Constant::getNullValue(And->getType()));
6741     }
6742     break;
6743   }
6744     
6745   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6746   case Instruction::AShr: {
6747     // Only handle equality comparisons of shift-by-constant.
6748     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6749     if (!ShAmt || !ICI.isEquality()) break;
6750
6751     // Check that the shift amount is in range.  If not, don't perform
6752     // undefined shifts.  When the shift is visited it will be
6753     // simplified.
6754     uint32_t TypeBits = RHSV.getBitWidth();
6755     if (ShAmt->uge(TypeBits))
6756       break;
6757     
6758     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6759       
6760     // If we are comparing against bits always shifted out, the
6761     // comparison cannot succeed.
6762     APInt Comp = RHSV << ShAmtVal;
6763     if (LHSI->getOpcode() == Instruction::LShr)
6764       Comp = Comp.lshr(ShAmtVal);
6765     else
6766       Comp = Comp.ashr(ShAmtVal);
6767     
6768     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6769       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6770       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6771       return ReplaceInstUsesWith(ICI, Cst);
6772     }
6773     
6774     // Otherwise, check to see if the bits shifted out are known to be zero.
6775     // If so, we can compare against the unshifted value:
6776     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6777     if (LHSI->hasOneUse() &&
6778         MaskedValueIsZero(LHSI->getOperand(0), 
6779                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6780       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6781                           ConstantExpr::getShl(RHS, ShAmt));
6782     }
6783       
6784     if (LHSI->hasOneUse()) {
6785       // Otherwise strength reduce the shift into an and.
6786       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6787       Constant *Mask = ConstantInt::get(Val);
6788       
6789       Instruction *AndI =
6790         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6791                                   Mask, LHSI->getName()+".mask");
6792       Value *And = InsertNewInstBefore(AndI, ICI);
6793       return new ICmpInst(ICI.getPredicate(), And,
6794                           ConstantExpr::getShl(RHS, ShAmt));
6795     }
6796     break;
6797   }
6798     
6799   case Instruction::SDiv:
6800   case Instruction::UDiv:
6801     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6802     // Fold this div into the comparison, producing a range check. 
6803     // Determine, based on the divide type, what the range is being 
6804     // checked.  If there is an overflow on the low or high side, remember 
6805     // it, otherwise compute the range [low, hi) bounding the new value.
6806     // See: InsertRangeTest above for the kinds of replacements possible.
6807     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6808       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6809                                           DivRHS))
6810         return R;
6811     break;
6812
6813   case Instruction::Add:
6814     // Fold: icmp pred (add, X, C1), C2
6815
6816     if (!ICI.isEquality()) {
6817       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6818       if (!LHSC) break;
6819       const APInt &LHSV = LHSC->getValue();
6820
6821       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6822                             .subtract(LHSV);
6823
6824       if (ICI.isSignedPredicate()) {
6825         if (CR.getLower().isSignBit()) {
6826           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6827                               ConstantInt::get(CR.getUpper()));
6828         } else if (CR.getUpper().isSignBit()) {
6829           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6830                               ConstantInt::get(CR.getLower()));
6831         }
6832       } else {
6833         if (CR.getLower().isMinValue()) {
6834           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6835                               ConstantInt::get(CR.getUpper()));
6836         } else if (CR.getUpper().isMinValue()) {
6837           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6838                               ConstantInt::get(CR.getLower()));
6839         }
6840       }
6841     }
6842     break;
6843   }
6844   
6845   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6846   if (ICI.isEquality()) {
6847     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6848     
6849     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6850     // the second operand is a constant, simplify a bit.
6851     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6852       switch (BO->getOpcode()) {
6853       case Instruction::SRem:
6854         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6855         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6856           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6857           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6858             Instruction *NewRem =
6859               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6860                                          BO->getName());
6861             InsertNewInstBefore(NewRem, ICI);
6862             return new ICmpInst(ICI.getPredicate(), NewRem, 
6863                                 Constant::getNullValue(BO->getType()));
6864           }
6865         }
6866         break;
6867       case Instruction::Add:
6868         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6869         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6870           if (BO->hasOneUse())
6871             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6872                                 Subtract(RHS, BOp1C));
6873         } else if (RHSV == 0) {
6874           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6875           // efficiently invertible, or if the add has just this one use.
6876           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6877           
6878           if (Value *NegVal = dyn_castNegVal(BOp1))
6879             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6880           else if (Value *NegVal = dyn_castNegVal(BOp0))
6881             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6882           else if (BO->hasOneUse()) {
6883             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6884             InsertNewInstBefore(Neg, ICI);
6885             Neg->takeName(BO);
6886             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6887           }
6888         }
6889         break;
6890       case Instruction::Xor:
6891         // For the xor case, we can xor two constants together, eliminating
6892         // the explicit xor.
6893         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6894           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6895                               ConstantExpr::getXor(RHS, BOC));
6896         
6897         // FALLTHROUGH
6898       case Instruction::Sub:
6899         // Replace (([sub|xor] A, B) != 0) with (A != B)
6900         if (RHSV == 0)
6901           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6902                               BO->getOperand(1));
6903         break;
6904         
6905       case Instruction::Or:
6906         // If bits are being or'd in that are not present in the constant we
6907         // are comparing against, then the comparison could never succeed!
6908         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6909           Constant *NotCI = ConstantExpr::getNot(RHS);
6910           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6911             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6912                                                              isICMP_NE));
6913         }
6914         break;
6915         
6916       case Instruction::And:
6917         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6918           // If bits are being compared against that are and'd out, then the
6919           // comparison can never succeed!
6920           if ((RHSV & ~BOC->getValue()) != 0)
6921             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6922                                                              isICMP_NE));
6923           
6924           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6925           if (RHS == BOC && RHSV.isPowerOf2())
6926             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6927                                 ICmpInst::ICMP_NE, LHSI,
6928                                 Constant::getNullValue(RHS->getType()));
6929           
6930           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6931           if (BOC->getValue().isSignBit()) {
6932             Value *X = BO->getOperand(0);
6933             Constant *Zero = Constant::getNullValue(X->getType());
6934             ICmpInst::Predicate pred = isICMP_NE ? 
6935               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6936             return new ICmpInst(pred, X, Zero);
6937           }
6938           
6939           // ((X & ~7) == 0) --> X < 8
6940           if (RHSV == 0 && isHighOnes(BOC)) {
6941             Value *X = BO->getOperand(0);
6942             Constant *NegX = ConstantExpr::getNeg(BOC);
6943             ICmpInst::Predicate pred = isICMP_NE ? 
6944               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6945             return new ICmpInst(pred, X, NegX);
6946           }
6947         }
6948       default: break;
6949       }
6950     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6951       // Handle icmp {eq|ne} <intrinsic>, intcst.
6952       if (II->getIntrinsicID() == Intrinsic::bswap) {
6953         AddToWorkList(II);
6954         ICI.setOperand(0, II->getOperand(1));
6955         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6956         return &ICI;
6957       }
6958     }
6959   }
6960   return 0;
6961 }
6962
6963 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6964 /// We only handle extending casts so far.
6965 ///
6966 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6967   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6968   Value *LHSCIOp        = LHSCI->getOperand(0);
6969   const Type *SrcTy     = LHSCIOp->getType();
6970   const Type *DestTy    = LHSCI->getType();
6971   Value *RHSCIOp;
6972
6973   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6974   // integer type is the same size as the pointer type.
6975   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6976       getTargetData().getPointerSizeInBits() == 
6977          cast<IntegerType>(DestTy)->getBitWidth()) {
6978     Value *RHSOp = 0;
6979     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6980       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6981     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6982       RHSOp = RHSC->getOperand(0);
6983       // If the pointer types don't match, insert a bitcast.
6984       if (LHSCIOp->getType() != RHSOp->getType())
6985         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6986     }
6987
6988     if (RHSOp)
6989       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6990   }
6991   
6992   // The code below only handles extension cast instructions, so far.
6993   // Enforce this.
6994   if (LHSCI->getOpcode() != Instruction::ZExt &&
6995       LHSCI->getOpcode() != Instruction::SExt)
6996     return 0;
6997
6998   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6999   bool isSignedCmp = ICI.isSignedPredicate();
7000
7001   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7002     // Not an extension from the same type?
7003     RHSCIOp = CI->getOperand(0);
7004     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7005       return 0;
7006     
7007     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7008     // and the other is a zext), then we can't handle this.
7009     if (CI->getOpcode() != LHSCI->getOpcode())
7010       return 0;
7011
7012     // Deal with equality cases early.
7013     if (ICI.isEquality())
7014       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7015
7016     // A signed comparison of sign extended values simplifies into a
7017     // signed comparison.
7018     if (isSignedCmp && isSignedExt)
7019       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7020
7021     // The other three cases all fold into an unsigned comparison.
7022     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7023   }
7024
7025   // If we aren't dealing with a constant on the RHS, exit early
7026   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7027   if (!CI)
7028     return 0;
7029
7030   // Compute the constant that would happen if we truncated to SrcTy then
7031   // reextended to DestTy.
7032   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7033   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7034
7035   // If the re-extended constant didn't change...
7036   if (Res2 == CI) {
7037     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7038     // For example, we might have:
7039     //    %A = sext short %X to uint
7040     //    %B = icmp ugt uint %A, 1330
7041     // It is incorrect to transform this into 
7042     //    %B = icmp ugt short %X, 1330 
7043     // because %A may have negative value. 
7044     //
7045     // However, we allow this when the compare is EQ/NE, because they are
7046     // signless.
7047     if (isSignedExt == isSignedCmp || ICI.isEquality())
7048       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7049     return 0;
7050   }
7051
7052   // The re-extended constant changed so the constant cannot be represented 
7053   // in the shorter type. Consequently, we cannot emit a simple comparison.
7054
7055   // First, handle some easy cases. We know the result cannot be equal at this
7056   // point so handle the ICI.isEquality() cases
7057   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7058     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7059   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7060     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7061
7062   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7063   // should have been folded away previously and not enter in here.
7064   Value *Result;
7065   if (isSignedCmp) {
7066     // We're performing a signed comparison.
7067     if (cast<ConstantInt>(CI)->getValue().isNegative())
7068       Result = ConstantInt::getFalse();          // X < (small) --> false
7069     else
7070       Result = ConstantInt::getTrue();           // X < (large) --> true
7071   } else {
7072     // We're performing an unsigned comparison.
7073     if (isSignedExt) {
7074       // We're performing an unsigned comp with a sign extended value.
7075       // This is true if the input is >= 0. [aka >s -1]
7076       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7077       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7078                                    NegOne, ICI.getName()), ICI);
7079     } else {
7080       // Unsigned extend & unsigned compare -> always true.
7081       Result = ConstantInt::getTrue();
7082     }
7083   }
7084
7085   // Finally, return the value computed.
7086   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7087       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7088     return ReplaceInstUsesWith(ICI, Result);
7089
7090   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7091           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7092          "ICmp should be folded!");
7093   if (Constant *CI = dyn_cast<Constant>(Result))
7094     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7095   return BinaryOperator::CreateNot(Result);
7096 }
7097
7098 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7099   return commonShiftTransforms(I);
7100 }
7101
7102 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7103   return commonShiftTransforms(I);
7104 }
7105
7106 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7107   if (Instruction *R = commonShiftTransforms(I))
7108     return R;
7109   
7110   Value *Op0 = I.getOperand(0);
7111   
7112   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7113   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7114     if (CSI->isAllOnesValue())
7115       return ReplaceInstUsesWith(I, CSI);
7116   
7117   // See if we can turn a signed shr into an unsigned shr.
7118   if (!isa<VectorType>(I.getType())) {
7119     if (MaskedValueIsZero(Op0,
7120                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7121       return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7122
7123     // Arithmetic shifting an all-sign-bit value is a no-op.
7124     unsigned NumSignBits = ComputeNumSignBits(Op0);
7125     if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7126       return ReplaceInstUsesWith(I, Op0);
7127   }
7128
7129   return 0;
7130 }
7131
7132 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7133   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7134   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7135
7136   // shl X, 0 == X and shr X, 0 == X
7137   // shl 0, X == 0 and shr 0, X == 0
7138   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7139       Op0 == Constant::getNullValue(Op0->getType()))
7140     return ReplaceInstUsesWith(I, Op0);
7141   
7142   if (isa<UndefValue>(Op0)) {            
7143     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7144       return ReplaceInstUsesWith(I, Op0);
7145     else                                    // undef << X -> 0, undef >>u X -> 0
7146       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7147   }
7148   if (isa<UndefValue>(Op1)) {
7149     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7150       return ReplaceInstUsesWith(I, Op0);          
7151     else                                     // X << undef, X >>u undef -> 0
7152       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7153   }
7154
7155   // See if we can fold away this shift.
7156   if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
7157     return &I;
7158
7159   // Try to fold constant and into select arguments.
7160   if (isa<Constant>(Op0))
7161     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7162       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7163         return R;
7164
7165   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7166     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7167       return Res;
7168   return 0;
7169 }
7170
7171 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7172                                                BinaryOperator &I) {
7173   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7174
7175   // See if we can simplify any instructions used by the instruction whose sole 
7176   // purpose is to compute bits we don't care about.
7177   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7178   
7179   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7180   // of a signed value.
7181   //
7182   if (Op1->uge(TypeBits)) {
7183     if (I.getOpcode() != Instruction::AShr)
7184       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7185     else {
7186       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7187       return &I;
7188     }
7189   }
7190   
7191   // ((X*C1) << C2) == (X * (C1 << C2))
7192   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7193     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7194       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7195         return BinaryOperator::CreateMul(BO->getOperand(0),
7196                                          ConstantExpr::getShl(BOOp, Op1));
7197   
7198   // Try to fold constant and into select arguments.
7199   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7200     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7201       return R;
7202   if (isa<PHINode>(Op0))
7203     if (Instruction *NV = FoldOpIntoPhi(I))
7204       return NV;
7205   
7206   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7207   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7208     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7209     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7210     // place.  Don't try to do this transformation in this case.  Also, we
7211     // require that the input operand is a shift-by-constant so that we have
7212     // confidence that the shifts will get folded together.  We could do this
7213     // xform in more cases, but it is unlikely to be profitable.
7214     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7215         isa<ConstantInt>(TrOp->getOperand(1))) {
7216       // Okay, we'll do this xform.  Make the shift of shift.
7217       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7218       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7219                                                 I.getName());
7220       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7221
7222       // For logical shifts, the truncation has the effect of making the high
7223       // part of the register be zeros.  Emulate this by inserting an AND to
7224       // clear the top bits as needed.  This 'and' will usually be zapped by
7225       // other xforms later if dead.
7226       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7227       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7228       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7229       
7230       // The mask we constructed says what the trunc would do if occurring
7231       // between the shifts.  We want to know the effect *after* the second
7232       // shift.  We know that it is a logical shift by a constant, so adjust the
7233       // mask as appropriate.
7234       if (I.getOpcode() == Instruction::Shl)
7235         MaskV <<= Op1->getZExtValue();
7236       else {
7237         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7238         MaskV = MaskV.lshr(Op1->getZExtValue());
7239       }
7240
7241       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7242                                                    TI->getName());
7243       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7244
7245       // Return the value truncated to the interesting size.
7246       return new TruncInst(And, I.getType());
7247     }
7248   }
7249   
7250   if (Op0->hasOneUse()) {
7251     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7252       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7253       Value *V1, *V2;
7254       ConstantInt *CC;
7255       switch (Op0BO->getOpcode()) {
7256         default: break;
7257         case Instruction::Add:
7258         case Instruction::And:
7259         case Instruction::Or:
7260         case Instruction::Xor: {
7261           // These operators commute.
7262           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7263           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7264               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7265             Instruction *YS = BinaryOperator::CreateShl(
7266                                             Op0BO->getOperand(0), Op1,
7267                                             Op0BO->getName());
7268             InsertNewInstBefore(YS, I); // (Y << C)
7269             Instruction *X = 
7270               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7271                                      Op0BO->getOperand(1)->getName());
7272             InsertNewInstBefore(X, I);  // (X + (Y << C))
7273             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7274             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7275                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7276           }
7277           
7278           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7279           Value *Op0BOOp1 = Op0BO->getOperand(1);
7280           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7281               match(Op0BOOp1, 
7282                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7283                           m_ConstantInt(CC))) &&
7284               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7285             Instruction *YS = BinaryOperator::CreateShl(
7286                                                      Op0BO->getOperand(0), Op1,
7287                                                      Op0BO->getName());
7288             InsertNewInstBefore(YS, I); // (Y << C)
7289             Instruction *XM =
7290               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7291                                         V1->getName()+".mask");
7292             InsertNewInstBefore(XM, I); // X & (CC << C)
7293             
7294             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7295           }
7296         }
7297           
7298         // FALL THROUGH.
7299         case Instruction::Sub: {
7300           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7301           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7302               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7303             Instruction *YS = BinaryOperator::CreateShl(
7304                                                      Op0BO->getOperand(1), Op1,
7305                                                      Op0BO->getName());
7306             InsertNewInstBefore(YS, I); // (Y << C)
7307             Instruction *X =
7308               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7309                                      Op0BO->getOperand(0)->getName());
7310             InsertNewInstBefore(X, I);  // (X + (Y << C))
7311             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7312             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7313                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7314           }
7315           
7316           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7317           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7318               match(Op0BO->getOperand(0),
7319                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7320                           m_ConstantInt(CC))) && V2 == Op1 &&
7321               cast<BinaryOperator>(Op0BO->getOperand(0))
7322                   ->getOperand(0)->hasOneUse()) {
7323             Instruction *YS = BinaryOperator::CreateShl(
7324                                                      Op0BO->getOperand(1), Op1,
7325                                                      Op0BO->getName());
7326             InsertNewInstBefore(YS, I); // (Y << C)
7327             Instruction *XM =
7328               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7329                                         V1->getName()+".mask");
7330             InsertNewInstBefore(XM, I); // X & (CC << C)
7331             
7332             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7333           }
7334           
7335           break;
7336         }
7337       }
7338       
7339       
7340       // If the operand is an bitwise operator with a constant RHS, and the
7341       // shift is the only use, we can pull it out of the shift.
7342       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7343         bool isValid = true;     // Valid only for And, Or, Xor
7344         bool highBitSet = false; // Transform if high bit of constant set?
7345         
7346         switch (Op0BO->getOpcode()) {
7347           default: isValid = false; break;   // Do not perform transform!
7348           case Instruction::Add:
7349             isValid = isLeftShift;
7350             break;
7351           case Instruction::Or:
7352           case Instruction::Xor:
7353             highBitSet = false;
7354             break;
7355           case Instruction::And:
7356             highBitSet = true;
7357             break;
7358         }
7359         
7360         // If this is a signed shift right, and the high bit is modified
7361         // by the logical operation, do not perform the transformation.
7362         // The highBitSet boolean indicates the value of the high bit of
7363         // the constant which would cause it to be modified for this
7364         // operation.
7365         //
7366         if (isValid && I.getOpcode() == Instruction::AShr)
7367           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7368         
7369         if (isValid) {
7370           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7371           
7372           Instruction *NewShift =
7373             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7374           InsertNewInstBefore(NewShift, I);
7375           NewShift->takeName(Op0BO);
7376           
7377           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7378                                         NewRHS);
7379         }
7380       }
7381     }
7382   }
7383   
7384   // Find out if this is a shift of a shift by a constant.
7385   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7386   if (ShiftOp && !ShiftOp->isShift())
7387     ShiftOp = 0;
7388   
7389   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7390     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7391     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7392     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7393     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7394     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7395     Value *X = ShiftOp->getOperand(0);
7396     
7397     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7398     
7399     const IntegerType *Ty = cast<IntegerType>(I.getType());
7400     
7401     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7402     if (I.getOpcode() == ShiftOp->getOpcode()) {
7403       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7404       // saturates.
7405       if (AmtSum >= TypeBits) {
7406         if (I.getOpcode() != Instruction::AShr)
7407           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7408         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7409       }
7410       
7411       return BinaryOperator::Create(I.getOpcode(), X,
7412                                     ConstantInt::get(Ty, AmtSum));
7413     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7414                I.getOpcode() == Instruction::AShr) {
7415       if (AmtSum >= TypeBits)
7416         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7417       
7418       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7419       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7420     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7421                I.getOpcode() == Instruction::LShr) {
7422       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7423       if (AmtSum >= TypeBits)
7424         AmtSum = TypeBits-1;
7425       
7426       Instruction *Shift =
7427         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7428       InsertNewInstBefore(Shift, I);
7429
7430       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7431       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7432     }
7433     
7434     // Okay, if we get here, one shift must be left, and the other shift must be
7435     // right.  See if the amounts are equal.
7436     if (ShiftAmt1 == ShiftAmt2) {
7437       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7438       if (I.getOpcode() == Instruction::Shl) {
7439         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7440         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7441       }
7442       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7443       if (I.getOpcode() == Instruction::LShr) {
7444         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7445         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7446       }
7447       // We can simplify ((X << C) >>s C) into a trunc + sext.
7448       // NOTE: we could do this for any C, but that would make 'unusual' integer
7449       // types.  For now, just stick to ones well-supported by the code
7450       // generators.
7451       const Type *SExtType = 0;
7452       switch (Ty->getBitWidth() - ShiftAmt1) {
7453       case 1  :
7454       case 8  :
7455       case 16 :
7456       case 32 :
7457       case 64 :
7458       case 128:
7459         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7460         break;
7461       default: break;
7462       }
7463       if (SExtType) {
7464         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7465         InsertNewInstBefore(NewTrunc, I);
7466         return new SExtInst(NewTrunc, Ty);
7467       }
7468       // Otherwise, we can't handle it yet.
7469     } else if (ShiftAmt1 < ShiftAmt2) {
7470       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7471       
7472       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7473       if (I.getOpcode() == Instruction::Shl) {
7474         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7475                ShiftOp->getOpcode() == Instruction::AShr);
7476         Instruction *Shift =
7477           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7478         InsertNewInstBefore(Shift, I);
7479         
7480         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7481         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7482       }
7483       
7484       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7485       if (I.getOpcode() == Instruction::LShr) {
7486         assert(ShiftOp->getOpcode() == Instruction::Shl);
7487         Instruction *Shift =
7488           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7489         InsertNewInstBefore(Shift, I);
7490         
7491         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7492         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7493       }
7494       
7495       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7496     } else {
7497       assert(ShiftAmt2 < ShiftAmt1);
7498       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7499
7500       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7501       if (I.getOpcode() == Instruction::Shl) {
7502         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7503                ShiftOp->getOpcode() == Instruction::AShr);
7504         Instruction *Shift =
7505           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7506                                  ConstantInt::get(Ty, ShiftDiff));
7507         InsertNewInstBefore(Shift, I);
7508         
7509         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7510         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7511       }
7512       
7513       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7514       if (I.getOpcode() == Instruction::LShr) {
7515         assert(ShiftOp->getOpcode() == Instruction::Shl);
7516         Instruction *Shift =
7517           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7518         InsertNewInstBefore(Shift, I);
7519         
7520         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7521         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7522       }
7523       
7524       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7525     }
7526   }
7527   return 0;
7528 }
7529
7530
7531 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7532 /// expression.  If so, decompose it, returning some value X, such that Val is
7533 /// X*Scale+Offset.
7534 ///
7535 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7536                                         int &Offset) {
7537   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7538   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7539     Offset = CI->getZExtValue();
7540     Scale  = 0;
7541     return ConstantInt::get(Type::Int32Ty, 0);
7542   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7543     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7544       if (I->getOpcode() == Instruction::Shl) {
7545         // This is a value scaled by '1 << the shift amt'.
7546         Scale = 1U << RHS->getZExtValue();
7547         Offset = 0;
7548         return I->getOperand(0);
7549       } else if (I->getOpcode() == Instruction::Mul) {
7550         // This value is scaled by 'RHS'.
7551         Scale = RHS->getZExtValue();
7552         Offset = 0;
7553         return I->getOperand(0);
7554       } else if (I->getOpcode() == Instruction::Add) {
7555         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7556         // where C1 is divisible by C2.
7557         unsigned SubScale;
7558         Value *SubVal = 
7559           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7560         Offset += RHS->getZExtValue();
7561         Scale = SubScale;
7562         return SubVal;
7563       }
7564     }
7565   }
7566
7567   // Otherwise, we can't look past this.
7568   Scale = 1;
7569   Offset = 0;
7570   return Val;
7571 }
7572
7573
7574 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7575 /// try to eliminate the cast by moving the type information into the alloc.
7576 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7577                                                    AllocationInst &AI) {
7578   const PointerType *PTy = cast<PointerType>(CI.getType());
7579   
7580   // Remove any uses of AI that are dead.
7581   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7582   
7583   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7584     Instruction *User = cast<Instruction>(*UI++);
7585     if (isInstructionTriviallyDead(User)) {
7586       while (UI != E && *UI == User)
7587         ++UI; // If this instruction uses AI more than once, don't break UI.
7588       
7589       ++NumDeadInst;
7590       DOUT << "IC: DCE: " << *User;
7591       EraseInstFromFunction(*User);
7592     }
7593   }
7594   
7595   // Get the type really allocated and the type casted to.
7596   const Type *AllocElTy = AI.getAllocatedType();
7597   const Type *CastElTy = PTy->getElementType();
7598   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7599
7600   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7601   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7602   if (CastElTyAlign < AllocElTyAlign) return 0;
7603
7604   // If the allocation has multiple uses, only promote it if we are strictly
7605   // increasing the alignment of the resultant allocation.  If we keep it the
7606   // same, we open the door to infinite loops of various kinds.  (A reference
7607   // from a dbg.declare doesn't count as a use for this purpose.)
7608   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7609       CastElTyAlign == AllocElTyAlign) return 0;
7610
7611   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7612   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7613   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7614
7615   // See if we can satisfy the modulus by pulling a scale out of the array
7616   // size argument.
7617   unsigned ArraySizeScale;
7618   int ArrayOffset;
7619   Value *NumElements = // See if the array size is a decomposable linear expr.
7620     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7621  
7622   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7623   // do the xform.
7624   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7625       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7626
7627   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7628   Value *Amt = 0;
7629   if (Scale == 1) {
7630     Amt = NumElements;
7631   } else {
7632     // If the allocation size is constant, form a constant mul expression
7633     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7634     if (isa<ConstantInt>(NumElements))
7635       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7636     // otherwise multiply the amount and the number of elements
7637     else {
7638       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7639       Amt = InsertNewInstBefore(Tmp, AI);
7640     }
7641   }
7642   
7643   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7644     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7645     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7646     Amt = InsertNewInstBefore(Tmp, AI);
7647   }
7648   
7649   AllocationInst *New;
7650   if (isa<MallocInst>(AI))
7651     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7652   else
7653     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7654   InsertNewInstBefore(New, AI);
7655   New->takeName(&AI);
7656   
7657   // If the allocation has one real use plus a dbg.declare, just remove the
7658   // declare.
7659   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7660     EraseInstFromFunction(*DI);
7661   }
7662   // If the allocation has multiple real uses, insert a cast and change all
7663   // things that used it to use the new cast.  This will also hack on CI, but it
7664   // will die soon.
7665   else if (!AI.hasOneUse()) {
7666     AddUsesToWorkList(AI);
7667     // New is the allocation instruction, pointer typed. AI is the original
7668     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7669     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7670     InsertNewInstBefore(NewCast, AI);
7671     AI.replaceAllUsesWith(NewCast);
7672   }
7673   return ReplaceInstUsesWith(CI, New);
7674 }
7675
7676 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7677 /// and return it as type Ty without inserting any new casts and without
7678 /// changing the computed value.  This is used by code that tries to decide
7679 /// whether promoting or shrinking integer operations to wider or smaller types
7680 /// will allow us to eliminate a truncate or extend.
7681 ///
7682 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7683 /// extension operation if Ty is larger.
7684 ///
7685 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7686 /// should return true if trunc(V) can be computed by computing V in the smaller
7687 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7688 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7689 /// efficiently truncated.
7690 ///
7691 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7692 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7693 /// the final result.
7694 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7695                                               unsigned CastOpc,
7696                                               int &NumCastsRemoved){
7697   // We can always evaluate constants in another type.
7698   if (isa<ConstantInt>(V))
7699     return true;
7700   
7701   Instruction *I = dyn_cast<Instruction>(V);
7702   if (!I) return false;
7703   
7704   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7705   
7706   // If this is an extension or truncate, we can often eliminate it.
7707   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7708     // If this is a cast from the destination type, we can trivially eliminate
7709     // it, and this will remove a cast overall.
7710     if (I->getOperand(0)->getType() == Ty) {
7711       // If the first operand is itself a cast, and is eliminable, do not count
7712       // this as an eliminable cast.  We would prefer to eliminate those two
7713       // casts first.
7714       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7715         ++NumCastsRemoved;
7716       return true;
7717     }
7718   }
7719
7720   // We can't extend or shrink something that has multiple uses: doing so would
7721   // require duplicating the instruction in general, which isn't profitable.
7722   if (!I->hasOneUse()) return false;
7723
7724   unsigned Opc = I->getOpcode();
7725   switch (Opc) {
7726   case Instruction::Add:
7727   case Instruction::Sub:
7728   case Instruction::Mul:
7729   case Instruction::And:
7730   case Instruction::Or:
7731   case Instruction::Xor:
7732     // These operators can all arbitrarily be extended or truncated.
7733     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7734                                       NumCastsRemoved) &&
7735            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7736                                       NumCastsRemoved);
7737
7738   case Instruction::Shl:
7739     // If we are truncating the result of this SHL, and if it's a shift of a
7740     // constant amount, we can always perform a SHL in a smaller type.
7741     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7742       uint32_t BitWidth = Ty->getBitWidth();
7743       if (BitWidth < OrigTy->getBitWidth() && 
7744           CI->getLimitedValue(BitWidth) < BitWidth)
7745         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7746                                           NumCastsRemoved);
7747     }
7748     break;
7749   case Instruction::LShr:
7750     // If this is a truncate of a logical shr, we can truncate it to a smaller
7751     // lshr iff we know that the bits we would otherwise be shifting in are
7752     // already zeros.
7753     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7754       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7755       uint32_t BitWidth = Ty->getBitWidth();
7756       if (BitWidth < OrigBitWidth &&
7757           MaskedValueIsZero(I->getOperand(0),
7758             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7759           CI->getLimitedValue(BitWidth) < BitWidth) {
7760         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7761                                           NumCastsRemoved);
7762       }
7763     }
7764     break;
7765   case Instruction::ZExt:
7766   case Instruction::SExt:
7767   case Instruction::Trunc:
7768     // If this is the same kind of case as our original (e.g. zext+zext), we
7769     // can safely replace it.  Note that replacing it does not reduce the number
7770     // of casts in the input.
7771     if (Opc == CastOpc)
7772       return true;
7773
7774     // sext (zext ty1), ty2 -> zext ty2
7775     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7776       return true;
7777     break;
7778   case Instruction::Select: {
7779     SelectInst *SI = cast<SelectInst>(I);
7780     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7781                                       NumCastsRemoved) &&
7782            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7783                                       NumCastsRemoved);
7784   }
7785   case Instruction::PHI: {
7786     // We can change a phi if we can change all operands.
7787     PHINode *PN = cast<PHINode>(I);
7788     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7789       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7790                                       NumCastsRemoved))
7791         return false;
7792     return true;
7793   }
7794   default:
7795     // TODO: Can handle more cases here.
7796     break;
7797   }
7798   
7799   return false;
7800 }
7801
7802 /// EvaluateInDifferentType - Given an expression that 
7803 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7804 /// evaluate the expression.
7805 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7806                                              bool isSigned) {
7807   if (Constant *C = dyn_cast<Constant>(V))
7808     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7809
7810   // Otherwise, it must be an instruction.
7811   Instruction *I = cast<Instruction>(V);
7812   Instruction *Res = 0;
7813   unsigned Opc = I->getOpcode();
7814   switch (Opc) {
7815   case Instruction::Add:
7816   case Instruction::Sub:
7817   case Instruction::Mul:
7818   case Instruction::And:
7819   case Instruction::Or:
7820   case Instruction::Xor:
7821   case Instruction::AShr:
7822   case Instruction::LShr:
7823   case Instruction::Shl: {
7824     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7825     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7826     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7827     break;
7828   }    
7829   case Instruction::Trunc:
7830   case Instruction::ZExt:
7831   case Instruction::SExt:
7832     // If the source type of the cast is the type we're trying for then we can
7833     // just return the source.  There's no need to insert it because it is not
7834     // new.
7835     if (I->getOperand(0)->getType() == Ty)
7836       return I->getOperand(0);
7837     
7838     // Otherwise, must be the same type of cast, so just reinsert a new one.
7839     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7840                            Ty);
7841     break;
7842   case Instruction::Select: {
7843     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7844     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7845     Res = SelectInst::Create(I->getOperand(0), True, False);
7846     break;
7847   }
7848   case Instruction::PHI: {
7849     PHINode *OPN = cast<PHINode>(I);
7850     PHINode *NPN = PHINode::Create(Ty);
7851     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7852       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7853       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7854     }
7855     Res = NPN;
7856     break;
7857   }
7858   default: 
7859     // TODO: Can handle more cases here.
7860     assert(0 && "Unreachable!");
7861     break;
7862   }
7863   
7864   Res->takeName(I);
7865   return InsertNewInstBefore(Res, *I);
7866 }
7867
7868 /// @brief Implement the transforms common to all CastInst visitors.
7869 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7870   Value *Src = CI.getOperand(0);
7871
7872   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7873   // eliminate it now.
7874   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7875     if (Instruction::CastOps opc = 
7876         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7877       // The first cast (CSrc) is eliminable so we need to fix up or replace
7878       // the second cast (CI). CSrc will then have a good chance of being dead.
7879       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7880     }
7881   }
7882
7883   // If we are casting a select then fold the cast into the select
7884   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7885     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7886       return NV;
7887
7888   // If we are casting a PHI then fold the cast into the PHI
7889   if (isa<PHINode>(Src))
7890     if (Instruction *NV = FoldOpIntoPhi(CI))
7891       return NV;
7892   
7893   return 0;
7894 }
7895
7896 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7897 /// or not there is a sequence of GEP indices into the type that will land us at
7898 /// the specified offset.  If so, fill them into NewIndices and return the
7899 /// resultant element type, otherwise return null.
7900 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7901                                        SmallVectorImpl<Value*> &NewIndices,
7902                                        const TargetData *TD) {
7903   if (!Ty->isSized()) return 0;
7904   
7905   // Start with the index over the outer type.  Note that the type size
7906   // might be zero (even if the offset isn't zero) if the indexed type
7907   // is something like [0 x {int, int}]
7908   const Type *IntPtrTy = TD->getIntPtrType();
7909   int64_t FirstIdx = 0;
7910   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
7911     FirstIdx = Offset/TySize;
7912     Offset -= FirstIdx*TySize;
7913     
7914     // Handle hosts where % returns negative instead of values [0..TySize).
7915     if (Offset < 0) {
7916       --FirstIdx;
7917       Offset += TySize;
7918       assert(Offset >= 0);
7919     }
7920     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7921   }
7922   
7923   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7924     
7925   // Index into the types.  If we fail, set OrigBase to null.
7926   while (Offset) {
7927     // Indexing into tail padding between struct/array elements.
7928     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7929       return 0;
7930     
7931     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7932       const StructLayout *SL = TD->getStructLayout(STy);
7933       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7934              "Offset must stay within the indexed type");
7935       
7936       unsigned Elt = SL->getElementContainingOffset(Offset);
7937       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7938       
7939       Offset -= SL->getElementOffset(Elt);
7940       Ty = STy->getElementType(Elt);
7941     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7942       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
7943       assert(EltSize && "Cannot index into a zero-sized array");
7944       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7945       Offset %= EltSize;
7946       Ty = AT->getElementType();
7947     } else {
7948       // Otherwise, we can't index into the middle of this atomic type, bail.
7949       return 0;
7950     }
7951   }
7952   
7953   return Ty;
7954 }
7955
7956 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7957 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7958   Value *Src = CI.getOperand(0);
7959   
7960   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7961     // If casting the result of a getelementptr instruction with no offset, turn
7962     // this into a cast of the original pointer!
7963     if (GEP->hasAllZeroIndices()) {
7964       // Changing the cast operand is usually not a good idea but it is safe
7965       // here because the pointer operand is being replaced with another 
7966       // pointer operand so the opcode doesn't need to change.
7967       AddToWorkList(GEP);
7968       CI.setOperand(0, GEP->getOperand(0));
7969       return &CI;
7970     }
7971     
7972     // If the GEP has a single use, and the base pointer is a bitcast, and the
7973     // GEP computes a constant offset, see if we can convert these three
7974     // instructions into fewer.  This typically happens with unions and other
7975     // non-type-safe code.
7976     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7977       if (GEP->hasAllConstantIndices()) {
7978         // We are guaranteed to get a constant from EmitGEPOffset.
7979         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7980         int64_t Offset = OffsetV->getSExtValue();
7981         
7982         // Get the base pointer input of the bitcast, and the type it points to.
7983         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7984         const Type *GEPIdxTy =
7985           cast<PointerType>(OrigBase->getType())->getElementType();
7986         SmallVector<Value*, 8> NewIndices;
7987         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7988           // If we were able to index down into an element, create the GEP
7989           // and bitcast the result.  This eliminates one bitcast, potentially
7990           // two.
7991           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7992                                                         NewIndices.begin(),
7993                                                         NewIndices.end(), "");
7994           InsertNewInstBefore(NGEP, CI);
7995           NGEP->takeName(GEP);
7996           
7997           if (isa<BitCastInst>(CI))
7998             return new BitCastInst(NGEP, CI.getType());
7999           assert(isa<PtrToIntInst>(CI));
8000           return new PtrToIntInst(NGEP, CI.getType());
8001         }
8002       }      
8003     }
8004   }
8005     
8006   return commonCastTransforms(CI);
8007 }
8008
8009 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8010 /// type like i42.  We don't want to introduce operations on random non-legal
8011 /// integer types where they don't already exist in the code.  In the future,
8012 /// we should consider making this based off target-data, so that 32-bit targets
8013 /// won't get i64 operations etc.
8014 static bool isSafeIntegerType(const Type *Ty) {
8015   switch (Ty->getPrimitiveSizeInBits()) {
8016   case 8:
8017   case 16:
8018   case 32:
8019   case 64:
8020     return true;
8021   default: 
8022     return false;
8023   }
8024 }
8025
8026 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8027 /// integer types. This function implements the common transforms for all those
8028 /// cases.
8029 /// @brief Implement the transforms common to CastInst with integer operands
8030 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8031   if (Instruction *Result = commonCastTransforms(CI))
8032     return Result;
8033
8034   Value *Src = CI.getOperand(0);
8035   const Type *SrcTy = Src->getType();
8036   const Type *DestTy = CI.getType();
8037   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8038   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
8039
8040   // See if we can simplify any instructions used by the LHS whose sole 
8041   // purpose is to compute bits we don't care about.
8042   if (SimplifyDemandedInstructionBits(CI))
8043     return &CI;
8044
8045   // If the source isn't an instruction or has more than one use then we
8046   // can't do anything more. 
8047   Instruction *SrcI = dyn_cast<Instruction>(Src);
8048   if (!SrcI || !Src->hasOneUse())
8049     return 0;
8050
8051   // Attempt to propagate the cast into the instruction for int->int casts.
8052   int NumCastsRemoved = 0;
8053   if (!isa<BitCastInst>(CI) &&
8054       // Only do this if the dest type is a simple type, don't convert the
8055       // expression tree to something weird like i93 unless the source is also
8056       // strange.
8057       (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
8058       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
8059                                  CI.getOpcode(), NumCastsRemoved)) {
8060     // If this cast is a truncate, evaluting in a different type always
8061     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8062     // we need to do an AND to maintain the clear top-part of the computation,
8063     // so we require that the input have eliminated at least one cast.  If this
8064     // is a sign extension, we insert two new casts (to do the extension) so we
8065     // require that two casts have been eliminated.
8066     bool DoXForm = false;
8067     bool JustReplace = false;
8068     switch (CI.getOpcode()) {
8069     default:
8070       // All the others use floating point so we shouldn't actually 
8071       // get here because of the check above.
8072       assert(0 && "Unknown cast type");
8073     case Instruction::Trunc:
8074       DoXForm = true;
8075       break;
8076     case Instruction::ZExt: {
8077       DoXForm = NumCastsRemoved >= 1;
8078       if (!DoXForm && 0) {
8079         // If it's unnecessary to issue an AND to clear the high bits, it's
8080         // always profitable to do this xform.
8081         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8082         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8083         if (MaskedValueIsZero(TryRes, Mask))
8084           return ReplaceInstUsesWith(CI, TryRes);
8085         
8086         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8087           if (TryI->use_empty())
8088             EraseInstFromFunction(*TryI);
8089       }
8090       break;
8091     }
8092     case Instruction::SExt: {
8093       DoXForm = NumCastsRemoved >= 2;
8094       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8095         // If we do not have to emit the truncate + sext pair, then it's always
8096         // profitable to do this xform.
8097         //
8098         // It's not safe to eliminate the trunc + sext pair if one of the
8099         // eliminated cast is a truncate. e.g.
8100         // t2 = trunc i32 t1 to i16
8101         // t3 = sext i16 t2 to i32
8102         // !=
8103         // i32 t1
8104         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8105         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8106         if (NumSignBits > (DestBitSize - SrcBitSize))
8107           return ReplaceInstUsesWith(CI, TryRes);
8108         
8109         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8110           if (TryI->use_empty())
8111             EraseInstFromFunction(*TryI);
8112       }
8113       break;
8114     }
8115     }
8116     
8117     if (DoXForm) {
8118       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8119            << " cast: " << CI;
8120       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8121                                            CI.getOpcode() == Instruction::SExt);
8122       if (JustReplace)
8123         // Just replace this cast with the result.
8124         return ReplaceInstUsesWith(CI, Res);
8125
8126       assert(Res->getType() == DestTy);
8127       switch (CI.getOpcode()) {
8128       default: assert(0 && "Unknown cast type!");
8129       case Instruction::Trunc:
8130       case Instruction::BitCast:
8131         // Just replace this cast with the result.
8132         return ReplaceInstUsesWith(CI, Res);
8133       case Instruction::ZExt: {
8134         assert(SrcBitSize < DestBitSize && "Not a zext?");
8135
8136         // If the high bits are already zero, just replace this cast with the
8137         // result.
8138         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8139         if (MaskedValueIsZero(Res, Mask))
8140           return ReplaceInstUsesWith(CI, Res);
8141
8142         // We need to emit an AND to clear the high bits.
8143         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8144                                                             SrcBitSize));
8145         return BinaryOperator::CreateAnd(Res, C);
8146       }
8147       case Instruction::SExt: {
8148         // If the high bits are already filled with sign bit, just replace this
8149         // cast with the result.
8150         unsigned NumSignBits = ComputeNumSignBits(Res);
8151         if (NumSignBits > (DestBitSize - SrcBitSize))
8152           return ReplaceInstUsesWith(CI, Res);
8153
8154         // We need to emit a cast to truncate, then a cast to sext.
8155         return CastInst::Create(Instruction::SExt,
8156             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8157                              CI), DestTy);
8158       }
8159       }
8160     }
8161   }
8162   
8163   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8164   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8165
8166   switch (SrcI->getOpcode()) {
8167   case Instruction::Add:
8168   case Instruction::Mul:
8169   case Instruction::And:
8170   case Instruction::Or:
8171   case Instruction::Xor:
8172     // If we are discarding information, rewrite.
8173     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8174       // Don't insert two casts if they cannot be eliminated.  We allow 
8175       // two casts to be inserted if the sizes are the same.  This could 
8176       // only be converting signedness, which is a noop.
8177       if (DestBitSize == SrcBitSize || 
8178           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8179           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8180         Instruction::CastOps opcode = CI.getOpcode();
8181         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8182         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8183         return BinaryOperator::Create(
8184             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8185       }
8186     }
8187
8188     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8189     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8190         SrcI->getOpcode() == Instruction::Xor &&
8191         Op1 == ConstantInt::getTrue() &&
8192         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8193       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8194       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8195     }
8196     break;
8197   case Instruction::SDiv:
8198   case Instruction::UDiv:
8199   case Instruction::SRem:
8200   case Instruction::URem:
8201     // If we are just changing the sign, rewrite.
8202     if (DestBitSize == SrcBitSize) {
8203       // Don't insert two casts if they cannot be eliminated.  We allow 
8204       // two casts to be inserted if the sizes are the same.  This could 
8205       // only be converting signedness, which is a noop.
8206       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8207           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8208         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8209                                        Op0, DestTy, *SrcI);
8210         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8211                                        Op1, DestTy, *SrcI);
8212         return BinaryOperator::Create(
8213           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8214       }
8215     }
8216     break;
8217
8218   case Instruction::Shl:
8219     // Allow changing the sign of the source operand.  Do not allow 
8220     // changing the size of the shift, UNLESS the shift amount is a 
8221     // constant.  We must not change variable sized shifts to a smaller 
8222     // size, because it is undefined to shift more bits out than exist 
8223     // in the value.
8224     if (DestBitSize == SrcBitSize ||
8225         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8226       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8227           Instruction::BitCast : Instruction::Trunc);
8228       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8229       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8230       return BinaryOperator::CreateShl(Op0c, Op1c);
8231     }
8232     break;
8233   case Instruction::AShr:
8234     // If this is a signed shr, and if all bits shifted in are about to be
8235     // truncated off, turn it into an unsigned shr to allow greater
8236     // simplifications.
8237     if (DestBitSize < SrcBitSize &&
8238         isa<ConstantInt>(Op1)) {
8239       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8240       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8241         // Insert the new logical shift right.
8242         return BinaryOperator::CreateLShr(Op0, Op1);
8243       }
8244     }
8245     break;
8246   }
8247   return 0;
8248 }
8249
8250 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8251   if (Instruction *Result = commonIntCastTransforms(CI))
8252     return Result;
8253   
8254   Value *Src = CI.getOperand(0);
8255   const Type *Ty = CI.getType();
8256   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8257   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8258
8259   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8260   if (DestBitWidth == 1) {
8261     Constant *One = ConstantInt::get(Src->getType(), 1);
8262     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8263     Value *Zero = Constant::getNullValue(Src->getType());
8264     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8265   }
8266   
8267   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8268   ConstantInt *ShAmtV = 0;
8269   Value *ShiftOp = 0;
8270   if (Src->hasOneUse() &&
8271       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8272     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8273     
8274     // Get a mask for the bits shifting in.
8275     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8276     if (MaskedValueIsZero(ShiftOp, Mask)) {
8277       if (ShAmt >= DestBitWidth)        // All zeros.
8278         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8279       
8280       // Okay, we can shrink this.  Truncate the input, then return a new
8281       // shift.
8282       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8283       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8284       return BinaryOperator::CreateLShr(V1, V2);
8285     }
8286   }
8287   
8288   return 0;
8289 }
8290
8291 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8292 /// in order to eliminate the icmp.
8293 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8294                                              bool DoXform) {
8295   // If we are just checking for a icmp eq of a single bit and zext'ing it
8296   // to an integer, then shift the bit to the appropriate place and then
8297   // cast to integer to avoid the comparison.
8298   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8299     const APInt &Op1CV = Op1C->getValue();
8300       
8301     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8302     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8303     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8304         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8305       if (!DoXform) return ICI;
8306
8307       Value *In = ICI->getOperand(0);
8308       Value *Sh = ConstantInt::get(In->getType(),
8309                                    In->getType()->getPrimitiveSizeInBits()-1);
8310       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8311                                                         In->getName()+".lobit"),
8312                                CI);
8313       if (In->getType() != CI.getType())
8314         In = CastInst::CreateIntegerCast(In, CI.getType(),
8315                                          false/*ZExt*/, "tmp", &CI);
8316
8317       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8318         Constant *One = ConstantInt::get(In->getType(), 1);
8319         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8320                                                          In->getName()+".not"),
8321                                  CI);
8322       }
8323
8324       return ReplaceInstUsesWith(CI, In);
8325     }
8326       
8327       
8328       
8329     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8330     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8331     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8332     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8333     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8334     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8335     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8336     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8337     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8338         // This only works for EQ and NE
8339         ICI->isEquality()) {
8340       // If Op1C some other power of two, convert:
8341       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8342       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8343       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8344       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8345         
8346       APInt KnownZeroMask(~KnownZero);
8347       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8348         if (!DoXform) return ICI;
8349
8350         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8351         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8352           // (X&4) == 2 --> false
8353           // (X&4) != 2 --> true
8354           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8355           Res = ConstantExpr::getZExt(Res, CI.getType());
8356           return ReplaceInstUsesWith(CI, Res);
8357         }
8358           
8359         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8360         Value *In = ICI->getOperand(0);
8361         if (ShiftAmt) {
8362           // Perform a logical shr by shiftamt.
8363           // Insert the shift to put the result in the low bit.
8364           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8365                                   ConstantInt::get(In->getType(), ShiftAmt),
8366                                                    In->getName()+".lobit"), CI);
8367         }
8368           
8369         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8370           Constant *One = ConstantInt::get(In->getType(), 1);
8371           In = BinaryOperator::CreateXor(In, One, "tmp");
8372           InsertNewInstBefore(cast<Instruction>(In), CI);
8373         }
8374           
8375         if (CI.getType() == In->getType())
8376           return ReplaceInstUsesWith(CI, In);
8377         else
8378           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8379       }
8380     }
8381   }
8382
8383   return 0;
8384 }
8385
8386 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8387   // If one of the common conversion will work ..
8388   if (Instruction *Result = commonIntCastTransforms(CI))
8389     return Result;
8390
8391   Value *Src = CI.getOperand(0);
8392
8393   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8394   // types and if the sizes are just right we can convert this into a logical
8395   // 'and' which will be much cheaper than the pair of casts.
8396   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8397     // Get the sizes of the types involved.  We know that the intermediate type
8398     // will be smaller than A or C, but don't know the relation between A and C.
8399     Value *A = CSrc->getOperand(0);
8400     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8401     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8402     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8403     // If we're actually extending zero bits, then if
8404     // SrcSize <  DstSize: zext(a & mask)
8405     // SrcSize == DstSize: a & mask
8406     // SrcSize  > DstSize: trunc(a) & mask
8407     if (SrcSize < DstSize) {
8408       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8409       Constant *AndConst = ConstantInt::get(AndValue);
8410       Instruction *And =
8411         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8412       InsertNewInstBefore(And, CI);
8413       return new ZExtInst(And, CI.getType());
8414     } else if (SrcSize == DstSize) {
8415       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8416       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8417     } else if (SrcSize > DstSize) {
8418       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8419       InsertNewInstBefore(Trunc, CI);
8420       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8421       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8422     }
8423   }
8424
8425   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8426     return transformZExtICmp(ICI, CI);
8427
8428   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8429   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8430     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8431     // of the (zext icmp) will be transformed.
8432     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8433     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8434     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8435         (transformZExtICmp(LHS, CI, false) ||
8436          transformZExtICmp(RHS, CI, false))) {
8437       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8438       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8439       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8440     }
8441   }
8442
8443   return 0;
8444 }
8445
8446 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8447   if (Instruction *I = commonIntCastTransforms(CI))
8448     return I;
8449   
8450   Value *Src = CI.getOperand(0);
8451   
8452   // Canonicalize sign-extend from i1 to a select.
8453   if (Src->getType() == Type::Int1Ty)
8454     return SelectInst::Create(Src,
8455                               ConstantInt::getAllOnesValue(CI.getType()),
8456                               Constant::getNullValue(CI.getType()));
8457
8458   // See if the value being truncated is already sign extended.  If so, just
8459   // eliminate the trunc/sext pair.
8460   if (getOpcode(Src) == Instruction::Trunc) {
8461     Value *Op = cast<User>(Src)->getOperand(0);
8462     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8463     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8464     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8465     unsigned NumSignBits = ComputeNumSignBits(Op);
8466
8467     if (OpBits == DestBits) {
8468       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8469       // bits, it is already ready.
8470       if (NumSignBits > DestBits-MidBits)
8471         return ReplaceInstUsesWith(CI, Op);
8472     } else if (OpBits < DestBits) {
8473       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8474       // bits, just sext from i32.
8475       if (NumSignBits > OpBits-MidBits)
8476         return new SExtInst(Op, CI.getType(), "tmp");
8477     } else {
8478       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8479       // bits, just truncate to i32.
8480       if (NumSignBits > OpBits-MidBits)
8481         return new TruncInst(Op, CI.getType(), "tmp");
8482     }
8483   }
8484
8485   // If the input is a shl/ashr pair of a same constant, then this is a sign
8486   // extension from a smaller value.  If we could trust arbitrary bitwidth
8487   // integers, we could turn this into a truncate to the smaller bit and then
8488   // use a sext for the whole extension.  Since we don't, look deeper and check
8489   // for a truncate.  If the source and dest are the same type, eliminate the
8490   // trunc and extend and just do shifts.  For example, turn:
8491   //   %a = trunc i32 %i to i8
8492   //   %b = shl i8 %a, 6
8493   //   %c = ashr i8 %b, 6
8494   //   %d = sext i8 %c to i32
8495   // into:
8496   //   %a = shl i32 %i, 30
8497   //   %d = ashr i32 %a, 30
8498   Value *A = 0;
8499   ConstantInt *BA = 0, *CA = 0;
8500   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8501                         m_ConstantInt(CA))) &&
8502       BA == CA && isa<TruncInst>(A)) {
8503     Value *I = cast<TruncInst>(A)->getOperand(0);
8504     if (I->getType() == CI.getType()) {
8505       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8506       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8507       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8508       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8509       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8510                                                         CI.getName()), CI);
8511       return BinaryOperator::CreateAShr(I, ShAmtV);
8512     }
8513   }
8514   
8515   return 0;
8516 }
8517
8518 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8519 /// in the specified FP type without changing its value.
8520 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8521   bool losesInfo;
8522   APFloat F = CFP->getValueAPF();
8523   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8524   if (!losesInfo)
8525     return ConstantFP::get(F);
8526   return 0;
8527 }
8528
8529 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8530 /// through it until we get the source value.
8531 static Value *LookThroughFPExtensions(Value *V) {
8532   if (Instruction *I = dyn_cast<Instruction>(V))
8533     if (I->getOpcode() == Instruction::FPExt)
8534       return LookThroughFPExtensions(I->getOperand(0));
8535   
8536   // If this value is a constant, return the constant in the smallest FP type
8537   // that can accurately represent it.  This allows us to turn
8538   // (float)((double)X+2.0) into x+2.0f.
8539   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8540     if (CFP->getType() == Type::PPC_FP128Ty)
8541       return V;  // No constant folding of this.
8542     // See if the value can be truncated to float and then reextended.
8543     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8544       return V;
8545     if (CFP->getType() == Type::DoubleTy)
8546       return V;  // Won't shrink.
8547     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8548       return V;
8549     // Don't try to shrink to various long double types.
8550   }
8551   
8552   return V;
8553 }
8554
8555 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8556   if (Instruction *I = commonCastTransforms(CI))
8557     return I;
8558   
8559   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8560   // smaller than the destination type, we can eliminate the truncate by doing
8561   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8562   // many builtins (sqrt, etc).
8563   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8564   if (OpI && OpI->hasOneUse()) {
8565     switch (OpI->getOpcode()) {
8566     default: break;
8567     case Instruction::Add:
8568     case Instruction::Sub:
8569     case Instruction::Mul:
8570     case Instruction::FDiv:
8571     case Instruction::FRem:
8572       const Type *SrcTy = OpI->getType();
8573       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8574       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8575       if (LHSTrunc->getType() != SrcTy && 
8576           RHSTrunc->getType() != SrcTy) {
8577         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8578         // If the source types were both smaller than the destination type of
8579         // the cast, do this xform.
8580         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8581             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8582           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8583                                       CI.getType(), CI);
8584           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8585                                       CI.getType(), CI);
8586           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8587         }
8588       }
8589       break;  
8590     }
8591   }
8592   return 0;
8593 }
8594
8595 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8596   return commonCastTransforms(CI);
8597 }
8598
8599 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8600   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8601   if (OpI == 0)
8602     return commonCastTransforms(FI);
8603
8604   // fptoui(uitofp(X)) --> X
8605   // fptoui(sitofp(X)) --> X
8606   // This is safe if the intermediate type has enough bits in its mantissa to
8607   // accurately represent all values of X.  For example, do not do this with
8608   // i64->float->i64.  This is also safe for sitofp case, because any negative
8609   // 'X' value would cause an undefined result for the fptoui. 
8610   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8611       OpI->getOperand(0)->getType() == FI.getType() &&
8612       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8613                     OpI->getType()->getFPMantissaWidth())
8614     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8615
8616   return commonCastTransforms(FI);
8617 }
8618
8619 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8620   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8621   if (OpI == 0)
8622     return commonCastTransforms(FI);
8623   
8624   // fptosi(sitofp(X)) --> X
8625   // fptosi(uitofp(X)) --> X
8626   // This is safe if the intermediate type has enough bits in its mantissa to
8627   // accurately represent all values of X.  For example, do not do this with
8628   // i64->float->i64.  This is also safe for sitofp case, because any negative
8629   // 'X' value would cause an undefined result for the fptoui. 
8630   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8631       OpI->getOperand(0)->getType() == FI.getType() &&
8632       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8633                     OpI->getType()->getFPMantissaWidth())
8634     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8635   
8636   return commonCastTransforms(FI);
8637 }
8638
8639 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8640   return commonCastTransforms(CI);
8641 }
8642
8643 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8644   return commonCastTransforms(CI);
8645 }
8646
8647 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8648   // If the destination integer type is smaller than the intptr_t type for
8649   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8650   // trunc to be exposed to other transforms.  Don't do this for extending
8651   // ptrtoint's, because we don't know if the target sign or zero extends its
8652   // pointers.
8653   if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8654     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8655                                                     TD->getIntPtrType(),
8656                                                     "tmp"), CI);
8657     return new TruncInst(P, CI.getType());
8658   }
8659   
8660   return commonPointerCastTransforms(CI);
8661 }
8662
8663 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8664   // If the source integer type is larger than the intptr_t type for
8665   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8666   // allows the trunc to be exposed to other transforms.  Don't do this for
8667   // extending inttoptr's, because we don't know if the target sign or zero
8668   // extends to pointers.
8669   if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8670       TD->getPointerSizeInBits()) {
8671     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8672                                                  TD->getIntPtrType(),
8673                                                  "tmp"), CI);
8674     return new IntToPtrInst(P, CI.getType());
8675   }
8676   
8677   if (Instruction *I = commonCastTransforms(CI))
8678     return I;
8679   
8680   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8681   if (!DestPointee->isSized()) return 0;
8682
8683   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8684   ConstantInt *Cst;
8685   Value *X;
8686   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8687                                     m_ConstantInt(Cst)))) {
8688     // If the source and destination operands have the same type, see if this
8689     // is a single-index GEP.
8690     if (X->getType() == CI.getType()) {
8691       // Get the size of the pointee type.
8692       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8693
8694       // Convert the constant to intptr type.
8695       APInt Offset = Cst->getValue();
8696       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8697
8698       // If Offset is evenly divisible by Size, we can do this xform.
8699       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8700         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8701         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8702       }
8703     }
8704     // TODO: Could handle other cases, e.g. where add is indexing into field of
8705     // struct etc.
8706   } else if (CI.getOperand(0)->hasOneUse() &&
8707              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8708     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8709     // "inttoptr+GEP" instead of "add+intptr".
8710     
8711     // Get the size of the pointee type.
8712     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8713     
8714     // Convert the constant to intptr type.
8715     APInt Offset = Cst->getValue();
8716     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8717     
8718     // If Offset is evenly divisible by Size, we can do this xform.
8719     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8720       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8721       
8722       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8723                                                             "tmp"), CI);
8724       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8725     }
8726   }
8727   return 0;
8728 }
8729
8730 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8731   // If the operands are integer typed then apply the integer transforms,
8732   // otherwise just apply the common ones.
8733   Value *Src = CI.getOperand(0);
8734   const Type *SrcTy = Src->getType();
8735   const Type *DestTy = CI.getType();
8736
8737   if (SrcTy->isInteger() && DestTy->isInteger()) {
8738     if (Instruction *Result = commonIntCastTransforms(CI))
8739       return Result;
8740   } else if (isa<PointerType>(SrcTy)) {
8741     if (Instruction *I = commonPointerCastTransforms(CI))
8742       return I;
8743   } else {
8744     if (Instruction *Result = commonCastTransforms(CI))
8745       return Result;
8746   }
8747
8748
8749   // Get rid of casts from one type to the same type. These are useless and can
8750   // be replaced by the operand.
8751   if (DestTy == Src->getType())
8752     return ReplaceInstUsesWith(CI, Src);
8753
8754   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8755     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8756     const Type *DstElTy = DstPTy->getElementType();
8757     const Type *SrcElTy = SrcPTy->getElementType();
8758     
8759     // If the address spaces don't match, don't eliminate the bitcast, which is
8760     // required for changing types.
8761     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8762       return 0;
8763     
8764     // If we are casting a malloc or alloca to a pointer to a type of the same
8765     // size, rewrite the allocation instruction to allocate the "right" type.
8766     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8767       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8768         return V;
8769     
8770     // If the source and destination are pointers, and this cast is equivalent
8771     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8772     // This can enhance SROA and other transforms that want type-safe pointers.
8773     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8774     unsigned NumZeros = 0;
8775     while (SrcElTy != DstElTy && 
8776            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8777            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8778       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8779       ++NumZeros;
8780     }
8781
8782     // If we found a path from the src to dest, create the getelementptr now.
8783     if (SrcElTy == DstElTy) {
8784       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8785       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8786                                        ((Instruction*) NULL));
8787     }
8788   }
8789
8790   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8791     if (SVI->hasOneUse()) {
8792       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8793       // a bitconvert to a vector with the same # elts.
8794       if (isa<VectorType>(DestTy) && 
8795           cast<VectorType>(DestTy)->getNumElements() ==
8796                 SVI->getType()->getNumElements() &&
8797           SVI->getType()->getNumElements() ==
8798             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8799         CastInst *Tmp;
8800         // If either of the operands is a cast from CI.getType(), then
8801         // evaluating the shuffle in the casted destination's type will allow
8802         // us to eliminate at least one cast.
8803         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8804              Tmp->getOperand(0)->getType() == DestTy) ||
8805             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8806              Tmp->getOperand(0)->getType() == DestTy)) {
8807           Value *LHS = InsertCastBefore(Instruction::BitCast,
8808                                         SVI->getOperand(0), DestTy, CI);
8809           Value *RHS = InsertCastBefore(Instruction::BitCast,
8810                                         SVI->getOperand(1), DestTy, CI);
8811           // Return a new shuffle vector.  Use the same element ID's, as we
8812           // know the vector types match #elts.
8813           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8814         }
8815       }
8816     }
8817   }
8818   return 0;
8819 }
8820
8821 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8822 ///   %C = or %A, %B
8823 ///   %D = select %cond, %C, %A
8824 /// into:
8825 ///   %C = select %cond, %B, 0
8826 ///   %D = or %A, %C
8827 ///
8828 /// Assuming that the specified instruction is an operand to the select, return
8829 /// a bitmask indicating which operands of this instruction are foldable if they
8830 /// equal the other incoming value of the select.
8831 ///
8832 static unsigned GetSelectFoldableOperands(Instruction *I) {
8833   switch (I->getOpcode()) {
8834   case Instruction::Add:
8835   case Instruction::Mul:
8836   case Instruction::And:
8837   case Instruction::Or:
8838   case Instruction::Xor:
8839     return 3;              // Can fold through either operand.
8840   case Instruction::Sub:   // Can only fold on the amount subtracted.
8841   case Instruction::Shl:   // Can only fold on the shift amount.
8842   case Instruction::LShr:
8843   case Instruction::AShr:
8844     return 1;
8845   default:
8846     return 0;              // Cannot fold
8847   }
8848 }
8849
8850 /// GetSelectFoldableConstant - For the same transformation as the previous
8851 /// function, return the identity constant that goes into the select.
8852 static Constant *GetSelectFoldableConstant(Instruction *I) {
8853   switch (I->getOpcode()) {
8854   default: assert(0 && "This cannot happen!"); abort();
8855   case Instruction::Add:
8856   case Instruction::Sub:
8857   case Instruction::Or:
8858   case Instruction::Xor:
8859   case Instruction::Shl:
8860   case Instruction::LShr:
8861   case Instruction::AShr:
8862     return Constant::getNullValue(I->getType());
8863   case Instruction::And:
8864     return Constant::getAllOnesValue(I->getType());
8865   case Instruction::Mul:
8866     return ConstantInt::get(I->getType(), 1);
8867   }
8868 }
8869
8870 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8871 /// have the same opcode and only one use each.  Try to simplify this.
8872 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8873                                           Instruction *FI) {
8874   if (TI->getNumOperands() == 1) {
8875     // If this is a non-volatile load or a cast from the same type,
8876     // merge.
8877     if (TI->isCast()) {
8878       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8879         return 0;
8880     } else {
8881       return 0;  // unknown unary op.
8882     }
8883
8884     // Fold this by inserting a select from the input values.
8885     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8886                                            FI->getOperand(0), SI.getName()+".v");
8887     InsertNewInstBefore(NewSI, SI);
8888     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8889                             TI->getType());
8890   }
8891
8892   // Only handle binary operators here.
8893   if (!isa<BinaryOperator>(TI))
8894     return 0;
8895
8896   // Figure out if the operations have any operands in common.
8897   Value *MatchOp, *OtherOpT, *OtherOpF;
8898   bool MatchIsOpZero;
8899   if (TI->getOperand(0) == FI->getOperand(0)) {
8900     MatchOp  = TI->getOperand(0);
8901     OtherOpT = TI->getOperand(1);
8902     OtherOpF = FI->getOperand(1);
8903     MatchIsOpZero = true;
8904   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8905     MatchOp  = TI->getOperand(1);
8906     OtherOpT = TI->getOperand(0);
8907     OtherOpF = FI->getOperand(0);
8908     MatchIsOpZero = false;
8909   } else if (!TI->isCommutative()) {
8910     return 0;
8911   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8912     MatchOp  = TI->getOperand(0);
8913     OtherOpT = TI->getOperand(1);
8914     OtherOpF = FI->getOperand(0);
8915     MatchIsOpZero = true;
8916   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8917     MatchOp  = TI->getOperand(1);
8918     OtherOpT = TI->getOperand(0);
8919     OtherOpF = FI->getOperand(1);
8920     MatchIsOpZero = true;
8921   } else {
8922     return 0;
8923   }
8924
8925   // If we reach here, they do have operations in common.
8926   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8927                                          OtherOpF, SI.getName()+".v");
8928   InsertNewInstBefore(NewSI, SI);
8929
8930   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8931     if (MatchIsOpZero)
8932       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8933     else
8934       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8935   }
8936   assert(0 && "Shouldn't get here");
8937   return 0;
8938 }
8939
8940 static bool isSelect01(Constant *C1, Constant *C2) {
8941   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8942   if (!C1I)
8943     return false;
8944   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8945   if (!C2I)
8946     return false;
8947   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8948 }
8949
8950 /// FoldSelectIntoOp - Try fold the select into one of the operands to
8951 /// facilitate further optimization.
8952 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8953                                             Value *FalseVal) {
8954   // See the comment above GetSelectFoldableOperands for a description of the
8955   // transformation we are doing here.
8956   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8957     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8958         !isa<Constant>(FalseVal)) {
8959       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8960         unsigned OpToFold = 0;
8961         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8962           OpToFold = 1;
8963         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8964           OpToFold = 2;
8965         }
8966
8967         if (OpToFold) {
8968           Constant *C = GetSelectFoldableConstant(TVI);
8969           Value *OOp = TVI->getOperand(2-OpToFold);
8970           // Avoid creating select between 2 constants unless it's selecting
8971           // between 0 and 1.
8972           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8973             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
8974             InsertNewInstBefore(NewSel, SI);
8975             NewSel->takeName(TVI);
8976             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8977               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8978             assert(0 && "Unknown instruction!!");
8979           }
8980         }
8981       }
8982     }
8983   }
8984
8985   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
8986     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8987         !isa<Constant>(TrueVal)) {
8988       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8989         unsigned OpToFold = 0;
8990         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8991           OpToFold = 1;
8992         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8993           OpToFold = 2;
8994         }
8995
8996         if (OpToFold) {
8997           Constant *C = GetSelectFoldableConstant(FVI);
8998           Value *OOp = FVI->getOperand(2-OpToFold);
8999           // Avoid creating select between 2 constants unless it's selecting
9000           // between 0 and 1.
9001           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9002             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9003             InsertNewInstBefore(NewSel, SI);
9004             NewSel->takeName(FVI);
9005             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9006               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9007             assert(0 && "Unknown instruction!!");
9008           }
9009         }
9010       }
9011     }
9012   }
9013
9014   return 0;
9015 }
9016
9017 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9018 /// ICmpInst as its first operand.
9019 ///
9020 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9021                                                    ICmpInst *ICI) {
9022   bool Changed = false;
9023   ICmpInst::Predicate Pred = ICI->getPredicate();
9024   Value *CmpLHS = ICI->getOperand(0);
9025   Value *CmpRHS = ICI->getOperand(1);
9026   Value *TrueVal = SI.getTrueValue();
9027   Value *FalseVal = SI.getFalseValue();
9028
9029   // Check cases where the comparison is with a constant that
9030   // can be adjusted to fit the min/max idiom. We may edit ICI in
9031   // place here, so make sure the select is the only user.
9032   if (ICI->hasOneUse())
9033     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9034       switch (Pred) {
9035       default: break;
9036       case ICmpInst::ICMP_ULT:
9037       case ICmpInst::ICMP_SLT: {
9038         // X < MIN ? T : F  -->  F
9039         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9040           return ReplaceInstUsesWith(SI, FalseVal);
9041         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9042         Constant *AdjustedRHS = SubOne(CI);
9043         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9044             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9045           Pred = ICmpInst::getSwappedPredicate(Pred);
9046           CmpRHS = AdjustedRHS;
9047           std::swap(FalseVal, TrueVal);
9048           ICI->setPredicate(Pred);
9049           ICI->setOperand(1, CmpRHS);
9050           SI.setOperand(1, TrueVal);
9051           SI.setOperand(2, FalseVal);
9052           Changed = true;
9053         }
9054         break;
9055       }
9056       case ICmpInst::ICMP_UGT:
9057       case ICmpInst::ICMP_SGT: {
9058         // X > MAX ? T : F  -->  F
9059         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9060           return ReplaceInstUsesWith(SI, FalseVal);
9061         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9062         Constant *AdjustedRHS = AddOne(CI);
9063         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9064             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9065           Pred = ICmpInst::getSwappedPredicate(Pred);
9066           CmpRHS = AdjustedRHS;
9067           std::swap(FalseVal, TrueVal);
9068           ICI->setPredicate(Pred);
9069           ICI->setOperand(1, CmpRHS);
9070           SI.setOperand(1, TrueVal);
9071           SI.setOperand(2, FalseVal);
9072           Changed = true;
9073         }
9074         break;
9075       }
9076       }
9077
9078       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9079       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9080       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9081       if (match(TrueVal, m_ConstantInt<-1>()) &&
9082           match(FalseVal, m_ConstantInt<0>()))
9083         Pred = ICI->getPredicate();
9084       else if (match(TrueVal, m_ConstantInt<0>()) &&
9085                match(FalseVal, m_ConstantInt<-1>()))
9086         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9087       
9088       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9089         // If we are just checking for a icmp eq of a single bit and zext'ing it
9090         // to an integer, then shift the bit to the appropriate place and then
9091         // cast to integer to avoid the comparison.
9092         const APInt &Op1CV = CI->getValue();
9093     
9094         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9095         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9096         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9097             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9098           Value *In = ICI->getOperand(0);
9099           Value *Sh = ConstantInt::get(In->getType(),
9100                                        In->getType()->getPrimitiveSizeInBits()-1);
9101           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9102                                                           In->getName()+".lobit"),
9103                                    *ICI);
9104           if (In->getType() != SI.getType())
9105             In = CastInst::CreateIntegerCast(In, SI.getType(),
9106                                              true/*SExt*/, "tmp", ICI);
9107     
9108           if (Pred == ICmpInst::ICMP_SGT)
9109             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9110                                        In->getName()+".not"), *ICI);
9111     
9112           return ReplaceInstUsesWith(SI, In);
9113         }
9114       }
9115     }
9116
9117   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9118     // Transform (X == Y) ? X : Y  -> Y
9119     if (Pred == ICmpInst::ICMP_EQ)
9120       return ReplaceInstUsesWith(SI, FalseVal);
9121     // Transform (X != Y) ? X : Y  -> X
9122     if (Pred == ICmpInst::ICMP_NE)
9123       return ReplaceInstUsesWith(SI, TrueVal);
9124     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9125
9126   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9127     // Transform (X == Y) ? Y : X  -> X
9128     if (Pred == ICmpInst::ICMP_EQ)
9129       return ReplaceInstUsesWith(SI, FalseVal);
9130     // Transform (X != Y) ? Y : X  -> Y
9131     if (Pred == ICmpInst::ICMP_NE)
9132       return ReplaceInstUsesWith(SI, TrueVal);
9133     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9134   }
9135
9136   /// NOTE: if we wanted to, this is where to detect integer ABS
9137
9138   return Changed ? &SI : 0;
9139 }
9140
9141 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9142   Value *CondVal = SI.getCondition();
9143   Value *TrueVal = SI.getTrueValue();
9144   Value *FalseVal = SI.getFalseValue();
9145
9146   // select true, X, Y  -> X
9147   // select false, X, Y -> Y
9148   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9149     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9150
9151   // select C, X, X -> X
9152   if (TrueVal == FalseVal)
9153     return ReplaceInstUsesWith(SI, TrueVal);
9154
9155   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9156     return ReplaceInstUsesWith(SI, FalseVal);
9157   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9158     return ReplaceInstUsesWith(SI, TrueVal);
9159   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9160     if (isa<Constant>(TrueVal))
9161       return ReplaceInstUsesWith(SI, TrueVal);
9162     else
9163       return ReplaceInstUsesWith(SI, FalseVal);
9164   }
9165
9166   if (SI.getType() == Type::Int1Ty) {
9167     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9168       if (C->getZExtValue()) {
9169         // Change: A = select B, true, C --> A = or B, C
9170         return BinaryOperator::CreateOr(CondVal, FalseVal);
9171       } else {
9172         // Change: A = select B, false, C --> A = and !B, C
9173         Value *NotCond =
9174           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9175                                              "not."+CondVal->getName()), SI);
9176         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9177       }
9178     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9179       if (C->getZExtValue() == false) {
9180         // Change: A = select B, C, false --> A = and B, C
9181         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9182       } else {
9183         // Change: A = select B, C, true --> A = or !B, C
9184         Value *NotCond =
9185           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9186                                              "not."+CondVal->getName()), SI);
9187         return BinaryOperator::CreateOr(NotCond, TrueVal);
9188       }
9189     }
9190     
9191     // select a, b, a  -> a&b
9192     // select a, a, b  -> a|b
9193     if (CondVal == TrueVal)
9194       return BinaryOperator::CreateOr(CondVal, FalseVal);
9195     else if (CondVal == FalseVal)
9196       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9197   }
9198
9199   // Selecting between two integer constants?
9200   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9201     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9202       // select C, 1, 0 -> zext C to int
9203       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9204         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9205       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9206         // select C, 0, 1 -> zext !C to int
9207         Value *NotCond =
9208           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9209                                                "not."+CondVal->getName()), SI);
9210         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9211       }
9212
9213       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9214
9215         // (x <s 0) ? -1 : 0 -> ashr x, 31
9216         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9217           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9218             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9219               // The comparison constant and the result are not neccessarily the
9220               // same width. Make an all-ones value by inserting a AShr.
9221               Value *X = IC->getOperand(0);
9222               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9223               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9224               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9225                                                         ShAmt, "ones");
9226               InsertNewInstBefore(SRA, SI);
9227
9228               // Then cast to the appropriate width.
9229               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9230             }
9231           }
9232
9233
9234         // If one of the constants is zero (we know they can't both be) and we
9235         // have an icmp instruction with zero, and we have an 'and' with the
9236         // non-constant value, eliminate this whole mess.  This corresponds to
9237         // cases like this: ((X & 27) ? 27 : 0)
9238         if (TrueValC->isZero() || FalseValC->isZero())
9239           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9240               cast<Constant>(IC->getOperand(1))->isNullValue())
9241             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9242               if (ICA->getOpcode() == Instruction::And &&
9243                   isa<ConstantInt>(ICA->getOperand(1)) &&
9244                   (ICA->getOperand(1) == TrueValC ||
9245                    ICA->getOperand(1) == FalseValC) &&
9246                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9247                 // Okay, now we know that everything is set up, we just don't
9248                 // know whether we have a icmp_ne or icmp_eq and whether the 
9249                 // true or false val is the zero.
9250                 bool ShouldNotVal = !TrueValC->isZero();
9251                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9252                 Value *V = ICA;
9253                 if (ShouldNotVal)
9254                   V = InsertNewInstBefore(BinaryOperator::Create(
9255                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9256                 return ReplaceInstUsesWith(SI, V);
9257               }
9258       }
9259     }
9260
9261   // See if we are selecting two values based on a comparison of the two values.
9262   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9263     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9264       // Transform (X == Y) ? X : Y  -> Y
9265       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9266         // This is not safe in general for floating point:  
9267         // consider X== -0, Y== +0.
9268         // It becomes safe if either operand is a nonzero constant.
9269         ConstantFP *CFPt, *CFPf;
9270         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9271               !CFPt->getValueAPF().isZero()) ||
9272             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9273              !CFPf->getValueAPF().isZero()))
9274         return ReplaceInstUsesWith(SI, FalseVal);
9275       }
9276       // Transform (X != Y) ? X : Y  -> X
9277       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9278         return ReplaceInstUsesWith(SI, TrueVal);
9279       // NOTE: if we wanted to, this is where to detect MIN/MAX
9280
9281     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9282       // Transform (X == Y) ? Y : X  -> X
9283       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9284         // This is not safe in general for floating point:  
9285         // consider X== -0, Y== +0.
9286         // It becomes safe if either operand is a nonzero constant.
9287         ConstantFP *CFPt, *CFPf;
9288         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9289               !CFPt->getValueAPF().isZero()) ||
9290             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9291              !CFPf->getValueAPF().isZero()))
9292           return ReplaceInstUsesWith(SI, FalseVal);
9293       }
9294       // Transform (X != Y) ? Y : X  -> Y
9295       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9296         return ReplaceInstUsesWith(SI, TrueVal);
9297       // NOTE: if we wanted to, this is where to detect MIN/MAX
9298     }
9299     // NOTE: if we wanted to, this is where to detect ABS
9300   }
9301
9302   // See if we are selecting two values based on a comparison of the two values.
9303   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9304     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9305       return Result;
9306
9307   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9308     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9309       if (TI->hasOneUse() && FI->hasOneUse()) {
9310         Instruction *AddOp = 0, *SubOp = 0;
9311
9312         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9313         if (TI->getOpcode() == FI->getOpcode())
9314           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9315             return IV;
9316
9317         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9318         // even legal for FP.
9319         if (TI->getOpcode() == Instruction::Sub &&
9320             FI->getOpcode() == Instruction::Add) {
9321           AddOp = FI; SubOp = TI;
9322         } else if (FI->getOpcode() == Instruction::Sub &&
9323                    TI->getOpcode() == Instruction::Add) {
9324           AddOp = TI; SubOp = FI;
9325         }
9326
9327         if (AddOp) {
9328           Value *OtherAddOp = 0;
9329           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9330             OtherAddOp = AddOp->getOperand(1);
9331           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9332             OtherAddOp = AddOp->getOperand(0);
9333           }
9334
9335           if (OtherAddOp) {
9336             // So at this point we know we have (Y -> OtherAddOp):
9337             //        select C, (add X, Y), (sub X, Z)
9338             Value *NegVal;  // Compute -Z
9339             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9340               NegVal = ConstantExpr::getNeg(C);
9341             } else {
9342               NegVal = InsertNewInstBefore(
9343                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9344             }
9345
9346             Value *NewTrueOp = OtherAddOp;
9347             Value *NewFalseOp = NegVal;
9348             if (AddOp != TI)
9349               std::swap(NewTrueOp, NewFalseOp);
9350             Instruction *NewSel =
9351               SelectInst::Create(CondVal, NewTrueOp,
9352                                  NewFalseOp, SI.getName() + ".p");
9353
9354             NewSel = InsertNewInstBefore(NewSel, SI);
9355             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9356           }
9357         }
9358       }
9359
9360   // See if we can fold the select into one of our operands.
9361   if (SI.getType()->isInteger()) {
9362     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9363     if (FoldI)
9364       return FoldI;
9365   }
9366
9367   if (BinaryOperator::isNot(CondVal)) {
9368     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9369     SI.setOperand(1, FalseVal);
9370     SI.setOperand(2, TrueVal);
9371     return &SI;
9372   }
9373
9374   return 0;
9375 }
9376
9377 /// EnforceKnownAlignment - If the specified pointer points to an object that
9378 /// we control, modify the object's alignment to PrefAlign. This isn't
9379 /// often possible though. If alignment is important, a more reliable approach
9380 /// is to simply align all global variables and allocation instructions to
9381 /// their preferred alignment from the beginning.
9382 ///
9383 static unsigned EnforceKnownAlignment(Value *V,
9384                                       unsigned Align, unsigned PrefAlign) {
9385
9386   User *U = dyn_cast<User>(V);
9387   if (!U) return Align;
9388
9389   switch (getOpcode(U)) {
9390   default: break;
9391   case Instruction::BitCast:
9392     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9393   case Instruction::GetElementPtr: {
9394     // If all indexes are zero, it is just the alignment of the base pointer.
9395     bool AllZeroOperands = true;
9396     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9397       if (!isa<Constant>(*i) ||
9398           !cast<Constant>(*i)->isNullValue()) {
9399         AllZeroOperands = false;
9400         break;
9401       }
9402
9403     if (AllZeroOperands) {
9404       // Treat this like a bitcast.
9405       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9406     }
9407     break;
9408   }
9409   }
9410
9411   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9412     // If there is a large requested alignment and we can, bump up the alignment
9413     // of the global.
9414     if (!GV->isDeclaration()) {
9415       if (GV->getAlignment() >= PrefAlign)
9416         Align = GV->getAlignment();
9417       else {
9418         GV->setAlignment(PrefAlign);
9419         Align = PrefAlign;
9420       }
9421     }
9422   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9423     // If there is a requested alignment and if this is an alloca, round up.  We
9424     // don't do this for malloc, because some systems can't respect the request.
9425     if (isa<AllocaInst>(AI)) {
9426       if (AI->getAlignment() >= PrefAlign)
9427         Align = AI->getAlignment();
9428       else {
9429         AI->setAlignment(PrefAlign);
9430         Align = PrefAlign;
9431       }
9432     }
9433   }
9434
9435   return Align;
9436 }
9437
9438 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9439 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9440 /// and it is more than the alignment of the ultimate object, see if we can
9441 /// increase the alignment of the ultimate object, making this check succeed.
9442 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9443                                                   unsigned PrefAlign) {
9444   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9445                       sizeof(PrefAlign) * CHAR_BIT;
9446   APInt Mask = APInt::getAllOnesValue(BitWidth);
9447   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9448   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9449   unsigned TrailZ = KnownZero.countTrailingOnes();
9450   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9451
9452   if (PrefAlign > Align)
9453     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9454   
9455     // We don't need to make any adjustment.
9456   return Align;
9457 }
9458
9459 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9460   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9461   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9462   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9463   unsigned CopyAlign = MI->getAlignment();
9464
9465   if (CopyAlign < MinAlign) {
9466     MI->setAlignment(MinAlign);
9467     return MI;
9468   }
9469   
9470   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9471   // load/store.
9472   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9473   if (MemOpLength == 0) return 0;
9474   
9475   // Source and destination pointer types are always "i8*" for intrinsic.  See
9476   // if the size is something we can handle with a single primitive load/store.
9477   // A single load+store correctly handles overlapping memory in the memmove
9478   // case.
9479   unsigned Size = MemOpLength->getZExtValue();
9480   if (Size == 0) return MI;  // Delete this mem transfer.
9481   
9482   if (Size > 8 || (Size&(Size-1)))
9483     return 0;  // If not 1/2/4/8 bytes, exit.
9484   
9485   // Use an integer load+store unless we can find something better.
9486   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9487   
9488   // Memcpy forces the use of i8* for the source and destination.  That means
9489   // that if you're using memcpy to move one double around, you'll get a cast
9490   // from double* to i8*.  We'd much rather use a double load+store rather than
9491   // an i64 load+store, here because this improves the odds that the source or
9492   // dest address will be promotable.  See if we can find a better type than the
9493   // integer datatype.
9494   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9495     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9496     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9497       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9498       // down through these levels if so.
9499       while (!SrcETy->isSingleValueType()) {
9500         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9501           if (STy->getNumElements() == 1)
9502             SrcETy = STy->getElementType(0);
9503           else
9504             break;
9505         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9506           if (ATy->getNumElements() == 1)
9507             SrcETy = ATy->getElementType();
9508           else
9509             break;
9510         } else
9511           break;
9512       }
9513       
9514       if (SrcETy->isSingleValueType())
9515         NewPtrTy = PointerType::getUnqual(SrcETy);
9516     }
9517   }
9518   
9519   
9520   // If the memcpy/memmove provides better alignment info than we can
9521   // infer, use it.
9522   SrcAlign = std::max(SrcAlign, CopyAlign);
9523   DstAlign = std::max(DstAlign, CopyAlign);
9524   
9525   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9526   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9527   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9528   InsertNewInstBefore(L, *MI);
9529   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9530
9531   // Set the size of the copy to 0, it will be deleted on the next iteration.
9532   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9533   return MI;
9534 }
9535
9536 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9537   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9538   if (MI->getAlignment() < Alignment) {
9539     MI->setAlignment(Alignment);
9540     return MI;
9541   }
9542   
9543   // Extract the length and alignment and fill if they are constant.
9544   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9545   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9546   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9547     return 0;
9548   uint64_t Len = LenC->getZExtValue();
9549   Alignment = MI->getAlignment();
9550   
9551   // If the length is zero, this is a no-op
9552   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9553   
9554   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9555   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9556     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9557     
9558     Value *Dest = MI->getDest();
9559     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9560
9561     // Alignment 0 is identity for alignment 1 for memset, but not store.
9562     if (Alignment == 0) Alignment = 1;
9563     
9564     // Extract the fill value and store.
9565     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9566     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9567                                       Alignment), *MI);
9568     
9569     // Set the size of the copy to 0, it will be deleted on the next iteration.
9570     MI->setLength(Constant::getNullValue(LenC->getType()));
9571     return MI;
9572   }
9573
9574   return 0;
9575 }
9576
9577
9578 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9579 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9580 /// the heavy lifting.
9581 ///
9582 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9583   // If the caller function is nounwind, mark the call as nounwind, even if the
9584   // callee isn't.
9585   if (CI.getParent()->getParent()->doesNotThrow() &&
9586       !CI.doesNotThrow()) {
9587     CI.setDoesNotThrow();
9588     return &CI;
9589   }
9590   
9591   
9592   
9593   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9594   if (!II) return visitCallSite(&CI);
9595   
9596   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9597   // visitCallSite.
9598   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9599     bool Changed = false;
9600
9601     // memmove/cpy/set of zero bytes is a noop.
9602     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9603       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9604
9605       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9606         if (CI->getZExtValue() == 1) {
9607           // Replace the instruction with just byte operations.  We would
9608           // transform other cases to loads/stores, but we don't know if
9609           // alignment is sufficient.
9610         }
9611     }
9612
9613     // If we have a memmove and the source operation is a constant global,
9614     // then the source and dest pointers can't alias, so we can change this
9615     // into a call to memcpy.
9616     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9617       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9618         if (GVSrc->isConstant()) {
9619           Module *M = CI.getParent()->getParent()->getParent();
9620           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9621           const Type *Tys[1];
9622           Tys[0] = CI.getOperand(3)->getType();
9623           CI.setOperand(0, 
9624                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9625           Changed = true;
9626         }
9627
9628       // memmove(x,x,size) -> noop.
9629       if (MMI->getSource() == MMI->getDest())
9630         return EraseInstFromFunction(CI);
9631     }
9632
9633     // If we can determine a pointer alignment that is bigger than currently
9634     // set, update the alignment.
9635     if (isa<MemTransferInst>(MI)) {
9636       if (Instruction *I = SimplifyMemTransfer(MI))
9637         return I;
9638     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9639       if (Instruction *I = SimplifyMemSet(MSI))
9640         return I;
9641     }
9642           
9643     if (Changed) return II;
9644   }
9645   
9646   switch (II->getIntrinsicID()) {
9647   default: break;
9648   case Intrinsic::bswap:
9649     // bswap(bswap(x)) -> x
9650     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9651       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9652         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9653     break;
9654   case Intrinsic::ppc_altivec_lvx:
9655   case Intrinsic::ppc_altivec_lvxl:
9656   case Intrinsic::x86_sse_loadu_ps:
9657   case Intrinsic::x86_sse2_loadu_pd:
9658   case Intrinsic::x86_sse2_loadu_dq:
9659     // Turn PPC lvx     -> load if the pointer is known aligned.
9660     // Turn X86 loadups -> load if the pointer is known aligned.
9661     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9662       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9663                                        PointerType::getUnqual(II->getType()),
9664                                        CI);
9665       return new LoadInst(Ptr);
9666     }
9667     break;
9668   case Intrinsic::ppc_altivec_stvx:
9669   case Intrinsic::ppc_altivec_stvxl:
9670     // Turn stvx -> store if the pointer is known aligned.
9671     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9672       const Type *OpPtrTy = 
9673         PointerType::getUnqual(II->getOperand(1)->getType());
9674       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9675       return new StoreInst(II->getOperand(1), Ptr);
9676     }
9677     break;
9678   case Intrinsic::x86_sse_storeu_ps:
9679   case Intrinsic::x86_sse2_storeu_pd:
9680   case Intrinsic::x86_sse2_storeu_dq:
9681     // Turn X86 storeu -> store if the pointer is known aligned.
9682     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9683       const Type *OpPtrTy = 
9684         PointerType::getUnqual(II->getOperand(2)->getType());
9685       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9686       return new StoreInst(II->getOperand(2), Ptr);
9687     }
9688     break;
9689     
9690   case Intrinsic::x86_sse_cvttss2si: {
9691     // These intrinsics only demands the 0th element of its input vector.  If
9692     // we can simplify the input based on that, do so now.
9693     unsigned VWidth =
9694       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9695     APInt DemandedElts(VWidth, 1);
9696     APInt UndefElts(VWidth, 0);
9697     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9698                                               UndefElts)) {
9699       II->setOperand(1, V);
9700       return II;
9701     }
9702     break;
9703   }
9704     
9705   case Intrinsic::ppc_altivec_vperm:
9706     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9707     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9708       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9709       
9710       // Check that all of the elements are integer constants or undefs.
9711       bool AllEltsOk = true;
9712       for (unsigned i = 0; i != 16; ++i) {
9713         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9714             !isa<UndefValue>(Mask->getOperand(i))) {
9715           AllEltsOk = false;
9716           break;
9717         }
9718       }
9719       
9720       if (AllEltsOk) {
9721         // Cast the input vectors to byte vectors.
9722         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9723         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9724         Value *Result = UndefValue::get(Op0->getType());
9725         
9726         // Only extract each element once.
9727         Value *ExtractedElts[32];
9728         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9729         
9730         for (unsigned i = 0; i != 16; ++i) {
9731           if (isa<UndefValue>(Mask->getOperand(i)))
9732             continue;
9733           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9734           Idx &= 31;  // Match the hardware behavior.
9735           
9736           if (ExtractedElts[Idx] == 0) {
9737             Instruction *Elt = 
9738               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9739             InsertNewInstBefore(Elt, CI);
9740             ExtractedElts[Idx] = Elt;
9741           }
9742         
9743           // Insert this value into the result vector.
9744           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9745                                              i, "tmp");
9746           InsertNewInstBefore(cast<Instruction>(Result), CI);
9747         }
9748         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9749       }
9750     }
9751     break;
9752
9753   case Intrinsic::stackrestore: {
9754     // If the save is right next to the restore, remove the restore.  This can
9755     // happen when variable allocas are DCE'd.
9756     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9757       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9758         BasicBlock::iterator BI = SS;
9759         if (&*++BI == II)
9760           return EraseInstFromFunction(CI);
9761       }
9762     }
9763     
9764     // Scan down this block to see if there is another stack restore in the
9765     // same block without an intervening call/alloca.
9766     BasicBlock::iterator BI = II;
9767     TerminatorInst *TI = II->getParent()->getTerminator();
9768     bool CannotRemove = false;
9769     for (++BI; &*BI != TI; ++BI) {
9770       if (isa<AllocaInst>(BI)) {
9771         CannotRemove = true;
9772         break;
9773       }
9774       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9775         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9776           // If there is a stackrestore below this one, remove this one.
9777           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9778             return EraseInstFromFunction(CI);
9779           // Otherwise, ignore the intrinsic.
9780         } else {
9781           // If we found a non-intrinsic call, we can't remove the stack
9782           // restore.
9783           CannotRemove = true;
9784           break;
9785         }
9786       }
9787     }
9788     
9789     // If the stack restore is in a return/unwind block and if there are no
9790     // allocas or calls between the restore and the return, nuke the restore.
9791     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9792       return EraseInstFromFunction(CI);
9793     break;
9794   }
9795   }
9796
9797   return visitCallSite(II);
9798 }
9799
9800 // InvokeInst simplification
9801 //
9802 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9803   return visitCallSite(&II);
9804 }
9805
9806 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9807 /// passed through the varargs area, we can eliminate the use of the cast.
9808 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9809                                          const CastInst * const CI,
9810                                          const TargetData * const TD,
9811                                          const int ix) {
9812   if (!CI->isLosslessCast())
9813     return false;
9814
9815   // The size of ByVal arguments is derived from the type, so we
9816   // can't change to a type with a different size.  If the size were
9817   // passed explicitly we could avoid this check.
9818   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9819     return true;
9820
9821   const Type* SrcTy = 
9822             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9823   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9824   if (!SrcTy->isSized() || !DstTy->isSized())
9825     return false;
9826   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9827     return false;
9828   return true;
9829 }
9830
9831 // visitCallSite - Improvements for call and invoke instructions.
9832 //
9833 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9834   bool Changed = false;
9835
9836   // If the callee is a constexpr cast of a function, attempt to move the cast
9837   // to the arguments of the call/invoke.
9838   if (transformConstExprCastCall(CS)) return 0;
9839
9840   Value *Callee = CS.getCalledValue();
9841
9842   if (Function *CalleeF = dyn_cast<Function>(Callee))
9843     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9844       Instruction *OldCall = CS.getInstruction();
9845       // If the call and callee calling conventions don't match, this call must
9846       // be unreachable, as the call is undefined.
9847       new StoreInst(ConstantInt::getTrue(),
9848                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9849                                     OldCall);
9850       if (!OldCall->use_empty())
9851         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9852       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9853         return EraseInstFromFunction(*OldCall);
9854       return 0;
9855     }
9856
9857   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9858     // This instruction is not reachable, just remove it.  We insert a store to
9859     // undef so that we know that this code is not reachable, despite the fact
9860     // that we can't modify the CFG here.
9861     new StoreInst(ConstantInt::getTrue(),
9862                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9863                   CS.getInstruction());
9864
9865     if (!CS.getInstruction()->use_empty())
9866       CS.getInstruction()->
9867         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9868
9869     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9870       // Don't break the CFG, insert a dummy cond branch.
9871       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9872                          ConstantInt::getTrue(), II);
9873     }
9874     return EraseInstFromFunction(*CS.getInstruction());
9875   }
9876
9877   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9878     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9879       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9880         return transformCallThroughTrampoline(CS);
9881
9882   const PointerType *PTy = cast<PointerType>(Callee->getType());
9883   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9884   if (FTy->isVarArg()) {
9885     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9886     // See if we can optimize any arguments passed through the varargs area of
9887     // the call.
9888     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9889            E = CS.arg_end(); I != E; ++I, ++ix) {
9890       CastInst *CI = dyn_cast<CastInst>(*I);
9891       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9892         *I = CI->getOperand(0);
9893         Changed = true;
9894       }
9895     }
9896   }
9897
9898   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9899     // Inline asm calls cannot throw - mark them 'nounwind'.
9900     CS.setDoesNotThrow();
9901     Changed = true;
9902   }
9903
9904   return Changed ? CS.getInstruction() : 0;
9905 }
9906
9907 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9908 // attempt to move the cast to the arguments of the call/invoke.
9909 //
9910 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9911   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9912   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9913   if (CE->getOpcode() != Instruction::BitCast || 
9914       !isa<Function>(CE->getOperand(0)))
9915     return false;
9916   Function *Callee = cast<Function>(CE->getOperand(0));
9917   Instruction *Caller = CS.getInstruction();
9918   const AttrListPtr &CallerPAL = CS.getAttributes();
9919
9920   // Okay, this is a cast from a function to a different type.  Unless doing so
9921   // would cause a type conversion of one of our arguments, change this call to
9922   // be a direct call with arguments casted to the appropriate types.
9923   //
9924   const FunctionType *FT = Callee->getFunctionType();
9925   const Type *OldRetTy = Caller->getType();
9926   const Type *NewRetTy = FT->getReturnType();
9927
9928   if (isa<StructType>(NewRetTy))
9929     return false; // TODO: Handle multiple return values.
9930
9931   // Check to see if we are changing the return type...
9932   if (OldRetTy != NewRetTy) {
9933     if (Callee->isDeclaration() &&
9934         // Conversion is ok if changing from one pointer type to another or from
9935         // a pointer to an integer of the same size.
9936         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9937           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9938       return false;   // Cannot transform this return value.
9939
9940     if (!Caller->use_empty() &&
9941         // void -> non-void is handled specially
9942         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9943       return false;   // Cannot transform this return value.
9944
9945     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9946       Attributes RAttrs = CallerPAL.getRetAttributes();
9947       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9948         return false;   // Attribute not compatible with transformed value.
9949     }
9950
9951     // If the callsite is an invoke instruction, and the return value is used by
9952     // a PHI node in a successor, we cannot change the return type of the call
9953     // because there is no place to put the cast instruction (without breaking
9954     // the critical edge).  Bail out in this case.
9955     if (!Caller->use_empty())
9956       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9957         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9958              UI != E; ++UI)
9959           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9960             if (PN->getParent() == II->getNormalDest() ||
9961                 PN->getParent() == II->getUnwindDest())
9962               return false;
9963   }
9964
9965   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9966   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9967
9968   CallSite::arg_iterator AI = CS.arg_begin();
9969   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9970     const Type *ParamTy = FT->getParamType(i);
9971     const Type *ActTy = (*AI)->getType();
9972
9973     if (!CastInst::isCastable(ActTy, ParamTy))
9974       return false;   // Cannot transform this parameter value.
9975
9976     if (CallerPAL.getParamAttributes(i + 1) 
9977         & Attribute::typeIncompatible(ParamTy))
9978       return false;   // Attribute not compatible with transformed value.
9979
9980     // Converting from one pointer type to another or between a pointer and an
9981     // integer of the same size is safe even if we do not have a body.
9982     bool isConvertible = ActTy == ParamTy ||
9983       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9984        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9985     if (Callee->isDeclaration() && !isConvertible) return false;
9986   }
9987
9988   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9989       Callee->isDeclaration())
9990     return false;   // Do not delete arguments unless we have a function body.
9991
9992   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9993       !CallerPAL.isEmpty())
9994     // In this case we have more arguments than the new function type, but we
9995     // won't be dropping them.  Check that these extra arguments have attributes
9996     // that are compatible with being a vararg call argument.
9997     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9998       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9999         break;
10000       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10001       if (PAttrs & Attribute::VarArgsIncompatible)
10002         return false;
10003     }
10004
10005   // Okay, we decided that this is a safe thing to do: go ahead and start
10006   // inserting cast instructions as necessary...
10007   std::vector<Value*> Args;
10008   Args.reserve(NumActualArgs);
10009   SmallVector<AttributeWithIndex, 8> attrVec;
10010   attrVec.reserve(NumCommonArgs);
10011
10012   // Get any return attributes.
10013   Attributes RAttrs = CallerPAL.getRetAttributes();
10014
10015   // If the return value is not being used, the type may not be compatible
10016   // with the existing attributes.  Wipe out any problematic attributes.
10017   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10018
10019   // Add the new return attributes.
10020   if (RAttrs)
10021     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10022
10023   AI = CS.arg_begin();
10024   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10025     const Type *ParamTy = FT->getParamType(i);
10026     if ((*AI)->getType() == ParamTy) {
10027       Args.push_back(*AI);
10028     } else {
10029       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10030           false, ParamTy, false);
10031       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10032       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10033     }
10034
10035     // Add any parameter attributes.
10036     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10037       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10038   }
10039
10040   // If the function takes more arguments than the call was taking, add them
10041   // now...
10042   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10043     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10044
10045   // If we are removing arguments to the function, emit an obnoxious warning...
10046   if (FT->getNumParams() < NumActualArgs) {
10047     if (!FT->isVarArg()) {
10048       cerr << "WARNING: While resolving call to function '"
10049            << Callee->getName() << "' arguments were dropped!\n";
10050     } else {
10051       // Add all of the arguments in their promoted form to the arg list...
10052       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10053         const Type *PTy = getPromotedType((*AI)->getType());
10054         if (PTy != (*AI)->getType()) {
10055           // Must promote to pass through va_arg area!
10056           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10057                                                                 PTy, false);
10058           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10059           InsertNewInstBefore(Cast, *Caller);
10060           Args.push_back(Cast);
10061         } else {
10062           Args.push_back(*AI);
10063         }
10064
10065         // Add any parameter attributes.
10066         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10067           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10068       }
10069     }
10070   }
10071
10072   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10073     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10074
10075   if (NewRetTy == Type::VoidTy)
10076     Caller->setName("");   // Void type should not have a name.
10077
10078   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10079
10080   Instruction *NC;
10081   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10082     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10083                             Args.begin(), Args.end(),
10084                             Caller->getName(), Caller);
10085     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10086     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10087   } else {
10088     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10089                           Caller->getName(), Caller);
10090     CallInst *CI = cast<CallInst>(Caller);
10091     if (CI->isTailCall())
10092       cast<CallInst>(NC)->setTailCall();
10093     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10094     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10095   }
10096
10097   // Insert a cast of the return type as necessary.
10098   Value *NV = NC;
10099   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10100     if (NV->getType() != Type::VoidTy) {
10101       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10102                                                             OldRetTy, false);
10103       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10104
10105       // If this is an invoke instruction, we should insert it after the first
10106       // non-phi, instruction in the normal successor block.
10107       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10108         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10109         InsertNewInstBefore(NC, *I);
10110       } else {
10111         // Otherwise, it's a call, just insert cast right after the call instr
10112         InsertNewInstBefore(NC, *Caller);
10113       }
10114       AddUsersToWorkList(*Caller);
10115     } else {
10116       NV = UndefValue::get(Caller->getType());
10117     }
10118   }
10119
10120   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10121     Caller->replaceAllUsesWith(NV);
10122   Caller->eraseFromParent();
10123   RemoveFromWorkList(Caller);
10124   return true;
10125 }
10126
10127 // transformCallThroughTrampoline - Turn a call to a function created by the
10128 // init_trampoline intrinsic into a direct call to the underlying function.
10129 //
10130 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10131   Value *Callee = CS.getCalledValue();
10132   const PointerType *PTy = cast<PointerType>(Callee->getType());
10133   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10134   const AttrListPtr &Attrs = CS.getAttributes();
10135
10136   // If the call already has the 'nest' attribute somewhere then give up -
10137   // otherwise 'nest' would occur twice after splicing in the chain.
10138   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10139     return 0;
10140
10141   IntrinsicInst *Tramp =
10142     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10143
10144   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10145   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10146   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10147
10148   const AttrListPtr &NestAttrs = NestF->getAttributes();
10149   if (!NestAttrs.isEmpty()) {
10150     unsigned NestIdx = 1;
10151     const Type *NestTy = 0;
10152     Attributes NestAttr = Attribute::None;
10153
10154     // Look for a parameter marked with the 'nest' attribute.
10155     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10156          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10157       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10158         // Record the parameter type and any other attributes.
10159         NestTy = *I;
10160         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10161         break;
10162       }
10163
10164     if (NestTy) {
10165       Instruction *Caller = CS.getInstruction();
10166       std::vector<Value*> NewArgs;
10167       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10168
10169       SmallVector<AttributeWithIndex, 8> NewAttrs;
10170       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10171
10172       // Insert the nest argument into the call argument list, which may
10173       // mean appending it.  Likewise for attributes.
10174
10175       // Add any result attributes.
10176       if (Attributes Attr = Attrs.getRetAttributes())
10177         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10178
10179       {
10180         unsigned Idx = 1;
10181         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10182         do {
10183           if (Idx == NestIdx) {
10184             // Add the chain argument and attributes.
10185             Value *NestVal = Tramp->getOperand(3);
10186             if (NestVal->getType() != NestTy)
10187               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10188             NewArgs.push_back(NestVal);
10189             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10190           }
10191
10192           if (I == E)
10193             break;
10194
10195           // Add the original argument and attributes.
10196           NewArgs.push_back(*I);
10197           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10198             NewAttrs.push_back
10199               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10200
10201           ++Idx, ++I;
10202         } while (1);
10203       }
10204
10205       // Add any function attributes.
10206       if (Attributes Attr = Attrs.getFnAttributes())
10207         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10208
10209       // The trampoline may have been bitcast to a bogus type (FTy).
10210       // Handle this by synthesizing a new function type, equal to FTy
10211       // with the chain parameter inserted.
10212
10213       std::vector<const Type*> NewTypes;
10214       NewTypes.reserve(FTy->getNumParams()+1);
10215
10216       // Insert the chain's type into the list of parameter types, which may
10217       // mean appending it.
10218       {
10219         unsigned Idx = 1;
10220         FunctionType::param_iterator I = FTy->param_begin(),
10221           E = FTy->param_end();
10222
10223         do {
10224           if (Idx == NestIdx)
10225             // Add the chain's type.
10226             NewTypes.push_back(NestTy);
10227
10228           if (I == E)
10229             break;
10230
10231           // Add the original type.
10232           NewTypes.push_back(*I);
10233
10234           ++Idx, ++I;
10235         } while (1);
10236       }
10237
10238       // Replace the trampoline call with a direct call.  Let the generic
10239       // code sort out any function type mismatches.
10240       FunctionType *NewFTy =
10241         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10242       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10243         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10244       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10245
10246       Instruction *NewCaller;
10247       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10248         NewCaller = InvokeInst::Create(NewCallee,
10249                                        II->getNormalDest(), II->getUnwindDest(),
10250                                        NewArgs.begin(), NewArgs.end(),
10251                                        Caller->getName(), Caller);
10252         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10253         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10254       } else {
10255         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10256                                      Caller->getName(), Caller);
10257         if (cast<CallInst>(Caller)->isTailCall())
10258           cast<CallInst>(NewCaller)->setTailCall();
10259         cast<CallInst>(NewCaller)->
10260           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10261         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10262       }
10263       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10264         Caller->replaceAllUsesWith(NewCaller);
10265       Caller->eraseFromParent();
10266       RemoveFromWorkList(Caller);
10267       return 0;
10268     }
10269   }
10270
10271   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10272   // parameter, there is no need to adjust the argument list.  Let the generic
10273   // code sort out any function type mismatches.
10274   Constant *NewCallee =
10275     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10276   CS.setCalledFunction(NewCallee);
10277   return CS.getInstruction();
10278 }
10279
10280 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10281 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10282 /// and a single binop.
10283 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10284   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10285   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10286   unsigned Opc = FirstInst->getOpcode();
10287   Value *LHSVal = FirstInst->getOperand(0);
10288   Value *RHSVal = FirstInst->getOperand(1);
10289     
10290   const Type *LHSType = LHSVal->getType();
10291   const Type *RHSType = RHSVal->getType();
10292   
10293   // Scan to see if all operands are the same opcode, all have one use, and all
10294   // kill their operands (i.e. the operands have one use).
10295   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10296     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10297     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10298         // Verify type of the LHS matches so we don't fold cmp's of different
10299         // types or GEP's with different index types.
10300         I->getOperand(0)->getType() != LHSType ||
10301         I->getOperand(1)->getType() != RHSType)
10302       return 0;
10303
10304     // If they are CmpInst instructions, check their predicates
10305     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10306       if (cast<CmpInst>(I)->getPredicate() !=
10307           cast<CmpInst>(FirstInst)->getPredicate())
10308         return 0;
10309     
10310     // Keep track of which operand needs a phi node.
10311     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10312     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10313   }
10314   
10315   // Otherwise, this is safe to transform!
10316   
10317   Value *InLHS = FirstInst->getOperand(0);
10318   Value *InRHS = FirstInst->getOperand(1);
10319   PHINode *NewLHS = 0, *NewRHS = 0;
10320   if (LHSVal == 0) {
10321     NewLHS = PHINode::Create(LHSType,
10322                              FirstInst->getOperand(0)->getName() + ".pn");
10323     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10324     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10325     InsertNewInstBefore(NewLHS, PN);
10326     LHSVal = NewLHS;
10327   }
10328   
10329   if (RHSVal == 0) {
10330     NewRHS = PHINode::Create(RHSType,
10331                              FirstInst->getOperand(1)->getName() + ".pn");
10332     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10333     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10334     InsertNewInstBefore(NewRHS, PN);
10335     RHSVal = NewRHS;
10336   }
10337   
10338   // Add all operands to the new PHIs.
10339   if (NewLHS || NewRHS) {
10340     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10341       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10342       if (NewLHS) {
10343         Value *NewInLHS = InInst->getOperand(0);
10344         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10345       }
10346       if (NewRHS) {
10347         Value *NewInRHS = InInst->getOperand(1);
10348         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10349       }
10350     }
10351   }
10352     
10353   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10354     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10355   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10356   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10357                          RHSVal);
10358 }
10359
10360 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10361   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10362   
10363   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10364                                         FirstInst->op_end());
10365   // This is true if all GEP bases are allocas and if all indices into them are
10366   // constants.
10367   bool AllBasePointersAreAllocas = true;
10368   
10369   // Scan to see if all operands are the same opcode, all have one use, and all
10370   // kill their operands (i.e. the operands have one use).
10371   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10372     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10373     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10374       GEP->getNumOperands() != FirstInst->getNumOperands())
10375       return 0;
10376
10377     // Keep track of whether or not all GEPs are of alloca pointers.
10378     if (AllBasePointersAreAllocas &&
10379         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10380          !GEP->hasAllConstantIndices()))
10381       AllBasePointersAreAllocas = false;
10382     
10383     // Compare the operand lists.
10384     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10385       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10386         continue;
10387       
10388       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10389       // if one of the PHIs has a constant for the index.  The index may be
10390       // substantially cheaper to compute for the constants, so making it a
10391       // variable index could pessimize the path.  This also handles the case
10392       // for struct indices, which must always be constant.
10393       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10394           isa<ConstantInt>(GEP->getOperand(op)))
10395         return 0;
10396       
10397       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10398         return 0;
10399       FixedOperands[op] = 0;  // Needs a PHI.
10400     }
10401   }
10402   
10403   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10404   // bother doing this transformation.  At best, this will just save a bit of
10405   // offset calculation, but all the predecessors will have to materialize the
10406   // stack address into a register anyway.  We'd actually rather *clone* the
10407   // load up into the predecessors so that we have a load of a gep of an alloca,
10408   // which can usually all be folded into the load.
10409   if (AllBasePointersAreAllocas)
10410     return 0;
10411   
10412   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10413   // that is variable.
10414   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10415   
10416   bool HasAnyPHIs = false;
10417   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10418     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10419     Value *FirstOp = FirstInst->getOperand(i);
10420     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10421                                      FirstOp->getName()+".pn");
10422     InsertNewInstBefore(NewPN, PN);
10423     
10424     NewPN->reserveOperandSpace(e);
10425     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10426     OperandPhis[i] = NewPN;
10427     FixedOperands[i] = NewPN;
10428     HasAnyPHIs = true;
10429   }
10430
10431   
10432   // Add all operands to the new PHIs.
10433   if (HasAnyPHIs) {
10434     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10435       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10436       BasicBlock *InBB = PN.getIncomingBlock(i);
10437       
10438       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10439         if (PHINode *OpPhi = OperandPhis[op])
10440           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10441     }
10442   }
10443   
10444   Value *Base = FixedOperands[0];
10445   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10446                                    FixedOperands.end());
10447 }
10448
10449
10450 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10451 /// sink the load out of the block that defines it.  This means that it must be
10452 /// obvious the value of the load is not changed from the point of the load to
10453 /// the end of the block it is in.
10454 ///
10455 /// Finally, it is safe, but not profitable, to sink a load targetting a
10456 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10457 /// to a register.
10458 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10459   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10460   
10461   for (++BBI; BBI != E; ++BBI)
10462     if (BBI->mayWriteToMemory())
10463       return false;
10464   
10465   // Check for non-address taken alloca.  If not address-taken already, it isn't
10466   // profitable to do this xform.
10467   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10468     bool isAddressTaken = false;
10469     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10470          UI != E; ++UI) {
10471       if (isa<LoadInst>(UI)) continue;
10472       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10473         // If storing TO the alloca, then the address isn't taken.
10474         if (SI->getOperand(1) == AI) continue;
10475       }
10476       isAddressTaken = true;
10477       break;
10478     }
10479     
10480     if (!isAddressTaken && AI->isStaticAlloca())
10481       return false;
10482   }
10483   
10484   // If this load is a load from a GEP with a constant offset from an alloca,
10485   // then we don't want to sink it.  In its present form, it will be
10486   // load [constant stack offset].  Sinking it will cause us to have to
10487   // materialize the stack addresses in each predecessor in a register only to
10488   // do a shared load from register in the successor.
10489   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10490     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10491       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10492         return false;
10493   
10494   return true;
10495 }
10496
10497
10498 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10499 // operator and they all are only used by the PHI, PHI together their
10500 // inputs, and do the operation once, to the result of the PHI.
10501 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10502   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10503
10504   // Scan the instruction, looking for input operations that can be folded away.
10505   // If all input operands to the phi are the same instruction (e.g. a cast from
10506   // the same type or "+42") we can pull the operation through the PHI, reducing
10507   // code size and simplifying code.
10508   Constant *ConstantOp = 0;
10509   const Type *CastSrcTy = 0;
10510   bool isVolatile = false;
10511   if (isa<CastInst>(FirstInst)) {
10512     CastSrcTy = FirstInst->getOperand(0)->getType();
10513   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10514     // Can fold binop, compare or shift here if the RHS is a constant, 
10515     // otherwise call FoldPHIArgBinOpIntoPHI.
10516     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10517     if (ConstantOp == 0)
10518       return FoldPHIArgBinOpIntoPHI(PN);
10519   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10520     isVolatile = LI->isVolatile();
10521     // We can't sink the load if the loaded value could be modified between the
10522     // load and the PHI.
10523     if (LI->getParent() != PN.getIncomingBlock(0) ||
10524         !isSafeAndProfitableToSinkLoad(LI))
10525       return 0;
10526     
10527     // If the PHI is of volatile loads and the load block has multiple
10528     // successors, sinking it would remove a load of the volatile value from
10529     // the path through the other successor.
10530     if (isVolatile &&
10531         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10532       return 0;
10533     
10534   } else if (isa<GetElementPtrInst>(FirstInst)) {
10535     return FoldPHIArgGEPIntoPHI(PN);
10536   } else {
10537     return 0;  // Cannot fold this operation.
10538   }
10539
10540   // Check to see if all arguments are the same operation.
10541   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10542     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10543     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10544     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10545       return 0;
10546     if (CastSrcTy) {
10547       if (I->getOperand(0)->getType() != CastSrcTy)
10548         return 0;  // Cast operation must match.
10549     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10550       // We can't sink the load if the loaded value could be modified between 
10551       // the load and the PHI.
10552       if (LI->isVolatile() != isVolatile ||
10553           LI->getParent() != PN.getIncomingBlock(i) ||
10554           !isSafeAndProfitableToSinkLoad(LI))
10555         return 0;
10556       
10557       // If the PHI is of volatile loads and the load block has multiple
10558       // successors, sinking it would remove a load of the volatile value from
10559       // the path through the other successor.
10560       if (isVolatile &&
10561           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10562         return 0;
10563       
10564     } else if (I->getOperand(1) != ConstantOp) {
10565       return 0;
10566     }
10567   }
10568
10569   // Okay, they are all the same operation.  Create a new PHI node of the
10570   // correct type, and PHI together all of the LHS's of the instructions.
10571   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10572                                    PN.getName()+".in");
10573   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10574
10575   Value *InVal = FirstInst->getOperand(0);
10576   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10577
10578   // Add all operands to the new PHI.
10579   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10580     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10581     if (NewInVal != InVal)
10582       InVal = 0;
10583     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10584   }
10585
10586   Value *PhiVal;
10587   if (InVal) {
10588     // The new PHI unions all of the same values together.  This is really
10589     // common, so we handle it intelligently here for compile-time speed.
10590     PhiVal = InVal;
10591     delete NewPN;
10592   } else {
10593     InsertNewInstBefore(NewPN, PN);
10594     PhiVal = NewPN;
10595   }
10596
10597   // Insert and return the new operation.
10598   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10599     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10600   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10601     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10602   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10603     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10604                            PhiVal, ConstantOp);
10605   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10606   
10607   // If this was a volatile load that we are merging, make sure to loop through
10608   // and mark all the input loads as non-volatile.  If we don't do this, we will
10609   // insert a new volatile load and the old ones will not be deletable.
10610   if (isVolatile)
10611     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10612       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10613   
10614   return new LoadInst(PhiVal, "", isVolatile);
10615 }
10616
10617 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10618 /// that is dead.
10619 static bool DeadPHICycle(PHINode *PN,
10620                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10621   if (PN->use_empty()) return true;
10622   if (!PN->hasOneUse()) return false;
10623
10624   // Remember this node, and if we find the cycle, return.
10625   if (!PotentiallyDeadPHIs.insert(PN))
10626     return true;
10627   
10628   // Don't scan crazily complex things.
10629   if (PotentiallyDeadPHIs.size() == 16)
10630     return false;
10631
10632   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10633     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10634
10635   return false;
10636 }
10637
10638 /// PHIsEqualValue - Return true if this phi node is always equal to
10639 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10640 ///   z = some value; x = phi (y, z); y = phi (x, z)
10641 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10642                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10643   // See if we already saw this PHI node.
10644   if (!ValueEqualPHIs.insert(PN))
10645     return true;
10646   
10647   // Don't scan crazily complex things.
10648   if (ValueEqualPHIs.size() == 16)
10649     return false;
10650  
10651   // Scan the operands to see if they are either phi nodes or are equal to
10652   // the value.
10653   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10654     Value *Op = PN->getIncomingValue(i);
10655     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10656       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10657         return false;
10658     } else if (Op != NonPhiInVal)
10659       return false;
10660   }
10661   
10662   return true;
10663 }
10664
10665
10666 // PHINode simplification
10667 //
10668 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10669   // If LCSSA is around, don't mess with Phi nodes
10670   if (MustPreserveLCSSA) return 0;
10671   
10672   if (Value *V = PN.hasConstantValue())
10673     return ReplaceInstUsesWith(PN, V);
10674
10675   // If all PHI operands are the same operation, pull them through the PHI,
10676   // reducing code size.
10677   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10678       isa<Instruction>(PN.getIncomingValue(1)) &&
10679       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10680       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10681       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10682       // than themselves more than once.
10683       PN.getIncomingValue(0)->hasOneUse())
10684     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10685       return Result;
10686
10687   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10688   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10689   // PHI)... break the cycle.
10690   if (PN.hasOneUse()) {
10691     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10692     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10693       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10694       PotentiallyDeadPHIs.insert(&PN);
10695       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10696         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10697     }
10698    
10699     // If this phi has a single use, and if that use just computes a value for
10700     // the next iteration of a loop, delete the phi.  This occurs with unused
10701     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10702     // common case here is good because the only other things that catch this
10703     // are induction variable analysis (sometimes) and ADCE, which is only run
10704     // late.
10705     if (PHIUser->hasOneUse() &&
10706         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10707         PHIUser->use_back() == &PN) {
10708       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10709     }
10710   }
10711
10712   // We sometimes end up with phi cycles that non-obviously end up being the
10713   // same value, for example:
10714   //   z = some value; x = phi (y, z); y = phi (x, z)
10715   // where the phi nodes don't necessarily need to be in the same block.  Do a
10716   // quick check to see if the PHI node only contains a single non-phi value, if
10717   // so, scan to see if the phi cycle is actually equal to that value.
10718   {
10719     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10720     // Scan for the first non-phi operand.
10721     while (InValNo != NumOperandVals && 
10722            isa<PHINode>(PN.getIncomingValue(InValNo)))
10723       ++InValNo;
10724
10725     if (InValNo != NumOperandVals) {
10726       Value *NonPhiInVal = PN.getOperand(InValNo);
10727       
10728       // Scan the rest of the operands to see if there are any conflicts, if so
10729       // there is no need to recursively scan other phis.
10730       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10731         Value *OpVal = PN.getIncomingValue(InValNo);
10732         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10733           break;
10734       }
10735       
10736       // If we scanned over all operands, then we have one unique value plus
10737       // phi values.  Scan PHI nodes to see if they all merge in each other or
10738       // the value.
10739       if (InValNo == NumOperandVals) {
10740         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10741         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10742           return ReplaceInstUsesWith(PN, NonPhiInVal);
10743       }
10744     }
10745   }
10746   return 0;
10747 }
10748
10749 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10750                                    Instruction *InsertPoint,
10751                                    InstCombiner *IC) {
10752   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10753   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10754   // We must cast correctly to the pointer type. Ensure that we
10755   // sign extend the integer value if it is smaller as this is
10756   // used for address computation.
10757   Instruction::CastOps opcode = 
10758      (VTySize < PtrSize ? Instruction::SExt :
10759       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10760   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10761 }
10762
10763
10764 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10765   Value *PtrOp = GEP.getOperand(0);
10766   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10767   // If so, eliminate the noop.
10768   if (GEP.getNumOperands() == 1)
10769     return ReplaceInstUsesWith(GEP, PtrOp);
10770
10771   if (isa<UndefValue>(GEP.getOperand(0)))
10772     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10773
10774   bool HasZeroPointerIndex = false;
10775   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10776     HasZeroPointerIndex = C->isNullValue();
10777
10778   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10779     return ReplaceInstUsesWith(GEP, PtrOp);
10780
10781   // Eliminate unneeded casts for indices.
10782   bool MadeChange = false;
10783   
10784   gep_type_iterator GTI = gep_type_begin(GEP);
10785   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10786        i != e; ++i, ++GTI) {
10787     if (isa<SequentialType>(*GTI)) {
10788       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10789         if (CI->getOpcode() == Instruction::ZExt ||
10790             CI->getOpcode() == Instruction::SExt) {
10791           const Type *SrcTy = CI->getOperand(0)->getType();
10792           // We can eliminate a cast from i32 to i64 iff the target 
10793           // is a 32-bit pointer target.
10794           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10795             MadeChange = true;
10796             *i = CI->getOperand(0);
10797           }
10798         }
10799       }
10800       // If we are using a wider index than needed for this platform, shrink it
10801       // to what we need.  If narrower, sign-extend it to what we need.
10802       // If the incoming value needs a cast instruction,
10803       // insert it.  This explicit cast can make subsequent optimizations more
10804       // obvious.
10805       Value *Op = *i;
10806       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10807         if (Constant *C = dyn_cast<Constant>(Op)) {
10808           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10809           MadeChange = true;
10810         } else {
10811           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10812                                 GEP);
10813           *i = Op;
10814           MadeChange = true;
10815         }
10816       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10817         if (Constant *C = dyn_cast<Constant>(Op)) {
10818           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10819           MadeChange = true;
10820         } else {
10821           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10822                                 GEP);
10823           *i = Op;
10824           MadeChange = true;
10825         }
10826       }
10827     }
10828   }
10829   if (MadeChange) return &GEP;
10830
10831   // Combine Indices - If the source pointer to this getelementptr instruction
10832   // is a getelementptr instruction, combine the indices of the two
10833   // getelementptr instructions into a single instruction.
10834   //
10835   SmallVector<Value*, 8> SrcGEPOperands;
10836   if (User *Src = dyn_castGetElementPtr(PtrOp))
10837     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10838
10839   if (!SrcGEPOperands.empty()) {
10840     // Note that if our source is a gep chain itself that we wait for that
10841     // chain to be resolved before we perform this transformation.  This
10842     // avoids us creating a TON of code in some cases.
10843     //
10844     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10845         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10846       return 0;   // Wait until our source is folded to completion.
10847
10848     SmallVector<Value*, 8> Indices;
10849
10850     // Find out whether the last index in the source GEP is a sequential idx.
10851     bool EndsWithSequential = false;
10852     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10853            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10854       EndsWithSequential = !isa<StructType>(*I);
10855
10856     // Can we combine the two pointer arithmetics offsets?
10857     if (EndsWithSequential) {
10858       // Replace: gep (gep %P, long B), long A, ...
10859       // With:    T = long A+B; gep %P, T, ...
10860       //
10861       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10862       if (SO1 == Constant::getNullValue(SO1->getType())) {
10863         Sum = GO1;
10864       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10865         Sum = SO1;
10866       } else {
10867         // If they aren't the same type, convert both to an integer of the
10868         // target's pointer size.
10869         if (SO1->getType() != GO1->getType()) {
10870           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10871             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10872           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10873             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10874           } else {
10875             unsigned PS = TD->getPointerSizeInBits();
10876             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10877               // Convert GO1 to SO1's type.
10878               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10879
10880             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10881               // Convert SO1 to GO1's type.
10882               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10883             } else {
10884               const Type *PT = TD->getIntPtrType();
10885               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10886               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10887             }
10888           }
10889         }
10890         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10891           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10892         else {
10893           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10894           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10895         }
10896       }
10897
10898       // Recycle the GEP we already have if possible.
10899       if (SrcGEPOperands.size() == 2) {
10900         GEP.setOperand(0, SrcGEPOperands[0]);
10901         GEP.setOperand(1, Sum);
10902         return &GEP;
10903       } else {
10904         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10905                        SrcGEPOperands.end()-1);
10906         Indices.push_back(Sum);
10907         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10908       }
10909     } else if (isa<Constant>(*GEP.idx_begin()) &&
10910                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10911                SrcGEPOperands.size() != 1) {
10912       // Otherwise we can do the fold if the first index of the GEP is a zero
10913       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10914                      SrcGEPOperands.end());
10915       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10916     }
10917
10918     if (!Indices.empty())
10919       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10920                                        Indices.end(), GEP.getName());
10921
10922   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10923     // GEP of global variable.  If all of the indices for this GEP are
10924     // constants, we can promote this to a constexpr instead of an instruction.
10925
10926     // Scan for nonconstants...
10927     SmallVector<Constant*, 8> Indices;
10928     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10929     for (; I != E && isa<Constant>(*I); ++I)
10930       Indices.push_back(cast<Constant>(*I));
10931
10932     if (I == E) {  // If they are all constants...
10933       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10934                                                     &Indices[0],Indices.size());
10935
10936       // Replace all uses of the GEP with the new constexpr...
10937       return ReplaceInstUsesWith(GEP, CE);
10938     }
10939   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10940     if (!isa<PointerType>(X->getType())) {
10941       // Not interesting.  Source pointer must be a cast from pointer.
10942     } else if (HasZeroPointerIndex) {
10943       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10944       // into     : GEP [10 x i8]* X, i32 0, ...
10945       //
10946       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10947       //           into     : GEP i8* X, ...
10948       // 
10949       // This occurs when the program declares an array extern like "int X[];"
10950       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10951       const PointerType *XTy = cast<PointerType>(X->getType());
10952       if (const ArrayType *CATy =
10953           dyn_cast<ArrayType>(CPTy->getElementType())) {
10954         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10955         if (CATy->getElementType() == XTy->getElementType()) {
10956           // -> GEP i8* X, ...
10957           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10958           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10959                                            GEP.getName());
10960         } else if (const ArrayType *XATy =
10961                  dyn_cast<ArrayType>(XTy->getElementType())) {
10962           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10963           if (CATy->getElementType() == XATy->getElementType()) {
10964             // -> GEP [10 x i8]* X, i32 0, ...
10965             // At this point, we know that the cast source type is a pointer
10966             // to an array of the same type as the destination pointer
10967             // array.  Because the array type is never stepped over (there
10968             // is a leading zero) we can fold the cast into this GEP.
10969             GEP.setOperand(0, X);
10970             return &GEP;
10971           }
10972         }
10973       }
10974     } else if (GEP.getNumOperands() == 2) {
10975       // Transform things like:
10976       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10977       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10978       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10979       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10980       if (isa<ArrayType>(SrcElTy) &&
10981           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10982           TD->getTypeAllocSize(ResElTy)) {
10983         Value *Idx[2];
10984         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10985         Idx[1] = GEP.getOperand(1);
10986         Value *V = InsertNewInstBefore(
10987                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10988         // V and GEP are both pointer types --> BitCast
10989         return new BitCastInst(V, GEP.getType());
10990       }
10991       
10992       // Transform things like:
10993       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10994       //   (where tmp = 8*tmp2) into:
10995       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10996       
10997       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10998         uint64_t ArrayEltSize =
10999             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11000         
11001         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11002         // allow either a mul, shift, or constant here.
11003         Value *NewIdx = 0;
11004         ConstantInt *Scale = 0;
11005         if (ArrayEltSize == 1) {
11006           NewIdx = GEP.getOperand(1);
11007           Scale = ConstantInt::get(NewIdx->getType(), 1);
11008         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11009           NewIdx = ConstantInt::get(CI->getType(), 1);
11010           Scale = CI;
11011         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11012           if (Inst->getOpcode() == Instruction::Shl &&
11013               isa<ConstantInt>(Inst->getOperand(1))) {
11014             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11015             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11016             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
11017             NewIdx = Inst->getOperand(0);
11018           } else if (Inst->getOpcode() == Instruction::Mul &&
11019                      isa<ConstantInt>(Inst->getOperand(1))) {
11020             Scale = cast<ConstantInt>(Inst->getOperand(1));
11021             NewIdx = Inst->getOperand(0);
11022           }
11023         }
11024         
11025         // If the index will be to exactly the right offset with the scale taken
11026         // out, perform the transformation. Note, we don't know whether Scale is
11027         // signed or not. We'll use unsigned version of division/modulo
11028         // operation after making sure Scale doesn't have the sign bit set.
11029         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11030             Scale->getZExtValue() % ArrayEltSize == 0) {
11031           Scale = ConstantInt::get(Scale->getType(),
11032                                    Scale->getZExtValue() / ArrayEltSize);
11033           if (Scale->getZExtValue() != 1) {
11034             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11035                                                        false /*ZExt*/);
11036             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11037             NewIdx = InsertNewInstBefore(Sc, GEP);
11038           }
11039
11040           // Insert the new GEP instruction.
11041           Value *Idx[2];
11042           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11043           Idx[1] = NewIdx;
11044           Instruction *NewGEP =
11045             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11046           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11047           // The NewGEP must be pointer typed, so must the old one -> BitCast
11048           return new BitCastInst(NewGEP, GEP.getType());
11049         }
11050       }
11051     }
11052   }
11053   
11054   /// See if we can simplify:
11055   ///   X = bitcast A to B*
11056   ///   Y = gep X, <...constant indices...>
11057   /// into a gep of the original struct.  This is important for SROA and alias
11058   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11059   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11060     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11061       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11062       // a constant back from EmitGEPOffset.
11063       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11064       int64_t Offset = OffsetV->getSExtValue();
11065       
11066       // If this GEP instruction doesn't move the pointer, just replace the GEP
11067       // with a bitcast of the real input to the dest type.
11068       if (Offset == 0) {
11069         // If the bitcast is of an allocation, and the allocation will be
11070         // converted to match the type of the cast, don't touch this.
11071         if (isa<AllocationInst>(BCI->getOperand(0))) {
11072           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11073           if (Instruction *I = visitBitCast(*BCI)) {
11074             if (I != BCI) {
11075               I->takeName(BCI);
11076               BCI->getParent()->getInstList().insert(BCI, I);
11077               ReplaceInstUsesWith(*BCI, I);
11078             }
11079             return &GEP;
11080           }
11081         }
11082         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11083       }
11084       
11085       // Otherwise, if the offset is non-zero, we need to find out if there is a
11086       // field at Offset in 'A's type.  If so, we can pull the cast through the
11087       // GEP.
11088       SmallVector<Value*, 8> NewIndices;
11089       const Type *InTy =
11090         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11091       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11092         Instruction *NGEP =
11093            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11094                                      NewIndices.end());
11095         if (NGEP->getType() == GEP.getType()) return NGEP;
11096         InsertNewInstBefore(NGEP, GEP);
11097         NGEP->takeName(&GEP);
11098         return new BitCastInst(NGEP, GEP.getType());
11099       }
11100     }
11101   }    
11102     
11103   return 0;
11104 }
11105
11106 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11107   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11108   if (AI.isArrayAllocation()) {  // Check C != 1
11109     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11110       const Type *NewTy = 
11111         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11112       AllocationInst *New = 0;
11113
11114       // Create and insert the replacement instruction...
11115       if (isa<MallocInst>(AI))
11116         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11117       else {
11118         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11119         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11120       }
11121
11122       InsertNewInstBefore(New, AI);
11123
11124       // Scan to the end of the allocation instructions, to skip over a block of
11125       // allocas if possible...also skip interleaved debug info
11126       //
11127       BasicBlock::iterator It = New;
11128       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11129
11130       // Now that I is pointing to the first non-allocation-inst in the block,
11131       // insert our getelementptr instruction...
11132       //
11133       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11134       Value *Idx[2];
11135       Idx[0] = NullIdx;
11136       Idx[1] = NullIdx;
11137       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11138                                            New->getName()+".sub", It);
11139
11140       // Now make everything use the getelementptr instead of the original
11141       // allocation.
11142       return ReplaceInstUsesWith(AI, V);
11143     } else if (isa<UndefValue>(AI.getArraySize())) {
11144       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11145     }
11146   }
11147
11148   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11149     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11150     // Note that we only do this for alloca's, because malloc should allocate
11151     // and return a unique pointer, even for a zero byte allocation.
11152     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11153       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11154
11155     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11156     if (AI.getAlignment() == 0)
11157       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11158   }
11159
11160   return 0;
11161 }
11162
11163 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11164   Value *Op = FI.getOperand(0);
11165
11166   // free undef -> unreachable.
11167   if (isa<UndefValue>(Op)) {
11168     // Insert a new store to null because we cannot modify the CFG here.
11169     new StoreInst(ConstantInt::getTrue(),
11170                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11171     return EraseInstFromFunction(FI);
11172   }
11173   
11174   // If we have 'free null' delete the instruction.  This can happen in stl code
11175   // when lots of inlining happens.
11176   if (isa<ConstantPointerNull>(Op))
11177     return EraseInstFromFunction(FI);
11178   
11179   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11180   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11181     FI.setOperand(0, CI->getOperand(0));
11182     return &FI;
11183   }
11184   
11185   // Change free (gep X, 0,0,0,0) into free(X)
11186   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11187     if (GEPI->hasAllZeroIndices()) {
11188       AddToWorkList(GEPI);
11189       FI.setOperand(0, GEPI->getOperand(0));
11190       return &FI;
11191     }
11192   }
11193   
11194   // Change free(malloc) into nothing, if the malloc has a single use.
11195   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11196     if (MI->hasOneUse()) {
11197       EraseInstFromFunction(FI);
11198       return EraseInstFromFunction(*MI);
11199     }
11200
11201   return 0;
11202 }
11203
11204
11205 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11206 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11207                                         const TargetData *TD) {
11208   User *CI = cast<User>(LI.getOperand(0));
11209   Value *CastOp = CI->getOperand(0);
11210
11211   if (TD) {
11212     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11213       // Instead of loading constant c string, use corresponding integer value
11214       // directly if string length is small enough.
11215       std::string Str;
11216       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11217         unsigned len = Str.length();
11218         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11219         unsigned numBits = Ty->getPrimitiveSizeInBits();
11220         // Replace LI with immediate integer store.
11221         if ((numBits >> 3) == len + 1) {
11222           APInt StrVal(numBits, 0);
11223           APInt SingleChar(numBits, 0);
11224           if (TD->isLittleEndian()) {
11225             for (signed i = len-1; i >= 0; i--) {
11226               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11227               StrVal = (StrVal << 8) | SingleChar;
11228             }
11229           } else {
11230             for (unsigned i = 0; i < len; i++) {
11231               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11232               StrVal = (StrVal << 8) | SingleChar;
11233             }
11234             // Append NULL at the end.
11235             SingleChar = 0;
11236             StrVal = (StrVal << 8) | SingleChar;
11237           }
11238           Value *NL = ConstantInt::get(StrVal);
11239           return IC.ReplaceInstUsesWith(LI, NL);
11240         }
11241       }
11242     }
11243   }
11244
11245   const PointerType *DestTy = cast<PointerType>(CI->getType());
11246   const Type *DestPTy = DestTy->getElementType();
11247   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11248
11249     // If the address spaces don't match, don't eliminate the cast.
11250     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11251       return 0;
11252
11253     const Type *SrcPTy = SrcTy->getElementType();
11254
11255     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11256          isa<VectorType>(DestPTy)) {
11257       // If the source is an array, the code below will not succeed.  Check to
11258       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11259       // constants.
11260       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11261         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11262           if (ASrcTy->getNumElements() != 0) {
11263             Value *Idxs[2];
11264             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11265             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11266             SrcTy = cast<PointerType>(CastOp->getType());
11267             SrcPTy = SrcTy->getElementType();
11268           }
11269
11270       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11271             isa<VectorType>(SrcPTy)) &&
11272           // Do not allow turning this into a load of an integer, which is then
11273           // casted to a pointer, this pessimizes pointer analysis a lot.
11274           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11275           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11276                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11277
11278         // Okay, we are casting from one integer or pointer type to another of
11279         // the same size.  Instead of casting the pointer before the load, cast
11280         // the result of the loaded value.
11281         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11282                                                              CI->getName(),
11283                                                          LI.isVolatile()),LI);
11284         // Now cast the result of the load.
11285         return new BitCastInst(NewLoad, LI.getType());
11286       }
11287     }
11288   }
11289   return 0;
11290 }
11291
11292 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11293 /// from this value cannot trap.  If it is not obviously safe to load from the
11294 /// specified pointer, we do a quick local scan of the basic block containing
11295 /// ScanFrom, to determine if the address is already accessed.
11296 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11297   // If it is an alloca it is always safe to load from.
11298   if (isa<AllocaInst>(V)) return true;
11299
11300   // If it is a global variable it is mostly safe to load from.
11301   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11302     // Don't try to evaluate aliases.  External weak GV can be null.
11303     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11304
11305   // Otherwise, be a little bit agressive by scanning the local block where we
11306   // want to check to see if the pointer is already being loaded or stored
11307   // from/to.  If so, the previous load or store would have already trapped,
11308   // so there is no harm doing an extra load (also, CSE will later eliminate
11309   // the load entirely).
11310   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11311
11312   while (BBI != E) {
11313     --BBI;
11314
11315     // If we see a free or a call (which might do a free) the pointer could be
11316     // marked invalid.
11317     if (isa<FreeInst>(BBI) || 
11318         (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
11319       return false;
11320     
11321     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11322       if (LI->getOperand(0) == V) return true;
11323     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11324       if (SI->getOperand(1) == V) return true;
11325     }
11326
11327   }
11328   return false;
11329 }
11330
11331 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11332   Value *Op = LI.getOperand(0);
11333
11334   // Attempt to improve the alignment.
11335   unsigned KnownAlign =
11336     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11337   if (KnownAlign >
11338       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11339                                 LI.getAlignment()))
11340     LI.setAlignment(KnownAlign);
11341
11342   // load (cast X) --> cast (load X) iff safe
11343   if (isa<CastInst>(Op))
11344     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11345       return Res;
11346
11347   // None of the following transforms are legal for volatile loads.
11348   if (LI.isVolatile()) return 0;
11349   
11350   // Do really simple store-to-load forwarding and load CSE, to catch cases
11351   // where there are several consequtive memory accesses to the same location,
11352   // separated by a few arithmetic operations.
11353   BasicBlock::iterator BBI = &LI;
11354   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11355     return ReplaceInstUsesWith(LI, AvailableVal);
11356
11357   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11358     const Value *GEPI0 = GEPI->getOperand(0);
11359     // TODO: Consider a target hook for valid address spaces for this xform.
11360     if (isa<ConstantPointerNull>(GEPI0) &&
11361         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11362       // Insert a new store to null instruction before the load to indicate
11363       // that this code is not reachable.  We do this instead of inserting
11364       // an unreachable instruction directly because we cannot modify the
11365       // CFG.
11366       new StoreInst(UndefValue::get(LI.getType()),
11367                     Constant::getNullValue(Op->getType()), &LI);
11368       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11369     }
11370   } 
11371
11372   if (Constant *C = dyn_cast<Constant>(Op)) {
11373     // load null/undef -> undef
11374     // TODO: Consider a target hook for valid address spaces for this xform.
11375     if (isa<UndefValue>(C) || (C->isNullValue() && 
11376         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11377       // Insert a new store to null instruction before the load to indicate that
11378       // this code is not reachable.  We do this instead of inserting an
11379       // unreachable instruction directly because we cannot modify the CFG.
11380       new StoreInst(UndefValue::get(LI.getType()),
11381                     Constant::getNullValue(Op->getType()), &LI);
11382       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11383     }
11384
11385     // Instcombine load (constant global) into the value loaded.
11386     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11387       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11388         return ReplaceInstUsesWith(LI, GV->getInitializer());
11389
11390     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11391     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11392       if (CE->getOpcode() == Instruction::GetElementPtr) {
11393         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11394           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11395             if (Constant *V = 
11396                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11397               return ReplaceInstUsesWith(LI, V);
11398         if (CE->getOperand(0)->isNullValue()) {
11399           // Insert a new store to null instruction before the load to indicate
11400           // that this code is not reachable.  We do this instead of inserting
11401           // an unreachable instruction directly because we cannot modify the
11402           // CFG.
11403           new StoreInst(UndefValue::get(LI.getType()),
11404                         Constant::getNullValue(Op->getType()), &LI);
11405           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11406         }
11407
11408       } else if (CE->isCast()) {
11409         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11410           return Res;
11411       }
11412     }
11413   }
11414     
11415   // If this load comes from anywhere in a constant global, and if the global
11416   // is all undef or zero, we know what it loads.
11417   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11418     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11419       if (GV->getInitializer()->isNullValue())
11420         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11421       else if (isa<UndefValue>(GV->getInitializer()))
11422         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11423     }
11424   }
11425
11426   if (Op->hasOneUse()) {
11427     // Change select and PHI nodes to select values instead of addresses: this
11428     // helps alias analysis out a lot, allows many others simplifications, and
11429     // exposes redundancy in the code.
11430     //
11431     // Note that we cannot do the transformation unless we know that the
11432     // introduced loads cannot trap!  Something like this is valid as long as
11433     // the condition is always false: load (select bool %C, int* null, int* %G),
11434     // but it would not be valid if we transformed it to load from null
11435     // unconditionally.
11436     //
11437     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11438       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11439       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11440           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11441         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11442                                      SI->getOperand(1)->getName()+".val"), LI);
11443         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11444                                      SI->getOperand(2)->getName()+".val"), LI);
11445         return SelectInst::Create(SI->getCondition(), V1, V2);
11446       }
11447
11448       // load (select (cond, null, P)) -> load P
11449       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11450         if (C->isNullValue()) {
11451           LI.setOperand(0, SI->getOperand(2));
11452           return &LI;
11453         }
11454
11455       // load (select (cond, P, null)) -> load P
11456       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11457         if (C->isNullValue()) {
11458           LI.setOperand(0, SI->getOperand(1));
11459           return &LI;
11460         }
11461     }
11462   }
11463   return 0;
11464 }
11465
11466 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11467 /// when possible.  This makes it generally easy to do alias analysis and/or
11468 /// SROA/mem2reg of the memory object.
11469 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11470   User *CI = cast<User>(SI.getOperand(1));
11471   Value *CastOp = CI->getOperand(0);
11472
11473   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11474   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11475   if (SrcTy == 0) return 0;
11476   
11477   const Type *SrcPTy = SrcTy->getElementType();
11478
11479   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11480     return 0;
11481   
11482   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11483   /// to its first element.  This allows us to handle things like:
11484   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11485   /// on 32-bit hosts.
11486   SmallVector<Value*, 4> NewGEPIndices;
11487   
11488   // If the source is an array, the code below will not succeed.  Check to
11489   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11490   // constants.
11491   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11492     // Index through pointer.
11493     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11494     NewGEPIndices.push_back(Zero);
11495     
11496     while (1) {
11497       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11498         if (!STy->getNumElements()) /* Struct can be empty {} */
11499           break;
11500         NewGEPIndices.push_back(Zero);
11501         SrcPTy = STy->getElementType(0);
11502       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11503         NewGEPIndices.push_back(Zero);
11504         SrcPTy = ATy->getElementType();
11505       } else {
11506         break;
11507       }
11508     }
11509     
11510     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11511   }
11512
11513   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11514     return 0;
11515   
11516   // If the pointers point into different address spaces or if they point to
11517   // values with different sizes, we can't do the transformation.
11518   if (SrcTy->getAddressSpace() != 
11519         cast<PointerType>(CI->getType())->getAddressSpace() ||
11520       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11521       IC.getTargetData().getTypeSizeInBits(DestPTy))
11522     return 0;
11523
11524   // Okay, we are casting from one integer or pointer type to another of
11525   // the same size.  Instead of casting the pointer before 
11526   // the store, cast the value to be stored.
11527   Value *NewCast;
11528   Value *SIOp0 = SI.getOperand(0);
11529   Instruction::CastOps opcode = Instruction::BitCast;
11530   const Type* CastSrcTy = SIOp0->getType();
11531   const Type* CastDstTy = SrcPTy;
11532   if (isa<PointerType>(CastDstTy)) {
11533     if (CastSrcTy->isInteger())
11534       opcode = Instruction::IntToPtr;
11535   } else if (isa<IntegerType>(CastDstTy)) {
11536     if (isa<PointerType>(SIOp0->getType()))
11537       opcode = Instruction::PtrToInt;
11538   }
11539   
11540   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11541   // emit a GEP to index into its first field.
11542   if (!NewGEPIndices.empty()) {
11543     if (Constant *C = dyn_cast<Constant>(CastOp))
11544       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11545                                               NewGEPIndices.size());
11546     else
11547       CastOp = IC.InsertNewInstBefore(
11548               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11549                                         NewGEPIndices.end()), SI);
11550   }
11551   
11552   if (Constant *C = dyn_cast<Constant>(SIOp0))
11553     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11554   else
11555     NewCast = IC.InsertNewInstBefore(
11556       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11557       SI);
11558   return new StoreInst(NewCast, CastOp);
11559 }
11560
11561 /// equivalentAddressValues - Test if A and B will obviously have the same
11562 /// value. This includes recognizing that %t0 and %t1 will have the same
11563 /// value in code like this:
11564 ///   %t0 = getelementptr \@a, 0, 3
11565 ///   store i32 0, i32* %t0
11566 ///   %t1 = getelementptr \@a, 0, 3
11567 ///   %t2 = load i32* %t1
11568 ///
11569 static bool equivalentAddressValues(Value *A, Value *B) {
11570   // Test if the values are trivially equivalent.
11571   if (A == B) return true;
11572   
11573   // Test if the values come form identical arithmetic instructions.
11574   if (isa<BinaryOperator>(A) ||
11575       isa<CastInst>(A) ||
11576       isa<PHINode>(A) ||
11577       isa<GetElementPtrInst>(A))
11578     if (Instruction *BI = dyn_cast<Instruction>(B))
11579       if (cast<Instruction>(A)->isIdenticalTo(BI))
11580         return true;
11581   
11582   // Otherwise they may not be equivalent.
11583   return false;
11584 }
11585
11586 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11587 // return the llvm.dbg.declare.
11588 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11589   if (!V->hasNUses(2))
11590     return 0;
11591   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11592        UI != E; ++UI) {
11593     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11594       return DI;
11595     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11596       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11597         return DI;
11598       }
11599   }
11600   return 0;
11601 }
11602
11603 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11604   Value *Val = SI.getOperand(0);
11605   Value *Ptr = SI.getOperand(1);
11606
11607   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11608     EraseInstFromFunction(SI);
11609     ++NumCombined;
11610     return 0;
11611   }
11612   
11613   // If the RHS is an alloca with a single use, zapify the store, making the
11614   // alloca dead.
11615   // If the RHS is an alloca with a two uses, the other one being a 
11616   // llvm.dbg.declare, zapify the store and the declare, making the
11617   // alloca dead.  We must do this to prevent declare's from affecting
11618   // codegen.
11619   if (!SI.isVolatile()) {
11620     if (Ptr->hasOneUse()) {
11621       if (isa<AllocaInst>(Ptr)) {
11622         EraseInstFromFunction(SI);
11623         ++NumCombined;
11624         return 0;
11625       }
11626       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11627         if (isa<AllocaInst>(GEP->getOperand(0))) {
11628           if (GEP->getOperand(0)->hasOneUse()) {
11629             EraseInstFromFunction(SI);
11630             ++NumCombined;
11631             return 0;
11632           }
11633           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11634             EraseInstFromFunction(*DI);
11635             EraseInstFromFunction(SI);
11636             ++NumCombined;
11637             return 0;
11638           }
11639         }
11640       }
11641     }
11642     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11643       EraseInstFromFunction(*DI);
11644       EraseInstFromFunction(SI);
11645       ++NumCombined;
11646       return 0;
11647     }
11648   }
11649
11650   // Attempt to improve the alignment.
11651   unsigned KnownAlign =
11652     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11653   if (KnownAlign >
11654       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11655                                 SI.getAlignment()))
11656     SI.setAlignment(KnownAlign);
11657
11658   // Do really simple DSE, to catch cases where there are several consecutive
11659   // stores to the same location, separated by a few arithmetic operations. This
11660   // situation often occurs with bitfield accesses.
11661   BasicBlock::iterator BBI = &SI;
11662   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11663        --ScanInsts) {
11664     --BBI;
11665     // Don't count debug info directives, lest they affect codegen,
11666     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11667     // It is necessary for correctness to skip those that feed into a
11668     // llvm.dbg.declare, as these are not present when debugging is off.
11669     if (isa<DbgInfoIntrinsic>(BBI) ||
11670         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11671       ScanInsts++;
11672       continue;
11673     }    
11674     
11675     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11676       // Prev store isn't volatile, and stores to the same location?
11677       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11678                                                           SI.getOperand(1))) {
11679         ++NumDeadStore;
11680         ++BBI;
11681         EraseInstFromFunction(*PrevSI);
11682         continue;
11683       }
11684       break;
11685     }
11686     
11687     // If this is a load, we have to stop.  However, if the loaded value is from
11688     // the pointer we're loading and is producing the pointer we're storing,
11689     // then *this* store is dead (X = load P; store X -> P).
11690     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11691       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11692           !SI.isVolatile()) {
11693         EraseInstFromFunction(SI);
11694         ++NumCombined;
11695         return 0;
11696       }
11697       // Otherwise, this is a load from some other location.  Stores before it
11698       // may not be dead.
11699       break;
11700     }
11701     
11702     // Don't skip over loads or things that can modify memory.
11703     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11704       break;
11705   }
11706   
11707   
11708   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11709
11710   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11711   if (isa<ConstantPointerNull>(Ptr)) {
11712     if (!isa<UndefValue>(Val)) {
11713       SI.setOperand(0, UndefValue::get(Val->getType()));
11714       if (Instruction *U = dyn_cast<Instruction>(Val))
11715         AddToWorkList(U);  // Dropped a use.
11716       ++NumCombined;
11717     }
11718     return 0;  // Do not modify these!
11719   }
11720
11721   // store undef, Ptr -> noop
11722   if (isa<UndefValue>(Val)) {
11723     EraseInstFromFunction(SI);
11724     ++NumCombined;
11725     return 0;
11726   }
11727
11728   // If the pointer destination is a cast, see if we can fold the cast into the
11729   // source instead.
11730   if (isa<CastInst>(Ptr))
11731     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11732       return Res;
11733   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11734     if (CE->isCast())
11735       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11736         return Res;
11737
11738   
11739   // If this store is the last instruction in the basic block (possibly
11740   // excepting debug info instructions and the pointer bitcasts that feed
11741   // into them), and if the block ends with an unconditional branch, try
11742   // to move it to the successor block.
11743   BBI = &SI; 
11744   do {
11745     ++BBI;
11746   } while (isa<DbgInfoIntrinsic>(BBI) ||
11747            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11748   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11749     if (BI->isUnconditional())
11750       if (SimplifyStoreAtEndOfBlock(SI))
11751         return 0;  // xform done!
11752   
11753   return 0;
11754 }
11755
11756 /// SimplifyStoreAtEndOfBlock - Turn things like:
11757 ///   if () { *P = v1; } else { *P = v2 }
11758 /// into a phi node with a store in the successor.
11759 ///
11760 /// Simplify things like:
11761 ///   *P = v1; if () { *P = v2; }
11762 /// into a phi node with a store in the successor.
11763 ///
11764 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11765   BasicBlock *StoreBB = SI.getParent();
11766   
11767   // Check to see if the successor block has exactly two incoming edges.  If
11768   // so, see if the other predecessor contains a store to the same location.
11769   // if so, insert a PHI node (if needed) and move the stores down.
11770   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11771   
11772   // Determine whether Dest has exactly two predecessors and, if so, compute
11773   // the other predecessor.
11774   pred_iterator PI = pred_begin(DestBB);
11775   BasicBlock *OtherBB = 0;
11776   if (*PI != StoreBB)
11777     OtherBB = *PI;
11778   ++PI;
11779   if (PI == pred_end(DestBB))
11780     return false;
11781   
11782   if (*PI != StoreBB) {
11783     if (OtherBB)
11784       return false;
11785     OtherBB = *PI;
11786   }
11787   if (++PI != pred_end(DestBB))
11788     return false;
11789
11790   // Bail out if all the relevant blocks aren't distinct (this can happen,
11791   // for example, if SI is in an infinite loop)
11792   if (StoreBB == DestBB || OtherBB == DestBB)
11793     return false;
11794
11795   // Verify that the other block ends in a branch and is not otherwise empty.
11796   BasicBlock::iterator BBI = OtherBB->getTerminator();
11797   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11798   if (!OtherBr || BBI == OtherBB->begin())
11799     return false;
11800   
11801   // If the other block ends in an unconditional branch, check for the 'if then
11802   // else' case.  there is an instruction before the branch.
11803   StoreInst *OtherStore = 0;
11804   if (OtherBr->isUnconditional()) {
11805     --BBI;
11806     // Skip over debugging info.
11807     while (isa<DbgInfoIntrinsic>(BBI) ||
11808            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11809       if (BBI==OtherBB->begin())
11810         return false;
11811       --BBI;
11812     }
11813     // If this isn't a store, or isn't a store to the same location, bail out.
11814     OtherStore = dyn_cast<StoreInst>(BBI);
11815     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11816       return false;
11817   } else {
11818     // Otherwise, the other block ended with a conditional branch. If one of the
11819     // destinations is StoreBB, then we have the if/then case.
11820     if (OtherBr->getSuccessor(0) != StoreBB && 
11821         OtherBr->getSuccessor(1) != StoreBB)
11822       return false;
11823     
11824     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11825     // if/then triangle.  See if there is a store to the same ptr as SI that
11826     // lives in OtherBB.
11827     for (;; --BBI) {
11828       // Check to see if we find the matching store.
11829       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11830         if (OtherStore->getOperand(1) != SI.getOperand(1))
11831           return false;
11832         break;
11833       }
11834       // If we find something that may be using or overwriting the stored
11835       // value, or if we run out of instructions, we can't do the xform.
11836       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11837           BBI == OtherBB->begin())
11838         return false;
11839     }
11840     
11841     // In order to eliminate the store in OtherBr, we have to
11842     // make sure nothing reads or overwrites the stored value in
11843     // StoreBB.
11844     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11845       // FIXME: This should really be AA driven.
11846       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11847         return false;
11848     }
11849   }
11850   
11851   // Insert a PHI node now if we need it.
11852   Value *MergedVal = OtherStore->getOperand(0);
11853   if (MergedVal != SI.getOperand(0)) {
11854     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11855     PN->reserveOperandSpace(2);
11856     PN->addIncoming(SI.getOperand(0), SI.getParent());
11857     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11858     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11859   }
11860   
11861   // Advance to a place where it is safe to insert the new store and
11862   // insert it.
11863   BBI = DestBB->getFirstNonPHI();
11864   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11865                                     OtherStore->isVolatile()), *BBI);
11866   
11867   // Nuke the old stores.
11868   EraseInstFromFunction(SI);
11869   EraseInstFromFunction(*OtherStore);
11870   ++NumCombined;
11871   return true;
11872 }
11873
11874
11875 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11876   // Change br (not X), label True, label False to: br X, label False, True
11877   Value *X = 0;
11878   BasicBlock *TrueDest;
11879   BasicBlock *FalseDest;
11880   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11881       !isa<Constant>(X)) {
11882     // Swap Destinations and condition...
11883     BI.setCondition(X);
11884     BI.setSuccessor(0, FalseDest);
11885     BI.setSuccessor(1, TrueDest);
11886     return &BI;
11887   }
11888
11889   // Cannonicalize fcmp_one -> fcmp_oeq
11890   FCmpInst::Predicate FPred; Value *Y;
11891   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11892                              TrueDest, FalseDest)))
11893     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11894          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11895       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11896       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11897       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11898       NewSCC->takeName(I);
11899       // Swap Destinations and condition...
11900       BI.setCondition(NewSCC);
11901       BI.setSuccessor(0, FalseDest);
11902       BI.setSuccessor(1, TrueDest);
11903       RemoveFromWorkList(I);
11904       I->eraseFromParent();
11905       AddToWorkList(NewSCC);
11906       return &BI;
11907     }
11908
11909   // Cannonicalize icmp_ne -> icmp_eq
11910   ICmpInst::Predicate IPred;
11911   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11912                       TrueDest, FalseDest)))
11913     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11914          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11915          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11916       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11917       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11918       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11919       NewSCC->takeName(I);
11920       // Swap Destinations and condition...
11921       BI.setCondition(NewSCC);
11922       BI.setSuccessor(0, FalseDest);
11923       BI.setSuccessor(1, TrueDest);
11924       RemoveFromWorkList(I);
11925       I->eraseFromParent();;
11926       AddToWorkList(NewSCC);
11927       return &BI;
11928     }
11929
11930   return 0;
11931 }
11932
11933 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11934   Value *Cond = SI.getCondition();
11935   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11936     if (I->getOpcode() == Instruction::Add)
11937       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11938         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11939         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11940           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11941                                                 AddRHS));
11942         SI.setOperand(0, I->getOperand(0));
11943         AddToWorkList(I);
11944         return &SI;
11945       }
11946   }
11947   return 0;
11948 }
11949
11950 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11951   Value *Agg = EV.getAggregateOperand();
11952
11953   if (!EV.hasIndices())
11954     return ReplaceInstUsesWith(EV, Agg);
11955
11956   if (Constant *C = dyn_cast<Constant>(Agg)) {
11957     if (isa<UndefValue>(C))
11958       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11959       
11960     if (isa<ConstantAggregateZero>(C))
11961       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11962
11963     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11964       // Extract the element indexed by the first index out of the constant
11965       Value *V = C->getOperand(*EV.idx_begin());
11966       if (EV.getNumIndices() > 1)
11967         // Extract the remaining indices out of the constant indexed by the
11968         // first index
11969         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11970       else
11971         return ReplaceInstUsesWith(EV, V);
11972     }
11973     return 0; // Can't handle other constants
11974   } 
11975   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11976     // We're extracting from an insertvalue instruction, compare the indices
11977     const unsigned *exti, *exte, *insi, *inse;
11978     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11979          exte = EV.idx_end(), inse = IV->idx_end();
11980          exti != exte && insi != inse;
11981          ++exti, ++insi) {
11982       if (*insi != *exti)
11983         // The insert and extract both reference distinctly different elements.
11984         // This means the extract is not influenced by the insert, and we can
11985         // replace the aggregate operand of the extract with the aggregate
11986         // operand of the insert. i.e., replace
11987         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11988         // %E = extractvalue { i32, { i32 } } %I, 0
11989         // with
11990         // %E = extractvalue { i32, { i32 } } %A, 0
11991         return ExtractValueInst::Create(IV->getAggregateOperand(),
11992                                         EV.idx_begin(), EV.idx_end());
11993     }
11994     if (exti == exte && insi == inse)
11995       // Both iterators are at the end: Index lists are identical. Replace
11996       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11997       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11998       // with "i32 42"
11999       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12000     if (exti == exte) {
12001       // The extract list is a prefix of the insert list. i.e. replace
12002       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12003       // %E = extractvalue { i32, { i32 } } %I, 1
12004       // with
12005       // %X = extractvalue { i32, { i32 } } %A, 1
12006       // %E = insertvalue { i32 } %X, i32 42, 0
12007       // by switching the order of the insert and extract (though the
12008       // insertvalue should be left in, since it may have other uses).
12009       Value *NewEV = InsertNewInstBefore(
12010         ExtractValueInst::Create(IV->getAggregateOperand(),
12011                                  EV.idx_begin(), EV.idx_end()),
12012         EV);
12013       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12014                                      insi, inse);
12015     }
12016     if (insi == inse)
12017       // The insert list is a prefix of the extract list
12018       // We can simply remove the common indices from the extract and make it
12019       // operate on the inserted value instead of the insertvalue result.
12020       // i.e., replace
12021       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12022       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12023       // with
12024       // %E extractvalue { i32 } { i32 42 }, 0
12025       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12026                                       exti, exte);
12027   }
12028   // Can't simplify extracts from other values. Note that nested extracts are
12029   // already simplified implicitely by the above (extract ( extract (insert) )
12030   // will be translated into extract ( insert ( extract ) ) first and then just
12031   // the value inserted, if appropriate).
12032   return 0;
12033 }
12034
12035 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12036 /// is to leave as a vector operation.
12037 static bool CheapToScalarize(Value *V, bool isConstant) {
12038   if (isa<ConstantAggregateZero>(V)) 
12039     return true;
12040   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12041     if (isConstant) return true;
12042     // If all elts are the same, we can extract.
12043     Constant *Op0 = C->getOperand(0);
12044     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12045       if (C->getOperand(i) != Op0)
12046         return false;
12047     return true;
12048   }
12049   Instruction *I = dyn_cast<Instruction>(V);
12050   if (!I) return false;
12051   
12052   // Insert element gets simplified to the inserted element or is deleted if
12053   // this is constant idx extract element and its a constant idx insertelt.
12054   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12055       isa<ConstantInt>(I->getOperand(2)))
12056     return true;
12057   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12058     return true;
12059   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12060     if (BO->hasOneUse() &&
12061         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12062          CheapToScalarize(BO->getOperand(1), isConstant)))
12063       return true;
12064   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12065     if (CI->hasOneUse() &&
12066         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12067          CheapToScalarize(CI->getOperand(1), isConstant)))
12068       return true;
12069   
12070   return false;
12071 }
12072
12073 /// Read and decode a shufflevector mask.
12074 ///
12075 /// It turns undef elements into values that are larger than the number of
12076 /// elements in the input.
12077 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12078   unsigned NElts = SVI->getType()->getNumElements();
12079   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12080     return std::vector<unsigned>(NElts, 0);
12081   if (isa<UndefValue>(SVI->getOperand(2)))
12082     return std::vector<unsigned>(NElts, 2*NElts);
12083
12084   std::vector<unsigned> Result;
12085   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12086   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12087     if (isa<UndefValue>(*i))
12088       Result.push_back(NElts*2);  // undef -> 8
12089     else
12090       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12091   return Result;
12092 }
12093
12094 /// FindScalarElement - Given a vector and an element number, see if the scalar
12095 /// value is already around as a register, for example if it were inserted then
12096 /// extracted from the vector.
12097 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12098   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12099   const VectorType *PTy = cast<VectorType>(V->getType());
12100   unsigned Width = PTy->getNumElements();
12101   if (EltNo >= Width)  // Out of range access.
12102     return UndefValue::get(PTy->getElementType());
12103   
12104   if (isa<UndefValue>(V))
12105     return UndefValue::get(PTy->getElementType());
12106   else if (isa<ConstantAggregateZero>(V))
12107     return Constant::getNullValue(PTy->getElementType());
12108   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12109     return CP->getOperand(EltNo);
12110   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12111     // If this is an insert to a variable element, we don't know what it is.
12112     if (!isa<ConstantInt>(III->getOperand(2))) 
12113       return 0;
12114     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12115     
12116     // If this is an insert to the element we are looking for, return the
12117     // inserted value.
12118     if (EltNo == IIElt) 
12119       return III->getOperand(1);
12120     
12121     // Otherwise, the insertelement doesn't modify the value, recurse on its
12122     // vector input.
12123     return FindScalarElement(III->getOperand(0), EltNo);
12124   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12125     unsigned LHSWidth =
12126       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12127     unsigned InEl = getShuffleMask(SVI)[EltNo];
12128     if (InEl < LHSWidth)
12129       return FindScalarElement(SVI->getOperand(0), InEl);
12130     else if (InEl < LHSWidth*2)
12131       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12132     else
12133       return UndefValue::get(PTy->getElementType());
12134   }
12135   
12136   // Otherwise, we don't know.
12137   return 0;
12138 }
12139
12140 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12141   // If vector val is undef, replace extract with scalar undef.
12142   if (isa<UndefValue>(EI.getOperand(0)))
12143     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12144
12145   // If vector val is constant 0, replace extract with scalar 0.
12146   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12147     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12148   
12149   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12150     // If vector val is constant with all elements the same, replace EI with
12151     // that element. When the elements are not identical, we cannot replace yet
12152     // (we do that below, but only when the index is constant).
12153     Constant *op0 = C->getOperand(0);
12154     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12155       if (C->getOperand(i) != op0) {
12156         op0 = 0; 
12157         break;
12158       }
12159     if (op0)
12160       return ReplaceInstUsesWith(EI, op0);
12161   }
12162   
12163   // If extracting a specified index from the vector, see if we can recursively
12164   // find a previously computed scalar that was inserted into the vector.
12165   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12166     unsigned IndexVal = IdxC->getZExtValue();
12167     unsigned VectorWidth = 
12168       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12169       
12170     // If this is extracting an invalid index, turn this into undef, to avoid
12171     // crashing the code below.
12172     if (IndexVal >= VectorWidth)
12173       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12174     
12175     // This instruction only demands the single element from the input vector.
12176     // If the input vector has a single use, simplify it based on this use
12177     // property.
12178     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12179       APInt UndefElts(VectorWidth, 0);
12180       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12181       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12182                                                 DemandedMask, UndefElts)) {
12183         EI.setOperand(0, V);
12184         return &EI;
12185       }
12186     }
12187     
12188     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12189       return ReplaceInstUsesWith(EI, Elt);
12190     
12191     // If the this extractelement is directly using a bitcast from a vector of
12192     // the same number of elements, see if we can find the source element from
12193     // it.  In this case, we will end up needing to bitcast the scalars.
12194     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12195       if (const VectorType *VT = 
12196               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12197         if (VT->getNumElements() == VectorWidth)
12198           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12199             return new BitCastInst(Elt, EI.getType());
12200     }
12201   }
12202   
12203   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12204     if (I->hasOneUse()) {
12205       // Push extractelement into predecessor operation if legal and
12206       // profitable to do so
12207       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12208         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12209         if (CheapToScalarize(BO, isConstantElt)) {
12210           ExtractElementInst *newEI0 = 
12211             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12212                                    EI.getName()+".lhs");
12213           ExtractElementInst *newEI1 =
12214             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12215                                    EI.getName()+".rhs");
12216           InsertNewInstBefore(newEI0, EI);
12217           InsertNewInstBefore(newEI1, EI);
12218           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12219         }
12220       } else if (isa<LoadInst>(I)) {
12221         unsigned AS = 
12222           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12223         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12224                                          PointerType::get(EI.getType(), AS),EI);
12225         GetElementPtrInst *GEP =
12226           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12227         InsertNewInstBefore(GEP, EI);
12228         return new LoadInst(GEP);
12229       }
12230     }
12231     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12232       // Extracting the inserted element?
12233       if (IE->getOperand(2) == EI.getOperand(1))
12234         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12235       // If the inserted and extracted elements are constants, they must not
12236       // be the same value, extract from the pre-inserted value instead.
12237       if (isa<Constant>(IE->getOperand(2)) &&
12238           isa<Constant>(EI.getOperand(1))) {
12239         AddUsesToWorkList(EI);
12240         EI.setOperand(0, IE->getOperand(0));
12241         return &EI;
12242       }
12243     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12244       // If this is extracting an element from a shufflevector, figure out where
12245       // it came from and extract from the appropriate input element instead.
12246       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12247         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12248         Value *Src;
12249         unsigned LHSWidth =
12250           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12251
12252         if (SrcIdx < LHSWidth)
12253           Src = SVI->getOperand(0);
12254         else if (SrcIdx < LHSWidth*2) {
12255           SrcIdx -= LHSWidth;
12256           Src = SVI->getOperand(1);
12257         } else {
12258           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12259         }
12260         return new ExtractElementInst(Src, SrcIdx);
12261       }
12262     }
12263   }
12264   return 0;
12265 }
12266
12267 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12268 /// elements from either LHS or RHS, return the shuffle mask and true. 
12269 /// Otherwise, return false.
12270 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12271                                          std::vector<Constant*> &Mask) {
12272   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12273          "Invalid CollectSingleShuffleElements");
12274   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12275
12276   if (isa<UndefValue>(V)) {
12277     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12278     return true;
12279   } else if (V == LHS) {
12280     for (unsigned i = 0; i != NumElts; ++i)
12281       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12282     return true;
12283   } else if (V == RHS) {
12284     for (unsigned i = 0; i != NumElts; ++i)
12285       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12286     return true;
12287   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12288     // If this is an insert of an extract from some other vector, include it.
12289     Value *VecOp    = IEI->getOperand(0);
12290     Value *ScalarOp = IEI->getOperand(1);
12291     Value *IdxOp    = IEI->getOperand(2);
12292     
12293     if (!isa<ConstantInt>(IdxOp))
12294       return false;
12295     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12296     
12297     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12298       // Okay, we can handle this if the vector we are insertinting into is
12299       // transitively ok.
12300       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12301         // If so, update the mask to reflect the inserted undef.
12302         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12303         return true;
12304       }      
12305     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12306       if (isa<ConstantInt>(EI->getOperand(1)) &&
12307           EI->getOperand(0)->getType() == V->getType()) {
12308         unsigned ExtractedIdx =
12309           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12310         
12311         // This must be extracting from either LHS or RHS.
12312         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12313           // Okay, we can handle this if the vector we are insertinting into is
12314           // transitively ok.
12315           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12316             // If so, update the mask to reflect the inserted value.
12317             if (EI->getOperand(0) == LHS) {
12318               Mask[InsertedIdx % NumElts] = 
12319                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12320             } else {
12321               assert(EI->getOperand(0) == RHS);
12322               Mask[InsertedIdx % NumElts] = 
12323                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12324               
12325             }
12326             return true;
12327           }
12328         }
12329       }
12330     }
12331   }
12332   // TODO: Handle shufflevector here!
12333   
12334   return false;
12335 }
12336
12337 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12338 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12339 /// that computes V and the LHS value of the shuffle.
12340 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12341                                      Value *&RHS) {
12342   assert(isa<VectorType>(V->getType()) && 
12343          (RHS == 0 || V->getType() == RHS->getType()) &&
12344          "Invalid shuffle!");
12345   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12346
12347   if (isa<UndefValue>(V)) {
12348     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12349     return V;
12350   } else if (isa<ConstantAggregateZero>(V)) {
12351     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12352     return V;
12353   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12354     // If this is an insert of an extract from some other vector, include it.
12355     Value *VecOp    = IEI->getOperand(0);
12356     Value *ScalarOp = IEI->getOperand(1);
12357     Value *IdxOp    = IEI->getOperand(2);
12358     
12359     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12360       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12361           EI->getOperand(0)->getType() == V->getType()) {
12362         unsigned ExtractedIdx =
12363           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12364         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12365         
12366         // Either the extracted from or inserted into vector must be RHSVec,
12367         // otherwise we'd end up with a shuffle of three inputs.
12368         if (EI->getOperand(0) == RHS || RHS == 0) {
12369           RHS = EI->getOperand(0);
12370           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12371           Mask[InsertedIdx % NumElts] = 
12372             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12373           return V;
12374         }
12375         
12376         if (VecOp == RHS) {
12377           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12378           // Everything but the extracted element is replaced with the RHS.
12379           for (unsigned i = 0; i != NumElts; ++i) {
12380             if (i != InsertedIdx)
12381               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12382           }
12383           return V;
12384         }
12385         
12386         // If this insertelement is a chain that comes from exactly these two
12387         // vectors, return the vector and the effective shuffle.
12388         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12389           return EI->getOperand(0);
12390         
12391       }
12392     }
12393   }
12394   // TODO: Handle shufflevector here!
12395   
12396   // Otherwise, can't do anything fancy.  Return an identity vector.
12397   for (unsigned i = 0; i != NumElts; ++i)
12398     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12399   return V;
12400 }
12401
12402 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12403   Value *VecOp    = IE.getOperand(0);
12404   Value *ScalarOp = IE.getOperand(1);
12405   Value *IdxOp    = IE.getOperand(2);
12406   
12407   // Inserting an undef or into an undefined place, remove this.
12408   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12409     ReplaceInstUsesWith(IE, VecOp);
12410   
12411   // If the inserted element was extracted from some other vector, and if the 
12412   // indexes are constant, try to turn this into a shufflevector operation.
12413   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12414     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12415         EI->getOperand(0)->getType() == IE.getType()) {
12416       unsigned NumVectorElts = IE.getType()->getNumElements();
12417       unsigned ExtractedIdx =
12418         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12419       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12420       
12421       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12422         return ReplaceInstUsesWith(IE, VecOp);
12423       
12424       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12425         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12426       
12427       // If we are extracting a value from a vector, then inserting it right
12428       // back into the same place, just use the input vector.
12429       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12430         return ReplaceInstUsesWith(IE, VecOp);      
12431       
12432       // We could theoretically do this for ANY input.  However, doing so could
12433       // turn chains of insertelement instructions into a chain of shufflevector
12434       // instructions, and right now we do not merge shufflevectors.  As such,
12435       // only do this in a situation where it is clear that there is benefit.
12436       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12437         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12438         // the values of VecOp, except then one read from EIOp0.
12439         // Build a new shuffle mask.
12440         std::vector<Constant*> Mask;
12441         if (isa<UndefValue>(VecOp))
12442           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12443         else {
12444           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12445           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12446                                                        NumVectorElts));
12447         } 
12448         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12449         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12450                                      ConstantVector::get(Mask));
12451       }
12452       
12453       // If this insertelement isn't used by some other insertelement, turn it
12454       // (and any insertelements it points to), into one big shuffle.
12455       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12456         std::vector<Constant*> Mask;
12457         Value *RHS = 0;
12458         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12459         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12460         // We now have a shuffle of LHS, RHS, Mask.
12461         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12462       }
12463     }
12464   }
12465
12466   return 0;
12467 }
12468
12469
12470 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12471   Value *LHS = SVI.getOperand(0);
12472   Value *RHS = SVI.getOperand(1);
12473   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12474
12475   bool MadeChange = false;
12476
12477   // Undefined shuffle mask -> undefined value.
12478   if (isa<UndefValue>(SVI.getOperand(2)))
12479     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12480
12481   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12482
12483   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12484     return 0;
12485
12486   APInt UndefElts(VWidth, 0);
12487   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12488   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12489     LHS = SVI.getOperand(0);
12490     RHS = SVI.getOperand(1);
12491     MadeChange = true;
12492   }
12493   
12494   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12495   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12496   if (LHS == RHS || isa<UndefValue>(LHS)) {
12497     if (isa<UndefValue>(LHS) && LHS == RHS) {
12498       // shuffle(undef,undef,mask) -> undef.
12499       return ReplaceInstUsesWith(SVI, LHS);
12500     }
12501     
12502     // Remap any references to RHS to use LHS.
12503     std::vector<Constant*> Elts;
12504     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12505       if (Mask[i] >= 2*e)
12506         Elts.push_back(UndefValue::get(Type::Int32Ty));
12507       else {
12508         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12509             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12510           Mask[i] = 2*e;     // Turn into undef.
12511           Elts.push_back(UndefValue::get(Type::Int32Ty));
12512         } else {
12513           Mask[i] = Mask[i] % e;  // Force to LHS.
12514           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12515         }
12516       }
12517     }
12518     SVI.setOperand(0, SVI.getOperand(1));
12519     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12520     SVI.setOperand(2, ConstantVector::get(Elts));
12521     LHS = SVI.getOperand(0);
12522     RHS = SVI.getOperand(1);
12523     MadeChange = true;
12524   }
12525   
12526   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12527   bool isLHSID = true, isRHSID = true;
12528     
12529   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12530     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12531     // Is this an identity shuffle of the LHS value?
12532     isLHSID &= (Mask[i] == i);
12533       
12534     // Is this an identity shuffle of the RHS value?
12535     isRHSID &= (Mask[i]-e == i);
12536   }
12537
12538   // Eliminate identity shuffles.
12539   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12540   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12541   
12542   // If the LHS is a shufflevector itself, see if we can combine it with this
12543   // one without producing an unusual shuffle.  Here we are really conservative:
12544   // we are absolutely afraid of producing a shuffle mask not in the input
12545   // program, because the code gen may not be smart enough to turn a merged
12546   // shuffle into two specific shuffles: it may produce worse code.  As such,
12547   // we only merge two shuffles if the result is one of the two input shuffle
12548   // masks.  In this case, merging the shuffles just removes one instruction,
12549   // which we know is safe.  This is good for things like turning:
12550   // (splat(splat)) -> splat.
12551   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12552     if (isa<UndefValue>(RHS)) {
12553       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12554
12555       std::vector<unsigned> NewMask;
12556       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12557         if (Mask[i] >= 2*e)
12558           NewMask.push_back(2*e);
12559         else
12560           NewMask.push_back(LHSMask[Mask[i]]);
12561       
12562       // If the result mask is equal to the src shuffle or this shuffle mask, do
12563       // the replacement.
12564       if (NewMask == LHSMask || NewMask == Mask) {
12565         unsigned LHSInNElts =
12566           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12567         std::vector<Constant*> Elts;
12568         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12569           if (NewMask[i] >= LHSInNElts*2) {
12570             Elts.push_back(UndefValue::get(Type::Int32Ty));
12571           } else {
12572             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12573           }
12574         }
12575         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12576                                      LHSSVI->getOperand(1),
12577                                      ConstantVector::get(Elts));
12578       }
12579     }
12580   }
12581
12582   return MadeChange ? &SVI : 0;
12583 }
12584
12585
12586
12587
12588 /// TryToSinkInstruction - Try to move the specified instruction from its
12589 /// current block into the beginning of DestBlock, which can only happen if it's
12590 /// safe to move the instruction past all of the instructions between it and the
12591 /// end of its block.
12592 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12593   assert(I->hasOneUse() && "Invariants didn't hold!");
12594
12595   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12596   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12597     return false;
12598
12599   // Do not sink alloca instructions out of the entry block.
12600   if (isa<AllocaInst>(I) && I->getParent() ==
12601         &DestBlock->getParent()->getEntryBlock())
12602     return false;
12603
12604   // We can only sink load instructions if there is nothing between the load and
12605   // the end of block that could change the value.
12606   if (I->mayReadFromMemory()) {
12607     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12608          Scan != E; ++Scan)
12609       if (Scan->mayWriteToMemory())
12610         return false;
12611   }
12612
12613   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12614
12615   CopyPrecedingStopPoint(I, InsertPos);
12616   I->moveBefore(InsertPos);
12617   ++NumSunkInst;
12618   return true;
12619 }
12620
12621
12622 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12623 /// all reachable code to the worklist.
12624 ///
12625 /// This has a couple of tricks to make the code faster and more powerful.  In
12626 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12627 /// them to the worklist (this significantly speeds up instcombine on code where
12628 /// many instructions are dead or constant).  Additionally, if we find a branch
12629 /// whose condition is a known constant, we only visit the reachable successors.
12630 ///
12631 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12632                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12633                                        InstCombiner &IC,
12634                                        const TargetData *TD) {
12635   SmallVector<BasicBlock*, 256> Worklist;
12636   Worklist.push_back(BB);
12637
12638   while (!Worklist.empty()) {
12639     BB = Worklist.back();
12640     Worklist.pop_back();
12641     
12642     // We have now visited this block!  If we've already been here, ignore it.
12643     if (!Visited.insert(BB)) continue;
12644
12645     DbgInfoIntrinsic *DBI_Prev = NULL;
12646     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12647       Instruction *Inst = BBI++;
12648       
12649       // DCE instruction if trivially dead.
12650       if (isInstructionTriviallyDead(Inst)) {
12651         ++NumDeadInst;
12652         DOUT << "IC: DCE: " << *Inst;
12653         Inst->eraseFromParent();
12654         continue;
12655       }
12656       
12657       // ConstantProp instruction if trivially constant.
12658       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12659         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12660         Inst->replaceAllUsesWith(C);
12661         ++NumConstProp;
12662         Inst->eraseFromParent();
12663         continue;
12664       }
12665      
12666       // If there are two consecutive llvm.dbg.stoppoint calls then
12667       // it is likely that the optimizer deleted code in between these
12668       // two intrinsics. 
12669       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12670       if (DBI_Next) {
12671         if (DBI_Prev
12672             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12673             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12674           IC.RemoveFromWorkList(DBI_Prev);
12675           DBI_Prev->eraseFromParent();
12676         }
12677         DBI_Prev = DBI_Next;
12678       } else {
12679         DBI_Prev = 0;
12680       }
12681
12682       IC.AddToWorkList(Inst);
12683     }
12684
12685     // Recursively visit successors.  If this is a branch or switch on a
12686     // constant, only visit the reachable successor.
12687     TerminatorInst *TI = BB->getTerminator();
12688     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12689       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12690         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12691         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12692         Worklist.push_back(ReachableBB);
12693         continue;
12694       }
12695     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12696       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12697         // See if this is an explicit destination.
12698         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12699           if (SI->getCaseValue(i) == Cond) {
12700             BasicBlock *ReachableBB = SI->getSuccessor(i);
12701             Worklist.push_back(ReachableBB);
12702             continue;
12703           }
12704         
12705         // Otherwise it is the default destination.
12706         Worklist.push_back(SI->getSuccessor(0));
12707         continue;
12708       }
12709     }
12710     
12711     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12712       Worklist.push_back(TI->getSuccessor(i));
12713   }
12714 }
12715
12716 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12717   bool Changed = false;
12718   TD = &getAnalysis<TargetData>();
12719   
12720   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12721              << F.getNameStr() << "\n");
12722
12723   {
12724     // Do a depth-first traversal of the function, populate the worklist with
12725     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12726     // track of which blocks we visit.
12727     SmallPtrSet<BasicBlock*, 64> Visited;
12728     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12729
12730     // Do a quick scan over the function.  If we find any blocks that are
12731     // unreachable, remove any instructions inside of them.  This prevents
12732     // the instcombine code from having to deal with some bad special cases.
12733     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12734       if (!Visited.count(BB)) {
12735         Instruction *Term = BB->getTerminator();
12736         while (Term != BB->begin()) {   // Remove instrs bottom-up
12737           BasicBlock::iterator I = Term; --I;
12738
12739           DOUT << "IC: DCE: " << *I;
12740           // A debug intrinsic shouldn't force another iteration if we weren't
12741           // going to do one without it.
12742           if (!isa<DbgInfoIntrinsic>(I)) {
12743             ++NumDeadInst;
12744             Changed = true;
12745           }
12746           if (!I->use_empty())
12747             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12748           I->eraseFromParent();
12749         }
12750       }
12751   }
12752
12753   while (!Worklist.empty()) {
12754     Instruction *I = RemoveOneFromWorkList();
12755     if (I == 0) continue;  // skip null values.
12756
12757     // Check to see if we can DCE the instruction.
12758     if (isInstructionTriviallyDead(I)) {
12759       // Add operands to the worklist.
12760       if (I->getNumOperands() < 4)
12761         AddUsesToWorkList(*I);
12762       ++NumDeadInst;
12763
12764       DOUT << "IC: DCE: " << *I;
12765
12766       I->eraseFromParent();
12767       RemoveFromWorkList(I);
12768       Changed = true;
12769       continue;
12770     }
12771
12772     // Instruction isn't dead, see if we can constant propagate it.
12773     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12774       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12775
12776       // Add operands to the worklist.
12777       AddUsesToWorkList(*I);
12778       ReplaceInstUsesWith(*I, C);
12779
12780       ++NumConstProp;
12781       I->eraseFromParent();
12782       RemoveFromWorkList(I);
12783       Changed = true;
12784       continue;
12785     }
12786
12787     if (TD &&
12788         (I->getType()->getTypeID() == Type::VoidTyID ||
12789          I->isTrapping())) {
12790       // See if we can constant fold its operands.
12791       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12792         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12793           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12794             if (NewC != CE) {
12795               i->set(NewC);
12796               Changed = true;
12797             }
12798     }
12799
12800     // See if we can trivially sink this instruction to a successor basic block.
12801     if (I->hasOneUse()) {
12802       BasicBlock *BB = I->getParent();
12803       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12804       if (UserParent != BB) {
12805         bool UserIsSuccessor = false;
12806         // See if the user is one of our successors.
12807         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12808           if (*SI == UserParent) {
12809             UserIsSuccessor = true;
12810             break;
12811           }
12812
12813         // If the user is one of our immediate successors, and if that successor
12814         // only has us as a predecessors (we'd have to split the critical edge
12815         // otherwise), we can keep going.
12816         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12817             next(pred_begin(UserParent)) == pred_end(UserParent))
12818           // Okay, the CFG is simple enough, try to sink this instruction.
12819           Changed |= TryToSinkInstruction(I, UserParent);
12820       }
12821     }
12822
12823     // Now that we have an instruction, try combining it to simplify it...
12824 #ifndef NDEBUG
12825     std::string OrigI;
12826 #endif
12827     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12828     if (Instruction *Result = visit(*I)) {
12829       ++NumCombined;
12830       // Should we replace the old instruction with a new one?
12831       if (Result != I) {
12832         DOUT << "IC: Old = " << *I
12833              << "    New = " << *Result;
12834
12835         // Everything uses the new instruction now.
12836         I->replaceAllUsesWith(Result);
12837
12838         // Push the new instruction and any users onto the worklist.
12839         AddToWorkList(Result);
12840         AddUsersToWorkList(*Result);
12841
12842         // Move the name to the new instruction first.
12843         Result->takeName(I);
12844
12845         // Insert the new instruction into the basic block...
12846         BasicBlock *InstParent = I->getParent();
12847         BasicBlock::iterator InsertPos = I;
12848
12849         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12850           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12851             ++InsertPos;
12852
12853         InstParent->getInstList().insert(InsertPos, Result);
12854
12855         // Make sure that we reprocess all operands now that we reduced their
12856         // use counts.
12857         AddUsesToWorkList(*I);
12858
12859         // Instructions can end up on the worklist more than once.  Make sure
12860         // we do not process an instruction that has been deleted.
12861         RemoveFromWorkList(I);
12862
12863         // Erase the old instruction.
12864         InstParent->getInstList().erase(I);
12865       } else {
12866 #ifndef NDEBUG
12867         DOUT << "IC: Mod = " << OrigI
12868              << "    New = " << *I;
12869 #endif
12870
12871         // If the instruction was modified, it's possible that it is now dead.
12872         // if so, remove it.
12873         if (isInstructionTriviallyDead(I)) {
12874           // Make sure we process all operands now that we are reducing their
12875           // use counts.
12876           AddUsesToWorkList(*I);
12877
12878           // Instructions may end up in the worklist more than once.  Erase all
12879           // occurrences of this instruction.
12880           RemoveFromWorkList(I);
12881           I->eraseFromParent();
12882         } else {
12883           AddToWorkList(I);
12884           AddUsersToWorkList(*I);
12885         }
12886       }
12887       Changed = true;
12888     }
12889   }
12890
12891   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12892     
12893   // Do an explicit clear, this shrinks the map if needed.
12894   WorklistMap.clear();
12895   return Changed;
12896 }
12897
12898
12899 bool InstCombiner::runOnFunction(Function &F) {
12900   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12901   
12902   bool EverMadeChange = false;
12903
12904   // Iterate while there is work to do.
12905   unsigned Iteration = 0;
12906   while (DoOneIteration(F, Iteration++))
12907     EverMadeChange = true;
12908   return EverMadeChange;
12909 }
12910
12911 FunctionPass *llvm::createInstructionCombiningPass() {
12912   return new InstCombiner();
12913 }