"LLVMContext* " --> "LLVMContext *"
[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/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/ValueTracking.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/ConstantRange.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Support/InstVisitor.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/PatternMatch.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/Statistic.h"
60 #include "llvm/ADT/STLExtras.h"
61 #include <algorithm>
62 #include <climits>
63 #include <sstream>
64 using namespace llvm;
65 using namespace llvm::PatternMatch;
66
67 STATISTIC(NumCombined , "Number of insts combined");
68 STATISTIC(NumConstProp, "Number of constant folds");
69 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
70 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
71 STATISTIC(NumSunkInst , "Number of instructions sunk");
72
73 namespace {
74   class VISIBILITY_HIDDEN InstCombiner
75     : public FunctionPass,
76       public InstVisitor<InstCombiner, Instruction*> {
77     // Worklist of all of the instructions that need to be simplified.
78     SmallVector<Instruction*, 256> Worklist;
79     DenseMap<Instruction*, unsigned> WorklistMap;
80     TargetData *TD;
81     bool MustPreserveLCSSA;
82   public:
83     static char ID; // Pass identification, replacement for typeid
84     InstCombiner() : FunctionPass(&ID) {}
85
86     LLVMContext *getContext() { return Context; }
87
88     /// AddToWorkList - Add the specified instruction to the worklist if it
89     /// isn't already in it.
90     void AddToWorkList(Instruction *I) {
91       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
92         Worklist.push_back(I);
93     }
94     
95     // RemoveFromWorkList - remove I from the worklist if it exists.
96     void RemoveFromWorkList(Instruction *I) {
97       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
98       if (It == WorklistMap.end()) return; // Not in worklist.
99       
100       // Don't bother moving everything down, just null out the slot.
101       Worklist[It->second] = 0;
102       
103       WorklistMap.erase(It);
104     }
105     
106     Instruction *RemoveOneFromWorkList() {
107       Instruction *I = Worklist.back();
108       Worklist.pop_back();
109       WorklistMap.erase(I);
110       return I;
111     }
112
113     
114     /// AddUsersToWorkList - When an instruction is simplified, add all users of
115     /// the instruction to the work lists because they might get more simplified
116     /// now.
117     ///
118     void AddUsersToWorkList(Value &I) {
119       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
120            UI != UE; ++UI)
121         AddToWorkList(cast<Instruction>(*UI));
122     }
123
124     /// AddUsesToWorkList - When an instruction is simplified, add operands to
125     /// the work lists because they might get more simplified now.
126     ///
127     void AddUsesToWorkList(Instruction &I) {
128       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
129         if (Instruction *Op = dyn_cast<Instruction>(*i))
130           AddToWorkList(Op);
131     }
132     
133     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
134     /// dead.  Add all of its operands to the worklist, turning them into
135     /// undef's to reduce the number of uses of those instructions.
136     ///
137     /// Return the specified operand before it is turned into an undef.
138     ///
139     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
140       Value *R = I.getOperand(op);
141       
142       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
143         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
144           AddToWorkList(Op);
145           // Set the operand to undef to drop the use.
146           *i = Context->getUndef(Op->getType());
147         }
148       
149       return R;
150     }
151
152   public:
153     virtual bool runOnFunction(Function &F);
154     
155     bool DoOneIteration(Function &F, unsigned ItNum);
156
157     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
158       AU.addRequired<TargetData>();
159       AU.addPreservedID(LCSSAID);
160       AU.setPreservesCFG();
161     }
162
163     TargetData &getTargetData() const { return *TD; }
164
165     // Visitation implementation - Implement instruction combining for different
166     // instruction types.  The semantics are as follows:
167     // Return Value:
168     //    null        - No change was made
169     //     I          - Change was made, I is still valid, I may be dead though
170     //   otherwise    - Change was made, replace I with returned instruction
171     //
172     Instruction *visitAdd(BinaryOperator &I);
173     Instruction *visitFAdd(BinaryOperator &I);
174     Instruction *visitSub(BinaryOperator &I);
175     Instruction *visitFSub(BinaryOperator &I);
176     Instruction *visitMul(BinaryOperator &I);
177     Instruction *visitFMul(BinaryOperator &I);
178     Instruction *visitURem(BinaryOperator &I);
179     Instruction *visitSRem(BinaryOperator &I);
180     Instruction *visitFRem(BinaryOperator &I);
181     bool SimplifyDivRemOfSelect(BinaryOperator &I);
182     Instruction *commonRemTransforms(BinaryOperator &I);
183     Instruction *commonIRemTransforms(BinaryOperator &I);
184     Instruction *commonDivTransforms(BinaryOperator &I);
185     Instruction *commonIDivTransforms(BinaryOperator &I);
186     Instruction *visitUDiv(BinaryOperator &I);
187     Instruction *visitSDiv(BinaryOperator &I);
188     Instruction *visitFDiv(BinaryOperator &I);
189     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
190     Instruction *visitAnd(BinaryOperator &I);
191     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
192     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
193                                      Value *A, Value *B, Value *C);
194     Instruction *visitOr (BinaryOperator &I);
195     Instruction *visitXor(BinaryOperator &I);
196     Instruction *visitShl(BinaryOperator &I);
197     Instruction *visitAShr(BinaryOperator &I);
198     Instruction *visitLShr(BinaryOperator &I);
199     Instruction *commonShiftTransforms(BinaryOperator &I);
200     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
201                                       Constant *RHSC);
202     Instruction *visitFCmpInst(FCmpInst &I);
203     Instruction *visitICmpInst(ICmpInst &I);
204     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
205     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
206                                                 Instruction *LHS,
207                                                 ConstantInt *RHS);
208     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
209                                 ConstantInt *DivRHS);
210
211     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
212                              ICmpInst::Predicate Cond, Instruction &I);
213     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
214                                      BinaryOperator &I);
215     Instruction *commonCastTransforms(CastInst &CI);
216     Instruction *commonIntCastTransforms(CastInst &CI);
217     Instruction *commonPointerCastTransforms(CastInst &CI);
218     Instruction *visitTrunc(TruncInst &CI);
219     Instruction *visitZExt(ZExtInst &CI);
220     Instruction *visitSExt(SExtInst &CI);
221     Instruction *visitFPTrunc(FPTruncInst &CI);
222     Instruction *visitFPExt(CastInst &CI);
223     Instruction *visitFPToUI(FPToUIInst &FI);
224     Instruction *visitFPToSI(FPToSIInst &FI);
225     Instruction *visitUIToFP(CastInst &CI);
226     Instruction *visitSIToFP(CastInst &CI);
227     Instruction *visitPtrToInt(PtrToIntInst &CI);
228     Instruction *visitIntToPtr(IntToPtrInst &CI);
229     Instruction *visitBitCast(BitCastInst &CI);
230     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
231                                 Instruction *FI);
232     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
233     Instruction *visitSelectInst(SelectInst &SI);
234     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
235     Instruction *visitCallInst(CallInst &CI);
236     Instruction *visitInvokeInst(InvokeInst &II);
237     Instruction *visitPHINode(PHINode &PN);
238     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
239     Instruction *visitAllocationInst(AllocationInst &AI);
240     Instruction *visitFreeInst(FreeInst &FI);
241     Instruction *visitLoadInst(LoadInst &LI);
242     Instruction *visitStoreInst(StoreInst &SI);
243     Instruction *visitBranchInst(BranchInst &BI);
244     Instruction *visitSwitchInst(SwitchInst &SI);
245     Instruction *visitInsertElementInst(InsertElementInst &IE);
246     Instruction *visitExtractElementInst(ExtractElementInst &EI);
247     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
248     Instruction *visitExtractValueInst(ExtractValueInst &EV);
249
250     // visitInstruction - Specify what to return for unhandled instructions...
251     Instruction *visitInstruction(Instruction &I) { return 0; }
252
253   private:
254     Instruction *visitCallSite(CallSite CS);
255     bool transformConstExprCastCall(CallSite CS);
256     Instruction *transformCallThroughTrampoline(CallSite CS);
257     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
258                                    bool DoXform = true);
259     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
260     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
261
262
263   public:
264     // InsertNewInstBefore - insert an instruction New before instruction Old
265     // in the program.  Add the new instruction to the worklist.
266     //
267     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
268       assert(New && New->getParent() == 0 &&
269              "New instruction already inserted into a basic block!");
270       BasicBlock *BB = Old.getParent();
271       BB->getInstList().insert(&Old, New);  // Insert inst
272       AddToWorkList(New);
273       return New;
274     }
275
276     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
277     /// This also adds the cast to the worklist.  Finally, this returns the
278     /// cast.
279     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
280                             Instruction &Pos) {
281       if (V->getType() == Ty) return V;
282
283       if (Constant *CV = dyn_cast<Constant>(V))
284         return Context->getConstantExprCast(opc, CV, Ty);
285       
286       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
287       AddToWorkList(C);
288       return C;
289     }
290         
291     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
292       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
293     }
294
295
296     // ReplaceInstUsesWith - This method is to be used when an instruction is
297     // found to be dead, replacable with another preexisting expression.  Here
298     // we add all uses of I to the worklist, replace all uses of I with the new
299     // value, then return I, so that the inst combiner will know that I was
300     // modified.
301     //
302     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
303       AddUsersToWorkList(I);         // Add all modified instrs to worklist
304       if (&I != V) {
305         I.replaceAllUsesWith(V);
306         return &I;
307       } else {
308         // If we are replacing the instruction with itself, this must be in a
309         // segment of unreachable code, so just clobber the instruction.
310         I.replaceAllUsesWith(Context->getUndef(I.getType()));
311         return &I;
312       }
313     }
314
315     // EraseInstFromFunction - When dealing with an instruction that has side
316     // effects or produces a void value, we can't rely on DCE to delete the
317     // instruction.  Instead, visit methods should return the value returned by
318     // this function.
319     Instruction *EraseInstFromFunction(Instruction &I) {
320       assert(I.use_empty() && "Cannot erase instruction that is used!");
321       AddUsesToWorkList(I);
322       RemoveFromWorkList(&I);
323       I.eraseFromParent();
324       return 0;  // Don't do anything with FI
325     }
326         
327     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
328                            APInt &KnownOne, unsigned Depth = 0) const {
329       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
330     }
331     
332     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
333                            unsigned Depth = 0) const {
334       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
335     }
336     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
337       return llvm::ComputeNumSignBits(Op, TD, Depth);
338     }
339
340   private:
341
342     /// SimplifyCommutative - This performs a few simplifications for 
343     /// commutative operators.
344     bool SimplifyCommutative(BinaryOperator &I);
345
346     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
347     /// most-complex to least-complex order.
348     bool SimplifyCompare(CmpInst &I);
349
350     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
351     /// based on the demanded bits.
352     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
353                                    APInt& KnownZero, APInt& KnownOne,
354                                    unsigned Depth);
355     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
356                               APInt& KnownZero, APInt& KnownOne,
357                               unsigned Depth=0);
358         
359     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
360     /// SimplifyDemandedBits knows about.  See if the instruction has any
361     /// properties that allow us to simplify its operands.
362     bool SimplifyDemandedInstructionBits(Instruction &Inst);
363         
364     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
365                                       APInt& UndefElts, unsigned Depth = 0);
366       
367     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368     // PHI node as operand #0, see if we can fold the instruction into the PHI
369     // (which is only possible if all operands to the PHI are constants).
370     Instruction *FoldOpIntoPhi(Instruction &I);
371
372     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373     // operator and they all are only used by the PHI, PHI together their
374     // inputs, and do the operation once, to the result of the PHI.
375     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
378
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
397                                     unsigned CastOpc, int &NumCastsRemoved);
398     unsigned GetOrEnforceKnownAlignment(Value *V,
399                                         unsigned PrefAlign = 0);
400
401   };
402 }
403
404 char InstCombiner::ID = 0;
405 static RegisterPass<InstCombiner>
406 X("instcombine", "Combine redundant instructions");
407
408 // getComplexity:  Assign a complexity or rank value to LLVM Values...
409 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
410 static unsigned getComplexity(Value *V) {
411   if (isa<Instruction>(V)) {
412     if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
413         BinaryOperator::isNot(V))
414       return 3;
415     return 4;
416   }
417   if (isa<Argument>(V)) return 3;
418   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419 }
420
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 // it.
423 static bool isOnlyUse(Value *V) {
424   return V->hasOneUse() || isa<Constant>(V);
425 }
426
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431     if (ITy->getBitWidth() < 32)
432       return Type::Int32Ty;
433   }
434   return Ty;
435 }
436
437 /// getBitCastOperand - If the specified operand is a CastInst, a constant
438 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
439 /// operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442     // BitCastInst?
443     return I->getOperand(0);
444   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
445     // GetElementPtrInst?
446     if (GEP->hasAllZeroIndices())
447       return GEP->getOperand(0);
448   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
449     if (CE->getOpcode() == Instruction::BitCast)
450       // BitCast ConstantExp?
451       return CE->getOperand(0);
452     else if (CE->getOpcode() == Instruction::GetElementPtr) {
453       // GetElementPtr ConstantExp?
454       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
455            I != E; ++I) {
456         ConstantInt *CI = dyn_cast<ConstantInt>(I);
457         if (!CI || !CI->isZero())
458           // Any non-zero indices? Not cast-like.
459           return 0;
460       }
461       // All-zero indices? This is just like casting.
462       return CE->getOperand(0);
463     }
464   }
465   return 0;
466 }
467
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps 
471 isEliminableCastPair(
472   const CastInst *CI, ///< The first cast instruction
473   unsigned opcode,       ///< The opcode of the second cast instruction
474   const Type *DstTy,     ///< The target type for the second cast instruction
475   TargetData *TD         ///< The target data for pointer size
476 ) {
477   
478   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
479   const Type *MidTy = CI->getType();                  // B from above
480
481   // Get the opcodes of the two Cast instructions
482   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
484
485   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486                                                 DstTy, TD->getIntPtrType());
487   
488   // We don't want to form an inttoptr or ptrtoint that converts to an integer
489   // type that differs from the pointer size.
490   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
491       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
492     Res = 0;
493   
494   return Instruction::CastOps(Res);
495 }
496
497 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
498 /// in any code being generated.  It does not require codegen if V is simple
499 /// enough or if the cast can be folded into other casts.
500 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
501                               const Type *Ty, TargetData *TD) {
502   if (V->getType() == Ty || isa<Constant>(V)) return false;
503   
504   // If this is another cast that can be eliminated, it isn't codegen either.
505   if (const CastInst *CI = dyn_cast<CastInst>(V))
506     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
507       return false;
508   return true;
509 }
510
511 // SimplifyCommutative - This performs a few simplifications for commutative
512 // operators:
513 //
514 //  1. Order operands such that they are listed from right (least complex) to
515 //     left (most complex).  This puts constants before unary operators before
516 //     binary operators.
517 //
518 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
519 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
520 //
521 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
522   bool Changed = false;
523   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
524     Changed = !I.swapOperands();
525
526   if (!I.isAssociative()) return Changed;
527   Instruction::BinaryOps Opcode = I.getOpcode();
528   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
529     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
530       if (isa<Constant>(I.getOperand(1))) {
531         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
532                                              cast<Constant>(I.getOperand(1)),
533                                              cast<Constant>(Op->getOperand(1)));
534         I.setOperand(0, Op->getOperand(0));
535         I.setOperand(1, Folded);
536         return true;
537       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
538         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
539             isOnlyUse(Op) && isOnlyUse(Op1)) {
540           Constant *C1 = cast<Constant>(Op->getOperand(1));
541           Constant *C2 = cast<Constant>(Op1->getOperand(1));
542
543           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
544           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
545           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
546                                                     Op1->getOperand(0),
547                                                     Op1->getName(), &I);
548           AddToWorkList(New);
549           I.setOperand(0, New);
550           I.setOperand(1, Folded);
551           return true;
552         }
553     }
554   return Changed;
555 }
556
557 /// SimplifyCompare - For a CmpInst this function just orders the operands
558 /// so that theyare listed from right (least complex) to left (most complex).
559 /// This puts constants before unary operators before binary operators.
560 bool InstCombiner::SimplifyCompare(CmpInst &I) {
561   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
562     return false;
563   I.swapOperands();
564   // Compare instructions are not associative so there's nothing else we can do.
565   return true;
566 }
567
568 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
569 // if the LHS is a constant zero (which is the 'negate' form).
570 //
571 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
572   if (BinaryOperator::isNeg(V))
573     return BinaryOperator::getNegArgument(V);
574
575   // Constants can be considered to be negated values if they can be folded.
576   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
577     return Context->getConstantExprNeg(C);
578
579   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
580     if (C->getType()->getElementType()->isInteger())
581       return Context->getConstantExprNeg(C);
582
583   return 0;
584 }
585
586 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
587 // instruction if the LHS is a constant negative zero (which is the 'negate'
588 // form).
589 //
590 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
591   if (BinaryOperator::isFNeg(V))
592     return BinaryOperator::getFNegArgument(V);
593
594   // Constants can be considered to be negated values if they can be folded.
595   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
596     return Context->getConstantExprFNeg(C);
597
598   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
599     if (C->getType()->getElementType()->isFloatingPoint())
600       return Context->getConstantExprFNeg(C);
601
602   return 0;
603 }
604
605 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
606   if (BinaryOperator::isNot(V))
607     return BinaryOperator::getNotArgument(V);
608
609   // Constants can be considered to be not'ed values...
610   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
611     return Context->getConstantInt(~C->getValue());
612   return 0;
613 }
614
615 // dyn_castFoldableMul - If this value is a multiply that can be folded into
616 // other computations (because it has a constant operand), return the
617 // non-constant operand of the multiply, and set CST to point to the multiplier.
618 // Otherwise, return null.
619 //
620 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
621                                          LLVMContext *Context) {
622   if (V->hasOneUse() && V->getType()->isInteger())
623     if (Instruction *I = dyn_cast<Instruction>(V)) {
624       if (I->getOpcode() == Instruction::Mul)
625         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
626           return I->getOperand(0);
627       if (I->getOpcode() == Instruction::Shl)
628         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
629           // The multiplier is really 1 << CST.
630           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
631           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
632           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
633           return I->getOperand(0);
634         }
635     }
636   return 0;
637 }
638
639 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
640 /// expression, return it.
641 static User *dyn_castGetElementPtr(Value *V) {
642   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
643   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
644     if (CE->getOpcode() == Instruction::GetElementPtr)
645       return cast<User>(V);
646   return false;
647 }
648
649 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
650 /// opcode value. Otherwise return UserOp1.
651 static unsigned getOpcode(const Value *V) {
652   if (const Instruction *I = dyn_cast<Instruction>(V))
653     return I->getOpcode();
654   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
655     return CE->getOpcode();
656   // Use UserOp1 to mean there's no opcode.
657   return Instruction::UserOp1;
658 }
659
660 /// AddOne - Add one to a ConstantInt
661 static Constant *AddOne(Constant *C, LLVMContext *Context) {
662   return Context->getConstantExprAdd(C, 
663     Context->getConstantInt(C->getType(), 1));
664 }
665 /// SubOne - Subtract one from a ConstantInt
666 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
667   return Context->getConstantExprSub(C, 
668     Context->getConstantInt(C->getType(), 1));
669 }
670 /// MultiplyOverflows - True if the multiply can not be expressed in an int
671 /// this size.
672 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
673                               LLVMContext *Context) {
674   uint32_t W = C1->getBitWidth();
675   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
676   if (sign) {
677     LHSExt.sext(W * 2);
678     RHSExt.sext(W * 2);
679   } else {
680     LHSExt.zext(W * 2);
681     RHSExt.zext(W * 2);
682   }
683
684   APInt MulExt = LHSExt * RHSExt;
685
686   if (sign) {
687     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
688     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
689     return MulExt.slt(Min) || MulExt.sgt(Max);
690   } else 
691     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
692 }
693
694
695 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
696 /// specified instruction is a constant integer.  If so, check to see if there
697 /// are any bits set in the constant that are not demanded.  If so, shrink the
698 /// constant and return true.
699 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
700                                    APInt Demanded, LLVMContext *Context) {
701   assert(I && "No instruction?");
702   assert(OpNo < I->getNumOperands() && "Operand index too large");
703
704   // If the operand is not a constant integer, nothing to do.
705   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
706   if (!OpC) return false;
707
708   // If there are no bits set that aren't demanded, nothing to do.
709   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
710   if ((~Demanded & OpC->getValue()) == 0)
711     return false;
712
713   // This instruction is producing bits that are not demanded. Shrink the RHS.
714   Demanded &= OpC->getValue();
715   I->setOperand(OpNo, Context->getConstantInt(Demanded));
716   return true;
717 }
718
719 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
720 // set of known zero and one bits, compute the maximum and minimum values that
721 // could have the specified known zero and known one bits, returning them in
722 // min/max.
723 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
724                                                    const APInt& KnownOne,
725                                                    APInt& Min, APInt& Max) {
726   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
727          KnownZero.getBitWidth() == Min.getBitWidth() &&
728          KnownZero.getBitWidth() == Max.getBitWidth() &&
729          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
730   APInt UnknownBits = ~(KnownZero|KnownOne);
731
732   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
733   // bit if it is unknown.
734   Min = KnownOne;
735   Max = KnownOne|UnknownBits;
736   
737   if (UnknownBits.isNegative()) { // Sign bit is unknown
738     Min.set(Min.getBitWidth()-1);
739     Max.clear(Max.getBitWidth()-1);
740   }
741 }
742
743 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
744 // a set of known zero and one bits, compute the maximum and minimum values that
745 // could have the specified known zero and known one bits, returning them in
746 // min/max.
747 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
748                                                      const APInt &KnownOne,
749                                                      APInt &Min, APInt &Max) {
750   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
751          KnownZero.getBitWidth() == Min.getBitWidth() &&
752          KnownZero.getBitWidth() == Max.getBitWidth() &&
753          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
754   APInt UnknownBits = ~(KnownZero|KnownOne);
755   
756   // The minimum value is when the unknown bits are all zeros.
757   Min = KnownOne;
758   // The maximum value is when the unknown bits are all ones.
759   Max = KnownOne|UnknownBits;
760 }
761
762 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
763 /// SimplifyDemandedBits knows about.  See if the instruction has any
764 /// properties that allow us to simplify its operands.
765 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
766   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
767   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
768   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
769   
770   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
771                                      KnownZero, KnownOne, 0);
772   if (V == 0) return false;
773   if (V == &Inst) return true;
774   ReplaceInstUsesWith(Inst, V);
775   return true;
776 }
777
778 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
779 /// specified instruction operand if possible, updating it in place.  It returns
780 /// true if it made any change and false otherwise.
781 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
782                                         APInt &KnownZero, APInt &KnownOne,
783                                         unsigned Depth) {
784   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
785                                           KnownZero, KnownOne, Depth);
786   if (NewVal == 0) return false;
787   U.set(NewVal);
788   return true;
789 }
790
791
792 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
793 /// value based on the demanded bits.  When this function is called, it is known
794 /// that only the bits set in DemandedMask of the result of V are ever used
795 /// downstream. Consequently, depending on the mask and V, it may be possible
796 /// to replace V with a constant or one of its operands. In such cases, this
797 /// function does the replacement and returns true. In all other cases, it
798 /// returns false after analyzing the expression and setting KnownOne and known
799 /// to be one in the expression.  KnownZero contains all the bits that are known
800 /// to be zero in the expression. These are provided to potentially allow the
801 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
802 /// the expression. KnownOne and KnownZero always follow the invariant that 
803 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
804 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
805 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
806 /// and KnownOne must all be the same.
807 ///
808 /// This returns null if it did not change anything and it permits no
809 /// simplification.  This returns V itself if it did some simplification of V's
810 /// operands based on the information about what bits are demanded. This returns
811 /// some other non-null value if it found out that V is equal to another value
812 /// in the context where the specified bits are demanded, but not for all users.
813 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
814                                              APInt &KnownZero, APInt &KnownOne,
815                                              unsigned Depth) {
816   assert(V != 0 && "Null pointer of Value???");
817   assert(Depth <= 6 && "Limit Search Depth");
818   uint32_t BitWidth = DemandedMask.getBitWidth();
819   const Type *VTy = V->getType();
820   assert((TD || !isa<PointerType>(VTy)) &&
821          "SimplifyDemandedBits needs to know bit widths!");
822   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
823          (!VTy->isIntOrIntVector() ||
824           VTy->getScalarSizeInBits() == BitWidth) &&
825          KnownZero.getBitWidth() == BitWidth &&
826          KnownOne.getBitWidth() == BitWidth &&
827          "Value *V, DemandedMask, KnownZero and KnownOne "
828          "must have same BitWidth");
829   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
830     // We know all of the bits for a constant!
831     KnownOne = CI->getValue() & DemandedMask;
832     KnownZero = ~KnownOne & DemandedMask;
833     return 0;
834   }
835   if (isa<ConstantPointerNull>(V)) {
836     // We know all of the bits for a constant!
837     KnownOne.clear();
838     KnownZero = DemandedMask;
839     return 0;
840   }
841
842   KnownZero.clear();
843   KnownOne.clear();
844   if (DemandedMask == 0) {   // Not demanding any bits from V.
845     if (isa<UndefValue>(V))
846       return 0;
847     return Context->getUndef(VTy);
848   }
849   
850   if (Depth == 6)        // Limit search depth.
851     return 0;
852   
853   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
854   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
855
856   Instruction *I = dyn_cast<Instruction>(V);
857   if (!I) {
858     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
859     return 0;        // Only analyze instructions.
860   }
861
862   // If there are multiple uses of this value and we aren't at the root, then
863   // we can't do any simplifications of the operands, because DemandedMask
864   // only reflects the bits demanded by *one* of the users.
865   if (Depth != 0 && !I->hasOneUse()) {
866     // Despite the fact that we can't simplify this instruction in all User's
867     // context, we can at least compute the knownzero/knownone bits, and we can
868     // do simplifications that apply to *just* the one user if we know that
869     // this instruction has a simpler value in that context.
870     if (I->getOpcode() == Instruction::And) {
871       // If either the LHS or the RHS are Zero, the result is zero.
872       ComputeMaskedBits(I->getOperand(1), DemandedMask,
873                         RHSKnownZero, RHSKnownOne, Depth+1);
874       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
875                         LHSKnownZero, LHSKnownOne, Depth+1);
876       
877       // If all of the demanded bits are known 1 on one side, return the other.
878       // These bits cannot contribute to the result of the 'and' in this
879       // context.
880       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
881           (DemandedMask & ~LHSKnownZero))
882         return I->getOperand(0);
883       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
884           (DemandedMask & ~RHSKnownZero))
885         return I->getOperand(1);
886       
887       // If all of the demanded bits in the inputs are known zeros, return zero.
888       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
889         return Context->getNullValue(VTy);
890       
891     } else if (I->getOpcode() == Instruction::Or) {
892       // We can simplify (X|Y) -> X or Y in the user's context if we know that
893       // only bits from X or Y are demanded.
894       
895       // If either the LHS or the RHS are One, the result is One.
896       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
897                         RHSKnownZero, RHSKnownOne, Depth+1);
898       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
899                         LHSKnownZero, LHSKnownOne, Depth+1);
900       
901       // If all of the demanded bits are known zero on one side, return the
902       // other.  These bits cannot contribute to the result of the 'or' in this
903       // context.
904       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
905           (DemandedMask & ~LHSKnownOne))
906         return I->getOperand(0);
907       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
908           (DemandedMask & ~RHSKnownOne))
909         return I->getOperand(1);
910       
911       // If all of the potentially set bits on one side are known to be set on
912       // the other side, just use the 'other' side.
913       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
914           (DemandedMask & (~RHSKnownZero)))
915         return I->getOperand(0);
916       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
917           (DemandedMask & (~LHSKnownZero)))
918         return I->getOperand(1);
919     }
920     
921     // Compute the KnownZero/KnownOne bits to simplify things downstream.
922     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
923     return 0;
924   }
925   
926   // If this is the root being simplified, allow it to have multiple uses,
927   // just set the DemandedMask to all bits so that we can try to simplify the
928   // operands.  This allows visitTruncInst (for example) to simplify the
929   // operand of a trunc without duplicating all the logic below.
930   if (Depth == 0 && !V->hasOneUse())
931     DemandedMask = APInt::getAllOnesValue(BitWidth);
932   
933   switch (I->getOpcode()) {
934   default:
935     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
936     break;
937   case Instruction::And:
938     // If either the LHS or the RHS are Zero, the result is zero.
939     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
940                              RHSKnownZero, RHSKnownOne, Depth+1) ||
941         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
942                              LHSKnownZero, LHSKnownOne, Depth+1))
943       return I;
944     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
945     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
946
947     // If all of the demanded bits are known 1 on one side, return the other.
948     // These bits cannot contribute to the result of the 'and'.
949     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
950         (DemandedMask & ~LHSKnownZero))
951       return I->getOperand(0);
952     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
953         (DemandedMask & ~RHSKnownZero))
954       return I->getOperand(1);
955     
956     // If all of the demanded bits in the inputs are known zeros, return zero.
957     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
958       return Context->getNullValue(VTy);
959       
960     // If the RHS is a constant, see if we can simplify it.
961     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
962       return I;
963       
964     // Output known-1 bits are only known if set in both the LHS & RHS.
965     RHSKnownOne &= LHSKnownOne;
966     // Output known-0 are known to be clear if zero in either the LHS | RHS.
967     RHSKnownZero |= LHSKnownZero;
968     break;
969   case Instruction::Or:
970     // If either the LHS or the RHS are One, the result is One.
971     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
972                              RHSKnownZero, RHSKnownOne, Depth+1) ||
973         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
974                              LHSKnownZero, LHSKnownOne, Depth+1))
975       return I;
976     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
977     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
978     
979     // If all of the demanded bits are known zero on one side, return the other.
980     // These bits cannot contribute to the result of the 'or'.
981     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
982         (DemandedMask & ~LHSKnownOne))
983       return I->getOperand(0);
984     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
985         (DemandedMask & ~RHSKnownOne))
986       return I->getOperand(1);
987
988     // If all of the potentially set bits on one side are known to be set on
989     // the other side, just use the 'other' side.
990     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
991         (DemandedMask & (~RHSKnownZero)))
992       return I->getOperand(0);
993     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
994         (DemandedMask & (~LHSKnownZero)))
995       return I->getOperand(1);
996         
997     // If the RHS is a constant, see if we can simplify it.
998     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
999       return I;
1000           
1001     // Output known-0 bits are only known if clear in both the LHS & RHS.
1002     RHSKnownZero &= LHSKnownZero;
1003     // Output known-1 are known to be set if set in either the LHS | RHS.
1004     RHSKnownOne |= LHSKnownOne;
1005     break;
1006   case Instruction::Xor: {
1007     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1008                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1009         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1010                              LHSKnownZero, LHSKnownOne, Depth+1))
1011       return I;
1012     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1013     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1014     
1015     // If all of the demanded bits are known zero on one side, return the other.
1016     // These bits cannot contribute to the result of the 'xor'.
1017     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1018       return I->getOperand(0);
1019     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1020       return I->getOperand(1);
1021     
1022     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1023     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1024                          (RHSKnownOne & LHSKnownOne);
1025     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1026     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1027                         (RHSKnownOne & LHSKnownZero);
1028     
1029     // If all of the demanded bits are known to be zero on one side or the
1030     // other, turn this into an *inclusive* or.
1031     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1032     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1033       Instruction *Or =
1034         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1035                                  I->getName());
1036       return InsertNewInstBefore(Or, *I);
1037     }
1038     
1039     // If all of the demanded bits on one side are known, and all of the set
1040     // bits on that side are also known to be set on the other side, turn this
1041     // into an AND, as we know the bits will be cleared.
1042     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1043     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1044       // all known
1045       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1046         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1047         Instruction *And = 
1048           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1049         return InsertNewInstBefore(And, *I);
1050       }
1051     }
1052     
1053     // If the RHS is a constant, see if we can simplify it.
1054     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1055     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1056       return I;
1057     
1058     RHSKnownZero = KnownZeroOut;
1059     RHSKnownOne  = KnownOneOut;
1060     break;
1061   }
1062   case Instruction::Select:
1063     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1064                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1065         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1066                              LHSKnownZero, LHSKnownOne, Depth+1))
1067       return I;
1068     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1069     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1070     
1071     // If the operands are constants, see if we can simplify them.
1072     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1073         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1074       return I;
1075     
1076     // Only known if known in both the LHS and RHS.
1077     RHSKnownOne &= LHSKnownOne;
1078     RHSKnownZero &= LHSKnownZero;
1079     break;
1080   case Instruction::Trunc: {
1081     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1082     DemandedMask.zext(truncBf);
1083     RHSKnownZero.zext(truncBf);
1084     RHSKnownOne.zext(truncBf);
1085     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1086                              RHSKnownZero, RHSKnownOne, Depth+1))
1087       return I;
1088     DemandedMask.trunc(BitWidth);
1089     RHSKnownZero.trunc(BitWidth);
1090     RHSKnownOne.trunc(BitWidth);
1091     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1092     break;
1093   }
1094   case Instruction::BitCast:
1095     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1096       return false;  // vector->int or fp->int?
1097
1098     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1099       if (const VectorType *SrcVTy =
1100             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1101         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1102           // Don't touch a bitcast between vectors of different element counts.
1103           return false;
1104       } else
1105         // Don't touch a scalar-to-vector bitcast.
1106         return false;
1107     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1108       // Don't touch a vector-to-scalar bitcast.
1109       return false;
1110
1111     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1112                              RHSKnownZero, RHSKnownOne, Depth+1))
1113       return I;
1114     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1115     break;
1116   case Instruction::ZExt: {
1117     // Compute the bits in the result that are not present in the input.
1118     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1119     
1120     DemandedMask.trunc(SrcBitWidth);
1121     RHSKnownZero.trunc(SrcBitWidth);
1122     RHSKnownOne.trunc(SrcBitWidth);
1123     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1124                              RHSKnownZero, RHSKnownOne, Depth+1))
1125       return I;
1126     DemandedMask.zext(BitWidth);
1127     RHSKnownZero.zext(BitWidth);
1128     RHSKnownOne.zext(BitWidth);
1129     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1130     // The top bits are known to be zero.
1131     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1132     break;
1133   }
1134   case Instruction::SExt: {
1135     // Compute the bits in the result that are not present in the input.
1136     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1137     
1138     APInt InputDemandedBits = DemandedMask & 
1139                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1140
1141     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1142     // If any of the sign extended bits are demanded, we know that the sign
1143     // bit is demanded.
1144     if ((NewBits & DemandedMask) != 0)
1145       InputDemandedBits.set(SrcBitWidth-1);
1146       
1147     InputDemandedBits.trunc(SrcBitWidth);
1148     RHSKnownZero.trunc(SrcBitWidth);
1149     RHSKnownOne.trunc(SrcBitWidth);
1150     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1151                              RHSKnownZero, RHSKnownOne, Depth+1))
1152       return I;
1153     InputDemandedBits.zext(BitWidth);
1154     RHSKnownZero.zext(BitWidth);
1155     RHSKnownOne.zext(BitWidth);
1156     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1157       
1158     // If the sign bit of the input is known set or clear, then we know the
1159     // top bits of the result.
1160
1161     // If the input sign bit is known zero, or if the NewBits are not demanded
1162     // convert this into a zero extension.
1163     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1164       // Convert to ZExt cast
1165       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1166       return InsertNewInstBefore(NewCast, *I);
1167     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1168       RHSKnownOne |= NewBits;
1169     }
1170     break;
1171   }
1172   case Instruction::Add: {
1173     // Figure out what the input bits are.  If the top bits of the and result
1174     // are not demanded, then the add doesn't demand them from its input
1175     // either.
1176     unsigned NLZ = DemandedMask.countLeadingZeros();
1177       
1178     // If there is a constant on the RHS, there are a variety of xformations
1179     // we can do.
1180     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1181       // If null, this should be simplified elsewhere.  Some of the xforms here
1182       // won't work if the RHS is zero.
1183       if (RHS->isZero())
1184         break;
1185       
1186       // If the top bit of the output is demanded, demand everything from the
1187       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1188       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1189
1190       // Find information about known zero/one bits in the input.
1191       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1192                                LHSKnownZero, LHSKnownOne, Depth+1))
1193         return I;
1194
1195       // If the RHS of the add has bits set that can't affect the input, reduce
1196       // the constant.
1197       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1198         return I;
1199       
1200       // Avoid excess work.
1201       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1202         break;
1203       
1204       // Turn it into OR if input bits are zero.
1205       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1206         Instruction *Or =
1207           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1208                                    I->getName());
1209         return InsertNewInstBefore(Or, *I);
1210       }
1211       
1212       // We can say something about the output known-zero and known-one bits,
1213       // depending on potential carries from the input constant and the
1214       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1215       // bits set and the RHS constant is 0x01001, then we know we have a known
1216       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1217       
1218       // To compute this, we first compute the potential carry bits.  These are
1219       // the bits which may be modified.  I'm not aware of a better way to do
1220       // this scan.
1221       const APInt &RHSVal = RHS->getValue();
1222       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1223       
1224       // Now that we know which bits have carries, compute the known-1/0 sets.
1225       
1226       // Bits are known one if they are known zero in one operand and one in the
1227       // other, and there is no input carry.
1228       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1229                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1230       
1231       // Bits are known zero if they are known zero in both operands and there
1232       // is no input carry.
1233       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1234     } else {
1235       // If the high-bits of this ADD are not demanded, then it does not demand
1236       // the high bits of its LHS or RHS.
1237       if (DemandedMask[BitWidth-1] == 0) {
1238         // Right fill the mask of bits for this ADD to demand the most
1239         // significant bit and all those below it.
1240         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1241         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1242                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1243             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1244                                  LHSKnownZero, LHSKnownOne, Depth+1))
1245           return I;
1246       }
1247     }
1248     break;
1249   }
1250   case Instruction::Sub:
1251     // If the high-bits of this SUB are not demanded, then it does not demand
1252     // the high bits of its LHS or RHS.
1253     if (DemandedMask[BitWidth-1] == 0) {
1254       // Right fill the mask of bits for this SUB to demand the most
1255       // significant bit and all those below it.
1256       uint32_t NLZ = DemandedMask.countLeadingZeros();
1257       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1258       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1259                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1260           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1261                                LHSKnownZero, LHSKnownOne, Depth+1))
1262         return I;
1263     }
1264     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1265     // the known zeros and ones.
1266     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1267     break;
1268   case Instruction::Shl:
1269     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1271       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1272       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1273                                RHSKnownZero, RHSKnownOne, Depth+1))
1274         return I;
1275       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1276       RHSKnownZero <<= ShiftAmt;
1277       RHSKnownOne  <<= ShiftAmt;
1278       // low bits known zero.
1279       if (ShiftAmt)
1280         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1281     }
1282     break;
1283   case Instruction::LShr:
1284     // For a logical shift right
1285     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1286       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1287       
1288       // Unsigned shift right.
1289       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1290       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1291                                RHSKnownZero, RHSKnownOne, Depth+1))
1292         return I;
1293       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1294       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1295       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1296       if (ShiftAmt) {
1297         // Compute the new bits that are at the top now.
1298         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1299         RHSKnownZero |= HighBits;  // high bits known zero.
1300       }
1301     }
1302     break;
1303   case Instruction::AShr:
1304     // If this is an arithmetic shift right and only the low-bit is set, we can
1305     // always convert this into a logical shr, even if the shift amount is
1306     // variable.  The low bit of the shift cannot be an input sign bit unless
1307     // the shift amount is >= the size of the datatype, which is undefined.
1308     if (DemandedMask == 1) {
1309       // Perform the logical shift right.
1310       Instruction *NewVal = BinaryOperator::CreateLShr(
1311                         I->getOperand(0), I->getOperand(1), I->getName());
1312       return InsertNewInstBefore(NewVal, *I);
1313     }    
1314
1315     // If the sign bit is the only bit demanded by this ashr, then there is no
1316     // need to do it, the shift doesn't change the high bit.
1317     if (DemandedMask.isSignBit())
1318       return I->getOperand(0);
1319     
1320     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1321       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1322       
1323       // Signed shift right.
1324       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1325       // If any of the "high bits" are demanded, we should set the sign bit as
1326       // demanded.
1327       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1328         DemandedMaskIn.set(BitWidth-1);
1329       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1330                                RHSKnownZero, RHSKnownOne, Depth+1))
1331         return I;
1332       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1333       // Compute the new bits that are at the top now.
1334       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1335       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1336       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1337         
1338       // Handle the sign bits.
1339       APInt SignBit(APInt::getSignBit(BitWidth));
1340       // Adjust to where it is now in the mask.
1341       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1342         
1343       // If the input sign bit is known to be zero, or if none of the top bits
1344       // are demanded, turn this into an unsigned shift right.
1345       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1346           (HighBits & ~DemandedMask) == HighBits) {
1347         // Perform the logical shift right.
1348         Instruction *NewVal = BinaryOperator::CreateLShr(
1349                           I->getOperand(0), SA, I->getName());
1350         return InsertNewInstBefore(NewVal, *I);
1351       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1352         RHSKnownOne |= HighBits;
1353       }
1354     }
1355     break;
1356   case Instruction::SRem:
1357     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358       APInt RA = Rem->getValue().abs();
1359       if (RA.isPowerOf2()) {
1360         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1361           return I->getOperand(0);
1362
1363         APInt LowBits = RA - 1;
1364         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1365         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1366                                  LHSKnownZero, LHSKnownOne, Depth+1))
1367           return I;
1368
1369         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1370           LHSKnownZero |= ~LowBits;
1371
1372         KnownZero |= LHSKnownZero & DemandedMask;
1373
1374         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1375       }
1376     }
1377     break;
1378   case Instruction::URem: {
1379     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1380     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1381     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1382                              KnownZero2, KnownOne2, Depth+1) ||
1383         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1384                              KnownZero2, KnownOne2, Depth+1))
1385       return I;
1386
1387     unsigned Leaders = KnownZero2.countLeadingOnes();
1388     Leaders = std::max(Leaders,
1389                        KnownZero2.countLeadingOnes());
1390     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1391     break;
1392   }
1393   case Instruction::Call:
1394     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1395       switch (II->getIntrinsicID()) {
1396       default: break;
1397       case Intrinsic::bswap: {
1398         // If the only bits demanded come from one byte of the bswap result,
1399         // just shift the input byte into position to eliminate the bswap.
1400         unsigned NLZ = DemandedMask.countLeadingZeros();
1401         unsigned NTZ = DemandedMask.countTrailingZeros();
1402           
1403         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1404         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1405         // have 14 leading zeros, round to 8.
1406         NLZ &= ~7;
1407         NTZ &= ~7;
1408         // If we need exactly one byte, we can do this transformation.
1409         if (BitWidth-NLZ-NTZ == 8) {
1410           unsigned ResultBit = NTZ;
1411           unsigned InputBit = BitWidth-NTZ-8;
1412           
1413           // Replace this with either a left or right shift to get the byte into
1414           // the right place.
1415           Instruction *NewVal;
1416           if (InputBit > ResultBit)
1417             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1418                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1419           else
1420             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1421                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1422           NewVal->takeName(I);
1423           return InsertNewInstBefore(NewVal, *I);
1424         }
1425           
1426         // TODO: Could compute known zero/one bits based on the input.
1427         break;
1428       }
1429       }
1430     }
1431     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1432     break;
1433   }
1434   
1435   // If the client is only demanding bits that we know, return the known
1436   // constant.
1437   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1438     Constant *C = Context->getConstantInt(RHSKnownOne);
1439     if (isa<PointerType>(V->getType()))
1440       C = Context->getConstantExprIntToPtr(C, V->getType());
1441     return C;
1442   }
1443   return false;
1444 }
1445
1446
1447 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1448 /// any number of elements. DemandedElts contains the set of elements that are
1449 /// actually used by the caller.  This method analyzes which elements of the
1450 /// operand are undef and returns that information in UndefElts.
1451 ///
1452 /// If the information about demanded elements can be used to simplify the
1453 /// operation, the operation is simplified, then the resultant value is
1454 /// returned.  This returns null if no change was made.
1455 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1456                                                 APInt& UndefElts,
1457                                                 unsigned Depth) {
1458   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1459   APInt EltMask(APInt::getAllOnesValue(VWidth));
1460   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1461
1462   if (isa<UndefValue>(V)) {
1463     // If the entire vector is undefined, just return this info.
1464     UndefElts = EltMask;
1465     return 0;
1466   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1467     UndefElts = EltMask;
1468     return Context->getUndef(V->getType());
1469   }
1470
1471   UndefElts = 0;
1472   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1473     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1474     Constant *Undef = Context->getUndef(EltTy);
1475
1476     std::vector<Constant*> Elts;
1477     for (unsigned i = 0; i != VWidth; ++i)
1478       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1479         Elts.push_back(Undef);
1480         UndefElts.set(i);
1481       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1482         Elts.push_back(Undef);
1483         UndefElts.set(i);
1484       } else {                               // Otherwise, defined.
1485         Elts.push_back(CP->getOperand(i));
1486       }
1487
1488     // If we changed the constant, return it.
1489     Constant *NewCP = Context->getConstantVector(Elts);
1490     return NewCP != CP ? NewCP : 0;
1491   } else if (isa<ConstantAggregateZero>(V)) {
1492     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1493     // set to undef.
1494     
1495     // Check if this is identity. If so, return 0 since we are not simplifying
1496     // anything.
1497     if (DemandedElts == ((1ULL << VWidth) -1))
1498       return 0;
1499     
1500     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1501     Constant *Zero = Context->getNullValue(EltTy);
1502     Constant *Undef = Context->getUndef(EltTy);
1503     std::vector<Constant*> Elts;
1504     for (unsigned i = 0; i != VWidth; ++i) {
1505       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1506       Elts.push_back(Elt);
1507     }
1508     UndefElts = DemandedElts ^ EltMask;
1509     return Context->getConstantVector(Elts);
1510   }
1511   
1512   // Limit search depth.
1513   if (Depth == 10)
1514     return 0;
1515
1516   // If multiple users are using the root value, procede with
1517   // simplification conservatively assuming that all elements
1518   // are needed.
1519   if (!V->hasOneUse()) {
1520     // Quit if we find multiple users of a non-root value though.
1521     // They'll be handled when it's their turn to be visited by
1522     // the main instcombine process.
1523     if (Depth != 0)
1524       // TODO: Just compute the UndefElts information recursively.
1525       return 0;
1526
1527     // Conservatively assume that all elements are needed.
1528     DemandedElts = EltMask;
1529   }
1530   
1531   Instruction *I = dyn_cast<Instruction>(V);
1532   if (!I) return 0;        // Only analyze instructions.
1533   
1534   bool MadeChange = false;
1535   APInt UndefElts2(VWidth, 0);
1536   Value *TmpV;
1537   switch (I->getOpcode()) {
1538   default: break;
1539     
1540   case Instruction::InsertElement: {
1541     // If this is a variable index, we don't know which element it overwrites.
1542     // demand exactly the same input as we produce.
1543     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1544     if (Idx == 0) {
1545       // Note that we can't propagate undef elt info, because we don't know
1546       // which elt is getting updated.
1547       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1548                                         UndefElts2, Depth+1);
1549       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1550       break;
1551     }
1552     
1553     // If this is inserting an element that isn't demanded, remove this
1554     // insertelement.
1555     unsigned IdxNo = Idx->getZExtValue();
1556     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1557       return AddSoonDeadInstToWorklist(*I, 0);
1558     
1559     // Otherwise, the element inserted overwrites whatever was there, so the
1560     // input demanded set is simpler than the output set.
1561     APInt DemandedElts2 = DemandedElts;
1562     DemandedElts2.clear(IdxNo);
1563     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1564                                       UndefElts, Depth+1);
1565     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1566
1567     // The inserted element is defined.
1568     UndefElts.clear(IdxNo);
1569     break;
1570   }
1571   case Instruction::ShuffleVector: {
1572     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1573     uint64_t LHSVWidth =
1574       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1575     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1576     for (unsigned i = 0; i < VWidth; i++) {
1577       if (DemandedElts[i]) {
1578         unsigned MaskVal = Shuffle->getMaskValue(i);
1579         if (MaskVal != -1u) {
1580           assert(MaskVal < LHSVWidth * 2 &&
1581                  "shufflevector mask index out of range!");
1582           if (MaskVal < LHSVWidth)
1583             LeftDemanded.set(MaskVal);
1584           else
1585             RightDemanded.set(MaskVal - LHSVWidth);
1586         }
1587       }
1588     }
1589
1590     APInt UndefElts4(LHSVWidth, 0);
1591     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1592                                       UndefElts4, Depth+1);
1593     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1594
1595     APInt UndefElts3(LHSVWidth, 0);
1596     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1597                                       UndefElts3, Depth+1);
1598     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1599
1600     bool NewUndefElts = false;
1601     for (unsigned i = 0; i < VWidth; i++) {
1602       unsigned MaskVal = Shuffle->getMaskValue(i);
1603       if (MaskVal == -1u) {
1604         UndefElts.set(i);
1605       } else if (MaskVal < LHSVWidth) {
1606         if (UndefElts4[MaskVal]) {
1607           NewUndefElts = true;
1608           UndefElts.set(i);
1609         }
1610       } else {
1611         if (UndefElts3[MaskVal - LHSVWidth]) {
1612           NewUndefElts = true;
1613           UndefElts.set(i);
1614         }
1615       }
1616     }
1617
1618     if (NewUndefElts) {
1619       // Add additional discovered undefs.
1620       std::vector<Constant*> Elts;
1621       for (unsigned i = 0; i < VWidth; ++i) {
1622         if (UndefElts[i])
1623           Elts.push_back(Context->getUndef(Type::Int32Ty));
1624         else
1625           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1626                                           Shuffle->getMaskValue(i)));
1627       }
1628       I->setOperand(2, Context->getConstantVector(Elts));
1629       MadeChange = true;
1630     }
1631     break;
1632   }
1633   case Instruction::BitCast: {
1634     // Vector->vector casts only.
1635     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1636     if (!VTy) break;
1637     unsigned InVWidth = VTy->getNumElements();
1638     APInt InputDemandedElts(InVWidth, 0);
1639     unsigned Ratio;
1640
1641     if (VWidth == InVWidth) {
1642       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1643       // elements as are demanded of us.
1644       Ratio = 1;
1645       InputDemandedElts = DemandedElts;
1646     } else if (VWidth > InVWidth) {
1647       // Untested so far.
1648       break;
1649       
1650       // If there are more elements in the result than there are in the source,
1651       // then an input element is live if any of the corresponding output
1652       // elements are live.
1653       Ratio = VWidth/InVWidth;
1654       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1655         if (DemandedElts[OutIdx])
1656           InputDemandedElts.set(OutIdx/Ratio);
1657       }
1658     } else {
1659       // Untested so far.
1660       break;
1661       
1662       // If there are more elements in the source than there are in the result,
1663       // then an input element is live if the corresponding output element is
1664       // live.
1665       Ratio = InVWidth/VWidth;
1666       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1667         if (DemandedElts[InIdx/Ratio])
1668           InputDemandedElts.set(InIdx);
1669     }
1670     
1671     // div/rem demand all inputs, because they don't want divide by zero.
1672     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1673                                       UndefElts2, Depth+1);
1674     if (TmpV) {
1675       I->setOperand(0, TmpV);
1676       MadeChange = true;
1677     }
1678     
1679     UndefElts = UndefElts2;
1680     if (VWidth > InVWidth) {
1681       assert(0 && "Unimp");
1682       // If there are more elements in the result than there are in the source,
1683       // then an output element is undef if the corresponding input element is
1684       // undef.
1685       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1686         if (UndefElts2[OutIdx/Ratio])
1687           UndefElts.set(OutIdx);
1688     } else if (VWidth < InVWidth) {
1689       assert(0 && "Unimp");
1690       // If there are more elements in the source than there are in the result,
1691       // then a result element is undef if all of the corresponding input
1692       // elements are undef.
1693       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1694       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1695         if (!UndefElts2[InIdx])            // Not undef?
1696           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1697     }
1698     break;
1699   }
1700   case Instruction::And:
1701   case Instruction::Or:
1702   case Instruction::Xor:
1703   case Instruction::Add:
1704   case Instruction::Sub:
1705   case Instruction::Mul:
1706     // div/rem demand all inputs, because they don't want divide by zero.
1707     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1708                                       UndefElts, Depth+1);
1709     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1710     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1711                                       UndefElts2, Depth+1);
1712     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1713       
1714     // Output elements are undefined if both are undefined.  Consider things
1715     // like undef&0.  The result is known zero, not undef.
1716     UndefElts &= UndefElts2;
1717     break;
1718     
1719   case Instruction::Call: {
1720     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1721     if (!II) break;
1722     switch (II->getIntrinsicID()) {
1723     default: break;
1724       
1725     // Binary vector operations that work column-wise.  A dest element is a
1726     // function of the corresponding input elements from the two inputs.
1727     case Intrinsic::x86_sse_sub_ss:
1728     case Intrinsic::x86_sse_mul_ss:
1729     case Intrinsic::x86_sse_min_ss:
1730     case Intrinsic::x86_sse_max_ss:
1731     case Intrinsic::x86_sse2_sub_sd:
1732     case Intrinsic::x86_sse2_mul_sd:
1733     case Intrinsic::x86_sse2_min_sd:
1734     case Intrinsic::x86_sse2_max_sd:
1735       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1736                                         UndefElts, Depth+1);
1737       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1738       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1739                                         UndefElts2, Depth+1);
1740       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1741
1742       // If only the low elt is demanded and this is a scalarizable intrinsic,
1743       // scalarize it now.
1744       if (DemandedElts == 1) {
1745         switch (II->getIntrinsicID()) {
1746         default: break;
1747         case Intrinsic::x86_sse_sub_ss:
1748         case Intrinsic::x86_sse_mul_ss:
1749         case Intrinsic::x86_sse2_sub_sd:
1750         case Intrinsic::x86_sse2_mul_sd:
1751           // TODO: Lower MIN/MAX/ABS/etc
1752           Value *LHS = II->getOperand(1);
1753           Value *RHS = II->getOperand(2);
1754           // Extract the element as scalars.
1755           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1756           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1757           
1758           switch (II->getIntrinsicID()) {
1759           default: assert(0 && "Case stmts out of sync!");
1760           case Intrinsic::x86_sse_sub_ss:
1761           case Intrinsic::x86_sse2_sub_sd:
1762             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1763                                                         II->getName()), *II);
1764             break;
1765           case Intrinsic::x86_sse_mul_ss:
1766           case Intrinsic::x86_sse2_mul_sd:
1767             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1768                                                          II->getName()), *II);
1769             break;
1770           }
1771           
1772           Instruction *New =
1773             InsertElementInst::Create(
1774               Context->getUndef(II->getType()), TmpV, 0U, II->getName());
1775           InsertNewInstBefore(New, *II);
1776           AddSoonDeadInstToWorklist(*II, 0);
1777           return New;
1778         }            
1779       }
1780         
1781       // Output elements are undefined if both are undefined.  Consider things
1782       // like undef&0.  The result is known zero, not undef.
1783       UndefElts &= UndefElts2;
1784       break;
1785     }
1786     break;
1787   }
1788   }
1789   return MadeChange ? I : 0;
1790 }
1791
1792
1793 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1794 /// function is designed to check a chain of associative operators for a
1795 /// potential to apply a certain optimization.  Since the optimization may be
1796 /// applicable if the expression was reassociated, this checks the chain, then
1797 /// reassociates the expression as necessary to expose the optimization
1798 /// opportunity.  This makes use of a special Functor, which must define
1799 /// 'shouldApply' and 'apply' methods.
1800 ///
1801 template<typename Functor>
1802 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1803                                    LLVMContext *Context) {
1804   unsigned Opcode = Root.getOpcode();
1805   Value *LHS = Root.getOperand(0);
1806
1807   // Quick check, see if the immediate LHS matches...
1808   if (F.shouldApply(LHS))
1809     return F.apply(Root);
1810
1811   // Otherwise, if the LHS is not of the same opcode as the root, return.
1812   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1813   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1814     // Should we apply this transform to the RHS?
1815     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1816
1817     // If not to the RHS, check to see if we should apply to the LHS...
1818     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1819       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1820       ShouldApply = true;
1821     }
1822
1823     // If the functor wants to apply the optimization to the RHS of LHSI,
1824     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1825     if (ShouldApply) {
1826       // Now all of the instructions are in the current basic block, go ahead
1827       // and perform the reassociation.
1828       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1829
1830       // First move the selected RHS to the LHS of the root...
1831       Root.setOperand(0, LHSI->getOperand(1));
1832
1833       // Make what used to be the LHS of the root be the user of the root...
1834       Value *ExtraOperand = TmpLHSI->getOperand(1);
1835       if (&Root == TmpLHSI) {
1836         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1837         return 0;
1838       }
1839       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1840       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1841       BasicBlock::iterator ARI = &Root; ++ARI;
1842       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1843       ARI = Root;
1844
1845       // Now propagate the ExtraOperand down the chain of instructions until we
1846       // get to LHSI.
1847       while (TmpLHSI != LHSI) {
1848         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1849         // Move the instruction to immediately before the chain we are
1850         // constructing to avoid breaking dominance properties.
1851         NextLHSI->moveBefore(ARI);
1852         ARI = NextLHSI;
1853
1854         Value *NextOp = NextLHSI->getOperand(1);
1855         NextLHSI->setOperand(1, ExtraOperand);
1856         TmpLHSI = NextLHSI;
1857         ExtraOperand = NextOp;
1858       }
1859
1860       // Now that the instructions are reassociated, have the functor perform
1861       // the transformation...
1862       return F.apply(Root);
1863     }
1864
1865     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1866   }
1867   return 0;
1868 }
1869
1870 namespace {
1871
1872 // AddRHS - Implements: X + X --> X << 1
1873 struct AddRHS {
1874   Value *RHS;
1875   LLVMContext *Context;
1876   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1877   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1878   Instruction *apply(BinaryOperator &Add) const {
1879     return BinaryOperator::CreateShl(Add.getOperand(0),
1880                                      Context->getConstantInt(Add.getType(), 1));
1881   }
1882 };
1883
1884 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1885 //                 iff C1&C2 == 0
1886 struct AddMaskingAnd {
1887   Constant *C2;
1888   LLVMContext *Context;
1889   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1890   bool shouldApply(Value *LHS) const {
1891     ConstantInt *C1;
1892     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1893            Context->getConstantExprAnd(C1, C2)->isNullValue();
1894   }
1895   Instruction *apply(BinaryOperator &Add) const {
1896     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1897   }
1898 };
1899
1900 }
1901
1902 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1903                                              InstCombiner *IC) {
1904   LLVMContext *Context = IC->getContext();
1905   
1906   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1907     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1908   }
1909
1910   // Figure out if the constant is the left or the right argument.
1911   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1912   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1913
1914   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1915     if (ConstIsRHS)
1916       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1917     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1918   }
1919
1920   Value *Op0 = SO, *Op1 = ConstOperand;
1921   if (!ConstIsRHS)
1922     std::swap(Op0, Op1);
1923   Instruction *New;
1924   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1925     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1926   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1927     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1928                           SO->getName()+".cmp");
1929   else {
1930     assert(0 && "Unknown binary instruction type!");
1931     abort();
1932   }
1933   return IC->InsertNewInstBefore(New, I);
1934 }
1935
1936 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1937 // constant as the other operand, try to fold the binary operator into the
1938 // select arguments.  This also works for Cast instructions, which obviously do
1939 // not have a second operand.
1940 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1941                                      InstCombiner *IC) {
1942   // Don't modify shared select instructions
1943   if (!SI->hasOneUse()) return 0;
1944   Value *TV = SI->getOperand(1);
1945   Value *FV = SI->getOperand(2);
1946
1947   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1948     // Bool selects with constant operands can be folded to logical ops.
1949     if (SI->getType() == Type::Int1Ty) return 0;
1950
1951     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1952     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1953
1954     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1955                               SelectFalseVal);
1956   }
1957   return 0;
1958 }
1959
1960
1961 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1962 /// node as operand #0, see if we can fold the instruction into the PHI (which
1963 /// is only possible if all operands to the PHI are constants).
1964 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1965   PHINode *PN = cast<PHINode>(I.getOperand(0));
1966   unsigned NumPHIValues = PN->getNumIncomingValues();
1967   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1968
1969   // Check to see if all of the operands of the PHI are constants.  If there is
1970   // one non-constant value, remember the BB it is.  If there is more than one
1971   // or if *it* is a PHI, bail out.
1972   BasicBlock *NonConstBB = 0;
1973   for (unsigned i = 0; i != NumPHIValues; ++i)
1974     if (!isa<Constant>(PN->getIncomingValue(i))) {
1975       if (NonConstBB) return 0;  // More than one non-const value.
1976       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1977       NonConstBB = PN->getIncomingBlock(i);
1978       
1979       // If the incoming non-constant value is in I's block, we have an infinite
1980       // loop.
1981       if (NonConstBB == I.getParent())
1982         return 0;
1983     }
1984   
1985   // If there is exactly one non-constant value, we can insert a copy of the
1986   // operation in that block.  However, if this is a critical edge, we would be
1987   // inserting the computation one some other paths (e.g. inside a loop).  Only
1988   // do this if the pred block is unconditionally branching into the phi block.
1989   if (NonConstBB) {
1990     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1991     if (!BI || !BI->isUnconditional()) return 0;
1992   }
1993
1994   // Okay, we can do the transformation: create the new PHI node.
1995   PHINode *NewPN = PHINode::Create(I.getType(), "");
1996   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1997   InsertNewInstBefore(NewPN, *PN);
1998   NewPN->takeName(PN);
1999
2000   // Next, add all of the operands to the PHI.
2001   if (I.getNumOperands() == 2) {
2002     Constant *C = cast<Constant>(I.getOperand(1));
2003     for (unsigned i = 0; i != NumPHIValues; ++i) {
2004       Value *InV = 0;
2005       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2006         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2007           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2008         else
2009           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2010       } else {
2011         assert(PN->getIncomingBlock(i) == NonConstBB);
2012         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2013           InV = BinaryOperator::Create(BO->getOpcode(),
2014                                        PN->getIncomingValue(i), C, "phitmp",
2015                                        NonConstBB->getTerminator());
2016         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2017           InV = CmpInst::Create(CI->getOpcode(), 
2018                                 CI->getPredicate(),
2019                                 PN->getIncomingValue(i), C, "phitmp",
2020                                 NonConstBB->getTerminator());
2021         else
2022           assert(0 && "Unknown binop!");
2023         
2024         AddToWorkList(cast<Instruction>(InV));
2025       }
2026       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2027     }
2028   } else { 
2029     CastInst *CI = cast<CastInst>(&I);
2030     const Type *RetTy = CI->getType();
2031     for (unsigned i = 0; i != NumPHIValues; ++i) {
2032       Value *InV;
2033       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2034         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2035       } else {
2036         assert(PN->getIncomingBlock(i) == NonConstBB);
2037         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2038                                I.getType(), "phitmp", 
2039                                NonConstBB->getTerminator());
2040         AddToWorkList(cast<Instruction>(InV));
2041       }
2042       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2043     }
2044   }
2045   return ReplaceInstUsesWith(I, NewPN);
2046 }
2047
2048
2049 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2050 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2051 /// This basically requires proving that the add in the original type would not
2052 /// overflow to change the sign bit or have a carry out.
2053 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2054   // There are different heuristics we can use for this.  Here are some simple
2055   // ones.
2056   
2057   // Add has the property that adding any two 2's complement numbers can only 
2058   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2059   // have at least two sign bits, we know that the addition of the two values will
2060   // sign extend fine.
2061   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2062     return true;
2063   
2064   
2065   // If one of the operands only has one non-zero bit, and if the other operand
2066   // has a known-zero bit in a more significant place than it (not including the
2067   // sign bit) the ripple may go up to and fill the zero, but won't change the
2068   // sign.  For example, (X & ~4) + 1.
2069   
2070   // TODO: Implement.
2071   
2072   return false;
2073 }
2074
2075
2076 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2077   bool Changed = SimplifyCommutative(I);
2078   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2079
2080   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2081     // X + undef -> undef
2082     if (isa<UndefValue>(RHS))
2083       return ReplaceInstUsesWith(I, RHS);
2084
2085     // X + 0 --> X
2086     if (RHSC->isNullValue())
2087       return ReplaceInstUsesWith(I, LHS);
2088
2089     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2090       // X + (signbit) --> X ^ signbit
2091       const APInt& Val = CI->getValue();
2092       uint32_t BitWidth = Val.getBitWidth();
2093       if (Val == APInt::getSignBit(BitWidth))
2094         return BinaryOperator::CreateXor(LHS, RHS);
2095       
2096       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2097       // (X & 254)+1 -> (X&254)|1
2098       if (SimplifyDemandedInstructionBits(I))
2099         return &I;
2100
2101       // zext(i1) - 1  ->  select i1, 0, -1
2102       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2103         if (CI->isAllOnesValue() &&
2104             ZI->getOperand(0)->getType() == Type::Int1Ty)
2105           return SelectInst::Create(ZI->getOperand(0),
2106                                     Context->getNullValue(I.getType()),
2107                               Context->getConstantIntAllOnesValue(I.getType()));
2108     }
2109
2110     if (isa<PHINode>(LHS))
2111       if (Instruction *NV = FoldOpIntoPhi(I))
2112         return NV;
2113     
2114     ConstantInt *XorRHS = 0;
2115     Value *XorLHS = 0;
2116     if (isa<ConstantInt>(RHSC) &&
2117         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2118       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2119       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2120       
2121       uint32_t Size = TySizeBits / 2;
2122       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123       APInt CFF80Val(-C0080Val);
2124       do {
2125         if (TySizeBits > Size) {
2126           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2128           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2130             // This is a sign extend if the top bits are known zero.
2131             if (!MaskedValueIsZero(XorLHS, 
2132                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2133               Size = 0;  // Not a sign ext, but can't be any others either.
2134             break;
2135           }
2136         }
2137         Size >>= 1;
2138         C0080Val = APIntOps::lshr(C0080Val, Size);
2139         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140       } while (Size >= 1);
2141       
2142       // FIXME: This shouldn't be necessary. When the backends can handle types
2143       // with funny bit widths then this switch statement should be removed. It
2144       // is just here to get the size of the "middle" type back up to something
2145       // that the back ends can handle.
2146       const Type *MiddleType = 0;
2147       switch (Size) {
2148         default: break;
2149         case 32: MiddleType = Type::Int32Ty; break;
2150         case 16: MiddleType = Type::Int16Ty; break;
2151         case  8: MiddleType = Type::Int8Ty; break;
2152       }
2153       if (MiddleType) {
2154         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2155         InsertNewInstBefore(NewTrunc, I);
2156         return new SExtInst(NewTrunc, I.getType(), I.getName());
2157       }
2158     }
2159   }
2160
2161   if (I.getType() == Type::Int1Ty)
2162     return BinaryOperator::CreateXor(LHS, RHS);
2163
2164   // X + X --> X << 1
2165   if (I.getType()->isInteger()) {
2166     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2167       return Result;
2168
2169     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170       if (RHSI->getOpcode() == Instruction::Sub)
2171         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2172           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2173     }
2174     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175       if (LHSI->getOpcode() == Instruction::Sub)
2176         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2177           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2178     }
2179   }
2180
2181   // -A + B  -->  B - A
2182   // -A + -B  -->  -(A + B)
2183   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2184     if (LHS->getType()->isIntOrIntVector()) {
2185       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2186         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2187         InsertNewInstBefore(NewAdd, I);
2188         return BinaryOperator::CreateNeg(NewAdd);
2189       }
2190     }
2191     
2192     return BinaryOperator::CreateSub(RHS, LHSV);
2193   }
2194
2195   // A + -B  -->  A - B
2196   if (!isa<Constant>(RHS))
2197     if (Value *V = dyn_castNegVal(RHS, Context))
2198       return BinaryOperator::CreateSub(LHS, V);
2199
2200
2201   ConstantInt *C2;
2202   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2203     if (X == RHS)   // X*C + X --> X * (C+1)
2204       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2205
2206     // X*C1 + X*C2 --> X * (C1+C2)
2207     ConstantInt *C1;
2208     if (X == dyn_castFoldableMul(RHS, C1, Context))
2209       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2210   }
2211
2212   // X + X*C --> X * (C+1)
2213   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2215
2216   // X + ~X --> -1   since   ~X = -X-1
2217   if (dyn_castNotVal(LHS, Context) == RHS ||
2218       dyn_castNotVal(RHS, Context) == LHS)
2219     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2220   
2221
2222   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2223   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2224     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2225       return R;
2226   
2227   // A+B --> A|B iff A and B have no bits set in common.
2228   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230     APInt LHSKnownOne(IT->getBitWidth(), 0);
2231     APInt LHSKnownZero(IT->getBitWidth(), 0);
2232     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233     if (LHSKnownZero != 0) {
2234       APInt RHSKnownOne(IT->getBitWidth(), 0);
2235       APInt RHSKnownZero(IT->getBitWidth(), 0);
2236       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2237       
2238       // No bits in common -> bitwise or.
2239       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2240         return BinaryOperator::CreateOr(LHS, RHS);
2241     }
2242   }
2243
2244   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2245   if (I.getType()->isIntOrIntVector()) {
2246     Value *W, *X, *Y, *Z;
2247     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2248         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2249       if (W != Y) {
2250         if (W == Z) {
2251           std::swap(Y, Z);
2252         } else if (Y == X) {
2253           std::swap(W, X);
2254         } else if (X == Z) {
2255           std::swap(Y, Z);
2256           std::swap(W, X);
2257         }
2258       }
2259
2260       if (W == Y) {
2261         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2262                                                             LHS->getName()), I);
2263         return BinaryOperator::CreateMul(W, NewAdd);
2264       }
2265     }
2266   }
2267
2268   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2269     Value *X = 0;
2270     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2271       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2272
2273     // (X & FF00) + xx00  -> (X+xx00) & FF00
2274     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2275       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2276       if (Anded == CRHS) {
2277         // See if all bits from the first bit set in the Add RHS up are included
2278         // in the mask.  First, get the rightmost bit.
2279         const APInt& AddRHSV = CRHS->getValue();
2280
2281         // Form a mask of all bits from the lowest bit added through the top.
2282         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2283
2284         // See if the and mask includes all of these bits.
2285         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2286
2287         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2288           // Okay, the xform is safe.  Insert the new add pronto.
2289           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2290                                                             LHS->getName()), I);
2291           return BinaryOperator::CreateAnd(NewAdd, C2);
2292         }
2293       }
2294     }
2295
2296     // Try to fold constant add into select arguments.
2297     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2298       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2299         return R;
2300   }
2301
2302   // add (cast *A to intptrtype) B -> 
2303   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2304   {
2305     CastInst *CI = dyn_cast<CastInst>(LHS);
2306     Value *Other = RHS;
2307     if (!CI) {
2308       CI = dyn_cast<CastInst>(RHS);
2309       Other = LHS;
2310     }
2311     if (CI && CI->getType()->isSized() && 
2312         (CI->getType()->getScalarSizeInBits() ==
2313          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2314         && isa<PointerType>(CI->getOperand(0)->getType())) {
2315       unsigned AS =
2316         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2317       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2318                                   Context->getPointerType(Type::Int8Ty, AS), I);
2319       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2320       return new PtrToIntInst(I2, CI->getType());
2321     }
2322   }
2323   
2324   // add (select X 0 (sub n A)) A  -->  select X A n
2325   {
2326     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2327     Value *A = RHS;
2328     if (!SI) {
2329       SI = dyn_cast<SelectInst>(RHS);
2330       A = LHS;
2331     }
2332     if (SI && SI->hasOneUse()) {
2333       Value *TV = SI->getTrueValue();
2334       Value *FV = SI->getFalseValue();
2335       Value *N;
2336
2337       // Can we fold the add into the argument of the select?
2338       // We check both true and false select arguments for a matching subtract.
2339       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2340         // Fold the add into the true select value.
2341         return SelectInst::Create(SI->getCondition(), N, A);
2342       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2343         // Fold the add into the false select value.
2344         return SelectInst::Create(SI->getCondition(), A, N);
2345     }
2346   }
2347
2348   // Check for (add (sext x), y), see if we can merge this into an
2349   // integer add followed by a sext.
2350   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2351     // (add (sext x), cst) --> (sext (add x, cst'))
2352     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2353       Constant *CI = 
2354         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2355       if (LHSConv->hasOneUse() &&
2356           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2357           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2358         // Insert the new, smaller add.
2359         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2360                                                         CI, "addconv");
2361         InsertNewInstBefore(NewAdd, I);
2362         return new SExtInst(NewAdd, I.getType());
2363       }
2364     }
2365     
2366     // (add (sext x), (sext y)) --> (sext (add int x, y))
2367     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2368       // Only do this if x/y have the same type, if at last one of them has a
2369       // single use (so we don't increase the number of sexts), and if the
2370       // integer add will not overflow.
2371       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2372           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2373           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2374                                    RHSConv->getOperand(0))) {
2375         // Insert the new integer add.
2376         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2377                                                         RHSConv->getOperand(0),
2378                                                         "addconv");
2379         InsertNewInstBefore(NewAdd, I);
2380         return new SExtInst(NewAdd, I.getType());
2381       }
2382     }
2383   }
2384
2385   return Changed ? &I : 0;
2386 }
2387
2388 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2389   bool Changed = SimplifyCommutative(I);
2390   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2391
2392   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2393     // X + 0 --> X
2394     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2395       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2396                               (I.getType())->getValueAPF()))
2397         return ReplaceInstUsesWith(I, LHS);
2398     }
2399
2400     if (isa<PHINode>(LHS))
2401       if (Instruction *NV = FoldOpIntoPhi(I))
2402         return NV;
2403   }
2404
2405   // -A + B  -->  B - A
2406   // -A + -B  -->  -(A + B)
2407   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2408     return BinaryOperator::CreateFSub(RHS, LHSV);
2409
2410   // A + -B  -->  A - B
2411   if (!isa<Constant>(RHS))
2412     if (Value *V = dyn_castFNegVal(RHS, Context))
2413       return BinaryOperator::CreateFSub(LHS, V);
2414
2415   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2416   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2417     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2418       return ReplaceInstUsesWith(I, LHS);
2419
2420   // Check for (add double (sitofp x), y), see if we can merge this into an
2421   // integer add followed by a promotion.
2422   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2423     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2424     // ... if the constant fits in the integer value.  This is useful for things
2425     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2426     // requires a constant pool load, and generally allows the add to be better
2427     // instcombined.
2428     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2429       Constant *CI = 
2430       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2431       if (LHSConv->hasOneUse() &&
2432           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2433           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2434         // Insert the new integer add.
2435         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2436                                                         CI, "addconv");
2437         InsertNewInstBefore(NewAdd, I);
2438         return new SIToFPInst(NewAdd, I.getType());
2439       }
2440     }
2441     
2442     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2443     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2444       // Only do this if x/y have the same type, if at last one of them has a
2445       // single use (so we don't increase the number of int->fp conversions),
2446       // and if the integer add will not overflow.
2447       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2448           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2449           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2450                                    RHSConv->getOperand(0))) {
2451         // Insert the new integer add.
2452         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2453                                                         RHSConv->getOperand(0),
2454                                                         "addconv");
2455         InsertNewInstBefore(NewAdd, I);
2456         return new SIToFPInst(NewAdd, I.getType());
2457       }
2458     }
2459   }
2460   
2461   return Changed ? &I : 0;
2462 }
2463
2464 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2465   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2466
2467   if (Op0 == Op1)                        // sub X, X  -> 0
2468     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2469
2470   // If this is a 'B = x-(-A)', change to B = x+A...
2471   if (Value *V = dyn_castNegVal(Op1, Context))
2472     return BinaryOperator::CreateAdd(Op0, V);
2473
2474   if (isa<UndefValue>(Op0))
2475     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2476   if (isa<UndefValue>(Op1))
2477     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2478
2479   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2480     // Replace (-1 - A) with (~A)...
2481     if (C->isAllOnesValue())
2482       return BinaryOperator::CreateNot(Op1);
2483
2484     // C - ~X == X + (1+C)
2485     Value *X = 0;
2486     if (match(Op1, m_Not(m_Value(X))))
2487       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2488
2489     // -(X >>u 31) -> (X >>s 31)
2490     // -(X >>s 31) -> (X >>u 31)
2491     if (C->isZero()) {
2492       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2493         if (SI->getOpcode() == Instruction::LShr) {
2494           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2495             // Check to see if we are shifting out everything but the sign bit.
2496             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2497                 SI->getType()->getPrimitiveSizeInBits()-1) {
2498               // Ok, the transformation is safe.  Insert AShr.
2499               return BinaryOperator::Create(Instruction::AShr, 
2500                                           SI->getOperand(0), CU, SI->getName());
2501             }
2502           }
2503         }
2504         else if (SI->getOpcode() == Instruction::AShr) {
2505           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2506             // Check to see if we are shifting out everything but the sign bit.
2507             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2508                 SI->getType()->getPrimitiveSizeInBits()-1) {
2509               // Ok, the transformation is safe.  Insert LShr. 
2510               return BinaryOperator::CreateLShr(
2511                                           SI->getOperand(0), CU, SI->getName());
2512             }
2513           }
2514         }
2515       }
2516     }
2517
2518     // Try to fold constant sub into select arguments.
2519     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2520       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2521         return R;
2522   }
2523
2524   if (I.getType() == Type::Int1Ty)
2525     return BinaryOperator::CreateXor(Op0, Op1);
2526
2527   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2528     if (Op1I->getOpcode() == Instruction::Add) {
2529       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2530         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2531       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2532         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2533       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2534         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2535           // C1-(X+C2) --> (C1-C2)-X
2536           return BinaryOperator::CreateSub(
2537             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2538       }
2539     }
2540
2541     if (Op1I->hasOneUse()) {
2542       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2543       // is not used by anyone else...
2544       //
2545       if (Op1I->getOpcode() == Instruction::Sub) {
2546         // Swap the two operands of the subexpr...
2547         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2548         Op1I->setOperand(0, IIOp1);
2549         Op1I->setOperand(1, IIOp0);
2550
2551         // Create the new top level add instruction...
2552         return BinaryOperator::CreateAdd(Op0, Op1);
2553       }
2554
2555       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2556       //
2557       if (Op1I->getOpcode() == Instruction::And &&
2558           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2559         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2560
2561         Value *NewNot =
2562           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2563         return BinaryOperator::CreateAnd(Op0, NewNot);
2564       }
2565
2566       // 0 - (X sdiv C)  -> (X sdiv -C)
2567       if (Op1I->getOpcode() == Instruction::SDiv)
2568         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2569           if (CSI->isZero())
2570             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2571               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2572                                           Context->getConstantExprNeg(DivRHS));
2573
2574       // X - X*C --> X * (1-C)
2575       ConstantInt *C2 = 0;
2576       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2577         Constant *CP1 = 
2578           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2579                                              C2);
2580         return BinaryOperator::CreateMul(Op0, CP1);
2581       }
2582     }
2583   }
2584
2585   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2586     if (Op0I->getOpcode() == Instruction::Add) {
2587       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2588         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2589       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2590         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2591     } else if (Op0I->getOpcode() == Instruction::Sub) {
2592       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2593         return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2594     }
2595   }
2596
2597   ConstantInt *C1;
2598   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2599     if (X == Op1)  // X*C - X --> X * (C-1)
2600       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2601
2602     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2603     if (X == dyn_castFoldableMul(Op1, C2, Context))
2604       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2605   }
2606   return 0;
2607 }
2608
2609 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2610   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2611
2612   // If this is a 'B = x-(-A)', change to B = x+A...
2613   if (Value *V = dyn_castFNegVal(Op1, Context))
2614     return BinaryOperator::CreateFAdd(Op0, V);
2615
2616   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2617     if (Op1I->getOpcode() == Instruction::FAdd) {
2618       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2619         return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2620       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2621         return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2622     }
2623   }
2624
2625   return 0;
2626 }
2627
2628 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2629 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2630 /// TrueIfSigned if the result of the comparison is true when the input value is
2631 /// signed.
2632 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2633                            bool &TrueIfSigned) {
2634   switch (pred) {
2635   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2636     TrueIfSigned = true;
2637     return RHS->isZero();
2638   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2639     TrueIfSigned = true;
2640     return RHS->isAllOnesValue();
2641   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2642     TrueIfSigned = false;
2643     return RHS->isAllOnesValue();
2644   case ICmpInst::ICMP_UGT:
2645     // True if LHS u> RHS and RHS == high-bit-mask - 1
2646     TrueIfSigned = true;
2647     return RHS->getValue() ==
2648       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2649   case ICmpInst::ICMP_UGE: 
2650     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2651     TrueIfSigned = true;
2652     return RHS->getValue().isSignBit();
2653   default:
2654     return false;
2655   }
2656 }
2657
2658 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2659   bool Changed = SimplifyCommutative(I);
2660   Value *Op0 = I.getOperand(0);
2661
2662   // TODO: If Op1 is undef and Op0 is finite, return zero.
2663   if (!I.getType()->isFPOrFPVector() &&
2664       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2665     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2666
2667   // Simplify mul instructions with a constant RHS...
2668   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2669     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2670
2671       // ((X << C1)*C2) == (X * (C2 << C1))
2672       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2673         if (SI->getOpcode() == Instruction::Shl)
2674           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2675             return BinaryOperator::CreateMul(SI->getOperand(0),
2676                                         Context->getConstantExprShl(CI, ShOp));
2677
2678       if (CI->isZero())
2679         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2680       if (CI->equalsInt(1))                  // X * 1  == X
2681         return ReplaceInstUsesWith(I, Op0);
2682       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2683         return BinaryOperator::CreateNeg(Op0, I.getName());
2684
2685       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2686       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2687         return BinaryOperator::CreateShl(Op0,
2688                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2689       }
2690     } else if (isa<VectorType>(Op1->getType())) {
2691       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2692
2693       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2694         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2695           return BinaryOperator::CreateNeg(Op0, I.getName());
2696
2697         // As above, vector X*splat(1.0) -> X in all defined cases.
2698         if (Constant *Splat = Op1V->getSplatValue()) {
2699           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2700             if (CI->equalsInt(1))
2701               return ReplaceInstUsesWith(I, Op0);
2702         }
2703       }
2704     }
2705     
2706     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2707       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2708           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2709         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2710         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2711                                                      Op1, "tmp");
2712         InsertNewInstBefore(Add, I);
2713         Value *C1C2 = Context->getConstantExprMul(Op1, 
2714                                            cast<Constant>(Op0I->getOperand(1)));
2715         return BinaryOperator::CreateAdd(Add, C1C2);
2716         
2717       }
2718
2719     // Try to fold constant mul into select arguments.
2720     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2721       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2722         return R;
2723
2724     if (isa<PHINode>(Op0))
2725       if (Instruction *NV = FoldOpIntoPhi(I))
2726         return NV;
2727   }
2728
2729   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2730     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2731       return BinaryOperator::CreateMul(Op0v, Op1v);
2732
2733   // (X / Y) *  Y = X - (X % Y)
2734   // (X / Y) * -Y = (X % Y) - X
2735   {
2736     Value *Op1 = I.getOperand(1);
2737     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2738     if (!BO ||
2739         (BO->getOpcode() != Instruction::UDiv && 
2740          BO->getOpcode() != Instruction::SDiv)) {
2741       Op1 = Op0;
2742       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2743     }
2744     Value *Neg = dyn_castNegVal(Op1, Context);
2745     if (BO && BO->hasOneUse() &&
2746         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2747         (BO->getOpcode() == Instruction::UDiv ||
2748          BO->getOpcode() == Instruction::SDiv)) {
2749       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2750
2751       Instruction *Rem;
2752       if (BO->getOpcode() == Instruction::UDiv)
2753         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2754       else
2755         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2756
2757       InsertNewInstBefore(Rem, I);
2758       Rem->takeName(BO);
2759
2760       if (Op1BO == Op1)
2761         return BinaryOperator::CreateSub(Op0BO, Rem);
2762       else
2763         return BinaryOperator::CreateSub(Rem, Op0BO);
2764     }
2765   }
2766
2767   if (I.getType() == Type::Int1Ty)
2768     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2769
2770   // If one of the operands of the multiply is a cast from a boolean value, then
2771   // we know the bool is either zero or one, so this is a 'masking' multiply.
2772   // See if we can simplify things based on how the boolean was originally
2773   // formed.
2774   CastInst *BoolCast = 0;
2775   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2776     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2777       BoolCast = CI;
2778   if (!BoolCast)
2779     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2780       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2781         BoolCast = CI;
2782   if (BoolCast) {
2783     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2784       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2785       const Type *SCOpTy = SCIOp0->getType();
2786       bool TIS = false;
2787       
2788       // If the icmp is true iff the sign bit of X is set, then convert this
2789       // multiply into a shift/and combination.
2790       if (isa<ConstantInt>(SCIOp1) &&
2791           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2792           TIS) {
2793         // Shift the X value right to turn it into "all signbits".
2794         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2795                                           SCOpTy->getPrimitiveSizeInBits()-1);
2796         Value *V =
2797           InsertNewInstBefore(
2798             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2799                                             BoolCast->getOperand(0)->getName()+
2800                                             ".mask"), I);
2801
2802         // If the multiply type is not the same as the source type, sign extend
2803         // or truncate to the multiply type.
2804         if (I.getType() != V->getType()) {
2805           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2806           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2807           Instruction::CastOps opcode = 
2808             (SrcBits == DstBits ? Instruction::BitCast : 
2809              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2810           V = InsertCastBefore(opcode, V, I.getType(), I);
2811         }
2812
2813         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2814         return BinaryOperator::CreateAnd(V, OtherOp);
2815       }
2816     }
2817   }
2818
2819   return Changed ? &I : 0;
2820 }
2821
2822 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2823   bool Changed = SimplifyCommutative(I);
2824   Value *Op0 = I.getOperand(0);
2825
2826   // Simplify mul instructions with a constant RHS...
2827   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2828     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2829       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2830       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2831       if (Op1F->isExactlyValue(1.0))
2832         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2833     } else if (isa<VectorType>(Op1->getType())) {
2834       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2835         // As above, vector X*splat(1.0) -> X in all defined cases.
2836         if (Constant *Splat = Op1V->getSplatValue()) {
2837           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2838             if (F->isExactlyValue(1.0))
2839               return ReplaceInstUsesWith(I, Op0);
2840         }
2841       }
2842     }
2843
2844     // Try to fold constant mul into select arguments.
2845     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2846       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2847         return R;
2848
2849     if (isa<PHINode>(Op0))
2850       if (Instruction *NV = FoldOpIntoPhi(I))
2851         return NV;
2852   }
2853
2854   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2855     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2856       return BinaryOperator::CreateFMul(Op0v, Op1v);
2857
2858   return Changed ? &I : 0;
2859 }
2860
2861 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2862 /// instruction.
2863 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2864   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2865   
2866   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2867   int NonNullOperand = -1;
2868   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2869     if (ST->isNullValue())
2870       NonNullOperand = 2;
2871   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2872   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2873     if (ST->isNullValue())
2874       NonNullOperand = 1;
2875   
2876   if (NonNullOperand == -1)
2877     return false;
2878   
2879   Value *SelectCond = SI->getOperand(0);
2880   
2881   // Change the div/rem to use 'Y' instead of the select.
2882   I.setOperand(1, SI->getOperand(NonNullOperand));
2883   
2884   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2885   // problem.  However, the select, or the condition of the select may have
2886   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2887   // propagate the known value for the select into other uses of it, and
2888   // propagate a known value of the condition into its other users.
2889   
2890   // If the select and condition only have a single use, don't bother with this,
2891   // early exit.
2892   if (SI->use_empty() && SelectCond->hasOneUse())
2893     return true;
2894   
2895   // Scan the current block backward, looking for other uses of SI.
2896   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2897   
2898   while (BBI != BBFront) {
2899     --BBI;
2900     // If we found a call to a function, we can't assume it will return, so
2901     // information from below it cannot be propagated above it.
2902     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2903       break;
2904     
2905     // Replace uses of the select or its condition with the known values.
2906     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2907          I != E; ++I) {
2908       if (*I == SI) {
2909         *I = SI->getOperand(NonNullOperand);
2910         AddToWorkList(BBI);
2911       } else if (*I == SelectCond) {
2912         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2913                                    Context->getConstantIntFalse();
2914         AddToWorkList(BBI);
2915       }
2916     }
2917     
2918     // If we past the instruction, quit looking for it.
2919     if (&*BBI == SI)
2920       SI = 0;
2921     if (&*BBI == SelectCond)
2922       SelectCond = 0;
2923     
2924     // If we ran out of things to eliminate, break out of the loop.
2925     if (SelectCond == 0 && SI == 0)
2926       break;
2927     
2928   }
2929   return true;
2930 }
2931
2932
2933 /// This function implements the transforms on div instructions that work
2934 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2935 /// used by the visitors to those instructions.
2936 /// @brief Transforms common to all three div instructions
2937 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2938   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2939
2940   // undef / X -> 0        for integer.
2941   // undef / X -> undef    for FP (the undef could be a snan).
2942   if (isa<UndefValue>(Op0)) {
2943     if (Op0->getType()->isFPOrFPVector())
2944       return ReplaceInstUsesWith(I, Op0);
2945     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2946   }
2947
2948   // X / undef -> undef
2949   if (isa<UndefValue>(Op1))
2950     return ReplaceInstUsesWith(I, Op1);
2951
2952   return 0;
2953 }
2954
2955 /// This function implements the transforms common to both integer division
2956 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2957 /// division instructions.
2958 /// @brief Common integer divide transforms
2959 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2960   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2961
2962   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2963   if (Op0 == Op1) {
2964     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2965       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2966       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2967       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2968     }
2969
2970     Constant *CI = Context->getConstantInt(I.getType(), 1);
2971     return ReplaceInstUsesWith(I, CI);
2972   }
2973   
2974   if (Instruction *Common = commonDivTransforms(I))
2975     return Common;
2976   
2977   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2978   // This does not apply for fdiv.
2979   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2980     return &I;
2981
2982   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2983     // div X, 1 == X
2984     if (RHS->equalsInt(1))
2985       return ReplaceInstUsesWith(I, Op0);
2986
2987     // (X / C1) / C2  -> X / (C1*C2)
2988     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2989       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2990         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2991           if (MultiplyOverflows(RHS, LHSRHS,
2992                                 I.getOpcode()==Instruction::SDiv, Context))
2993             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2994           else 
2995             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2996                                       Context->getConstantExprMul(RHS, LHSRHS));
2997         }
2998
2999     if (!RHS->isZero()) { // avoid X udiv 0
3000       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3001         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3002           return R;
3003       if (isa<PHINode>(Op0))
3004         if (Instruction *NV = FoldOpIntoPhi(I))
3005           return NV;
3006     }
3007   }
3008
3009   // 0 / X == 0, we don't need to preserve faults!
3010   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3011     if (LHS->equalsInt(0))
3012       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3013
3014   // It can't be division by zero, hence it must be division by one.
3015   if (I.getType() == Type::Int1Ty)
3016     return ReplaceInstUsesWith(I, Op0);
3017
3018   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3019     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3020       // div X, 1 == X
3021       if (X->isOne())
3022         return ReplaceInstUsesWith(I, Op0);
3023   }
3024
3025   return 0;
3026 }
3027
3028 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3029   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3030
3031   // Handle the integer div common cases
3032   if (Instruction *Common = commonIDivTransforms(I))
3033     return Common;
3034
3035   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3036     // X udiv C^2 -> X >> C
3037     // Check to see if this is an unsigned division with an exact power of 2,
3038     // if so, convert to a right shift.
3039     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3040       return BinaryOperator::CreateLShr(Op0, 
3041             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3042
3043     // X udiv C, where C >= signbit
3044     if (C->getValue().isNegative()) {
3045       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3046                                       I);
3047       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3048                                 Context->getConstantInt(I.getType(), 1));
3049     }
3050   }
3051
3052   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3053   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3054     if (RHSI->getOpcode() == Instruction::Shl &&
3055         isa<ConstantInt>(RHSI->getOperand(0))) {
3056       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3057       if (C1.isPowerOf2()) {
3058         Value *N = RHSI->getOperand(1);
3059         const Type *NTy = N->getType();
3060         if (uint32_t C2 = C1.logBase2()) {
3061           Constant *C2V = Context->getConstantInt(NTy, C2);
3062           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3063         }
3064         return BinaryOperator::CreateLShr(Op0, N);
3065       }
3066     }
3067   }
3068   
3069   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3070   // where C1&C2 are powers of two.
3071   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3072     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3073       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3074         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3075         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3076           // Compute the shift amounts
3077           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3078           // Construct the "on true" case of the select
3079           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3080           Instruction *TSI = BinaryOperator::CreateLShr(
3081                                                  Op0, TC, SI->getName()+".t");
3082           TSI = InsertNewInstBefore(TSI, I);
3083   
3084           // Construct the "on false" case of the select
3085           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3086           Instruction *FSI = BinaryOperator::CreateLShr(
3087                                                  Op0, FC, SI->getName()+".f");
3088           FSI = InsertNewInstBefore(FSI, I);
3089
3090           // construct the select instruction and return it.
3091           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3092         }
3093       }
3094   return 0;
3095 }
3096
3097 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3098   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3099
3100   // Handle the integer div common cases
3101   if (Instruction *Common = commonIDivTransforms(I))
3102     return Common;
3103
3104   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3105     // sdiv X, -1 == -X
3106     if (RHS->isAllOnesValue())
3107       return BinaryOperator::CreateNeg(Op0);
3108   }
3109
3110   // If the sign bits of both operands are zero (i.e. we can prove they are
3111   // unsigned inputs), turn this into a udiv.
3112   if (I.getType()->isInteger()) {
3113     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3114     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3115       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3116       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3117     }
3118   }      
3119   
3120   return 0;
3121 }
3122
3123 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3124   return commonDivTransforms(I);
3125 }
3126
3127 /// This function implements the transforms on rem instructions that work
3128 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3129 /// is used by the visitors to those instructions.
3130 /// @brief Transforms common to all three rem instructions
3131 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3132   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3133
3134   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3135     if (I.getType()->isFPOrFPVector())
3136       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3137     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3138   }
3139   if (isa<UndefValue>(Op1))
3140     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3141
3142   // Handle cases involving: rem X, (select Cond, Y, Z)
3143   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3144     return &I;
3145
3146   return 0;
3147 }
3148
3149 /// This function implements the transforms common to both integer remainder
3150 /// instructions (urem and srem). It is called by the visitors to those integer
3151 /// remainder instructions.
3152 /// @brief Common integer remainder transforms
3153 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3154   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3155
3156   if (Instruction *common = commonRemTransforms(I))
3157     return common;
3158
3159   // 0 % X == 0 for integer, we don't need to preserve faults!
3160   if (Constant *LHS = dyn_cast<Constant>(Op0))
3161     if (LHS->isNullValue())
3162       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3163
3164   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3165     // X % 0 == undef, we don't need to preserve faults!
3166     if (RHS->equalsInt(0))
3167       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3168     
3169     if (RHS->equalsInt(1))  // X % 1 == 0
3170       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3171
3172     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3173       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3174         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3175           return R;
3176       } else if (isa<PHINode>(Op0I)) {
3177         if (Instruction *NV = FoldOpIntoPhi(I))
3178           return NV;
3179       }
3180
3181       // See if we can fold away this rem instruction.
3182       if (SimplifyDemandedInstructionBits(I))
3183         return &I;
3184     }
3185   }
3186
3187   return 0;
3188 }
3189
3190 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3191   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3192
3193   if (Instruction *common = commonIRemTransforms(I))
3194     return common;
3195   
3196   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3197     // X urem C^2 -> X and C
3198     // Check to see if this is an unsigned remainder with an exact power of 2,
3199     // if so, convert to a bitwise and.
3200     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3201       if (C->getValue().isPowerOf2())
3202         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3203   }
3204
3205   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3206     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3207     if (RHSI->getOpcode() == Instruction::Shl &&
3208         isa<ConstantInt>(RHSI->getOperand(0))) {
3209       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3210         Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
3211         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3212                                                                    "tmp"), I);
3213         return BinaryOperator::CreateAnd(Op0, Add);
3214       }
3215     }
3216   }
3217
3218   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3219   // where C1&C2 are powers of two.
3220   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3221     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3222       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3223         // STO == 0 and SFO == 0 handled above.
3224         if ((STO->getValue().isPowerOf2()) && 
3225             (SFO->getValue().isPowerOf2())) {
3226           Value *TrueAnd = InsertNewInstBefore(
3227             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3228                                       SI->getName()+".t"), I);
3229           Value *FalseAnd = InsertNewInstBefore(
3230             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3231                                       SI->getName()+".f"), I);
3232           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3233         }
3234       }
3235   }
3236   
3237   return 0;
3238 }
3239
3240 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3241   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
3243   // Handle the integer rem common cases
3244   if (Instruction *common = commonIRemTransforms(I))
3245     return common;
3246   
3247   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3248     if (!isa<Constant>(RHSNeg) ||
3249         (isa<ConstantInt>(RHSNeg) &&
3250          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3251       // X % -Y -> X % Y
3252       AddUsesToWorkList(I);
3253       I.setOperand(1, RHSNeg);
3254       return &I;
3255     }
3256
3257   // If the sign bits of both operands are zero (i.e. we can prove they are
3258   // unsigned inputs), turn this into a urem.
3259   if (I.getType()->isInteger()) {
3260     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3261     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3262       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3263       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3264     }
3265   }
3266
3267   // If it's a constant vector, flip any negative values positive.
3268   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3269     unsigned VWidth = RHSV->getNumOperands();
3270
3271     bool hasNegative = false;
3272     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3273       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3274         if (RHS->getValue().isNegative())
3275           hasNegative = true;
3276
3277     if (hasNegative) {
3278       std::vector<Constant *> Elts(VWidth);
3279       for (unsigned i = 0; i != VWidth; ++i) {
3280         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3281           if (RHS->getValue().isNegative())
3282             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3283           else
3284             Elts[i] = RHS;
3285         }
3286       }
3287
3288       Constant *NewRHSV = Context->getConstantVector(Elts);
3289       if (NewRHSV != RHSV) {
3290         AddUsesToWorkList(I);
3291         I.setOperand(1, NewRHSV);
3292         return &I;
3293       }
3294     }
3295   }
3296
3297   return 0;
3298 }
3299
3300 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3301   return commonRemTransforms(I);
3302 }
3303
3304 // isOneBitSet - Return true if there is exactly one bit set in the specified
3305 // constant.
3306 static bool isOneBitSet(const ConstantInt *CI) {
3307   return CI->getValue().isPowerOf2();
3308 }
3309
3310 // isHighOnes - Return true if the constant is of the form 1+0+.
3311 // This is the same as lowones(~X).
3312 static bool isHighOnes(const ConstantInt *CI) {
3313   return (~CI->getValue() + 1).isPowerOf2();
3314 }
3315
3316 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3317 /// are carefully arranged to allow folding of expressions such as:
3318 ///
3319 ///      (A < B) | (A > B) --> (A != B)
3320 ///
3321 /// Note that this is only valid if the first and second predicates have the
3322 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3323 ///
3324 /// Three bits are used to represent the condition, as follows:
3325 ///   0  A > B
3326 ///   1  A == B
3327 ///   2  A < B
3328 ///
3329 /// <=>  Value  Definition
3330 /// 000     0   Always false
3331 /// 001     1   A >  B
3332 /// 010     2   A == B
3333 /// 011     3   A >= B
3334 /// 100     4   A <  B
3335 /// 101     5   A != B
3336 /// 110     6   A <= B
3337 /// 111     7   Always true
3338 ///  
3339 static unsigned getICmpCode(const ICmpInst *ICI) {
3340   switch (ICI->getPredicate()) {
3341     // False -> 0
3342   case ICmpInst::ICMP_UGT: return 1;  // 001
3343   case ICmpInst::ICMP_SGT: return 1;  // 001
3344   case ICmpInst::ICMP_EQ:  return 2;  // 010
3345   case ICmpInst::ICMP_UGE: return 3;  // 011
3346   case ICmpInst::ICMP_SGE: return 3;  // 011
3347   case ICmpInst::ICMP_ULT: return 4;  // 100
3348   case ICmpInst::ICMP_SLT: return 4;  // 100
3349   case ICmpInst::ICMP_NE:  return 5;  // 101
3350   case ICmpInst::ICMP_ULE: return 6;  // 110
3351   case ICmpInst::ICMP_SLE: return 6;  // 110
3352     // True -> 7
3353   default:
3354     assert(0 && "Invalid ICmp predicate!");
3355     return 0;
3356   }
3357 }
3358
3359 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3360 /// predicate into a three bit mask. It also returns whether it is an ordered
3361 /// predicate by reference.
3362 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3363   isOrdered = false;
3364   switch (CC) {
3365   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3366   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3367   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3368   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3369   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3370   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3371   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3372   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3373   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3374   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3375   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3376   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3377   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3378   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3379     // True -> 7
3380   default:
3381     // Not expecting FCMP_FALSE and FCMP_TRUE;
3382     assert(0 && "Unexpected FCmp predicate!");
3383     return 0;
3384   }
3385 }
3386
3387 /// getICmpValue - This is the complement of getICmpCode, which turns an
3388 /// opcode and two operands into either a constant true or false, or a brand 
3389 /// new ICmp instruction. The sign is passed in to determine which kind
3390 /// of predicate to use in the new icmp instruction.
3391 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3392                            LLVMContext *Context) {
3393   switch (code) {
3394   default: assert(0 && "Illegal ICmp code!");
3395   case  0: return Context->getConstantIntFalse();
3396   case  1: 
3397     if (sign)
3398       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3399     else
3400       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3401   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3402   case  3: 
3403     if (sign)
3404       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3405     else
3406       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3407   case  4: 
3408     if (sign)
3409       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3410     else
3411       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3412   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3413   case  6: 
3414     if (sign)
3415       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3416     else
3417       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3418   case  7: return Context->getConstantIntTrue();
3419   }
3420 }
3421
3422 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3423 /// opcode and two operands into either a FCmp instruction. isordered is passed
3424 /// in to determine which kind of predicate to use in the new fcmp instruction.
3425 static Value *getFCmpValue(bool isordered, unsigned code,
3426                            Value *LHS, Value *RHS, LLVMContext *Context) {
3427   switch (code) {
3428   default: assert(0 && "Illegal FCmp code!");
3429   case  0:
3430     if (isordered)
3431       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3432     else
3433       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3434   case  1: 
3435     if (isordered)
3436       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3437     else
3438       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3439   case  2: 
3440     if (isordered)
3441       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3442     else
3443       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3444   case  3: 
3445     if (isordered)
3446       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3447     else
3448       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3449   case  4: 
3450     if (isordered)
3451       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3452     else
3453       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3454   case  5: 
3455     if (isordered)
3456       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3457     else
3458       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3459   case  6: 
3460     if (isordered)
3461       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3462     else
3463       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3464   case  7: return Context->getConstantIntTrue();
3465   }
3466 }
3467
3468 /// PredicatesFoldable - Return true if both predicates match sign or if at
3469 /// least one of them is an equality comparison (which is signless).
3470 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3471   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3472          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3473          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3474 }
3475
3476 namespace { 
3477 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3478 struct FoldICmpLogical {
3479   InstCombiner &IC;
3480   Value *LHS, *RHS;
3481   ICmpInst::Predicate pred;
3482   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3483     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3484       pred(ICI->getPredicate()) {}
3485   bool shouldApply(Value *V) const {
3486     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3487       if (PredicatesFoldable(pred, ICI->getPredicate()))
3488         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3489                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3490     return false;
3491   }
3492   Instruction *apply(Instruction &Log) const {
3493     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3494     if (ICI->getOperand(0) != LHS) {
3495       assert(ICI->getOperand(1) == LHS);
3496       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3497     }
3498
3499     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3500     unsigned LHSCode = getICmpCode(ICI);
3501     unsigned RHSCode = getICmpCode(RHSICI);
3502     unsigned Code;
3503     switch (Log.getOpcode()) {
3504     case Instruction::And: Code = LHSCode & RHSCode; break;
3505     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3506     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3507     default: assert(0 && "Illegal logical opcode!"); return 0;
3508     }
3509
3510     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3511                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3512       
3513     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3514     if (Instruction *I = dyn_cast<Instruction>(RV))
3515       return I;
3516     // Otherwise, it's a constant boolean value...
3517     return IC.ReplaceInstUsesWith(Log, RV);
3518   }
3519 };
3520 } // end anonymous namespace
3521
3522 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3523 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3524 // guaranteed to be a binary operator.
3525 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3526                                     ConstantInt *OpRHS,
3527                                     ConstantInt *AndRHS,
3528                                     BinaryOperator &TheAnd) {
3529   Value *X = Op->getOperand(0);
3530   Constant *Together = 0;
3531   if (!Op->isShift())
3532     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3533
3534   switch (Op->getOpcode()) {
3535   case Instruction::Xor:
3536     if (Op->hasOneUse()) {
3537       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3538       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3539       InsertNewInstBefore(And, TheAnd);
3540       And->takeName(Op);
3541       return BinaryOperator::CreateXor(And, Together);
3542     }
3543     break;
3544   case Instruction::Or:
3545     if (Together == AndRHS) // (X | C) & C --> C
3546       return ReplaceInstUsesWith(TheAnd, AndRHS);
3547
3548     if (Op->hasOneUse() && Together != OpRHS) {
3549       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3550       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3551       InsertNewInstBefore(Or, TheAnd);
3552       Or->takeName(Op);
3553       return BinaryOperator::CreateAnd(Or, AndRHS);
3554     }
3555     break;
3556   case Instruction::Add:
3557     if (Op->hasOneUse()) {
3558       // Adding a one to a single bit bit-field should be turned into an XOR
3559       // of the bit.  First thing to check is to see if this AND is with a
3560       // single bit constant.
3561       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3562
3563       // If there is only one bit set...
3564       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3565         // Ok, at this point, we know that we are masking the result of the
3566         // ADD down to exactly one bit.  If the constant we are adding has
3567         // no bits set below this bit, then we can eliminate the ADD.
3568         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3569
3570         // Check to see if any bits below the one bit set in AndRHSV are set.
3571         if ((AddRHS & (AndRHSV-1)) == 0) {
3572           // If not, the only thing that can effect the output of the AND is
3573           // the bit specified by AndRHSV.  If that bit is set, the effect of
3574           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3575           // no effect.
3576           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3577             TheAnd.setOperand(0, X);
3578             return &TheAnd;
3579           } else {
3580             // Pull the XOR out of the AND.
3581             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3582             InsertNewInstBefore(NewAnd, TheAnd);
3583             NewAnd->takeName(Op);
3584             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3585           }
3586         }
3587       }
3588     }
3589     break;
3590
3591   case Instruction::Shl: {
3592     // We know that the AND will not produce any of the bits shifted in, so if
3593     // the anded constant includes them, clear them now!
3594     //
3595     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3596     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3597     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3598     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3599
3600     if (CI->getValue() == ShlMask) { 
3601     // Masking out bits that the shift already masks
3602       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3603     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3604       TheAnd.setOperand(1, CI);
3605       return &TheAnd;
3606     }
3607     break;
3608   }
3609   case Instruction::LShr:
3610   {
3611     // We know that the AND will not produce any of the bits shifted in, so if
3612     // the anded constant includes them, clear them now!  This only applies to
3613     // unsigned shifts, because a signed shr may bring in set bits!
3614     //
3615     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3616     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3617     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3618     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3619
3620     if (CI->getValue() == ShrMask) {   
3621     // Masking out bits that the shift already masks.
3622       return ReplaceInstUsesWith(TheAnd, Op);
3623     } else if (CI != AndRHS) {
3624       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3625       return &TheAnd;
3626     }
3627     break;
3628   }
3629   case Instruction::AShr:
3630     // Signed shr.
3631     // See if this is shifting in some sign extension, then masking it out
3632     // with an and.
3633     if (Op->hasOneUse()) {
3634       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3635       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3636       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3637       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3638       if (C == AndRHS) {          // Masking out bits shifted in.
3639         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3640         // Make the argument unsigned.
3641         Value *ShVal = Op->getOperand(0);
3642         ShVal = InsertNewInstBefore(
3643             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3644                                    Op->getName()), TheAnd);
3645         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3646       }
3647     }
3648     break;
3649   }
3650   return 0;
3651 }
3652
3653
3654 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3655 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3656 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3657 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3658 /// insert new instructions.
3659 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3660                                            bool isSigned, bool Inside, 
3661                                            Instruction &IB) {
3662   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3663             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3664          "Lo is not <= Hi in range emission code!");
3665     
3666   if (Inside) {
3667     if (Lo == Hi)  // Trivially false.
3668       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3669
3670     // V >= Min && V < Hi --> V < Hi
3671     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3672       ICmpInst::Predicate pred = (isSigned ? 
3673         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3674       return new ICmpInst(pred, V, Hi);
3675     }
3676
3677     // Emit V-Lo <u Hi-Lo
3678     Constant *NegLo = Context->getConstantExprNeg(Lo);
3679     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3680     InsertNewInstBefore(Add, IB);
3681     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3682     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3683   }
3684
3685   if (Lo == Hi)  // Trivially true.
3686     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3687
3688   // V < Min || V >= Hi -> V > Hi-1
3689   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3690   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3691     ICmpInst::Predicate pred = (isSigned ? 
3692         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3693     return new ICmpInst(pred, V, Hi);
3694   }
3695
3696   // Emit V-Lo >u Hi-1-Lo
3697   // Note that Hi has already had one subtracted from it, above.
3698   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3699   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3700   InsertNewInstBefore(Add, IB);
3701   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3702   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3703 }
3704
3705 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3706 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3707 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3708 // not, since all 1s are not contiguous.
3709 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3710   const APInt& V = Val->getValue();
3711   uint32_t BitWidth = Val->getType()->getBitWidth();
3712   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3713
3714   // look for the first zero bit after the run of ones
3715   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3716   // look for the first non-zero bit
3717   ME = V.getActiveBits(); 
3718   return true;
3719 }
3720
3721 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3722 /// where isSub determines whether the operator is a sub.  If we can fold one of
3723 /// the following xforms:
3724 /// 
3725 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3726 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3727 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3728 ///
3729 /// return (A +/- B).
3730 ///
3731 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3732                                         ConstantInt *Mask, bool isSub,
3733                                         Instruction &I) {
3734   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3735   if (!LHSI || LHSI->getNumOperands() != 2 ||
3736       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3737
3738   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3739
3740   switch (LHSI->getOpcode()) {
3741   default: return 0;
3742   case Instruction::And:
3743     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3744       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3745       if ((Mask->getValue().countLeadingZeros() + 
3746            Mask->getValue().countPopulation()) == 
3747           Mask->getValue().getBitWidth())
3748         break;
3749
3750       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3751       // part, we don't need any explicit masks to take them out of A.  If that
3752       // is all N is, ignore it.
3753       uint32_t MB = 0, ME = 0;
3754       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3755         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3756         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3757         if (MaskedValueIsZero(RHS, Mask))
3758           break;
3759       }
3760     }
3761     return 0;
3762   case Instruction::Or:
3763   case Instruction::Xor:
3764     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3765     if ((Mask->getValue().countLeadingZeros() + 
3766          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3767         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3768       break;
3769     return 0;
3770   }
3771   
3772   Instruction *New;
3773   if (isSub)
3774     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3775   else
3776     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3777   return InsertNewInstBefore(New, I);
3778 }
3779
3780 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3781 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3782                                           ICmpInst *LHS, ICmpInst *RHS) {
3783   Value *Val, *Val2;
3784   ConstantInt *LHSCst, *RHSCst;
3785   ICmpInst::Predicate LHSCC, RHSCC;
3786   
3787   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3788   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3789       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3790     return 0;
3791   
3792   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3793   // where C is a power of 2
3794   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3795       LHSCst->getValue().isPowerOf2()) {
3796     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3797     InsertNewInstBefore(NewOr, I);
3798     return new ICmpInst(LHSCC, NewOr, LHSCst);
3799   }
3800   
3801   // From here on, we only handle:
3802   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3803   if (Val != Val2) return 0;
3804   
3805   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3806   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3807       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3808       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3809       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3810     return 0;
3811   
3812   // We can't fold (ugt x, C) & (sgt x, C2).
3813   if (!PredicatesFoldable(LHSCC, RHSCC))
3814     return 0;
3815     
3816   // Ensure that the larger constant is on the RHS.
3817   bool ShouldSwap;
3818   if (ICmpInst::isSignedPredicate(LHSCC) ||
3819       (ICmpInst::isEquality(LHSCC) && 
3820        ICmpInst::isSignedPredicate(RHSCC)))
3821     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3822   else
3823     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3824     
3825   if (ShouldSwap) {
3826     std::swap(LHS, RHS);
3827     std::swap(LHSCst, RHSCst);
3828     std::swap(LHSCC, RHSCC);
3829   }
3830
3831   // At this point, we know we have have two icmp instructions
3832   // comparing a value against two constants and and'ing the result
3833   // together.  Because of the above check, we know that we only have
3834   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3835   // (from the FoldICmpLogical check above), that the two constants 
3836   // are not equal and that the larger constant is on the RHS
3837   assert(LHSCst != RHSCst && "Compares not folded above?");
3838
3839   switch (LHSCC) {
3840   default: assert(0 && "Unknown integer condition code!");
3841   case ICmpInst::ICMP_EQ:
3842     switch (RHSCC) {
3843     default: assert(0 && "Unknown integer condition code!");
3844     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3845     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3846     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3847       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3848     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3849     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3850     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3851       return ReplaceInstUsesWith(I, LHS);
3852     }
3853   case ICmpInst::ICMP_NE:
3854     switch (RHSCC) {
3855     default: assert(0 && "Unknown integer condition code!");
3856     case ICmpInst::ICMP_ULT:
3857       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3858         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3859       break;                        // (X != 13 & X u< 15) -> no change
3860     case ICmpInst::ICMP_SLT:
3861       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3862         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3863       break;                        // (X != 13 & X s< 15) -> no change
3864     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3865     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3866     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3867       return ReplaceInstUsesWith(I, RHS);
3868     case ICmpInst::ICMP_NE:
3869       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3870         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3871         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3872                                                      Val->getName()+".off");
3873         InsertNewInstBefore(Add, I);
3874         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3875                             Context->getConstantInt(Add->getType(), 1));
3876       }
3877       break;                        // (X != 13 & X != 15) -> no change
3878     }
3879     break;
3880   case ICmpInst::ICMP_ULT:
3881     switch (RHSCC) {
3882     default: assert(0 && "Unknown integer condition code!");
3883     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3884     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3885       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3886     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3887       break;
3888     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3889     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3890       return ReplaceInstUsesWith(I, LHS);
3891     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3892       break;
3893     }
3894     break;
3895   case ICmpInst::ICMP_SLT:
3896     switch (RHSCC) {
3897     default: assert(0 && "Unknown integer condition code!");
3898     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3899     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3900       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3901     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3902       break;
3903     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3904     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3905       return ReplaceInstUsesWith(I, LHS);
3906     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3907       break;
3908     }
3909     break;
3910   case ICmpInst::ICMP_UGT:
3911     switch (RHSCC) {
3912     default: assert(0 && "Unknown integer condition code!");
3913     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3914     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3915       return ReplaceInstUsesWith(I, RHS);
3916     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3917       break;
3918     case ICmpInst::ICMP_NE:
3919       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3920         return new ICmpInst(LHSCC, Val, RHSCst);
3921       break;                        // (X u> 13 & X != 15) -> no change
3922     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3923       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3924                              RHSCst, false, true, I);
3925     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3926       break;
3927     }
3928     break;
3929   case ICmpInst::ICMP_SGT:
3930     switch (RHSCC) {
3931     default: assert(0 && "Unknown integer condition code!");
3932     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3933     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3934       return ReplaceInstUsesWith(I, RHS);
3935     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3936       break;
3937     case ICmpInst::ICMP_NE:
3938       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3939         return new ICmpInst(LHSCC, Val, RHSCst);
3940       break;                        // (X s> 13 & X != 15) -> no change
3941     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3942       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3943                              RHSCst, true, true, I);
3944     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3945       break;
3946     }
3947     break;
3948   }
3949  
3950   return 0;
3951 }
3952
3953
3954 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3955   bool Changed = SimplifyCommutative(I);
3956   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3957
3958   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3959     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3960
3961   // and X, X = X
3962   if (Op0 == Op1)
3963     return ReplaceInstUsesWith(I, Op1);
3964
3965   // See if we can simplify any instructions used by the instruction whose sole 
3966   // purpose is to compute bits we don't care about.
3967   if (SimplifyDemandedInstructionBits(I))
3968     return &I;
3969   if (isa<VectorType>(I.getType())) {
3970     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3971       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3972         return ReplaceInstUsesWith(I, I.getOperand(0));
3973     } else if (isa<ConstantAggregateZero>(Op1)) {
3974       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3975     }
3976   }
3977
3978   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3979     const APInt& AndRHSMask = AndRHS->getValue();
3980     APInt NotAndRHS(~AndRHSMask);
3981
3982     // Optimize a variety of ((val OP C1) & C2) combinations...
3983     if (isa<BinaryOperator>(Op0)) {
3984       Instruction *Op0I = cast<Instruction>(Op0);
3985       Value *Op0LHS = Op0I->getOperand(0);
3986       Value *Op0RHS = Op0I->getOperand(1);
3987       switch (Op0I->getOpcode()) {
3988       case Instruction::Xor:
3989       case Instruction::Or:
3990         // If the mask is only needed on one incoming arm, push it up.
3991         if (Op0I->hasOneUse()) {
3992           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3993             // Not masking anything out for the LHS, move to RHS.
3994             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3995                                                    Op0RHS->getName()+".masked");
3996             InsertNewInstBefore(NewRHS, I);
3997             return BinaryOperator::Create(
3998                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3999           }
4000           if (!isa<Constant>(Op0RHS) &&
4001               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4002             // Not masking anything out for the RHS, move to LHS.
4003             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4004                                                    Op0LHS->getName()+".masked");
4005             InsertNewInstBefore(NewLHS, I);
4006             return BinaryOperator::Create(
4007                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4008           }
4009         }
4010
4011         break;
4012       case Instruction::Add:
4013         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4014         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4015         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4016         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4017           return BinaryOperator::CreateAnd(V, AndRHS);
4018         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4019           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4020         break;
4021
4022       case Instruction::Sub:
4023         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4024         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4025         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4026         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4027           return BinaryOperator::CreateAnd(V, AndRHS);
4028
4029         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4030         // has 1's for all bits that the subtraction with A might affect.
4031         if (Op0I->hasOneUse()) {
4032           uint32_t BitWidth = AndRHSMask.getBitWidth();
4033           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4034           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4035
4036           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4037           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4038               MaskedValueIsZero(Op0LHS, Mask)) {
4039             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4040             InsertNewInstBefore(NewNeg, I);
4041             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4042           }
4043         }
4044         break;
4045
4046       case Instruction::Shl:
4047       case Instruction::LShr:
4048         // (1 << x) & 1 --> zext(x == 0)
4049         // (1 >> x) & 1 --> zext(x == 0)
4050         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4051           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4052                                            Context->getNullValue(I.getType()));
4053           InsertNewInstBefore(NewICmp, I);
4054           return new ZExtInst(NewICmp, I.getType());
4055         }
4056         break;
4057       }
4058
4059       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4060         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4061           return Res;
4062     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4063       // If this is an integer truncation or change from signed-to-unsigned, and
4064       // if the source is an and/or with immediate, transform it.  This
4065       // frequently occurs for bitfield accesses.
4066       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4067         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4068             CastOp->getNumOperands() == 2)
4069           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4070             if (CastOp->getOpcode() == Instruction::And) {
4071               // Change: and (cast (and X, C1) to T), C2
4072               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4073               // This will fold the two constants together, which may allow 
4074               // other simplifications.
4075               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4076                 CastOp->getOperand(0), I.getType(), 
4077                 CastOp->getName()+".shrunk");
4078               NewCast = InsertNewInstBefore(NewCast, I);
4079               // trunc_or_bitcast(C1)&C2
4080               Constant *C3 =
4081                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4082               C3 = Context->getConstantExprAnd(C3, AndRHS);
4083               return BinaryOperator::CreateAnd(NewCast, C3);
4084             } else if (CastOp->getOpcode() == Instruction::Or) {
4085               // Change: and (cast (or X, C1) to T), C2
4086               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4087               Constant *C3 =
4088                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4089               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4090                 // trunc(C1)&C2
4091                 return ReplaceInstUsesWith(I, AndRHS);
4092             }
4093           }
4094       }
4095     }
4096
4097     // Try to fold constant and into select arguments.
4098     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4099       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4100         return R;
4101     if (isa<PHINode>(Op0))
4102       if (Instruction *NV = FoldOpIntoPhi(I))
4103         return NV;
4104   }
4105
4106   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4107   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4108
4109   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4110     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4111
4112   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4113   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4114     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4115                                                I.getName()+".demorgan");
4116     InsertNewInstBefore(Or, I);
4117     return BinaryOperator::CreateNot(Or);
4118   }
4119   
4120   {
4121     Value *A = 0, *B = 0, *C = 0, *D = 0;
4122     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4123       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4124         return ReplaceInstUsesWith(I, Op1);
4125     
4126       // (A|B) & ~(A&B) -> A^B
4127       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4128         if ((A == C && B == D) || (A == D && B == C))
4129           return BinaryOperator::CreateXor(A, B);
4130       }
4131     }
4132     
4133     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4134       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4135         return ReplaceInstUsesWith(I, Op0);
4136
4137       // ~(A&B) & (A|B) -> A^B
4138       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4139         if ((A == C && B == D) || (A == D && B == C))
4140           return BinaryOperator::CreateXor(A, B);
4141       }
4142     }
4143     
4144     if (Op0->hasOneUse() &&
4145         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4146       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4147         I.swapOperands();     // Simplify below
4148         std::swap(Op0, Op1);
4149       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4150         cast<BinaryOperator>(Op0)->swapOperands();
4151         I.swapOperands();     // Simplify below
4152         std::swap(Op0, Op1);
4153       }
4154     }
4155
4156     if (Op1->hasOneUse() &&
4157         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4158       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4159         cast<BinaryOperator>(Op1)->swapOperands();
4160         std::swap(A, B);
4161       }
4162       if (A == Op0) {                                // A&(A^B) -> A & ~B
4163         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4164         InsertNewInstBefore(NotB, I);
4165         return BinaryOperator::CreateAnd(A, NotB);
4166       }
4167     }
4168
4169     // (A&((~A)|B)) -> A&B
4170     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4171         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4172       return BinaryOperator::CreateAnd(A, Op1);
4173     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4174         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4175       return BinaryOperator::CreateAnd(A, Op0);
4176   }
4177   
4178   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4179     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4180     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4181       return R;
4182
4183     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4184       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4185         return Res;
4186   }
4187
4188   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4189   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4190     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4191       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4192         const Type *SrcTy = Op0C->getOperand(0)->getType();
4193         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4194             // Only do this if the casts both really cause code to be generated.
4195             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4196                               I.getType(), TD) &&
4197             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4198                               I.getType(), TD)) {
4199           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4200                                                          Op1C->getOperand(0),
4201                                                          I.getName());
4202           InsertNewInstBefore(NewOp, I);
4203           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4204         }
4205       }
4206     
4207   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4208   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4209     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4210       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4211           SI0->getOperand(1) == SI1->getOperand(1) &&
4212           (SI0->hasOneUse() || SI1->hasOneUse())) {
4213         Instruction *NewOp =
4214           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4215                                                         SI1->getOperand(0),
4216                                                         SI0->getName()), I);
4217         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4218                                       SI1->getOperand(1));
4219       }
4220   }
4221
4222   // If and'ing two fcmp, try combine them into one.
4223   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4224     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4225       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4226           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4227         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4228         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4229           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4230             // If either of the constants are nans, then the whole thing returns
4231             // false.
4232             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4233               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4234             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4235                                 RHS->getOperand(0));
4236           }
4237       } else {
4238         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4239         FCmpInst::Predicate Op0CC, Op1CC;
4240         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4241             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4242           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4243             // Swap RHS operands to match LHS.
4244             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4245             std::swap(Op1LHS, Op1RHS);
4246           }
4247           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4248             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4249             if (Op0CC == Op1CC)
4250               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4251             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4252                      Op1CC == FCmpInst::FCMP_FALSE)
4253               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4254             else if (Op0CC == FCmpInst::FCMP_TRUE)
4255               return ReplaceInstUsesWith(I, Op1);
4256             else if (Op1CC == FCmpInst::FCMP_TRUE)
4257               return ReplaceInstUsesWith(I, Op0);
4258             bool Op0Ordered;
4259             bool Op1Ordered;
4260             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4261             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4262             if (Op1Pred == 0) {
4263               std::swap(Op0, Op1);
4264               std::swap(Op0Pred, Op1Pred);
4265               std::swap(Op0Ordered, Op1Ordered);
4266             }
4267             if (Op0Pred == 0) {
4268               // uno && ueq -> uno && (uno || eq) -> ueq
4269               // ord && olt -> ord && (ord && lt) -> olt
4270               if (Op0Ordered == Op1Ordered)
4271                 return ReplaceInstUsesWith(I, Op1);
4272               // uno && oeq -> uno && (ord && eq) -> false
4273               // uno && ord -> false
4274               if (!Op0Ordered)
4275                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4276               // ord && ueq -> ord && (uno || eq) -> oeq
4277               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4278                                                     Op0LHS, Op0RHS, Context));
4279             }
4280           }
4281         }
4282       }
4283     }
4284   }
4285
4286   return Changed ? &I : 0;
4287 }
4288
4289 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4290 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4291 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4292 /// the expression came from the corresponding "byte swapped" byte in some other
4293 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4294 /// we know that the expression deposits the low byte of %X into the high byte
4295 /// of the bswap result and that all other bytes are zero.  This expression is
4296 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4297 /// match.
4298 ///
4299 /// This function returns true if the match was unsuccessful and false if so.
4300 /// On entry to the function the "OverallLeftShift" is a signed integer value
4301 /// indicating the number of bytes that the subexpression is later shifted.  For
4302 /// example, if the expression is later right shifted by 16 bits, the
4303 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4304 /// byte of ByteValues is actually being set.
4305 ///
4306 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4307 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4308 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4309 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4310 /// always in the local (OverallLeftShift) coordinate space.
4311 ///
4312 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4313                               SmallVector<Value*, 8> &ByteValues) {
4314   if (Instruction *I = dyn_cast<Instruction>(V)) {
4315     // If this is an or instruction, it may be an inner node of the bswap.
4316     if (I->getOpcode() == Instruction::Or) {
4317       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4318                                ByteValues) ||
4319              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4320                                ByteValues);
4321     }
4322   
4323     // If this is a logical shift by a constant multiple of 8, recurse with
4324     // OverallLeftShift and ByteMask adjusted.
4325     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4326       unsigned ShAmt = 
4327         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4328       // Ensure the shift amount is defined and of a byte value.
4329       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4330         return true;
4331
4332       unsigned ByteShift = ShAmt >> 3;
4333       if (I->getOpcode() == Instruction::Shl) {
4334         // X << 2 -> collect(X, +2)
4335         OverallLeftShift += ByteShift;
4336         ByteMask >>= ByteShift;
4337       } else {
4338         // X >>u 2 -> collect(X, -2)
4339         OverallLeftShift -= ByteShift;
4340         ByteMask <<= ByteShift;
4341         ByteMask &= (~0U >> (32-ByteValues.size()));
4342       }
4343
4344       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4345       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4346
4347       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4348                                ByteValues);
4349     }
4350
4351     // If this is a logical 'and' with a mask that clears bytes, clear the
4352     // corresponding bytes in ByteMask.
4353     if (I->getOpcode() == Instruction::And &&
4354         isa<ConstantInt>(I->getOperand(1))) {
4355       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4356       unsigned NumBytes = ByteValues.size();
4357       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4358       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4359       
4360       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4361         // If this byte is masked out by a later operation, we don't care what
4362         // the and mask is.
4363         if ((ByteMask & (1 << i)) == 0)
4364           continue;
4365         
4366         // If the AndMask is all zeros for this byte, clear the bit.
4367         APInt MaskB = AndMask & Byte;
4368         if (MaskB == 0) {
4369           ByteMask &= ~(1U << i);
4370           continue;
4371         }
4372         
4373         // If the AndMask is not all ones for this byte, it's not a bytezap.
4374         if (MaskB != Byte)
4375           return true;
4376
4377         // Otherwise, this byte is kept.
4378       }
4379
4380       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4381                                ByteValues);
4382     }
4383   }
4384   
4385   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4386   // the input value to the bswap.  Some observations: 1) if more than one byte
4387   // is demanded from this input, then it could not be successfully assembled
4388   // into a byteswap.  At least one of the two bytes would not be aligned with
4389   // their ultimate destination.
4390   if (!isPowerOf2_32(ByteMask)) return true;
4391   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4392   
4393   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4394   // is demanded, it needs to go into byte 0 of the result.  This means that the
4395   // byte needs to be shifted until it lands in the right byte bucket.  The
4396   // shift amount depends on the position: if the byte is coming from the high
4397   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4398   // low part, it must be shifted left.
4399   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4400   if (InputByteNo < ByteValues.size()/2) {
4401     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4402       return true;
4403   } else {
4404     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4405       return true;
4406   }
4407   
4408   // If the destination byte value is already defined, the values are or'd
4409   // together, which isn't a bswap (unless it's an or of the same bits).
4410   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4411     return true;
4412   ByteValues[DestByteNo] = V;
4413   return false;
4414 }
4415
4416 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4417 /// If so, insert the new bswap intrinsic and return it.
4418 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4419   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4420   if (!ITy || ITy->getBitWidth() % 16 || 
4421       // ByteMask only allows up to 32-byte values.
4422       ITy->getBitWidth() > 32*8) 
4423     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4424   
4425   /// ByteValues - For each byte of the result, we keep track of which value
4426   /// defines each byte.
4427   SmallVector<Value*, 8> ByteValues;
4428   ByteValues.resize(ITy->getBitWidth()/8);
4429     
4430   // Try to find all the pieces corresponding to the bswap.
4431   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4432   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4433     return 0;
4434   
4435   // Check to see if all of the bytes come from the same value.
4436   Value *V = ByteValues[0];
4437   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4438   
4439   // Check to make sure that all of the bytes come from the same value.
4440   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4441     if (ByteValues[i] != V)
4442       return 0;
4443   const Type *Tys[] = { ITy };
4444   Module *M = I.getParent()->getParent()->getParent();
4445   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4446   return CallInst::Create(F, V);
4447 }
4448
4449 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4450 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4451 /// we can simplify this expression to "cond ? C : D or B".
4452 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4453                                          Value *C, Value *D) {
4454   // If A is not a select of -1/0, this cannot match.
4455   Value *Cond = 0;
4456   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4457     return 0;
4458
4459   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4460   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4461     return SelectInst::Create(Cond, C, B);
4462   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4463     return SelectInst::Create(Cond, C, B);
4464   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4465   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4466     return SelectInst::Create(Cond, C, D);
4467   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4468     return SelectInst::Create(Cond, C, D);
4469   return 0;
4470 }
4471
4472 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4473 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4474                                          ICmpInst *LHS, ICmpInst *RHS) {
4475   Value *Val, *Val2;
4476   ConstantInt *LHSCst, *RHSCst;
4477   ICmpInst::Predicate LHSCC, RHSCC;
4478   
4479   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4480   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4481       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4482     return 0;
4483   
4484   // From here on, we only handle:
4485   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4486   if (Val != Val2) return 0;
4487   
4488   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4489   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4490       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4491       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4492       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4493     return 0;
4494   
4495   // We can't fold (ugt x, C) | (sgt x, C2).
4496   if (!PredicatesFoldable(LHSCC, RHSCC))
4497     return 0;
4498   
4499   // Ensure that the larger constant is on the RHS.
4500   bool ShouldSwap;
4501   if (ICmpInst::isSignedPredicate(LHSCC) ||
4502       (ICmpInst::isEquality(LHSCC) && 
4503        ICmpInst::isSignedPredicate(RHSCC)))
4504     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4505   else
4506     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4507   
4508   if (ShouldSwap) {
4509     std::swap(LHS, RHS);
4510     std::swap(LHSCst, RHSCst);
4511     std::swap(LHSCC, RHSCC);
4512   }
4513   
4514   // At this point, we know we have have two icmp instructions
4515   // comparing a value against two constants and or'ing the result
4516   // together.  Because of the above check, we know that we only have
4517   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4518   // FoldICmpLogical check above), that the two constants are not
4519   // equal.
4520   assert(LHSCst != RHSCst && "Compares not folded above?");
4521
4522   switch (LHSCC) {
4523   default: assert(0 && "Unknown integer condition code!");
4524   case ICmpInst::ICMP_EQ:
4525     switch (RHSCC) {
4526     default: assert(0 && "Unknown integer condition code!");
4527     case ICmpInst::ICMP_EQ:
4528       if (LHSCst == SubOne(RHSCst, Context)) {
4529         // (X == 13 | X == 14) -> X-13 <u 2
4530         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4531         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4532                                                      Val->getName()+".off");
4533         InsertNewInstBefore(Add, I);
4534         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4535         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4536       }
4537       break;                         // (X == 13 | X == 15) -> no change
4538     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4539     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4540       break;
4541     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4542     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4543     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4544       return ReplaceInstUsesWith(I, RHS);
4545     }
4546     break;
4547   case ICmpInst::ICMP_NE:
4548     switch (RHSCC) {
4549     default: assert(0 && "Unknown integer condition code!");
4550     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4551     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4552     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4553       return ReplaceInstUsesWith(I, LHS);
4554     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4555     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4556     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4557       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4558     }
4559     break;
4560   case ICmpInst::ICMP_ULT:
4561     switch (RHSCC) {
4562     default: assert(0 && "Unknown integer condition code!");
4563     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4564       break;
4565     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4566       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4567       // this can cause overflow.
4568       if (RHSCst->isMaxValue(false))
4569         return ReplaceInstUsesWith(I, LHS);
4570       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4571                              false, false, I);
4572     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4573       break;
4574     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4575     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4576       return ReplaceInstUsesWith(I, RHS);
4577     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4578       break;
4579     }
4580     break;
4581   case ICmpInst::ICMP_SLT:
4582     switch (RHSCC) {
4583     default: assert(0 && "Unknown integer condition code!");
4584     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4585       break;
4586     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4587       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4588       // this can cause overflow.
4589       if (RHSCst->isMaxValue(true))
4590         return ReplaceInstUsesWith(I, LHS);
4591       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4592                              true, false, I);
4593     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4594       break;
4595     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4596     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4597       return ReplaceInstUsesWith(I, RHS);
4598     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4599       break;
4600     }
4601     break;
4602   case ICmpInst::ICMP_UGT:
4603     switch (RHSCC) {
4604     default: assert(0 && "Unknown integer condition code!");
4605     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4606     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4607       return ReplaceInstUsesWith(I, LHS);
4608     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4609       break;
4610     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4611     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4612       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4613     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4614       break;
4615     }
4616     break;
4617   case ICmpInst::ICMP_SGT:
4618     switch (RHSCC) {
4619     default: assert(0 && "Unknown integer condition code!");
4620     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4621     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4622       return ReplaceInstUsesWith(I, LHS);
4623     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4624       break;
4625     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4626     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4627       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4628     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4629       break;
4630     }
4631     break;
4632   }
4633   return 0;
4634 }
4635
4636 /// FoldOrWithConstants - This helper function folds:
4637 ///
4638 ///     ((A | B) & C1) | (B & C2)
4639 ///
4640 /// into:
4641 /// 
4642 ///     (A & C1) | B
4643 ///
4644 /// when the XOR of the two constants is "all ones" (-1).
4645 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4646                                                Value *A, Value *B, Value *C) {
4647   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4648   if (!CI1) return 0;
4649
4650   Value *V1 = 0;
4651   ConstantInt *CI2 = 0;
4652   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4653
4654   APInt Xor = CI1->getValue() ^ CI2->getValue();
4655   if (!Xor.isAllOnesValue()) return 0;
4656
4657   if (V1 == A || V1 == B) {
4658     Instruction *NewOp =
4659       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4660     return BinaryOperator::CreateOr(NewOp, V1);
4661   }
4662
4663   return 0;
4664 }
4665
4666 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4667   bool Changed = SimplifyCommutative(I);
4668   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4669
4670   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4671     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4672
4673   // or X, X = X
4674   if (Op0 == Op1)
4675     return ReplaceInstUsesWith(I, Op0);
4676
4677   // See if we can simplify any instructions used by the instruction whose sole 
4678   // purpose is to compute bits we don't care about.
4679   if (SimplifyDemandedInstructionBits(I))
4680     return &I;
4681   if (isa<VectorType>(I.getType())) {
4682     if (isa<ConstantAggregateZero>(Op1)) {
4683       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4684     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4685       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4686         return ReplaceInstUsesWith(I, I.getOperand(1));
4687     }
4688   }
4689
4690   // or X, -1 == -1
4691   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4692     ConstantInt *C1 = 0; Value *X = 0;
4693     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4694     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4695       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4696       InsertNewInstBefore(Or, I);
4697       Or->takeName(Op0);
4698       return BinaryOperator::CreateAnd(Or, 
4699                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4700     }
4701
4702     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4703     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4704       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4705       InsertNewInstBefore(Or, I);
4706       Or->takeName(Op0);
4707       return BinaryOperator::CreateXor(Or,
4708                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4709     }
4710
4711     // Try to fold constant and into select arguments.
4712     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4713       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4714         return R;
4715     if (isa<PHINode>(Op0))
4716       if (Instruction *NV = FoldOpIntoPhi(I))
4717         return NV;
4718   }
4719
4720   Value *A = 0, *B = 0;
4721   ConstantInt *C1 = 0, *C2 = 0;
4722
4723   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4724     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4725       return ReplaceInstUsesWith(I, Op1);
4726   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4727     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4728       return ReplaceInstUsesWith(I, Op0);
4729
4730   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4731   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4732   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4733       match(Op1, m_Or(m_Value(), m_Value())) ||
4734       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4735        match(Op1, m_Shift(m_Value(), m_Value())))) {
4736     if (Instruction *BSwap = MatchBSwap(I))
4737       return BSwap;
4738   }
4739   
4740   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4741   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4742       MaskedValueIsZero(Op1, C1->getValue())) {
4743     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4744     InsertNewInstBefore(NOr, I);
4745     NOr->takeName(Op0);
4746     return BinaryOperator::CreateXor(NOr, C1);
4747   }
4748
4749   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4750   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4751       MaskedValueIsZero(Op0, C1->getValue())) {
4752     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4753     InsertNewInstBefore(NOr, I);
4754     NOr->takeName(Op0);
4755     return BinaryOperator::CreateXor(NOr, C1);
4756   }
4757
4758   // (A & C)|(B & D)
4759   Value *C = 0, *D = 0;
4760   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4761       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4762     Value *V1 = 0, *V2 = 0, *V3 = 0;
4763     C1 = dyn_cast<ConstantInt>(C);
4764     C2 = dyn_cast<ConstantInt>(D);
4765     if (C1 && C2) {  // (A & C1)|(B & C2)
4766       // If we have: ((V + N) & C1) | (V & C2)
4767       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4768       // replace with V+N.
4769       if (C1->getValue() == ~C2->getValue()) {
4770         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4771             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4772           // Add commutes, try both ways.
4773           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4774             return ReplaceInstUsesWith(I, A);
4775           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4776             return ReplaceInstUsesWith(I, A);
4777         }
4778         // Or commutes, try both ways.
4779         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4780             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4781           // Add commutes, try both ways.
4782           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4783             return ReplaceInstUsesWith(I, B);
4784           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4785             return ReplaceInstUsesWith(I, B);
4786         }
4787       }
4788       V1 = 0; V2 = 0; V3 = 0;
4789     }
4790     
4791     // Check to see if we have any common things being and'ed.  If so, find the
4792     // terms for V1 & (V2|V3).
4793     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4794       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4795         V1 = A, V2 = C, V3 = D;
4796       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4797         V1 = A, V2 = B, V3 = C;
4798       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4799         V1 = C, V2 = A, V3 = D;
4800       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4801         V1 = C, V2 = A, V3 = B;
4802       
4803       if (V1) {
4804         Value *Or =
4805           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4806         return BinaryOperator::CreateAnd(V1, Or);
4807       }
4808     }
4809
4810     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4811     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4812       return Match;
4813     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4814       return Match;
4815     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4816       return Match;
4817     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4818       return Match;
4819
4820     // ((A&~B)|(~A&B)) -> A^B
4821     if ((match(C, m_Not(m_Specific(D))) &&
4822          match(B, m_Not(m_Specific(A)))))
4823       return BinaryOperator::CreateXor(A, D);
4824     // ((~B&A)|(~A&B)) -> A^B
4825     if ((match(A, m_Not(m_Specific(D))) &&
4826          match(B, m_Not(m_Specific(C)))))
4827       return BinaryOperator::CreateXor(C, D);
4828     // ((A&~B)|(B&~A)) -> A^B
4829     if ((match(C, m_Not(m_Specific(B))) &&
4830          match(D, m_Not(m_Specific(A)))))
4831       return BinaryOperator::CreateXor(A, B);
4832     // ((~B&A)|(B&~A)) -> A^B
4833     if ((match(A, m_Not(m_Specific(B))) &&
4834          match(D, m_Not(m_Specific(C)))))
4835       return BinaryOperator::CreateXor(C, B);
4836   }
4837   
4838   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4839   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4840     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4841       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4842           SI0->getOperand(1) == SI1->getOperand(1) &&
4843           (SI0->hasOneUse() || SI1->hasOneUse())) {
4844         Instruction *NewOp =
4845         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4846                                                      SI1->getOperand(0),
4847                                                      SI0->getName()), I);
4848         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4849                                       SI1->getOperand(1));
4850       }
4851   }
4852
4853   // ((A|B)&1)|(B&-2) -> (A&1) | B
4854   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4855       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4856     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4857     if (Ret) return Ret;
4858   }
4859   // (B&-2)|((A|B)&1) -> (A&1) | B
4860   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4861       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4862     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4863     if (Ret) return Ret;
4864   }
4865
4866   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4867     if (A == Op1)   // ~A | A == -1
4868       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4869   } else {
4870     A = 0;
4871   }
4872   // Note, A is still live here!
4873   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4874     if (Op0 == B)
4875       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4876
4877     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4878     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4879       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4880                                               I.getName()+".demorgan"), I);
4881       return BinaryOperator::CreateNot(And);
4882     }
4883   }
4884
4885   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4886   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4887     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4888       return R;
4889
4890     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4891       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4892         return Res;
4893   }
4894     
4895   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4896   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4897     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4898       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4899         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4900             !isa<ICmpInst>(Op1C->getOperand(0))) {
4901           const Type *SrcTy = Op0C->getOperand(0)->getType();
4902           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4903               // Only do this if the casts both really cause code to be
4904               // generated.
4905               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4906                                 I.getType(), TD) &&
4907               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4908                                 I.getType(), TD)) {
4909             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4910                                                           Op1C->getOperand(0),
4911                                                           I.getName());
4912             InsertNewInstBefore(NewOp, I);
4913             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4914           }
4915         }
4916       }
4917   }
4918   
4919     
4920   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4921   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4922     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4923       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4924           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4925           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4926         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4927           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4928             // If either of the constants are nans, then the whole thing returns
4929             // true.
4930             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4931               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4932             
4933             // Otherwise, no need to compare the two constants, compare the
4934             // rest.
4935             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4936                                 RHS->getOperand(0));
4937           }
4938       } else {
4939         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4940         FCmpInst::Predicate Op0CC, Op1CC;
4941         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4942             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4943           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4944             // Swap RHS operands to match LHS.
4945             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4946             std::swap(Op1LHS, Op1RHS);
4947           }
4948           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4949             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4950             if (Op0CC == Op1CC)
4951               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4952             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4953                      Op1CC == FCmpInst::FCMP_TRUE)
4954               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4955             else if (Op0CC == FCmpInst::FCMP_FALSE)
4956               return ReplaceInstUsesWith(I, Op1);
4957             else if (Op1CC == FCmpInst::FCMP_FALSE)
4958               return ReplaceInstUsesWith(I, Op0);
4959             bool Op0Ordered;
4960             bool Op1Ordered;
4961             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4962             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4963             if (Op0Ordered == Op1Ordered) {
4964               // If both are ordered or unordered, return a new fcmp with
4965               // or'ed predicates.
4966               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4967                                        Op0LHS, Op0RHS, Context);
4968               if (Instruction *I = dyn_cast<Instruction>(RV))
4969                 return I;
4970               // Otherwise, it's a constant boolean value...
4971               return ReplaceInstUsesWith(I, RV);
4972             }
4973           }
4974         }
4975       }
4976     }
4977   }
4978
4979   return Changed ? &I : 0;
4980 }
4981
4982 namespace {
4983
4984 // XorSelf - Implements: X ^ X --> 0
4985 struct XorSelf {
4986   Value *RHS;
4987   XorSelf(Value *rhs) : RHS(rhs) {}
4988   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4989   Instruction *apply(BinaryOperator &Xor) const {
4990     return &Xor;
4991   }
4992 };
4993
4994 }
4995
4996 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4997   bool Changed = SimplifyCommutative(I);
4998   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4999
5000   if (isa<UndefValue>(Op1)) {
5001     if (isa<UndefValue>(Op0))
5002       // Handle undef ^ undef -> 0 special case. This is a common
5003       // idiom (misuse).
5004       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5005     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5006   }
5007
5008   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5009   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5010     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5011     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5012   }
5013   
5014   // See if we can simplify any instructions used by the instruction whose sole 
5015   // purpose is to compute bits we don't care about.
5016   if (SimplifyDemandedInstructionBits(I))
5017     return &I;
5018   if (isa<VectorType>(I.getType()))
5019     if (isa<ConstantAggregateZero>(Op1))
5020       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5021
5022   // Is this a ~ operation?
5023   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5024     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5025     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5026     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5027       if (Op0I->getOpcode() == Instruction::And || 
5028           Op0I->getOpcode() == Instruction::Or) {
5029         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5030         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5031           Instruction *NotY =
5032             BinaryOperator::CreateNot(Op0I->getOperand(1),
5033                                       Op0I->getOperand(1)->getName()+".not");
5034           InsertNewInstBefore(NotY, I);
5035           if (Op0I->getOpcode() == Instruction::And)
5036             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5037           else
5038             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5039         }
5040       }
5041     }
5042   }
5043   
5044   
5045   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5046     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5047       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5048       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5049         return new ICmpInst(ICI->getInversePredicate(),
5050                             ICI->getOperand(0), ICI->getOperand(1));
5051
5052       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5053         return new FCmpInst(FCI->getInversePredicate(),
5054                             FCI->getOperand(0), FCI->getOperand(1));
5055     }
5056
5057     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5058     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5059       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5060         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5061           Instruction::CastOps Opcode = Op0C->getOpcode();
5062           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5063             if (RHS == Context->getConstantExprCast(Opcode, 
5064                                              Context->getConstantIntTrue(),
5065                                              Op0C->getDestTy())) {
5066               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5067                                      CI->getOpcode(), CI->getInversePredicate(),
5068                                      CI->getOperand(0), CI->getOperand(1)), I);
5069               NewCI->takeName(CI);
5070               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5071             }
5072           }
5073         }
5074       }
5075     }
5076
5077     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5078       // ~(c-X) == X-c-1 == X+(-c-1)
5079       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5080         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5081           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5082           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5083                                       Context->getConstantInt(I.getType(), 1));
5084           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5085         }
5086           
5087       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5088         if (Op0I->getOpcode() == Instruction::Add) {
5089           // ~(X-c) --> (-c-1)-X
5090           if (RHS->isAllOnesValue()) {
5091             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5092             return BinaryOperator::CreateSub(
5093                            Context->getConstantExprSub(NegOp0CI,
5094                                       Context->getConstantInt(I.getType(), 1)),
5095                                       Op0I->getOperand(0));
5096           } else if (RHS->getValue().isSignBit()) {
5097             // (X + C) ^ signbit -> (X + C + signbit)
5098             Constant *C =
5099                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5100             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5101
5102           }
5103         } else if (Op0I->getOpcode() == Instruction::Or) {
5104           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5105           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5106             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5107             // Anything in both C1 and C2 is known to be zero, remove it from
5108             // NewRHS.
5109             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5110             NewRHS = Context->getConstantExprAnd(NewRHS, 
5111                                        Context->getConstantExprNot(CommonBits));
5112             AddToWorkList(Op0I);
5113             I.setOperand(0, Op0I->getOperand(0));
5114             I.setOperand(1, NewRHS);
5115             return &I;
5116           }
5117         }
5118       }
5119     }
5120
5121     // Try to fold constant and into select arguments.
5122     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5123       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5124         return R;
5125     if (isa<PHINode>(Op0))
5126       if (Instruction *NV = FoldOpIntoPhi(I))
5127         return NV;
5128   }
5129
5130   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5131     if (X == Op1)
5132       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5133
5134   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5135     if (X == Op0)
5136       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5137
5138   
5139   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5140   if (Op1I) {
5141     Value *A, *B;
5142     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5143       if (A == Op0) {              // B^(B|A) == (A|B)^B
5144         Op1I->swapOperands();
5145         I.swapOperands();
5146         std::swap(Op0, Op1);
5147       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5148         I.swapOperands();     // Simplified below.
5149         std::swap(Op0, Op1);
5150       }
5151     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5152       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5153     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5154       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5155     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5156       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5157         Op1I->swapOperands();
5158         std::swap(A, B);
5159       }
5160       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5161         I.swapOperands();     // Simplified below.
5162         std::swap(Op0, Op1);
5163       }
5164     }
5165   }
5166   
5167   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5168   if (Op0I) {
5169     Value *A, *B;
5170     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5171       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5172         std::swap(A, B);
5173       if (B == Op1) {                                // (A|B)^B == A & ~B
5174         Instruction *NotB =
5175           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5176         return BinaryOperator::CreateAnd(A, NotB);
5177       }
5178     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5179       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5180     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5181       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5182     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5183       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5184         std::swap(A, B);
5185       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5186           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5187         Instruction *N =
5188           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5189         return BinaryOperator::CreateAnd(N, Op1);
5190       }
5191     }
5192   }
5193   
5194   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5195   if (Op0I && Op1I && Op0I->isShift() && 
5196       Op0I->getOpcode() == Op1I->getOpcode() && 
5197       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5198       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5199     Instruction *NewOp =
5200       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5201                                                     Op1I->getOperand(0),
5202                                                     Op0I->getName()), I);
5203     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5204                                   Op1I->getOperand(1));
5205   }
5206     
5207   if (Op0I && Op1I) {
5208     Value *A, *B, *C, *D;
5209     // (A & B)^(A | B) -> A ^ B
5210     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5211         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5212       if ((A == C && B == D) || (A == D && B == C)) 
5213         return BinaryOperator::CreateXor(A, B);
5214     }
5215     // (A | B)^(A & B) -> A ^ B
5216     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5217         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5218       if ((A == C && B == D) || (A == D && B == C)) 
5219         return BinaryOperator::CreateXor(A, B);
5220     }
5221     
5222     // (A & B)^(C & D)
5223     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5224         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5225         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5226       // (X & Y)^(X & Y) -> (Y^Z) & X
5227       Value *X = 0, *Y = 0, *Z = 0;
5228       if (A == C)
5229         X = A, Y = B, Z = D;
5230       else if (A == D)
5231         X = A, Y = B, Z = C;
5232       else if (B == C)
5233         X = B, Y = A, Z = D;
5234       else if (B == D)
5235         X = B, Y = A, Z = C;
5236       
5237       if (X) {
5238         Instruction *NewOp =
5239         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5240         return BinaryOperator::CreateAnd(NewOp, X);
5241       }
5242     }
5243   }
5244     
5245   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5246   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5247     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5248       return R;
5249
5250   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5251   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5252     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5253       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5254         const Type *SrcTy = Op0C->getOperand(0)->getType();
5255         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5256             // Only do this if the casts both really cause code to be generated.
5257             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5258                               I.getType(), TD) &&
5259             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5260                               I.getType(), TD)) {
5261           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5262                                                          Op1C->getOperand(0),
5263                                                          I.getName());
5264           InsertNewInstBefore(NewOp, I);
5265           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5266         }
5267       }
5268   }
5269
5270   return Changed ? &I : 0;
5271 }
5272
5273 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5274                                    LLVMContext *Context) {
5275   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5276 }
5277
5278 static bool HasAddOverflow(ConstantInt *Result,
5279                            ConstantInt *In1, ConstantInt *In2,
5280                            bool IsSigned) {
5281   if (IsSigned)
5282     if (In2->getValue().isNegative())
5283       return Result->getValue().sgt(In1->getValue());
5284     else
5285       return Result->getValue().slt(In1->getValue());
5286   else
5287     return Result->getValue().ult(In1->getValue());
5288 }
5289
5290 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5291 /// overflowed for this type.
5292 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5293                             Constant *In2, LLVMContext *Context,
5294                             bool IsSigned = false) {
5295   Result = Context->getConstantExprAdd(In1, In2);
5296
5297   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5298     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5299       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5300       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5301                          ExtractElement(In1, Idx, Context),
5302                          ExtractElement(In2, Idx, Context),
5303                          IsSigned))
5304         return true;
5305     }
5306     return false;
5307   }
5308
5309   return HasAddOverflow(cast<ConstantInt>(Result),
5310                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5311                         IsSigned);
5312 }
5313
5314 static bool HasSubOverflow(ConstantInt *Result,
5315                            ConstantInt *In1, ConstantInt *In2,
5316                            bool IsSigned) {
5317   if (IsSigned)
5318     if (In2->getValue().isNegative())
5319       return Result->getValue().slt(In1->getValue());
5320     else
5321       return Result->getValue().sgt(In1->getValue());
5322   else
5323     return Result->getValue().ugt(In1->getValue());
5324 }
5325
5326 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5327 /// overflowed for this type.
5328 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5329                             Constant *In2, LLVMContext *Context,
5330                             bool IsSigned = false) {
5331   Result = Context->getConstantExprSub(In1, In2);
5332
5333   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5335       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5336       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5337                          ExtractElement(In1, Idx, Context),
5338                          ExtractElement(In2, Idx, Context),
5339                          IsSigned))
5340         return true;
5341     }
5342     return false;
5343   }
5344
5345   return HasSubOverflow(cast<ConstantInt>(Result),
5346                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5347                         IsSigned);
5348 }
5349
5350 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5351 /// code necessary to compute the offset from the base pointer (without adding
5352 /// in the base pointer).  Return the result as a signed integer of intptr size.
5353 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5354   TargetData &TD = IC.getTargetData();
5355   gep_type_iterator GTI = gep_type_begin(GEP);
5356   const Type *IntPtrTy = TD.getIntPtrType();
5357   LLVMContext *Context = IC.getContext();
5358   Value *Result = Context->getNullValue(IntPtrTy);
5359
5360   // Build a mask for high order bits.
5361   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5362   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5363
5364   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5365        ++i, ++GTI) {
5366     Value *Op = *i;
5367     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5368     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5369       if (OpC->isZero()) continue;
5370       
5371       // Handle a struct index, which adds its field offset to the pointer.
5372       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5373         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5374         
5375         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5376           Result = 
5377              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5378         else
5379           Result = IC.InsertNewInstBefore(
5380                    BinaryOperator::CreateAdd(Result,
5381                                         Context->getConstantInt(IntPtrTy, Size),
5382                                              GEP->getName()+".offs"), I);
5383         continue;
5384       }
5385       
5386       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5387       Constant *OC =
5388               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5389       Scale = Context->getConstantExprMul(OC, Scale);
5390       if (Constant *RC = dyn_cast<Constant>(Result))
5391         Result = Context->getConstantExprAdd(RC, Scale);
5392       else {
5393         // Emit an add instruction.
5394         Result = IC.InsertNewInstBefore(
5395            BinaryOperator::CreateAdd(Result, Scale,
5396                                      GEP->getName()+".offs"), I);
5397       }
5398       continue;
5399     }
5400     // Convert to correct type.
5401     if (Op->getType() != IntPtrTy) {
5402       if (Constant *OpC = dyn_cast<Constant>(Op))
5403         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5404       else
5405         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5406                                                                 true,
5407                                                       Op->getName()+".c"), I);
5408     }
5409     if (Size != 1) {
5410       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5411       if (Constant *OpC = dyn_cast<Constant>(Op))
5412         Op = Context->getConstantExprMul(OpC, Scale);
5413       else    // We'll let instcombine(mul) convert this to a shl if possible.
5414         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5415                                                   GEP->getName()+".idx"), I);
5416     }
5417
5418     // Emit an add instruction.
5419     if (isa<Constant>(Op) && isa<Constant>(Result))
5420       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5421                                     cast<Constant>(Result));
5422     else
5423       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5424                                                   GEP->getName()+".offs"), I);
5425   }
5426   return Result;
5427 }
5428
5429
5430 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5431 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5432 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5433 /// complex, and scales are involved.  The above expression would also be legal
5434 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5435 /// later form is less amenable to optimization though, and we are allowed to
5436 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5437 ///
5438 /// If we can't emit an optimized form for this expression, this returns null.
5439 /// 
5440 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5441                                           InstCombiner &IC) {
5442   TargetData &TD = IC.getTargetData();
5443   gep_type_iterator GTI = gep_type_begin(GEP);
5444
5445   // Check to see if this gep only has a single variable index.  If so, and if
5446   // any constant indices are a multiple of its scale, then we can compute this
5447   // in terms of the scale of the variable index.  For example, if the GEP
5448   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5449   // because the expression will cross zero at the same point.
5450   unsigned i, e = GEP->getNumOperands();
5451   int64_t Offset = 0;
5452   for (i = 1; i != e; ++i, ++GTI) {
5453     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5454       // Compute the aggregate offset of constant indices.
5455       if (CI->isZero()) continue;
5456
5457       // Handle a struct index, which adds its field offset to the pointer.
5458       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5459         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5460       } else {
5461         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5462         Offset += Size*CI->getSExtValue();
5463       }
5464     } else {
5465       // Found our variable index.
5466       break;
5467     }
5468   }
5469   
5470   // If there are no variable indices, we must have a constant offset, just
5471   // evaluate it the general way.
5472   if (i == e) return 0;
5473   
5474   Value *VariableIdx = GEP->getOperand(i);
5475   // Determine the scale factor of the variable element.  For example, this is
5476   // 4 if the variable index is into an array of i32.
5477   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5478   
5479   // Verify that there are no other variable indices.  If so, emit the hard way.
5480   for (++i, ++GTI; i != e; ++i, ++GTI) {
5481     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5482     if (!CI) return 0;
5483    
5484     // Compute the aggregate offset of constant indices.
5485     if (CI->isZero()) continue;
5486     
5487     // Handle a struct index, which adds its field offset to the pointer.
5488     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5489       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5490     } else {
5491       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5492       Offset += Size*CI->getSExtValue();
5493     }
5494   }
5495   
5496   // Okay, we know we have a single variable index, which must be a
5497   // pointer/array/vector index.  If there is no offset, life is simple, return
5498   // the index.
5499   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5500   if (Offset == 0) {
5501     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5502     // we don't need to bother extending: the extension won't affect where the
5503     // computation crosses zero.
5504     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5505       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5506                                   VariableIdx->getNameStart(), &I);
5507     return VariableIdx;
5508   }
5509   
5510   // Otherwise, there is an index.  The computation we will do will be modulo
5511   // the pointer size, so get it.
5512   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5513   
5514   Offset &= PtrSizeMask;
5515   VariableScale &= PtrSizeMask;
5516
5517   // To do this transformation, any constant index must be a multiple of the
5518   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5519   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5520   // multiple of the variable scale.
5521   int64_t NewOffs = Offset / (int64_t)VariableScale;
5522   if (Offset != NewOffs*(int64_t)VariableScale)
5523     return 0;
5524
5525   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5526   const Type *IntPtrTy = TD.getIntPtrType();
5527   if (VariableIdx->getType() != IntPtrTy)
5528     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5529                                               true /*SExt*/, 
5530                                               VariableIdx->getNameStart(), &I);
5531   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5532   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5533 }
5534
5535
5536 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5537 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5538 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5539                                        ICmpInst::Predicate Cond,
5540                                        Instruction &I) {
5541   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5542
5543   // Look through bitcasts.
5544   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5545     RHS = BCI->getOperand(0);
5546
5547   Value *PtrBase = GEPLHS->getOperand(0);
5548   if (PtrBase == RHS) {
5549     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5550     // This transformation (ignoring the base and scales) is valid because we
5551     // know pointers can't overflow.  See if we can output an optimized form.
5552     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5553     
5554     // If not, synthesize the offset the hard way.
5555     if (Offset == 0)
5556       Offset = EmitGEPOffset(GEPLHS, I, *this);
5557     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5558                         Context->getNullValue(Offset->getType()));
5559   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5560     // If the base pointers are different, but the indices are the same, just
5561     // compare the base pointer.
5562     if (PtrBase != GEPRHS->getOperand(0)) {
5563       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5564       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5565                         GEPRHS->getOperand(0)->getType();
5566       if (IndicesTheSame)
5567         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5568           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5569             IndicesTheSame = false;
5570             break;
5571           }
5572
5573       // If all indices are the same, just compare the base pointers.
5574       if (IndicesTheSame)
5575         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5576                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5577
5578       // Otherwise, the base pointers are different and the indices are
5579       // different, bail out.
5580       return 0;
5581     }
5582
5583     // If one of the GEPs has all zero indices, recurse.
5584     bool AllZeros = true;
5585     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5586       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5587           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5588         AllZeros = false;
5589         break;
5590       }
5591     if (AllZeros)
5592       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5593                           ICmpInst::getSwappedPredicate(Cond), I);
5594
5595     // If the other GEP has all zero indices, recurse.
5596     AllZeros = true;
5597     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5598       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5599           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5600         AllZeros = false;
5601         break;
5602       }
5603     if (AllZeros)
5604       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5605
5606     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5607       // If the GEPs only differ by one index, compare it.
5608       unsigned NumDifferences = 0;  // Keep track of # differences.
5609       unsigned DiffOperand = 0;     // The operand that differs.
5610       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5611         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5612           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5613                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5614             // Irreconcilable differences.
5615             NumDifferences = 2;
5616             break;
5617           } else {
5618             if (NumDifferences++) break;
5619             DiffOperand = i;
5620           }
5621         }
5622
5623       if (NumDifferences == 0)   // SAME GEP?
5624         return ReplaceInstUsesWith(I, // No comparison is needed here.
5625                                    Context->getConstantInt(Type::Int1Ty,
5626                                              ICmpInst::isTrueWhenEqual(Cond)));
5627
5628       else if (NumDifferences == 1) {
5629         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5630         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5631         // Make sure we do a signed comparison here.
5632         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5633       }
5634     }
5635
5636     // Only lower this if the icmp is the only user of the GEP or if we expect
5637     // the result to fold to a constant!
5638     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5639         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5640       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5641       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5642       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5643       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5644     }
5645   }
5646   return 0;
5647 }
5648
5649 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5650 ///
5651 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5652                                                 Instruction *LHSI,
5653                                                 Constant *RHSC) {
5654   if (!isa<ConstantFP>(RHSC)) return 0;
5655   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5656   
5657   // Get the width of the mantissa.  We don't want to hack on conversions that
5658   // might lose information from the integer, e.g. "i64 -> float"
5659   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5660   if (MantissaWidth == -1) return 0;  // Unknown.
5661   
5662   // Check to see that the input is converted from an integer type that is small
5663   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5664   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5665   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5666   
5667   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5668   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5669   if (LHSUnsigned)
5670     ++InputSize;
5671   
5672   // If the conversion would lose info, don't hack on this.
5673   if ((int)InputSize > MantissaWidth)
5674     return 0;
5675   
5676   // Otherwise, we can potentially simplify the comparison.  We know that it
5677   // will always come through as an integer value and we know the constant is
5678   // not a NAN (it would have been previously simplified).
5679   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5680   
5681   ICmpInst::Predicate Pred;
5682   switch (I.getPredicate()) {
5683   default: assert(0 && "Unexpected predicate!");
5684   case FCmpInst::FCMP_UEQ:
5685   case FCmpInst::FCMP_OEQ:
5686     Pred = ICmpInst::ICMP_EQ;
5687     break;
5688   case FCmpInst::FCMP_UGT:
5689   case FCmpInst::FCMP_OGT:
5690     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5691     break;
5692   case FCmpInst::FCMP_UGE:
5693   case FCmpInst::FCMP_OGE:
5694     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5695     break;
5696   case FCmpInst::FCMP_ULT:
5697   case FCmpInst::FCMP_OLT:
5698     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5699     break;
5700   case FCmpInst::FCMP_ULE:
5701   case FCmpInst::FCMP_OLE:
5702     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5703     break;
5704   case FCmpInst::FCMP_UNE:
5705   case FCmpInst::FCMP_ONE:
5706     Pred = ICmpInst::ICMP_NE;
5707     break;
5708   case FCmpInst::FCMP_ORD:
5709     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5710   case FCmpInst::FCMP_UNO:
5711     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5712   }
5713   
5714   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5715   
5716   // Now we know that the APFloat is a normal number, zero or inf.
5717   
5718   // See if the FP constant is too large for the integer.  For example,
5719   // comparing an i8 to 300.0.
5720   unsigned IntWidth = IntTy->getScalarSizeInBits();
5721   
5722   if (!LHSUnsigned) {
5723     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5724     // and large values.
5725     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5726     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5727                           APFloat::rmNearestTiesToEven);
5728     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5729       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5730           Pred == ICmpInst::ICMP_SLE)
5731         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5732       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5733     }
5734   } else {
5735     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5736     // +INF and large values.
5737     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5738     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5739                           APFloat::rmNearestTiesToEven);
5740     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5741       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5742           Pred == ICmpInst::ICMP_ULE)
5743         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5744       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5745     }
5746   }
5747   
5748   if (!LHSUnsigned) {
5749     // See if the RHS value is < SignedMin.
5750     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5751     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5752                           APFloat::rmNearestTiesToEven);
5753     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5754       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5755           Pred == ICmpInst::ICMP_SGE)
5756         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5757       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5758     }
5759   }
5760
5761   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5762   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5763   // casting the FP value to the integer value and back, checking for equality.
5764   // Don't do this for zero, because -0.0 is not fractional.
5765   Constant *RHSInt = LHSUnsigned
5766     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5767     : Context->getConstantExprFPToSI(RHSC, IntTy);
5768   if (!RHS.isZero()) {
5769     bool Equal = LHSUnsigned
5770       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5771       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5772     if (!Equal) {
5773       // If we had a comparison against a fractional value, we have to adjust
5774       // the compare predicate and sometimes the value.  RHSC is rounded towards
5775       // zero at this point.
5776       switch (Pred) {
5777       default: assert(0 && "Unexpected integer comparison!");
5778       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5779         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5780       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5781         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5782       case ICmpInst::ICMP_ULE:
5783         // (float)int <= 4.4   --> int <= 4
5784         // (float)int <= -4.4  --> false
5785         if (RHS.isNegative())
5786           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5787         break;
5788       case ICmpInst::ICMP_SLE:
5789         // (float)int <= 4.4   --> int <= 4
5790         // (float)int <= -4.4  --> int < -4
5791         if (RHS.isNegative())
5792           Pred = ICmpInst::ICMP_SLT;
5793         break;
5794       case ICmpInst::ICMP_ULT:
5795         // (float)int < -4.4   --> false
5796         // (float)int < 4.4    --> int <= 4
5797         if (RHS.isNegative())
5798           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5799         Pred = ICmpInst::ICMP_ULE;
5800         break;
5801       case ICmpInst::ICMP_SLT:
5802         // (float)int < -4.4   --> int < -4
5803         // (float)int < 4.4    --> int <= 4
5804         if (!RHS.isNegative())
5805           Pred = ICmpInst::ICMP_SLE;
5806         break;
5807       case ICmpInst::ICMP_UGT:
5808         // (float)int > 4.4    --> int > 4
5809         // (float)int > -4.4   --> true
5810         if (RHS.isNegative())
5811           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5812         break;
5813       case ICmpInst::ICMP_SGT:
5814         // (float)int > 4.4    --> int > 4
5815         // (float)int > -4.4   --> int >= -4
5816         if (RHS.isNegative())
5817           Pred = ICmpInst::ICMP_SGE;
5818         break;
5819       case ICmpInst::ICMP_UGE:
5820         // (float)int >= -4.4   --> true
5821         // (float)int >= 4.4    --> int > 4
5822         if (!RHS.isNegative())
5823           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5824         Pred = ICmpInst::ICMP_UGT;
5825         break;
5826       case ICmpInst::ICMP_SGE:
5827         // (float)int >= -4.4   --> int >= -4
5828         // (float)int >= 4.4    --> int > 4
5829         if (!RHS.isNegative())
5830           Pred = ICmpInst::ICMP_SGT;
5831         break;
5832       }
5833     }
5834   }
5835
5836   // Lower this FP comparison into an appropriate integer version of the
5837   // comparison.
5838   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5839 }
5840
5841 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5842   bool Changed = SimplifyCompare(I);
5843   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5844
5845   // Fold trivial predicates.
5846   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5847     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5848   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5849     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5850   
5851   // Simplify 'fcmp pred X, X'
5852   if (Op0 == Op1) {
5853     switch (I.getPredicate()) {
5854     default: assert(0 && "Unknown predicate!");
5855     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5856     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5857     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5858       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5859     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5860     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5861     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5862       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5863       
5864     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5865     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5866     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5867     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5868       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5869       I.setPredicate(FCmpInst::FCMP_UNO);
5870       I.setOperand(1, Context->getNullValue(Op0->getType()));
5871       return &I;
5872       
5873     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5874     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5875     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5876     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5877       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5878       I.setPredicate(FCmpInst::FCMP_ORD);
5879       I.setOperand(1, Context->getNullValue(Op0->getType()));
5880       return &I;
5881     }
5882   }
5883     
5884   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5885     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5886
5887   // Handle fcmp with constant RHS
5888   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5889     // If the constant is a nan, see if we can fold the comparison based on it.
5890     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5891       if (CFP->getValueAPF().isNaN()) {
5892         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5893           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5894         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5895                "Comparison must be either ordered or unordered!");
5896         // True if unordered.
5897         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5898       }
5899     }
5900     
5901     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5902       switch (LHSI->getOpcode()) {
5903       case Instruction::PHI:
5904         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5905         // block.  If in the same block, we're encouraging jump threading.  If
5906         // not, we are just pessimizing the code by making an i1 phi.
5907         if (LHSI->getParent() == I.getParent())
5908           if (Instruction *NV = FoldOpIntoPhi(I))
5909             return NV;
5910         break;
5911       case Instruction::SIToFP:
5912       case Instruction::UIToFP:
5913         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5914           return NV;
5915         break;
5916       case Instruction::Select:
5917         // If either operand of the select is a constant, we can fold the
5918         // comparison into the select arms, which will cause one to be
5919         // constant folded and the select turned into a bitwise or.
5920         Value *Op1 = 0, *Op2 = 0;
5921         if (LHSI->hasOneUse()) {
5922           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5923             // Fold the known value into the constant operand.
5924             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5925             // Insert a new FCmp of the other select operand.
5926             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5927                                                       LHSI->getOperand(2), RHSC,
5928                                                       I.getName()), I);
5929           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5930             // Fold the known value into the constant operand.
5931             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5932             // Insert a new FCmp of the other select operand.
5933             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5934                                                       LHSI->getOperand(1), RHSC,
5935                                                       I.getName()), I);
5936           }
5937         }
5938
5939         if (Op1)
5940           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5941         break;
5942       }
5943   }
5944
5945   return Changed ? &I : 0;
5946 }
5947
5948 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5949   bool Changed = SimplifyCompare(I);
5950   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5951   const Type *Ty = Op0->getType();
5952
5953   // icmp X, X
5954   if (Op0 == Op1)
5955     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5956                                                    I.isTrueWhenEqual()));
5957
5958   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5959     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5960   
5961   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5962   // addresses never equal each other!  We already know that Op0 != Op1.
5963   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5964        isa<ConstantPointerNull>(Op0)) &&
5965       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5966        isa<ConstantPointerNull>(Op1)))
5967     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5968                                                    !I.isTrueWhenEqual()));
5969
5970   // icmp's with boolean values can always be turned into bitwise operations
5971   if (Ty == Type::Int1Ty) {
5972     switch (I.getPredicate()) {
5973     default: assert(0 && "Invalid icmp instruction!");
5974     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5975       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5976       InsertNewInstBefore(Xor, I);
5977       return BinaryOperator::CreateNot(Xor);
5978     }
5979     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5980       return BinaryOperator::CreateXor(Op0, Op1);
5981
5982     case ICmpInst::ICMP_UGT:
5983       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5984       // FALL THROUGH
5985     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5986       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5987       InsertNewInstBefore(Not, I);
5988       return BinaryOperator::CreateAnd(Not, Op1);
5989     }
5990     case ICmpInst::ICMP_SGT:
5991       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5992       // FALL THROUGH
5993     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5994       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5995       InsertNewInstBefore(Not, I);
5996       return BinaryOperator::CreateAnd(Not, Op0);
5997     }
5998     case ICmpInst::ICMP_UGE:
5999       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6000       // FALL THROUGH
6001     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6002       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6003       InsertNewInstBefore(Not, I);
6004       return BinaryOperator::CreateOr(Not, Op1);
6005     }
6006     case ICmpInst::ICMP_SGE:
6007       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6008       // FALL THROUGH
6009     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6010       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6011       InsertNewInstBefore(Not, I);
6012       return BinaryOperator::CreateOr(Not, Op0);
6013     }
6014     }
6015   }
6016
6017   unsigned BitWidth = 0;
6018   if (TD)
6019     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6020   else if (Ty->isIntOrIntVector())
6021     BitWidth = Ty->getScalarSizeInBits();
6022
6023   bool isSignBit = false;
6024
6025   // See if we are doing a comparison with a constant.
6026   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6027     Value *A = 0, *B = 0;
6028     
6029     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6030     if (I.isEquality() && CI->isNullValue() &&
6031         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6032       // (icmp cond A B) if cond is equality
6033       return new ICmpInst(I.getPredicate(), A, B);
6034     }
6035     
6036     // If we have an icmp le or icmp ge instruction, turn it into the
6037     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6038     // them being folded in the code below.
6039     switch (I.getPredicate()) {
6040     default: break;
6041     case ICmpInst::ICMP_ULE:
6042       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6043         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6044       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI, Context));
6045     case ICmpInst::ICMP_SLE:
6046       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6047         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6048       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI, Context));
6049     case ICmpInst::ICMP_UGE:
6050       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6051         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6052       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI, Context));
6053     case ICmpInst::ICMP_SGE:
6054       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6055         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6056       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI, Context));
6057     }
6058     
6059     // If this comparison is a normal comparison, it demands all
6060     // bits, if it is a sign bit comparison, it only demands the sign bit.
6061     bool UnusedBit;
6062     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6063   }
6064
6065   // See if we can fold the comparison based on range information we can get
6066   // by checking whether bits are known to be zero or one in the input.
6067   if (BitWidth != 0) {
6068     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6069     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6070
6071     if (SimplifyDemandedBits(I.getOperandUse(0),
6072                              isSignBit ? APInt::getSignBit(BitWidth)
6073                                        : APInt::getAllOnesValue(BitWidth),
6074                              Op0KnownZero, Op0KnownOne, 0))
6075       return &I;
6076     if (SimplifyDemandedBits(I.getOperandUse(1),
6077                              APInt::getAllOnesValue(BitWidth),
6078                              Op1KnownZero, Op1KnownOne, 0))
6079       return &I;
6080
6081     // Given the known and unknown bits, compute a range that the LHS could be
6082     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6083     // EQ and NE we use unsigned values.
6084     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6085     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6086     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6087       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6088                                              Op0Min, Op0Max);
6089       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6090                                              Op1Min, Op1Max);
6091     } else {
6092       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6093                                                Op0Min, Op0Max);
6094       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6095                                                Op1Min, Op1Max);
6096     }
6097
6098     // If Min and Max are known to be the same, then SimplifyDemandedBits
6099     // figured out that the LHS is a constant.  Just constant fold this now so
6100     // that code below can assume that Min != Max.
6101     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6102       return new ICmpInst(I.getPredicate(),
6103                           Context->getConstantInt(Op0Min), Op1);
6104     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6105       return new ICmpInst(I.getPredicate(), Op0, 
6106                           Context->getConstantInt(Op1Min));
6107
6108     // Based on the range information we know about the LHS, see if we can
6109     // simplify this comparison.  For example, (x&4) < 8  is always true.
6110     switch (I.getPredicate()) {
6111     default: assert(0 && "Unknown icmp opcode!");
6112     case ICmpInst::ICMP_EQ:
6113       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6114         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6115       break;
6116     case ICmpInst::ICMP_NE:
6117       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6118         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6119       break;
6120     case ICmpInst::ICMP_ULT:
6121       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6122         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6123       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6124         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6125       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6126         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6127       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6128         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6129           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI, Context));
6130
6131         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6132         if (CI->isMinValue(true))
6133           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6134                            Context->getConstantIntAllOnesValue(Op0->getType()));
6135       }
6136       break;
6137     case ICmpInst::ICMP_UGT:
6138       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6139         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6140       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6141         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6142
6143       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6144         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6145       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6146         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6147           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI, Context));
6148
6149         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6150         if (CI->isMaxValue(true))
6151           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6152                               Context->getNullValue(Op0->getType()));
6153       }
6154       break;
6155     case ICmpInst::ICMP_SLT:
6156       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6157         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6158       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6159         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6160       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6161         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6162       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6163         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6164           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI, Context));
6165       }
6166       break;
6167     case ICmpInst::ICMP_SGT:
6168       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6169         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6170       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6171         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6172
6173       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6174         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6175       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6176         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6177           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI, Context));
6178       }
6179       break;
6180     case ICmpInst::ICMP_SGE:
6181       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6182       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6183         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6184       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6185         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6186       break;
6187     case ICmpInst::ICMP_SLE:
6188       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6189       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6190         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6191       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6192         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6193       break;
6194     case ICmpInst::ICMP_UGE:
6195       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6196       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6197         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6198       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6199         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6200       break;
6201     case ICmpInst::ICMP_ULE:
6202       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6203       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6204         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6205       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6206         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6207       break;
6208     }
6209
6210     // Turn a signed comparison into an unsigned one if both operands
6211     // are known to have the same sign.
6212     if (I.isSignedPredicate() &&
6213         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6214          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6215       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6216   }
6217
6218   // Test if the ICmpInst instruction is used exclusively by a select as
6219   // part of a minimum or maximum operation. If so, refrain from doing
6220   // any other folding. This helps out other analyses which understand
6221   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6222   // and CodeGen. And in this case, at least one of the comparison
6223   // operands has at least one user besides the compare (the select),
6224   // which would often largely negate the benefit of folding anyway.
6225   if (I.hasOneUse())
6226     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6227       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6228           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6229         return 0;
6230
6231   // See if we are doing a comparison between a constant and an instruction that
6232   // can be folded into the comparison.
6233   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6234     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6235     // instruction, see if that instruction also has constants so that the 
6236     // instruction can be folded into the icmp 
6237     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6238       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6239         return Res;
6240   }
6241
6242   // Handle icmp with constant (but not simple integer constant) RHS
6243   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6244     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6245       switch (LHSI->getOpcode()) {
6246       case Instruction::GetElementPtr:
6247         if (RHSC->isNullValue()) {
6248           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6249           bool isAllZeros = true;
6250           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6251             if (!isa<Constant>(LHSI->getOperand(i)) ||
6252                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6253               isAllZeros = false;
6254               break;
6255             }
6256           if (isAllZeros)
6257             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6258                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6259         }
6260         break;
6261
6262       case Instruction::PHI:
6263         // Only fold icmp into the PHI if the phi and fcmp are in the same
6264         // block.  If in the same block, we're encouraging jump threading.  If
6265         // not, we are just pessimizing the code by making an i1 phi.
6266         if (LHSI->getParent() == I.getParent())
6267           if (Instruction *NV = FoldOpIntoPhi(I))
6268             return NV;
6269         break;
6270       case Instruction::Select: {
6271         // If either operand of the select is a constant, we can fold the
6272         // comparison into the select arms, which will cause one to be
6273         // constant folded and the select turned into a bitwise or.
6274         Value *Op1 = 0, *Op2 = 0;
6275         if (LHSI->hasOneUse()) {
6276           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6277             // Fold the known value into the constant operand.
6278             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6279             // Insert a new ICmp of the other select operand.
6280             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6281                                                    LHSI->getOperand(2), RHSC,
6282                                                    I.getName()), I);
6283           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6284             // Fold the known value into the constant operand.
6285             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6286             // Insert a new ICmp of the other select operand.
6287             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6288                                                    LHSI->getOperand(1), RHSC,
6289                                                    I.getName()), I);
6290           }
6291         }
6292
6293         if (Op1)
6294           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6295         break;
6296       }
6297       case Instruction::Malloc:
6298         // If we have (malloc != null), and if the malloc has a single use, we
6299         // can assume it is successful and remove the malloc.
6300         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6301           AddToWorkList(LHSI);
6302           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6303                                                          !I.isTrueWhenEqual()));
6304         }
6305         break;
6306       }
6307   }
6308
6309   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6310   if (User *GEP = dyn_castGetElementPtr(Op0))
6311     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6312       return NI;
6313   if (User *GEP = dyn_castGetElementPtr(Op1))
6314     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6315                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6316       return NI;
6317
6318   // Test to see if the operands of the icmp are casted versions of other
6319   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6320   // now.
6321   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6322     if (isa<PointerType>(Op0->getType()) && 
6323         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6324       // We keep moving the cast from the left operand over to the right
6325       // operand, where it can often be eliminated completely.
6326       Op0 = CI->getOperand(0);
6327
6328       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6329       // so eliminate it as well.
6330       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6331         Op1 = CI2->getOperand(0);
6332
6333       // If Op1 is a constant, we can fold the cast into the constant.
6334       if (Op0->getType() != Op1->getType()) {
6335         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6336           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6337         } else {
6338           // Otherwise, cast the RHS right before the icmp
6339           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6340         }
6341       }
6342       return new ICmpInst(I.getPredicate(), Op0, Op1);
6343     }
6344   }
6345   
6346   if (isa<CastInst>(Op0)) {
6347     // Handle the special case of: icmp (cast bool to X), <cst>
6348     // This comes up when you have code like
6349     //   int X = A < B;
6350     //   if (X) ...
6351     // For generality, we handle any zero-extension of any operand comparison
6352     // with a constant or another cast from the same type.
6353     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6354       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6355         return R;
6356   }
6357   
6358   // See if it's the same type of instruction on the left and right.
6359   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6360     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6361       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6362           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6363         switch (Op0I->getOpcode()) {
6364         default: break;
6365         case Instruction::Add:
6366         case Instruction::Sub:
6367         case Instruction::Xor:
6368           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6369             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6370                                 Op1I->getOperand(0));
6371           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6372           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6373             if (CI->getValue().isSignBit()) {
6374               ICmpInst::Predicate Pred = I.isSignedPredicate()
6375                                              ? I.getUnsignedPredicate()
6376                                              : I.getSignedPredicate();
6377               return new ICmpInst(Pred, Op0I->getOperand(0),
6378                                   Op1I->getOperand(0));
6379             }
6380             
6381             if (CI->getValue().isMaxSignedValue()) {
6382               ICmpInst::Predicate Pred = I.isSignedPredicate()
6383                                              ? I.getUnsignedPredicate()
6384                                              : I.getSignedPredicate();
6385               Pred = I.getSwappedPredicate(Pred);
6386               return new ICmpInst(Pred, Op0I->getOperand(0),
6387                                   Op1I->getOperand(0));
6388             }
6389           }
6390           break;
6391         case Instruction::Mul:
6392           if (!I.isEquality())
6393             break;
6394
6395           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6396             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6397             // Mask = -1 >> count-trailing-zeros(Cst).
6398             if (!CI->isZero() && !CI->isOne()) {
6399               const APInt &AP = CI->getValue();
6400               ConstantInt *Mask = Context->getConstantInt(
6401                                       APInt::getLowBitsSet(AP.getBitWidth(),
6402                                                            AP.getBitWidth() -
6403                                                       AP.countTrailingZeros()));
6404               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6405                                                             Mask);
6406               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6407                                                             Mask);
6408               InsertNewInstBefore(And1, I);
6409               InsertNewInstBefore(And2, I);
6410               return new ICmpInst(I.getPredicate(), And1, And2);
6411             }
6412           }
6413           break;
6414         }
6415       }
6416     }
6417   }
6418   
6419   // ~x < ~y --> y < x
6420   { Value *A, *B;
6421     if (match(Op0, m_Not(m_Value(A))) &&
6422         match(Op1, m_Not(m_Value(B))))
6423       return new ICmpInst(I.getPredicate(), B, A);
6424   }
6425   
6426   if (I.isEquality()) {
6427     Value *A, *B, *C, *D;
6428     
6429     // -x == -y --> x == y
6430     if (match(Op0, m_Neg(m_Value(A))) &&
6431         match(Op1, m_Neg(m_Value(B))))
6432       return new ICmpInst(I.getPredicate(), A, B);
6433     
6434     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6435       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6436         Value *OtherVal = A == Op1 ? B : A;
6437         return new ICmpInst(I.getPredicate(), OtherVal,
6438                             Context->getNullValue(A->getType()));
6439       }
6440
6441       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6442         // A^c1 == C^c2 --> A == C^(c1^c2)
6443         ConstantInt *C1, *C2;
6444         if (match(B, m_ConstantInt(C1)) &&
6445             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6446           Constant *NC = 
6447                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6448           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6449           return new ICmpInst(I.getPredicate(), A,
6450                               InsertNewInstBefore(Xor, I));
6451         }
6452         
6453         // A^B == A^D -> B == D
6454         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6455         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6456         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6457         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6458       }
6459     }
6460     
6461     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6462         (A == Op0 || B == Op0)) {
6463       // A == (A^B)  ->  B == 0
6464       Value *OtherVal = A == Op0 ? B : A;
6465       return new ICmpInst(I.getPredicate(), OtherVal,
6466                           Context->getNullValue(A->getType()));
6467     }
6468
6469     // (A-B) == A  ->  B == 0
6470     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6471       return new ICmpInst(I.getPredicate(), B, 
6472                           Context->getNullValue(B->getType()));
6473
6474     // A == (A-B)  ->  B == 0
6475     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6476       return new ICmpInst(I.getPredicate(), B,
6477                           Context->getNullValue(B->getType()));
6478     
6479     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6480     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6481         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6482         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6483       Value *X = 0, *Y = 0, *Z = 0;
6484       
6485       if (A == C) {
6486         X = B; Y = D; Z = A;
6487       } else if (A == D) {
6488         X = B; Y = C; Z = A;
6489       } else if (B == C) {
6490         X = A; Y = D; Z = B;
6491       } else if (B == D) {
6492         X = A; Y = C; Z = B;
6493       }
6494       
6495       if (X) {   // Build (X^Y) & Z
6496         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6497         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6498         I.setOperand(0, Op1);
6499         I.setOperand(1, Context->getNullValue(Op1->getType()));
6500         return &I;
6501       }
6502     }
6503   }
6504   return Changed ? &I : 0;
6505 }
6506
6507
6508 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6509 /// and CmpRHS are both known to be integer constants.
6510 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6511                                           ConstantInt *DivRHS) {
6512   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6513   const APInt &CmpRHSV = CmpRHS->getValue();
6514   
6515   // FIXME: If the operand types don't match the type of the divide 
6516   // then don't attempt this transform. The code below doesn't have the
6517   // logic to deal with a signed divide and an unsigned compare (and
6518   // vice versa). This is because (x /s C1) <s C2  produces different 
6519   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6520   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6521   // work. :(  The if statement below tests that condition and bails 
6522   // if it finds it. 
6523   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6524   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6525     return 0;
6526   if (DivRHS->isZero())
6527     return 0; // The ProdOV computation fails on divide by zero.
6528   if (DivIsSigned && DivRHS->isAllOnesValue())
6529     return 0; // The overflow computation also screws up here
6530   if (DivRHS->isOne())
6531     return 0; // Not worth bothering, and eliminates some funny cases
6532               // with INT_MIN.
6533
6534   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6535   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6536   // C2 (CI). By solving for X we can turn this into a range check 
6537   // instead of computing a divide. 
6538   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6539
6540   // Determine if the product overflows by seeing if the product is
6541   // not equal to the divide. Make sure we do the same kind of divide
6542   // as in the LHS instruction that we're folding. 
6543   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6544                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6545
6546   // Get the ICmp opcode
6547   ICmpInst::Predicate Pred = ICI.getPredicate();
6548
6549   // Figure out the interval that is being checked.  For example, a comparison
6550   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6551   // Compute this interval based on the constants involved and the signedness of
6552   // the compare/divide.  This computes a half-open interval, keeping track of
6553   // whether either value in the interval overflows.  After analysis each
6554   // overflow variable is set to 0 if it's corresponding bound variable is valid
6555   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6556   int LoOverflow = 0, HiOverflow = 0;
6557   Constant *LoBound = 0, *HiBound = 0;
6558   
6559   if (!DivIsSigned) {  // udiv
6560     // e.g. X/5 op 3  --> [15, 20)
6561     LoBound = Prod;
6562     HiOverflow = LoOverflow = ProdOV;
6563     if (!HiOverflow)
6564       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6565   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6566     if (CmpRHSV == 0) {       // (X / pos) op 0
6567       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6568       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6569                                                                     Context)));
6570       HiBound = DivRHS;
6571     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6572       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6573       HiOverflow = LoOverflow = ProdOV;
6574       if (!HiOverflow)
6575         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6576     } else {                       // (X / pos) op neg
6577       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6578       HiBound = AddOne(Prod, Context);
6579       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6580       if (!LoOverflow) {
6581         ConstantInt* DivNeg =
6582                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6583         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6584                                      true) ? -1 : 0;
6585        }
6586     }
6587   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6588     if (CmpRHSV == 0) {       // (X / neg) op 0
6589       // e.g. X/-5 op 0  --> [-4, 5)
6590       LoBound = AddOne(DivRHS, Context);
6591       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6592       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6593         HiOverflow = 1;            // [INTMIN+1, overflow)
6594         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6595       }
6596     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6597       // e.g. X/-5 op 3  --> [-19, -14)
6598       HiBound = AddOne(Prod, Context);
6599       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6600       if (!LoOverflow)
6601         LoOverflow = AddWithOverflow(LoBound, HiBound,
6602                                      DivRHS, Context, true) ? -1 : 0;
6603     } else {                       // (X / neg) op neg
6604       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6605       LoOverflow = HiOverflow = ProdOV;
6606       if (!HiOverflow)
6607         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6608     }
6609     
6610     // Dividing by a negative swaps the condition.  LT <-> GT
6611     Pred = ICmpInst::getSwappedPredicate(Pred);
6612   }
6613
6614   Value *X = DivI->getOperand(0);
6615   switch (Pred) {
6616   default: assert(0 && "Unhandled icmp opcode!");
6617   case ICmpInst::ICMP_EQ:
6618     if (LoOverflow && HiOverflow)
6619       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6620     else if (HiOverflow)
6621       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6622                           ICmpInst::ICMP_UGE, X, LoBound);
6623     else if (LoOverflow)
6624       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6625                           ICmpInst::ICMP_ULT, X, HiBound);
6626     else
6627       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6628   case ICmpInst::ICMP_NE:
6629     if (LoOverflow && HiOverflow)
6630       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6631     else if (HiOverflow)
6632       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6633                           ICmpInst::ICMP_ULT, X, LoBound);
6634     else if (LoOverflow)
6635       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6636                           ICmpInst::ICMP_UGE, X, HiBound);
6637     else
6638       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6639   case ICmpInst::ICMP_ULT:
6640   case ICmpInst::ICMP_SLT:
6641     if (LoOverflow == +1)   // Low bound is greater than input range.
6642       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6643     if (LoOverflow == -1)   // Low bound is less than input range.
6644       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6645     return new ICmpInst(Pred, X, LoBound);
6646   case ICmpInst::ICMP_UGT:
6647   case ICmpInst::ICMP_SGT:
6648     if (HiOverflow == +1)       // High bound greater than input range.
6649       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6650     else if (HiOverflow == -1)  // High bound less than input range.
6651       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6652     if (Pred == ICmpInst::ICMP_UGT)
6653       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6654     else
6655       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6656   }
6657 }
6658
6659
6660 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6661 ///
6662 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6663                                                           Instruction *LHSI,
6664                                                           ConstantInt *RHS) {
6665   const APInt &RHSV = RHS->getValue();
6666   
6667   switch (LHSI->getOpcode()) {
6668   case Instruction::Trunc:
6669     if (ICI.isEquality() && LHSI->hasOneUse()) {
6670       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6671       // of the high bits truncated out of x are known.
6672       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6673              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6674       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6675       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6676       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6677       
6678       // If all the high bits are known, we can do this xform.
6679       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6680         // Pull in the high bits from known-ones set.
6681         APInt NewRHS(RHS->getValue());
6682         NewRHS.zext(SrcBits);
6683         NewRHS |= KnownOne;
6684         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6685                             Context->getConstantInt(NewRHS));
6686       }
6687     }
6688     break;
6689       
6690   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6691     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6692       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6693       // fold the xor.
6694       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6695           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6696         Value *CompareVal = LHSI->getOperand(0);
6697         
6698         // If the sign bit of the XorCST is not set, there is no change to
6699         // the operation, just stop using the Xor.
6700         if (!XorCST->getValue().isNegative()) {
6701           ICI.setOperand(0, CompareVal);
6702           AddToWorkList(LHSI);
6703           return &ICI;
6704         }
6705         
6706         // Was the old condition true if the operand is positive?
6707         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6708         
6709         // If so, the new one isn't.
6710         isTrueIfPositive ^= true;
6711         
6712         if (isTrueIfPositive)
6713           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6714                               SubOne(RHS, Context));
6715         else
6716           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6717                               AddOne(RHS, Context));
6718       }
6719
6720       if (LHSI->hasOneUse()) {
6721         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6722         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6723           const APInt &SignBit = XorCST->getValue();
6724           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6725                                          ? ICI.getUnsignedPredicate()
6726                                          : ICI.getSignedPredicate();
6727           return new ICmpInst(Pred, LHSI->getOperand(0),
6728                               Context->getConstantInt(RHSV ^ SignBit));
6729         }
6730
6731         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6732         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6733           const APInt &NotSignBit = XorCST->getValue();
6734           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6735                                          ? ICI.getUnsignedPredicate()
6736                                          : ICI.getSignedPredicate();
6737           Pred = ICI.getSwappedPredicate(Pred);
6738           return new ICmpInst(Pred, LHSI->getOperand(0),
6739                               Context->getConstantInt(RHSV ^ NotSignBit));
6740         }
6741       }
6742     }
6743     break;
6744   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6745     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6746         LHSI->getOperand(0)->hasOneUse()) {
6747       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6748       
6749       // If the LHS is an AND of a truncating cast, we can widen the
6750       // and/compare to be the input width without changing the value
6751       // produced, eliminating a cast.
6752       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6753         // We can do this transformation if either the AND constant does not
6754         // have its sign bit set or if it is an equality comparison. 
6755         // Extending a relational comparison when we're checking the sign
6756         // bit would not work.
6757         if (Cast->hasOneUse() &&
6758             (ICI.isEquality() ||
6759              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6760           uint32_t BitWidth = 
6761             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6762           APInt NewCST = AndCST->getValue();
6763           NewCST.zext(BitWidth);
6764           APInt NewCI = RHSV;
6765           NewCI.zext(BitWidth);
6766           Instruction *NewAnd = 
6767             BinaryOperator::CreateAnd(Cast->getOperand(0),
6768                                Context->getConstantInt(NewCST),LHSI->getName());
6769           InsertNewInstBefore(NewAnd, ICI);
6770           return new ICmpInst(ICI.getPredicate(), NewAnd,
6771                               Context->getConstantInt(NewCI));
6772         }
6773       }
6774       
6775       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6776       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6777       // happens a LOT in code produced by the C front-end, for bitfield
6778       // access.
6779       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6780       if (Shift && !Shift->isShift())
6781         Shift = 0;
6782       
6783       ConstantInt *ShAmt;
6784       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6785       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6786       const Type *AndTy = AndCST->getType();          // Type of the and.
6787       
6788       // We can fold this as long as we can't shift unknown bits
6789       // into the mask.  This can only happen with signed shift
6790       // rights, as they sign-extend.
6791       if (ShAmt) {
6792         bool CanFold = Shift->isLogicalShift();
6793         if (!CanFold) {
6794           // To test for the bad case of the signed shr, see if any
6795           // of the bits shifted in could be tested after the mask.
6796           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6797           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6798           
6799           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6800           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6801                AndCST->getValue()) == 0)
6802             CanFold = true;
6803         }
6804         
6805         if (CanFold) {
6806           Constant *NewCst;
6807           if (Shift->getOpcode() == Instruction::Shl)
6808             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6809           else
6810             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6811           
6812           // Check to see if we are shifting out any of the bits being
6813           // compared.
6814           if (Context->getConstantExpr(Shift->getOpcode(),
6815                                        NewCst, ShAmt) != RHS) {
6816             // If we shifted bits out, the fold is not going to work out.
6817             // As a special case, check to see if this means that the
6818             // result is always true or false now.
6819             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6820               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6821             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6822               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6823           } else {
6824             ICI.setOperand(1, NewCst);
6825             Constant *NewAndCST;
6826             if (Shift->getOpcode() == Instruction::Shl)
6827               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6828             else
6829               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6830             LHSI->setOperand(1, NewAndCST);
6831             LHSI->setOperand(0, Shift->getOperand(0));
6832             AddToWorkList(Shift); // Shift is dead.
6833             AddUsesToWorkList(ICI);
6834             return &ICI;
6835           }
6836         }
6837       }
6838       
6839       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6840       // preferable because it allows the C<<Y expression to be hoisted out
6841       // of a loop if Y is invariant and X is not.
6842       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6843           ICI.isEquality() && !Shift->isArithmeticShift() &&
6844           !isa<Constant>(Shift->getOperand(0))) {
6845         // Compute C << Y.
6846         Value *NS;
6847         if (Shift->getOpcode() == Instruction::LShr) {
6848           NS = BinaryOperator::CreateShl(AndCST, 
6849                                          Shift->getOperand(1), "tmp");
6850         } else {
6851           // Insert a logical shift.
6852           NS = BinaryOperator::CreateLShr(AndCST,
6853                                           Shift->getOperand(1), "tmp");
6854         }
6855         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6856         
6857         // Compute X & (C << Y).
6858         Instruction *NewAnd = 
6859           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6860         InsertNewInstBefore(NewAnd, ICI);
6861         
6862         ICI.setOperand(0, NewAnd);
6863         return &ICI;
6864       }
6865     }
6866     break;
6867     
6868   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6869     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6870     if (!ShAmt) break;
6871     
6872     uint32_t TypeBits = RHSV.getBitWidth();
6873     
6874     // Check that the shift amount is in range.  If not, don't perform
6875     // undefined shifts.  When the shift is visited it will be
6876     // simplified.
6877     if (ShAmt->uge(TypeBits))
6878       break;
6879     
6880     if (ICI.isEquality()) {
6881       // If we are comparing against bits always shifted out, the
6882       // comparison cannot succeed.
6883       Constant *Comp =
6884         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6885                                                                  ShAmt);
6886       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6887         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6888         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6889         return ReplaceInstUsesWith(ICI, Cst);
6890       }
6891       
6892       if (LHSI->hasOneUse()) {
6893         // Otherwise strength reduce the shift into an and.
6894         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6895         Constant *Mask =
6896           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6897                                                        TypeBits-ShAmtVal));
6898         
6899         Instruction *AndI =
6900           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6901                                     Mask, LHSI->getName()+".mask");
6902         Value *And = InsertNewInstBefore(AndI, ICI);
6903         return new ICmpInst(ICI.getPredicate(), And,
6904                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6905       }
6906     }
6907     
6908     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6909     bool TrueIfSigned = false;
6910     if (LHSI->hasOneUse() &&
6911         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6912       // (X << 31) <s 0  --> (X&1) != 0
6913       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6914                                            (TypeBits-ShAmt->getZExtValue()-1));
6915       Instruction *AndI =
6916         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6917                                   Mask, LHSI->getName()+".mask");
6918       Value *And = InsertNewInstBefore(AndI, ICI);
6919       
6920       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6921                           And, Context->getNullValue(And->getType()));
6922     }
6923     break;
6924   }
6925     
6926   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6927   case Instruction::AShr: {
6928     // Only handle equality comparisons of shift-by-constant.
6929     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6930     if (!ShAmt || !ICI.isEquality()) break;
6931
6932     // Check that the shift amount is in range.  If not, don't perform
6933     // undefined shifts.  When the shift is visited it will be
6934     // simplified.
6935     uint32_t TypeBits = RHSV.getBitWidth();
6936     if (ShAmt->uge(TypeBits))
6937       break;
6938     
6939     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6940       
6941     // If we are comparing against bits always shifted out, the
6942     // comparison cannot succeed.
6943     APInt Comp = RHSV << ShAmtVal;
6944     if (LHSI->getOpcode() == Instruction::LShr)
6945       Comp = Comp.lshr(ShAmtVal);
6946     else
6947       Comp = Comp.ashr(ShAmtVal);
6948     
6949     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6950       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6951       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6952       return ReplaceInstUsesWith(ICI, Cst);
6953     }
6954     
6955     // Otherwise, check to see if the bits shifted out are known to be zero.
6956     // If so, we can compare against the unshifted value:
6957     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6958     if (LHSI->hasOneUse() &&
6959         MaskedValueIsZero(LHSI->getOperand(0), 
6960                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6961       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6962                           Context->getConstantExprShl(RHS, ShAmt));
6963     }
6964       
6965     if (LHSI->hasOneUse()) {
6966       // Otherwise strength reduce the shift into an and.
6967       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6968       Constant *Mask = Context->getConstantInt(Val);
6969       
6970       Instruction *AndI =
6971         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6972                                   Mask, LHSI->getName()+".mask");
6973       Value *And = InsertNewInstBefore(AndI, ICI);
6974       return new ICmpInst(ICI.getPredicate(), And,
6975                           Context->getConstantExprShl(RHS, ShAmt));
6976     }
6977     break;
6978   }
6979     
6980   case Instruction::SDiv:
6981   case Instruction::UDiv:
6982     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6983     // Fold this div into the comparison, producing a range check. 
6984     // Determine, based on the divide type, what the range is being 
6985     // checked.  If there is an overflow on the low or high side, remember 
6986     // it, otherwise compute the range [low, hi) bounding the new value.
6987     // See: InsertRangeTest above for the kinds of replacements possible.
6988     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6989       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6990                                           DivRHS))
6991         return R;
6992     break;
6993
6994   case Instruction::Add:
6995     // Fold: icmp pred (add, X, C1), C2
6996
6997     if (!ICI.isEquality()) {
6998       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6999       if (!LHSC) break;
7000       const APInt &LHSV = LHSC->getValue();
7001
7002       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7003                             .subtract(LHSV);
7004
7005       if (ICI.isSignedPredicate()) {
7006         if (CR.getLower().isSignBit()) {
7007           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7008                               Context->getConstantInt(CR.getUpper()));
7009         } else if (CR.getUpper().isSignBit()) {
7010           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7011                               Context->getConstantInt(CR.getLower()));
7012         }
7013       } else {
7014         if (CR.getLower().isMinValue()) {
7015           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7016                               Context->getConstantInt(CR.getUpper()));
7017         } else if (CR.getUpper().isMinValue()) {
7018           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7019                               Context->getConstantInt(CR.getLower()));
7020         }
7021       }
7022     }
7023     break;
7024   }
7025   
7026   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7027   if (ICI.isEquality()) {
7028     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7029     
7030     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7031     // the second operand is a constant, simplify a bit.
7032     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7033       switch (BO->getOpcode()) {
7034       case Instruction::SRem:
7035         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7036         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7037           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7038           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7039             Instruction *NewRem =
7040               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7041                                          BO->getName());
7042             InsertNewInstBefore(NewRem, ICI);
7043             return new ICmpInst(ICI.getPredicate(), NewRem, 
7044                                 Context->getNullValue(BO->getType()));
7045           }
7046         }
7047         break;
7048       case Instruction::Add:
7049         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7050         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7051           if (BO->hasOneUse())
7052             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7053                                 Context->getConstantExprSub(RHS, BOp1C));
7054         } else if (RHSV == 0) {
7055           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7056           // efficiently invertible, or if the add has just this one use.
7057           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7058           
7059           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7060             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7061           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7062             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7063           else if (BO->hasOneUse()) {
7064             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7065             InsertNewInstBefore(Neg, ICI);
7066             Neg->takeName(BO);
7067             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7068           }
7069         }
7070         break;
7071       case Instruction::Xor:
7072         // For the xor case, we can xor two constants together, eliminating
7073         // the explicit xor.
7074         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7075           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7076                               Context->getConstantExprXor(RHS, BOC));
7077         
7078         // FALLTHROUGH
7079       case Instruction::Sub:
7080         // Replace (([sub|xor] A, B) != 0) with (A != B)
7081         if (RHSV == 0)
7082           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7083                               BO->getOperand(1));
7084         break;
7085         
7086       case Instruction::Or:
7087         // If bits are being or'd in that are not present in the constant we
7088         // are comparing against, then the comparison could never succeed!
7089         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7090           Constant *NotCI = Context->getConstantExprNot(RHS);
7091           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7092             return ReplaceInstUsesWith(ICI,
7093                                        Context->getConstantInt(Type::Int1Ty, 
7094                                        isICMP_NE));
7095         }
7096         break;
7097         
7098       case Instruction::And:
7099         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7100           // If bits are being compared against that are and'd out, then the
7101           // comparison can never succeed!
7102           if ((RHSV & ~BOC->getValue()) != 0)
7103             return ReplaceInstUsesWith(ICI,
7104                                        Context->getConstantInt(Type::Int1Ty,
7105                                        isICMP_NE));
7106           
7107           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7108           if (RHS == BOC && RHSV.isPowerOf2())
7109             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7110                                 ICmpInst::ICMP_NE, LHSI,
7111                                 Context->getNullValue(RHS->getType()));
7112           
7113           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7114           if (BOC->getValue().isSignBit()) {
7115             Value *X = BO->getOperand(0);
7116             Constant *Zero = Context->getNullValue(X->getType());
7117             ICmpInst::Predicate pred = isICMP_NE ? 
7118               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7119             return new ICmpInst(pred, X, Zero);
7120           }
7121           
7122           // ((X & ~7) == 0) --> X < 8
7123           if (RHSV == 0 && isHighOnes(BOC)) {
7124             Value *X = BO->getOperand(0);
7125             Constant *NegX = Context->getConstantExprNeg(BOC);
7126             ICmpInst::Predicate pred = isICMP_NE ? 
7127               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7128             return new ICmpInst(pred, X, NegX);
7129           }
7130         }
7131       default: break;
7132       }
7133     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7134       // Handle icmp {eq|ne} <intrinsic>, intcst.
7135       if (II->getIntrinsicID() == Intrinsic::bswap) {
7136         AddToWorkList(II);
7137         ICI.setOperand(0, II->getOperand(1));
7138         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7139         return &ICI;
7140       }
7141     }
7142   }
7143   return 0;
7144 }
7145
7146 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7147 /// We only handle extending casts so far.
7148 ///
7149 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7150   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7151   Value *LHSCIOp        = LHSCI->getOperand(0);
7152   const Type *SrcTy     = LHSCIOp->getType();
7153   const Type *DestTy    = LHSCI->getType();
7154   Value *RHSCIOp;
7155
7156   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7157   // integer type is the same size as the pointer type.
7158   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7159       getTargetData().getPointerSizeInBits() == 
7160          cast<IntegerType>(DestTy)->getBitWidth()) {
7161     Value *RHSOp = 0;
7162     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7163       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7164     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7165       RHSOp = RHSC->getOperand(0);
7166       // If the pointer types don't match, insert a bitcast.
7167       if (LHSCIOp->getType() != RHSOp->getType())
7168         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7169     }
7170
7171     if (RHSOp)
7172       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7173   }
7174   
7175   // The code below only handles extension cast instructions, so far.
7176   // Enforce this.
7177   if (LHSCI->getOpcode() != Instruction::ZExt &&
7178       LHSCI->getOpcode() != Instruction::SExt)
7179     return 0;
7180
7181   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7182   bool isSignedCmp = ICI.isSignedPredicate();
7183
7184   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7185     // Not an extension from the same type?
7186     RHSCIOp = CI->getOperand(0);
7187     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7188       return 0;
7189     
7190     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7191     // and the other is a zext), then we can't handle this.
7192     if (CI->getOpcode() != LHSCI->getOpcode())
7193       return 0;
7194
7195     // Deal with equality cases early.
7196     if (ICI.isEquality())
7197       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7198
7199     // A signed comparison of sign extended values simplifies into a
7200     // signed comparison.
7201     if (isSignedCmp && isSignedExt)
7202       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7203
7204     // The other three cases all fold into an unsigned comparison.
7205     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7206   }
7207
7208   // If we aren't dealing with a constant on the RHS, exit early
7209   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7210   if (!CI)
7211     return 0;
7212
7213   // Compute the constant that would happen if we truncated to SrcTy then
7214   // reextended to DestTy.
7215   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7216   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7217                                                 Res1, DestTy);
7218
7219   // If the re-extended constant didn't change...
7220   if (Res2 == CI) {
7221     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7222     // For example, we might have:
7223     //    %A = sext i16 %X to i32
7224     //    %B = icmp ugt i32 %A, 1330
7225     // It is incorrect to transform this into 
7226     //    %B = icmp ugt i16 %X, 1330
7227     // because %A may have negative value. 
7228     //
7229     // However, we allow this when the compare is EQ/NE, because they are
7230     // signless.
7231     if (isSignedExt == isSignedCmp || ICI.isEquality())
7232       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7233     return 0;
7234   }
7235
7236   // The re-extended constant changed so the constant cannot be represented 
7237   // in the shorter type. Consequently, we cannot emit a simple comparison.
7238
7239   // First, handle some easy cases. We know the result cannot be equal at this
7240   // point so handle the ICI.isEquality() cases
7241   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7242     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7243   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7244     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7245
7246   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7247   // should have been folded away previously and not enter in here.
7248   Value *Result;
7249   if (isSignedCmp) {
7250     // We're performing a signed comparison.
7251     if (cast<ConstantInt>(CI)->getValue().isNegative())
7252       Result = Context->getConstantIntFalse();          // X < (small) --> false
7253     else
7254       Result = Context->getConstantIntTrue();           // X < (large) --> true
7255   } else {
7256     // We're performing an unsigned comparison.
7257     if (isSignedExt) {
7258       // We're performing an unsigned comp with a sign extended value.
7259       // This is true if the input is >= 0. [aka >s -1]
7260       Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
7261       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7262                                    NegOne, ICI.getName()), ICI);
7263     } else {
7264       // Unsigned extend & unsigned compare -> always true.
7265       Result = Context->getConstantIntTrue();
7266     }
7267   }
7268
7269   // Finally, return the value computed.
7270   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7271       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7272     return ReplaceInstUsesWith(ICI, Result);
7273
7274   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7275           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7276          "ICmp should be folded!");
7277   if (Constant *CI = dyn_cast<Constant>(Result))
7278     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7279   return BinaryOperator::CreateNot(Result);
7280 }
7281
7282 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7283   return commonShiftTransforms(I);
7284 }
7285
7286 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7287   return commonShiftTransforms(I);
7288 }
7289
7290 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7291   if (Instruction *R = commonShiftTransforms(I))
7292     return R;
7293   
7294   Value *Op0 = I.getOperand(0);
7295   
7296   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7297   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7298     if (CSI->isAllOnesValue())
7299       return ReplaceInstUsesWith(I, CSI);
7300
7301   // See if we can turn a signed shr into an unsigned shr.
7302   if (MaskedValueIsZero(Op0,
7303                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7304     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7305
7306   // Arithmetic shifting an all-sign-bit value is a no-op.
7307   unsigned NumSignBits = ComputeNumSignBits(Op0);
7308   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7309     return ReplaceInstUsesWith(I, Op0);
7310
7311   return 0;
7312 }
7313
7314 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7315   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7316   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7317
7318   // shl X, 0 == X and shr X, 0 == X
7319   // shl 0, X == 0 and shr 0, X == 0
7320   if (Op1 == Context->getNullValue(Op1->getType()) ||
7321       Op0 == Context->getNullValue(Op0->getType()))
7322     return ReplaceInstUsesWith(I, Op0);
7323   
7324   if (isa<UndefValue>(Op0)) {            
7325     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7326       return ReplaceInstUsesWith(I, Op0);
7327     else                                    // undef << X -> 0, undef >>u X -> 0
7328       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7329   }
7330   if (isa<UndefValue>(Op1)) {
7331     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7332       return ReplaceInstUsesWith(I, Op0);          
7333     else                                     // X << undef, X >>u undef -> 0
7334       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7335   }
7336
7337   // See if we can fold away this shift.
7338   if (SimplifyDemandedInstructionBits(I))
7339     return &I;
7340
7341   // Try to fold constant and into select arguments.
7342   if (isa<Constant>(Op0))
7343     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7344       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7345         return R;
7346
7347   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7348     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7349       return Res;
7350   return 0;
7351 }
7352
7353 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7354                                                BinaryOperator &I) {
7355   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7356
7357   // See if we can simplify any instructions used by the instruction whose sole 
7358   // purpose is to compute bits we don't care about.
7359   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7360   
7361   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7362   // a signed shift.
7363   //
7364   if (Op1->uge(TypeBits)) {
7365     if (I.getOpcode() != Instruction::AShr)
7366       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7367     else {
7368       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7369       return &I;
7370     }
7371   }
7372   
7373   // ((X*C1) << C2) == (X * (C1 << C2))
7374   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7375     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7376       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7377         return BinaryOperator::CreateMul(BO->getOperand(0),
7378                                         Context->getConstantExprShl(BOOp, Op1));
7379   
7380   // Try to fold constant and into select arguments.
7381   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7382     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7383       return R;
7384   if (isa<PHINode>(Op0))
7385     if (Instruction *NV = FoldOpIntoPhi(I))
7386       return NV;
7387   
7388   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7389   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7390     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7391     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7392     // place.  Don't try to do this transformation in this case.  Also, we
7393     // require that the input operand is a shift-by-constant so that we have
7394     // confidence that the shifts will get folded together.  We could do this
7395     // xform in more cases, but it is unlikely to be profitable.
7396     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7397         isa<ConstantInt>(TrOp->getOperand(1))) {
7398       // Okay, we'll do this xform.  Make the shift of shift.
7399       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7400       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7401                                                 I.getName());
7402       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7403
7404       // For logical shifts, the truncation has the effect of making the high
7405       // part of the register be zeros.  Emulate this by inserting an AND to
7406       // clear the top bits as needed.  This 'and' will usually be zapped by
7407       // other xforms later if dead.
7408       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7409       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7410       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7411       
7412       // The mask we constructed says what the trunc would do if occurring
7413       // between the shifts.  We want to know the effect *after* the second
7414       // shift.  We know that it is a logical shift by a constant, so adjust the
7415       // mask as appropriate.
7416       if (I.getOpcode() == Instruction::Shl)
7417         MaskV <<= Op1->getZExtValue();
7418       else {
7419         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7420         MaskV = MaskV.lshr(Op1->getZExtValue());
7421       }
7422
7423       Instruction *And =
7424         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7425                                   TI->getName());
7426       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7427
7428       // Return the value truncated to the interesting size.
7429       return new TruncInst(And, I.getType());
7430     }
7431   }
7432   
7433   if (Op0->hasOneUse()) {
7434     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7435       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7436       Value *V1, *V2;
7437       ConstantInt *CC;
7438       switch (Op0BO->getOpcode()) {
7439         default: break;
7440         case Instruction::Add:
7441         case Instruction::And:
7442         case Instruction::Or:
7443         case Instruction::Xor: {
7444           // These operators commute.
7445           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7446           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7447               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7448             Instruction *YS = BinaryOperator::CreateShl(
7449                                             Op0BO->getOperand(0), Op1,
7450                                             Op0BO->getName());
7451             InsertNewInstBefore(YS, I); // (Y << C)
7452             Instruction *X = 
7453               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7454                                      Op0BO->getOperand(1)->getName());
7455             InsertNewInstBefore(X, I);  // (X + (Y << C))
7456             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7457             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7458                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7459           }
7460           
7461           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7462           Value *Op0BOOp1 = Op0BO->getOperand(1);
7463           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7464               match(Op0BOOp1, 
7465                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7466                           m_ConstantInt(CC))) &&
7467               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7468             Instruction *YS = BinaryOperator::CreateShl(
7469                                                      Op0BO->getOperand(0), Op1,
7470                                                      Op0BO->getName());
7471             InsertNewInstBefore(YS, I); // (Y << C)
7472             Instruction *XM =
7473               BinaryOperator::CreateAnd(V1,
7474                                         Context->getConstantExprShl(CC, Op1),
7475                                         V1->getName()+".mask");
7476             InsertNewInstBefore(XM, I); // X & (CC << C)
7477             
7478             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7479           }
7480         }
7481           
7482         // FALL THROUGH.
7483         case Instruction::Sub: {
7484           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7485           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7486               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7487             Instruction *YS = BinaryOperator::CreateShl(
7488                                                      Op0BO->getOperand(1), Op1,
7489                                                      Op0BO->getName());
7490             InsertNewInstBefore(YS, I); // (Y << C)
7491             Instruction *X =
7492               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7493                                      Op0BO->getOperand(0)->getName());
7494             InsertNewInstBefore(X, I);  // (X + (Y << C))
7495             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7496             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7497                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7498           }
7499           
7500           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7501           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7502               match(Op0BO->getOperand(0),
7503                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7504                           m_ConstantInt(CC))) && V2 == Op1 &&
7505               cast<BinaryOperator>(Op0BO->getOperand(0))
7506                   ->getOperand(0)->hasOneUse()) {
7507             Instruction *YS = BinaryOperator::CreateShl(
7508                                                      Op0BO->getOperand(1), Op1,
7509                                                      Op0BO->getName());
7510             InsertNewInstBefore(YS, I); // (Y << C)
7511             Instruction *XM =
7512               BinaryOperator::CreateAnd(V1, 
7513                                         Context->getConstantExprShl(CC, Op1),
7514                                         V1->getName()+".mask");
7515             InsertNewInstBefore(XM, I); // X & (CC << C)
7516             
7517             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7518           }
7519           
7520           break;
7521         }
7522       }
7523       
7524       
7525       // If the operand is an bitwise operator with a constant RHS, and the
7526       // shift is the only use, we can pull it out of the shift.
7527       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7528         bool isValid = true;     // Valid only for And, Or, Xor
7529         bool highBitSet = false; // Transform if high bit of constant set?
7530         
7531         switch (Op0BO->getOpcode()) {
7532           default: isValid = false; break;   // Do not perform transform!
7533           case Instruction::Add:
7534             isValid = isLeftShift;
7535             break;
7536           case Instruction::Or:
7537           case Instruction::Xor:
7538             highBitSet = false;
7539             break;
7540           case Instruction::And:
7541             highBitSet = true;
7542             break;
7543         }
7544         
7545         // If this is a signed shift right, and the high bit is modified
7546         // by the logical operation, do not perform the transformation.
7547         // The highBitSet boolean indicates the value of the high bit of
7548         // the constant which would cause it to be modified for this
7549         // operation.
7550         //
7551         if (isValid && I.getOpcode() == Instruction::AShr)
7552           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7553         
7554         if (isValid) {
7555           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7556           
7557           Instruction *NewShift =
7558             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7559           InsertNewInstBefore(NewShift, I);
7560           NewShift->takeName(Op0BO);
7561           
7562           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7563                                         NewRHS);
7564         }
7565       }
7566     }
7567   }
7568   
7569   // Find out if this is a shift of a shift by a constant.
7570   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7571   if (ShiftOp && !ShiftOp->isShift())
7572     ShiftOp = 0;
7573   
7574   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7575     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7576     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7577     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7578     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7579     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7580     Value *X = ShiftOp->getOperand(0);
7581     
7582     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7583     
7584     const IntegerType *Ty = cast<IntegerType>(I.getType());
7585     
7586     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7587     if (I.getOpcode() == ShiftOp->getOpcode()) {
7588       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7589       // saturates.
7590       if (AmtSum >= TypeBits) {
7591         if (I.getOpcode() != Instruction::AShr)
7592           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7593         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7594       }
7595       
7596       return BinaryOperator::Create(I.getOpcode(), X,
7597                                     Context->getConstantInt(Ty, AmtSum));
7598     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7599                I.getOpcode() == Instruction::AShr) {
7600       if (AmtSum >= TypeBits)
7601         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7602       
7603       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7604       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7605     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7606                I.getOpcode() == Instruction::LShr) {
7607       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7608       if (AmtSum >= TypeBits)
7609         AmtSum = TypeBits-1;
7610       
7611       Instruction *Shift =
7612         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7613       InsertNewInstBefore(Shift, I);
7614
7615       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7616       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7617     }
7618     
7619     // Okay, if we get here, one shift must be left, and the other shift must be
7620     // right.  See if the amounts are equal.
7621     if (ShiftAmt1 == ShiftAmt2) {
7622       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7623       if (I.getOpcode() == Instruction::Shl) {
7624         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7625         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7626       }
7627       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7628       if (I.getOpcode() == Instruction::LShr) {
7629         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7630         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7631       }
7632       // We can simplify ((X << C) >>s C) into a trunc + sext.
7633       // NOTE: we could do this for any C, but that would make 'unusual' integer
7634       // types.  For now, just stick to ones well-supported by the code
7635       // generators.
7636       const Type *SExtType = 0;
7637       switch (Ty->getBitWidth() - ShiftAmt1) {
7638       case 1  :
7639       case 8  :
7640       case 16 :
7641       case 32 :
7642       case 64 :
7643       case 128:
7644         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7645         break;
7646       default: break;
7647       }
7648       if (SExtType) {
7649         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7650         InsertNewInstBefore(NewTrunc, I);
7651         return new SExtInst(NewTrunc, Ty);
7652       }
7653       // Otherwise, we can't handle it yet.
7654     } else if (ShiftAmt1 < ShiftAmt2) {
7655       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7656       
7657       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7658       if (I.getOpcode() == Instruction::Shl) {
7659         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7660                ShiftOp->getOpcode() == Instruction::AShr);
7661         Instruction *Shift =
7662           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7663         InsertNewInstBefore(Shift, I);
7664         
7665         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7666         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7667       }
7668       
7669       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7670       if (I.getOpcode() == Instruction::LShr) {
7671         assert(ShiftOp->getOpcode() == Instruction::Shl);
7672         Instruction *Shift =
7673           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7674         InsertNewInstBefore(Shift, I);
7675         
7676         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7677         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7678       }
7679       
7680       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7681     } else {
7682       assert(ShiftAmt2 < ShiftAmt1);
7683       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7684
7685       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7686       if (I.getOpcode() == Instruction::Shl) {
7687         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7688                ShiftOp->getOpcode() == Instruction::AShr);
7689         Instruction *Shift =
7690           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7691                                  Context->getConstantInt(Ty, ShiftDiff));
7692         InsertNewInstBefore(Shift, I);
7693         
7694         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7695         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7696       }
7697       
7698       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7699       if (I.getOpcode() == Instruction::LShr) {
7700         assert(ShiftOp->getOpcode() == Instruction::Shl);
7701         Instruction *Shift =
7702           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7703         InsertNewInstBefore(Shift, I);
7704         
7705         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7706         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7707       }
7708       
7709       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7710     }
7711   }
7712   return 0;
7713 }
7714
7715
7716 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7717 /// expression.  If so, decompose it, returning some value X, such that Val is
7718 /// X*Scale+Offset.
7719 ///
7720 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7721                                         int &Offset, LLVMContext *Context) {
7722   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7723   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7724     Offset = CI->getZExtValue();
7725     Scale  = 0;
7726     return Context->getConstantInt(Type::Int32Ty, 0);
7727   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7728     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7729       if (I->getOpcode() == Instruction::Shl) {
7730         // This is a value scaled by '1 << the shift amt'.
7731         Scale = 1U << RHS->getZExtValue();
7732         Offset = 0;
7733         return I->getOperand(0);
7734       } else if (I->getOpcode() == Instruction::Mul) {
7735         // This value is scaled by 'RHS'.
7736         Scale = RHS->getZExtValue();
7737         Offset = 0;
7738         return I->getOperand(0);
7739       } else if (I->getOpcode() == Instruction::Add) {
7740         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7741         // where C1 is divisible by C2.
7742         unsigned SubScale;
7743         Value *SubVal = 
7744           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7745                                     Offset, Context);
7746         Offset += RHS->getZExtValue();
7747         Scale = SubScale;
7748         return SubVal;
7749       }
7750     }
7751   }
7752
7753   // Otherwise, we can't look past this.
7754   Scale = 1;
7755   Offset = 0;
7756   return Val;
7757 }
7758
7759
7760 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7761 /// try to eliminate the cast by moving the type information into the alloc.
7762 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7763                                                    AllocationInst &AI) {
7764   const PointerType *PTy = cast<PointerType>(CI.getType());
7765   
7766   // Remove any uses of AI that are dead.
7767   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7768   
7769   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7770     Instruction *User = cast<Instruction>(*UI++);
7771     if (isInstructionTriviallyDead(User)) {
7772       while (UI != E && *UI == User)
7773         ++UI; // If this instruction uses AI more than once, don't break UI.
7774       
7775       ++NumDeadInst;
7776       DOUT << "IC: DCE: " << *User;
7777       EraseInstFromFunction(*User);
7778     }
7779   }
7780   
7781   // Get the type really allocated and the type casted to.
7782   const Type *AllocElTy = AI.getAllocatedType();
7783   const Type *CastElTy = PTy->getElementType();
7784   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7785
7786   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7787   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7788   if (CastElTyAlign < AllocElTyAlign) return 0;
7789
7790   // If the allocation has multiple uses, only promote it if we are strictly
7791   // increasing the alignment of the resultant allocation.  If we keep it the
7792   // same, we open the door to infinite loops of various kinds.  (A reference
7793   // from a dbg.declare doesn't count as a use for this purpose.)
7794   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7795       CastElTyAlign == AllocElTyAlign) return 0;
7796
7797   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7798   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7799   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7800
7801   // See if we can satisfy the modulus by pulling a scale out of the array
7802   // size argument.
7803   unsigned ArraySizeScale;
7804   int ArrayOffset;
7805   Value *NumElements = // See if the array size is a decomposable linear expr.
7806     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7807                               ArrayOffset, Context);
7808  
7809   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7810   // do the xform.
7811   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7812       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7813
7814   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7815   Value *Amt = 0;
7816   if (Scale == 1) {
7817     Amt = NumElements;
7818   } else {
7819     // If the allocation size is constant, form a constant mul expression
7820     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7821     if (isa<ConstantInt>(NumElements))
7822       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7823                                  cast<ConstantInt>(Amt));
7824     // otherwise multiply the amount and the number of elements
7825     else {
7826       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7827       Amt = InsertNewInstBefore(Tmp, AI);
7828     }
7829   }
7830   
7831   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7832     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7833     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7834     Amt = InsertNewInstBefore(Tmp, AI);
7835   }
7836   
7837   AllocationInst *New;
7838   if (isa<MallocInst>(AI))
7839     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7840   else
7841     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7842   InsertNewInstBefore(New, AI);
7843   New->takeName(&AI);
7844   
7845   // If the allocation has one real use plus a dbg.declare, just remove the
7846   // declare.
7847   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7848     EraseInstFromFunction(*DI);
7849   }
7850   // If the allocation has multiple real uses, insert a cast and change all
7851   // things that used it to use the new cast.  This will also hack on CI, but it
7852   // will die soon.
7853   else if (!AI.hasOneUse()) {
7854     AddUsesToWorkList(AI);
7855     // New is the allocation instruction, pointer typed. AI is the original
7856     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7857     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7858     InsertNewInstBefore(NewCast, AI);
7859     AI.replaceAllUsesWith(NewCast);
7860   }
7861   return ReplaceInstUsesWith(CI, New);
7862 }
7863
7864 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7865 /// and return it as type Ty without inserting any new casts and without
7866 /// changing the computed value.  This is used by code that tries to decide
7867 /// whether promoting or shrinking integer operations to wider or smaller types
7868 /// will allow us to eliminate a truncate or extend.
7869 ///
7870 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7871 /// extension operation if Ty is larger.
7872 ///
7873 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7874 /// should return true if trunc(V) can be computed by computing V in the smaller
7875 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7876 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7877 /// efficiently truncated.
7878 ///
7879 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7880 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7881 /// the final result.
7882 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7883                                               unsigned CastOpc,
7884                                               int &NumCastsRemoved){
7885   // We can always evaluate constants in another type.
7886   if (isa<Constant>(V))
7887     return true;
7888   
7889   Instruction *I = dyn_cast<Instruction>(V);
7890   if (!I) return false;
7891   
7892   const Type *OrigTy = V->getType();
7893   
7894   // If this is an extension or truncate, we can often eliminate it.
7895   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7896     // If this is a cast from the destination type, we can trivially eliminate
7897     // it, and this will remove a cast overall.
7898     if (I->getOperand(0)->getType() == Ty) {
7899       // If the first operand is itself a cast, and is eliminable, do not count
7900       // this as an eliminable cast.  We would prefer to eliminate those two
7901       // casts first.
7902       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7903         ++NumCastsRemoved;
7904       return true;
7905     }
7906   }
7907
7908   // We can't extend or shrink something that has multiple uses: doing so would
7909   // require duplicating the instruction in general, which isn't profitable.
7910   if (!I->hasOneUse()) return false;
7911
7912   unsigned Opc = I->getOpcode();
7913   switch (Opc) {
7914   case Instruction::Add:
7915   case Instruction::Sub:
7916   case Instruction::Mul:
7917   case Instruction::And:
7918   case Instruction::Or:
7919   case Instruction::Xor:
7920     // These operators can all arbitrarily be extended or truncated.
7921     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7922                                       NumCastsRemoved) &&
7923            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7924                                       NumCastsRemoved);
7925
7926   case Instruction::Shl:
7927     // If we are truncating the result of this SHL, and if it's a shift of a
7928     // constant amount, we can always perform a SHL in a smaller type.
7929     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7930       uint32_t BitWidth = Ty->getScalarSizeInBits();
7931       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7932           CI->getLimitedValue(BitWidth) < BitWidth)
7933         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7934                                           NumCastsRemoved);
7935     }
7936     break;
7937   case Instruction::LShr:
7938     // If this is a truncate of a logical shr, we can truncate it to a smaller
7939     // lshr iff we know that the bits we would otherwise be shifting in are
7940     // already zeros.
7941     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7942       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7943       uint32_t BitWidth = Ty->getScalarSizeInBits();
7944       if (BitWidth < OrigBitWidth &&
7945           MaskedValueIsZero(I->getOperand(0),
7946             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7947           CI->getLimitedValue(BitWidth) < BitWidth) {
7948         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7949                                           NumCastsRemoved);
7950       }
7951     }
7952     break;
7953   case Instruction::ZExt:
7954   case Instruction::SExt:
7955   case Instruction::Trunc:
7956     // If this is the same kind of case as our original (e.g. zext+zext), we
7957     // can safely replace it.  Note that replacing it does not reduce the number
7958     // of casts in the input.
7959     if (Opc == CastOpc)
7960       return true;
7961
7962     // sext (zext ty1), ty2 -> zext ty2
7963     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7964       return true;
7965     break;
7966   case Instruction::Select: {
7967     SelectInst *SI = cast<SelectInst>(I);
7968     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7969                                       NumCastsRemoved) &&
7970            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7971                                       NumCastsRemoved);
7972   }
7973   case Instruction::PHI: {
7974     // We can change a phi if we can change all operands.
7975     PHINode *PN = cast<PHINode>(I);
7976     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7977       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7978                                       NumCastsRemoved))
7979         return false;
7980     return true;
7981   }
7982   default:
7983     // TODO: Can handle more cases here.
7984     break;
7985   }
7986   
7987   return false;
7988 }
7989
7990 /// EvaluateInDifferentType - Given an expression that 
7991 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7992 /// evaluate the expression.
7993 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7994                                              bool isSigned) {
7995   if (Constant *C = dyn_cast<Constant>(V))
7996     return Context->getConstantExprIntegerCast(C, Ty,
7997                                                isSigned /*Sext or ZExt*/);
7998
7999   // Otherwise, it must be an instruction.
8000   Instruction *I = cast<Instruction>(V);
8001   Instruction *Res = 0;
8002   unsigned Opc = I->getOpcode();
8003   switch (Opc) {
8004   case Instruction::Add:
8005   case Instruction::Sub:
8006   case Instruction::Mul:
8007   case Instruction::And:
8008   case Instruction::Or:
8009   case Instruction::Xor:
8010   case Instruction::AShr:
8011   case Instruction::LShr:
8012   case Instruction::Shl: {
8013     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8014     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8015     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8016     break;
8017   }    
8018   case Instruction::Trunc:
8019   case Instruction::ZExt:
8020   case Instruction::SExt:
8021     // If the source type of the cast is the type we're trying for then we can
8022     // just return the source.  There's no need to insert it because it is not
8023     // new.
8024     if (I->getOperand(0)->getType() == Ty)
8025       return I->getOperand(0);
8026     
8027     // Otherwise, must be the same type of cast, so just reinsert a new one.
8028     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8029                            Ty);
8030     break;
8031   case Instruction::Select: {
8032     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8033     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8034     Res = SelectInst::Create(I->getOperand(0), True, False);
8035     break;
8036   }
8037   case Instruction::PHI: {
8038     PHINode *OPN = cast<PHINode>(I);
8039     PHINode *NPN = PHINode::Create(Ty);
8040     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8041       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8042       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8043     }
8044     Res = NPN;
8045     break;
8046   }
8047   default: 
8048     // TODO: Can handle more cases here.
8049     assert(0 && "Unreachable!");
8050     break;
8051   }
8052   
8053   Res->takeName(I);
8054   return InsertNewInstBefore(Res, *I);
8055 }
8056
8057 /// @brief Implement the transforms common to all CastInst visitors.
8058 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8059   Value *Src = CI.getOperand(0);
8060
8061   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8062   // eliminate it now.
8063   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8064     if (Instruction::CastOps opc = 
8065         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8066       // The first cast (CSrc) is eliminable so we need to fix up or replace
8067       // the second cast (CI). CSrc will then have a good chance of being dead.
8068       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8069     }
8070   }
8071
8072   // If we are casting a select then fold the cast into the select
8073   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8074     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8075       return NV;
8076
8077   // If we are casting a PHI then fold the cast into the PHI
8078   if (isa<PHINode>(Src))
8079     if (Instruction *NV = FoldOpIntoPhi(CI))
8080       return NV;
8081   
8082   return 0;
8083 }
8084
8085 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8086 /// or not there is a sequence of GEP indices into the type that will land us at
8087 /// the specified offset.  If so, fill them into NewIndices and return the
8088 /// resultant element type, otherwise return null.
8089 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8090                                        SmallVectorImpl<Value*> &NewIndices,
8091                                        const TargetData *TD,
8092                                        LLVMContext *Context) {
8093   if (!Ty->isSized()) return 0;
8094   
8095   // Start with the index over the outer type.  Note that the type size
8096   // might be zero (even if the offset isn't zero) if the indexed type
8097   // is something like [0 x {int, int}]
8098   const Type *IntPtrTy = TD->getIntPtrType();
8099   int64_t FirstIdx = 0;
8100   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8101     FirstIdx = Offset/TySize;
8102     Offset -= FirstIdx*TySize;
8103     
8104     // Handle hosts where % returns negative instead of values [0..TySize).
8105     if (Offset < 0) {
8106       --FirstIdx;
8107       Offset += TySize;
8108       assert(Offset >= 0);
8109     }
8110     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8111   }
8112   
8113   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8114     
8115   // Index into the types.  If we fail, set OrigBase to null.
8116   while (Offset) {
8117     // Indexing into tail padding between struct/array elements.
8118     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8119       return 0;
8120     
8121     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8122       const StructLayout *SL = TD->getStructLayout(STy);
8123       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8124              "Offset must stay within the indexed type");
8125       
8126       unsigned Elt = SL->getElementContainingOffset(Offset);
8127       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8128       
8129       Offset -= SL->getElementOffset(Elt);
8130       Ty = STy->getElementType(Elt);
8131     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8132       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8133       assert(EltSize && "Cannot index into a zero-sized array");
8134       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8135       Offset %= EltSize;
8136       Ty = AT->getElementType();
8137     } else {
8138       // Otherwise, we can't index into the middle of this atomic type, bail.
8139       return 0;
8140     }
8141   }
8142   
8143   return Ty;
8144 }
8145
8146 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8147 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8148   Value *Src = CI.getOperand(0);
8149   
8150   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8151     // If casting the result of a getelementptr instruction with no offset, turn
8152     // this into a cast of the original pointer!
8153     if (GEP->hasAllZeroIndices()) {
8154       // Changing the cast operand is usually not a good idea but it is safe
8155       // here because the pointer operand is being replaced with another 
8156       // pointer operand so the opcode doesn't need to change.
8157       AddToWorkList(GEP);
8158       CI.setOperand(0, GEP->getOperand(0));
8159       return &CI;
8160     }
8161     
8162     // If the GEP has a single use, and the base pointer is a bitcast, and the
8163     // GEP computes a constant offset, see if we can convert these three
8164     // instructions into fewer.  This typically happens with unions and other
8165     // non-type-safe code.
8166     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8167       if (GEP->hasAllConstantIndices()) {
8168         // We are guaranteed to get a constant from EmitGEPOffset.
8169         ConstantInt *OffsetV =
8170                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8171         int64_t Offset = OffsetV->getSExtValue();
8172         
8173         // Get the base pointer input of the bitcast, and the type it points to.
8174         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8175         const Type *GEPIdxTy =
8176           cast<PointerType>(OrigBase->getType())->getElementType();
8177         SmallVector<Value*, 8> NewIndices;
8178         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8179           // If we were able to index down into an element, create the GEP
8180           // and bitcast the result.  This eliminates one bitcast, potentially
8181           // two.
8182           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8183                                                         NewIndices.begin(),
8184                                                         NewIndices.end(), "");
8185           InsertNewInstBefore(NGEP, CI);
8186           NGEP->takeName(GEP);
8187           
8188           if (isa<BitCastInst>(CI))
8189             return new BitCastInst(NGEP, CI.getType());
8190           assert(isa<PtrToIntInst>(CI));
8191           return new PtrToIntInst(NGEP, CI.getType());
8192         }
8193       }      
8194     }
8195   }
8196     
8197   return commonCastTransforms(CI);
8198 }
8199
8200 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8201 /// type like i42.  We don't want to introduce operations on random non-legal
8202 /// integer types where they don't already exist in the code.  In the future,
8203 /// we should consider making this based off target-data, so that 32-bit targets
8204 /// won't get i64 operations etc.
8205 static bool isSafeIntegerType(const Type *Ty) {
8206   switch (Ty->getPrimitiveSizeInBits()) {
8207   case 8:
8208   case 16:
8209   case 32:
8210   case 64:
8211     return true;
8212   default: 
8213     return false;
8214   }
8215 }
8216
8217 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8218 /// integer types. This function implements the common transforms for all those
8219 /// cases.
8220 /// @brief Implement the transforms common to CastInst with integer operands
8221 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8222   if (Instruction *Result = commonCastTransforms(CI))
8223     return Result;
8224
8225   Value *Src = CI.getOperand(0);
8226   const Type *SrcTy = Src->getType();
8227   const Type *DestTy = CI.getType();
8228   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8229   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8230
8231   // See if we can simplify any instructions used by the LHS whose sole 
8232   // purpose is to compute bits we don't care about.
8233   if (SimplifyDemandedInstructionBits(CI))
8234     return &CI;
8235
8236   // If the source isn't an instruction or has more than one use then we
8237   // can't do anything more. 
8238   Instruction *SrcI = dyn_cast<Instruction>(Src);
8239   if (!SrcI || !Src->hasOneUse())
8240     return 0;
8241
8242   // Attempt to propagate the cast into the instruction for int->int casts.
8243   int NumCastsRemoved = 0;
8244   if (!isa<BitCastInst>(CI) &&
8245       // Only do this if the dest type is a simple type, don't convert the
8246       // expression tree to something weird like i93 unless the source is also
8247       // strange.
8248       (isSafeIntegerType(DestTy->getScalarType()) ||
8249        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8250       CanEvaluateInDifferentType(SrcI, DestTy,
8251                                  CI.getOpcode(), NumCastsRemoved)) {
8252     // If this cast is a truncate, evaluting in a different type always
8253     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8254     // we need to do an AND to maintain the clear top-part of the computation,
8255     // so we require that the input have eliminated at least one cast.  If this
8256     // is a sign extension, we insert two new casts (to do the extension) so we
8257     // require that two casts have been eliminated.
8258     bool DoXForm = false;
8259     bool JustReplace = false;
8260     switch (CI.getOpcode()) {
8261     default:
8262       // All the others use floating point so we shouldn't actually 
8263       // get here because of the check above.
8264       assert(0 && "Unknown cast type");
8265     case Instruction::Trunc:
8266       DoXForm = true;
8267       break;
8268     case Instruction::ZExt: {
8269       DoXForm = NumCastsRemoved >= 1;
8270       if (!DoXForm && 0) {
8271         // If it's unnecessary to issue an AND to clear the high bits, it's
8272         // always profitable to do this xform.
8273         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8274         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8275         if (MaskedValueIsZero(TryRes, Mask))
8276           return ReplaceInstUsesWith(CI, TryRes);
8277         
8278         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8279           if (TryI->use_empty())
8280             EraseInstFromFunction(*TryI);
8281       }
8282       break;
8283     }
8284     case Instruction::SExt: {
8285       DoXForm = NumCastsRemoved >= 2;
8286       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8287         // If we do not have to emit the truncate + sext pair, then it's always
8288         // profitable to do this xform.
8289         //
8290         // It's not safe to eliminate the trunc + sext pair if one of the
8291         // eliminated cast is a truncate. e.g.
8292         // t2 = trunc i32 t1 to i16
8293         // t3 = sext i16 t2 to i32
8294         // !=
8295         // i32 t1
8296         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8297         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8298         if (NumSignBits > (DestBitSize - SrcBitSize))
8299           return ReplaceInstUsesWith(CI, TryRes);
8300         
8301         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8302           if (TryI->use_empty())
8303             EraseInstFromFunction(*TryI);
8304       }
8305       break;
8306     }
8307     }
8308     
8309     if (DoXForm) {
8310       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8311            << " cast: " << CI;
8312       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8313                                            CI.getOpcode() == Instruction::SExt);
8314       if (JustReplace)
8315         // Just replace this cast with the result.
8316         return ReplaceInstUsesWith(CI, Res);
8317
8318       assert(Res->getType() == DestTy);
8319       switch (CI.getOpcode()) {
8320       default: assert(0 && "Unknown cast type!");
8321       case Instruction::Trunc:
8322       case Instruction::BitCast:
8323         // Just replace this cast with the result.
8324         return ReplaceInstUsesWith(CI, Res);
8325       case Instruction::ZExt: {
8326         assert(SrcBitSize < DestBitSize && "Not a zext?");
8327
8328         // If the high bits are already zero, just replace this cast with the
8329         // result.
8330         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8331         if (MaskedValueIsZero(Res, Mask))
8332           return ReplaceInstUsesWith(CI, Res);
8333
8334         // We need to emit an AND to clear the high bits.
8335         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8336                                                             SrcBitSize));
8337         return BinaryOperator::CreateAnd(Res, C);
8338       }
8339       case Instruction::SExt: {
8340         // If the high bits are already filled with sign bit, just replace this
8341         // cast with the result.
8342         unsigned NumSignBits = ComputeNumSignBits(Res);
8343         if (NumSignBits > (DestBitSize - SrcBitSize))
8344           return ReplaceInstUsesWith(CI, Res);
8345
8346         // We need to emit a cast to truncate, then a cast to sext.
8347         return CastInst::Create(Instruction::SExt,
8348             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8349                              CI), DestTy);
8350       }
8351       }
8352     }
8353   }
8354   
8355   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8356   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8357
8358   switch (SrcI->getOpcode()) {
8359   case Instruction::Add:
8360   case Instruction::Mul:
8361   case Instruction::And:
8362   case Instruction::Or:
8363   case Instruction::Xor:
8364     // If we are discarding information, rewrite.
8365     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8366       // Don't insert two casts if they cannot be eliminated.  We allow 
8367       // two casts to be inserted if the sizes are the same.  This could 
8368       // only be converting signedness, which is a noop.
8369       if (DestBitSize == SrcBitSize || 
8370           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8371           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8372         Instruction::CastOps opcode = CI.getOpcode();
8373         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8374         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8375         return BinaryOperator::Create(
8376             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8377       }
8378     }
8379
8380     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8381     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8382         SrcI->getOpcode() == Instruction::Xor &&
8383         Op1 == Context->getConstantIntTrue() &&
8384         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8385       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8386       return BinaryOperator::CreateXor(New,
8387                                       Context->getConstantInt(CI.getType(), 1));
8388     }
8389     break;
8390   case Instruction::SDiv:
8391   case Instruction::UDiv:
8392   case Instruction::SRem:
8393   case Instruction::URem:
8394     // If we are just changing the sign, rewrite.
8395     if (DestBitSize == SrcBitSize) {
8396       // Don't insert two casts if they cannot be eliminated.  We allow 
8397       // two casts to be inserted if the sizes are the same.  This could 
8398       // only be converting signedness, which is a noop.
8399       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8400           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8401         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8402                                        Op0, DestTy, *SrcI);
8403         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8404                                        Op1, DestTy, *SrcI);
8405         return BinaryOperator::Create(
8406           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8407       }
8408     }
8409     break;
8410
8411   case Instruction::Shl:
8412     // Allow changing the sign of the source operand.  Do not allow 
8413     // changing the size of the shift, UNLESS the shift amount is a 
8414     // constant.  We must not change variable sized shifts to a smaller 
8415     // size, because it is undefined to shift more bits out than exist 
8416     // in the value.
8417     if (DestBitSize == SrcBitSize ||
8418         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8419       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8420           Instruction::BitCast : Instruction::Trunc);
8421       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8422       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8423       return BinaryOperator::CreateShl(Op0c, Op1c);
8424     }
8425     break;
8426   case Instruction::AShr:
8427     // If this is a signed shr, and if all bits shifted in are about to be
8428     // truncated off, turn it into an unsigned shr to allow greater
8429     // simplifications.
8430     if (DestBitSize < SrcBitSize &&
8431         isa<ConstantInt>(Op1)) {
8432       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8433       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8434         // Insert the new logical shift right.
8435         return BinaryOperator::CreateLShr(Op0, Op1);
8436       }
8437     }
8438     break;
8439   }
8440   return 0;
8441 }
8442
8443 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8444   if (Instruction *Result = commonIntCastTransforms(CI))
8445     return Result;
8446   
8447   Value *Src = CI.getOperand(0);
8448   const Type *Ty = CI.getType();
8449   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8450   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8451
8452   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8453   if (DestBitWidth == 1 &&
8454       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8455     Constant *One = Context->getConstantInt(Src->getType(), 1);
8456     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8457     Value *Zero = Context->getNullValue(Src->getType());
8458     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8459   }
8460
8461   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8462   ConstantInt *ShAmtV = 0;
8463   Value *ShiftOp = 0;
8464   if (Src->hasOneUse() &&
8465       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8466     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8467     
8468     // Get a mask for the bits shifting in.
8469     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8470     if (MaskedValueIsZero(ShiftOp, Mask)) {
8471       if (ShAmt >= DestBitWidth)        // All zeros.
8472         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8473       
8474       // Okay, we can shrink this.  Truncate the input, then return a new
8475       // shift.
8476       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8477       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8478       return BinaryOperator::CreateLShr(V1, V2);
8479     }
8480   }
8481   
8482   return 0;
8483 }
8484
8485 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8486 /// in order to eliminate the icmp.
8487 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8488                                              bool DoXform) {
8489   // If we are just checking for a icmp eq of a single bit and zext'ing it
8490   // to an integer, then shift the bit to the appropriate place and then
8491   // cast to integer to avoid the comparison.
8492   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8493     const APInt &Op1CV = Op1C->getValue();
8494       
8495     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8496     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8497     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8498         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8499       if (!DoXform) return ICI;
8500
8501       Value *In = ICI->getOperand(0);
8502       Value *Sh = Context->getConstantInt(In->getType(),
8503                                    In->getType()->getScalarSizeInBits()-1);
8504       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8505                                                         In->getName()+".lobit"),
8506                                CI);
8507       if (In->getType() != CI.getType())
8508         In = CastInst::CreateIntegerCast(In, CI.getType(),
8509                                          false/*ZExt*/, "tmp", &CI);
8510
8511       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8512         Constant *One = Context->getConstantInt(In->getType(), 1);
8513         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8514                                                          In->getName()+".not"),
8515                                  CI);
8516       }
8517
8518       return ReplaceInstUsesWith(CI, In);
8519     }
8520       
8521       
8522       
8523     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8524     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8525     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8526     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8527     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8528     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8529     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8530     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8531     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8532         // This only works for EQ and NE
8533         ICI->isEquality()) {
8534       // If Op1C some other power of two, convert:
8535       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8536       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8537       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8538       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8539         
8540       APInt KnownZeroMask(~KnownZero);
8541       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8542         if (!DoXform) return ICI;
8543
8544         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8545         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8546           // (X&4) == 2 --> false
8547           // (X&4) != 2 --> true
8548           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8549           Res = Context->getConstantExprZExt(Res, CI.getType());
8550           return ReplaceInstUsesWith(CI, Res);
8551         }
8552           
8553         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8554         Value *In = ICI->getOperand(0);
8555         if (ShiftAmt) {
8556           // Perform a logical shr by shiftamt.
8557           // Insert the shift to put the result in the low bit.
8558           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8559                               Context->getConstantInt(In->getType(), ShiftAmt),
8560                                                    In->getName()+".lobit"), CI);
8561         }
8562           
8563         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8564           Constant *One = Context->getConstantInt(In->getType(), 1);
8565           In = BinaryOperator::CreateXor(In, One, "tmp");
8566           InsertNewInstBefore(cast<Instruction>(In), CI);
8567         }
8568           
8569         if (CI.getType() == In->getType())
8570           return ReplaceInstUsesWith(CI, In);
8571         else
8572           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8573       }
8574     }
8575   }
8576
8577   return 0;
8578 }
8579
8580 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8581   // If one of the common conversion will work ..
8582   if (Instruction *Result = commonIntCastTransforms(CI))
8583     return Result;
8584
8585   Value *Src = CI.getOperand(0);
8586
8587   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8588   // types and if the sizes are just right we can convert this into a logical
8589   // 'and' which will be much cheaper than the pair of casts.
8590   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8591     // Get the sizes of the types involved.  We know that the intermediate type
8592     // will be smaller than A or C, but don't know the relation between A and C.
8593     Value *A = CSrc->getOperand(0);
8594     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8595     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8596     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8597     // If we're actually extending zero bits, then if
8598     // SrcSize <  DstSize: zext(a & mask)
8599     // SrcSize == DstSize: a & mask
8600     // SrcSize  > DstSize: trunc(a) & mask
8601     if (SrcSize < DstSize) {
8602       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8603       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8604       Instruction *And =
8605         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8606       InsertNewInstBefore(And, CI);
8607       return new ZExtInst(And, CI.getType());
8608     } else if (SrcSize == DstSize) {
8609       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8610       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8611                                                            AndValue));
8612     } else if (SrcSize > DstSize) {
8613       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8614       InsertNewInstBefore(Trunc, CI);
8615       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8616       return BinaryOperator::CreateAnd(Trunc, 
8617                                        Context->getConstantInt(Trunc->getType(),
8618                                                                AndValue));
8619     }
8620   }
8621
8622   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8623     return transformZExtICmp(ICI, CI);
8624
8625   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8626   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8627     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8628     // of the (zext icmp) will be transformed.
8629     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8630     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8631     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8632         (transformZExtICmp(LHS, CI, false) ||
8633          transformZExtICmp(RHS, CI, false))) {
8634       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8635       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8636       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8637     }
8638   }
8639
8640   // zext(trunc(t) & C) -> (t & zext(C)).
8641   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8642     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8643       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8644         Value *TI0 = TI->getOperand(0);
8645         if (TI0->getType() == CI.getType())
8646           return
8647             BinaryOperator::CreateAnd(TI0,
8648                                 Context->getConstantExprZExt(C, CI.getType()));
8649       }
8650
8651   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8652   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8653     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8654       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8655         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8656             And->getOperand(1) == C)
8657           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8658             Value *TI0 = TI->getOperand(0);
8659             if (TI0->getType() == CI.getType()) {
8660               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8661               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8662               InsertNewInstBefore(NewAnd, *And);
8663               return BinaryOperator::CreateXor(NewAnd, ZC);
8664             }
8665           }
8666
8667   return 0;
8668 }
8669
8670 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8671   if (Instruction *I = commonIntCastTransforms(CI))
8672     return I;
8673   
8674   Value *Src = CI.getOperand(0);
8675   
8676   // Canonicalize sign-extend from i1 to a select.
8677   if (Src->getType() == Type::Int1Ty)
8678     return SelectInst::Create(Src,
8679                               Context->getConstantIntAllOnesValue(CI.getType()),
8680                               Context->getNullValue(CI.getType()));
8681
8682   // See if the value being truncated is already sign extended.  If so, just
8683   // eliminate the trunc/sext pair.
8684   if (getOpcode(Src) == Instruction::Trunc) {
8685     Value *Op = cast<User>(Src)->getOperand(0);
8686     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8687     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8688     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8689     unsigned NumSignBits = ComputeNumSignBits(Op);
8690
8691     if (OpBits == DestBits) {
8692       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8693       // bits, it is already ready.
8694       if (NumSignBits > DestBits-MidBits)
8695         return ReplaceInstUsesWith(CI, Op);
8696     } else if (OpBits < DestBits) {
8697       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8698       // bits, just sext from i32.
8699       if (NumSignBits > OpBits-MidBits)
8700         return new SExtInst(Op, CI.getType(), "tmp");
8701     } else {
8702       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8703       // bits, just truncate to i32.
8704       if (NumSignBits > OpBits-MidBits)
8705         return new TruncInst(Op, CI.getType(), "tmp");
8706     }
8707   }
8708
8709   // If the input is a shl/ashr pair of a same constant, then this is a sign
8710   // extension from a smaller value.  If we could trust arbitrary bitwidth
8711   // integers, we could turn this into a truncate to the smaller bit and then
8712   // use a sext for the whole extension.  Since we don't, look deeper and check
8713   // for a truncate.  If the source and dest are the same type, eliminate the
8714   // trunc and extend and just do shifts.  For example, turn:
8715   //   %a = trunc i32 %i to i8
8716   //   %b = shl i8 %a, 6
8717   //   %c = ashr i8 %b, 6
8718   //   %d = sext i8 %c to i32
8719   // into:
8720   //   %a = shl i32 %i, 30
8721   //   %d = ashr i32 %a, 30
8722   Value *A = 0;
8723   ConstantInt *BA = 0, *CA = 0;
8724   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8725                         m_ConstantInt(CA))) &&
8726       BA == CA && isa<TruncInst>(A)) {
8727     Value *I = cast<TruncInst>(A)->getOperand(0);
8728     if (I->getType() == CI.getType()) {
8729       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8730       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8731       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8732       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8733       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8734                                                         CI.getName()), CI);
8735       return BinaryOperator::CreateAShr(I, ShAmtV);
8736     }
8737   }
8738   
8739   return 0;
8740 }
8741
8742 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8743 /// in the specified FP type without changing its value.
8744 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8745                               LLVMContext *Context) {
8746   bool losesInfo;
8747   APFloat F = CFP->getValueAPF();
8748   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8749   if (!losesInfo)
8750     return Context->getConstantFP(F);
8751   return 0;
8752 }
8753
8754 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8755 /// through it until we get the source value.
8756 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8757   if (Instruction *I = dyn_cast<Instruction>(V))
8758     if (I->getOpcode() == Instruction::FPExt)
8759       return LookThroughFPExtensions(I->getOperand(0), Context);
8760   
8761   // If this value is a constant, return the constant in the smallest FP type
8762   // that can accurately represent it.  This allows us to turn
8763   // (float)((double)X+2.0) into x+2.0f.
8764   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8765     if (CFP->getType() == Type::PPC_FP128Ty)
8766       return V;  // No constant folding of this.
8767     // See if the value can be truncated to float and then reextended.
8768     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8769       return V;
8770     if (CFP->getType() == Type::DoubleTy)
8771       return V;  // Won't shrink.
8772     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8773       return V;
8774     // Don't try to shrink to various long double types.
8775   }
8776   
8777   return V;
8778 }
8779
8780 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8781   if (Instruction *I = commonCastTransforms(CI))
8782     return I;
8783   
8784   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8785   // smaller than the destination type, we can eliminate the truncate by doing
8786   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8787   // many builtins (sqrt, etc).
8788   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8789   if (OpI && OpI->hasOneUse()) {
8790     switch (OpI->getOpcode()) {
8791     default: break;
8792     case Instruction::FAdd:
8793     case Instruction::FSub:
8794     case Instruction::FMul:
8795     case Instruction::FDiv:
8796     case Instruction::FRem:
8797       const Type *SrcTy = OpI->getType();
8798       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8799       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8800       if (LHSTrunc->getType() != SrcTy && 
8801           RHSTrunc->getType() != SrcTy) {
8802         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8803         // If the source types were both smaller than the destination type of
8804         // the cast, do this xform.
8805         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8806             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8807           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8808                                       CI.getType(), CI);
8809           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8810                                       CI.getType(), CI);
8811           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8812         }
8813       }
8814       break;  
8815     }
8816   }
8817   return 0;
8818 }
8819
8820 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8821   return commonCastTransforms(CI);
8822 }
8823
8824 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8825   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8826   if (OpI == 0)
8827     return commonCastTransforms(FI);
8828
8829   // fptoui(uitofp(X)) --> X
8830   // fptoui(sitofp(X)) --> X
8831   // This is safe if the intermediate type has enough bits in its mantissa to
8832   // accurately represent all values of X.  For example, do not do this with
8833   // i64->float->i64.  This is also safe for sitofp case, because any negative
8834   // 'X' value would cause an undefined result for the fptoui. 
8835   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8836       OpI->getOperand(0)->getType() == FI.getType() &&
8837       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8838                     OpI->getType()->getFPMantissaWidth())
8839     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8840
8841   return commonCastTransforms(FI);
8842 }
8843
8844 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8845   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8846   if (OpI == 0)
8847     return commonCastTransforms(FI);
8848   
8849   // fptosi(sitofp(X)) --> X
8850   // fptosi(uitofp(X)) --> X
8851   // This is safe if the intermediate type has enough bits in its mantissa to
8852   // accurately represent all values of X.  For example, do not do this with
8853   // i64->float->i64.  This is also safe for sitofp case, because any negative
8854   // 'X' value would cause an undefined result for the fptoui. 
8855   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8856       OpI->getOperand(0)->getType() == FI.getType() &&
8857       (int)FI.getType()->getScalarSizeInBits() <=
8858                     OpI->getType()->getFPMantissaWidth())
8859     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8860   
8861   return commonCastTransforms(FI);
8862 }
8863
8864 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8865   return commonCastTransforms(CI);
8866 }
8867
8868 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8869   return commonCastTransforms(CI);
8870 }
8871
8872 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8873   // If the destination integer type is smaller than the intptr_t type for
8874   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8875   // trunc to be exposed to other transforms.  Don't do this for extending
8876   // ptrtoint's, because we don't know if the target sign or zero extends its
8877   // pointers.
8878   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8879     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8880                                                     TD->getIntPtrType(),
8881                                                     "tmp"), CI);
8882     return new TruncInst(P, CI.getType());
8883   }
8884   
8885   return commonPointerCastTransforms(CI);
8886 }
8887
8888 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8889   // If the source integer type is larger than the intptr_t type for
8890   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8891   // allows the trunc to be exposed to other transforms.  Don't do this for
8892   // extending inttoptr's, because we don't know if the target sign or zero
8893   // extends to pointers.
8894   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8895       TD->getPointerSizeInBits()) {
8896     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8897                                                  TD->getIntPtrType(),
8898                                                  "tmp"), CI);
8899     return new IntToPtrInst(P, CI.getType());
8900   }
8901   
8902   if (Instruction *I = commonCastTransforms(CI))
8903     return I;
8904   
8905   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8906   if (!DestPointee->isSized()) return 0;
8907
8908   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8909   ConstantInt *Cst;
8910   Value *X;
8911   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8912                                     m_ConstantInt(Cst)))) {
8913     // If the source and destination operands have the same type, see if this
8914     // is a single-index GEP.
8915     if (X->getType() == CI.getType()) {
8916       // Get the size of the pointee type.
8917       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8918
8919       // Convert the constant to intptr type.
8920       APInt Offset = Cst->getValue();
8921       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8922
8923       // If Offset is evenly divisible by Size, we can do this xform.
8924       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8925         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8926         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8927       }
8928     }
8929     // TODO: Could handle other cases, e.g. where add is indexing into field of
8930     // struct etc.
8931   } else if (CI.getOperand(0)->hasOneUse() &&
8932              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8933     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8934     // "inttoptr+GEP" instead of "add+intptr".
8935     
8936     // Get the size of the pointee type.
8937     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8938     
8939     // Convert the constant to intptr type.
8940     APInt Offset = Cst->getValue();
8941     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8942     
8943     // If Offset is evenly divisible by Size, we can do this xform.
8944     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8945       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8946       
8947       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8948                                                             "tmp"), CI);
8949       return GetElementPtrInst::Create(P,
8950                                        Context->getConstantInt(Offset), "tmp");
8951     }
8952   }
8953   return 0;
8954 }
8955
8956 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8957   // If the operands are integer typed then apply the integer transforms,
8958   // otherwise just apply the common ones.
8959   Value *Src = CI.getOperand(0);
8960   const Type *SrcTy = Src->getType();
8961   const Type *DestTy = CI.getType();
8962
8963   if (SrcTy->isInteger() && DestTy->isInteger()) {
8964     if (Instruction *Result = commonIntCastTransforms(CI))
8965       return Result;
8966   } else if (isa<PointerType>(SrcTy)) {
8967     if (Instruction *I = commonPointerCastTransforms(CI))
8968       return I;
8969   } else {
8970     if (Instruction *Result = commonCastTransforms(CI))
8971       return Result;
8972   }
8973
8974
8975   // Get rid of casts from one type to the same type. These are useless and can
8976   // be replaced by the operand.
8977   if (DestTy == Src->getType())
8978     return ReplaceInstUsesWith(CI, Src);
8979
8980   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8981     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8982     const Type *DstElTy = DstPTy->getElementType();
8983     const Type *SrcElTy = SrcPTy->getElementType();
8984     
8985     // If the address spaces don't match, don't eliminate the bitcast, which is
8986     // required for changing types.
8987     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8988       return 0;
8989     
8990     // If we are casting a malloc or alloca to a pointer to a type of the same
8991     // size, rewrite the allocation instruction to allocate the "right" type.
8992     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8993       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8994         return V;
8995     
8996     // If the source and destination are pointers, and this cast is equivalent
8997     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8998     // This can enhance SROA and other transforms that want type-safe pointers.
8999     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9000     unsigned NumZeros = 0;
9001     while (SrcElTy != DstElTy && 
9002            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9003            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9004       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9005       ++NumZeros;
9006     }
9007
9008     // If we found a path from the src to dest, create the getelementptr now.
9009     if (SrcElTy == DstElTy) {
9010       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9011       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9012                                        ((Instruction*) NULL));
9013     }
9014   }
9015
9016   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9017     if (SVI->hasOneUse()) {
9018       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9019       // a bitconvert to a vector with the same # elts.
9020       if (isa<VectorType>(DestTy) && 
9021           cast<VectorType>(DestTy)->getNumElements() ==
9022                 SVI->getType()->getNumElements() &&
9023           SVI->getType()->getNumElements() ==
9024             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9025         CastInst *Tmp;
9026         // If either of the operands is a cast from CI.getType(), then
9027         // evaluating the shuffle in the casted destination's type will allow
9028         // us to eliminate at least one cast.
9029         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9030              Tmp->getOperand(0)->getType() == DestTy) ||
9031             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9032              Tmp->getOperand(0)->getType() == DestTy)) {
9033           Value *LHS = InsertCastBefore(Instruction::BitCast,
9034                                         SVI->getOperand(0), DestTy, CI);
9035           Value *RHS = InsertCastBefore(Instruction::BitCast,
9036                                         SVI->getOperand(1), DestTy, CI);
9037           // Return a new shuffle vector.  Use the same element ID's, as we
9038           // know the vector types match #elts.
9039           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9040         }
9041       }
9042     }
9043   }
9044   return 0;
9045 }
9046
9047 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9048 ///   %C = or %A, %B
9049 ///   %D = select %cond, %C, %A
9050 /// into:
9051 ///   %C = select %cond, %B, 0
9052 ///   %D = or %A, %C
9053 ///
9054 /// Assuming that the specified instruction is an operand to the select, return
9055 /// a bitmask indicating which operands of this instruction are foldable if they
9056 /// equal the other incoming value of the select.
9057 ///
9058 static unsigned GetSelectFoldableOperands(Instruction *I) {
9059   switch (I->getOpcode()) {
9060   case Instruction::Add:
9061   case Instruction::Mul:
9062   case Instruction::And:
9063   case Instruction::Or:
9064   case Instruction::Xor:
9065     return 3;              // Can fold through either operand.
9066   case Instruction::Sub:   // Can only fold on the amount subtracted.
9067   case Instruction::Shl:   // Can only fold on the shift amount.
9068   case Instruction::LShr:
9069   case Instruction::AShr:
9070     return 1;
9071   default:
9072     return 0;              // Cannot fold
9073   }
9074 }
9075
9076 /// GetSelectFoldableConstant - For the same transformation as the previous
9077 /// function, return the identity constant that goes into the select.
9078 static Constant *GetSelectFoldableConstant(Instruction *I,
9079                                            LLVMContext *Context) {
9080   switch (I->getOpcode()) {
9081   default: assert(0 && "This cannot happen!"); abort();
9082   case Instruction::Add:
9083   case Instruction::Sub:
9084   case Instruction::Or:
9085   case Instruction::Xor:
9086   case Instruction::Shl:
9087   case Instruction::LShr:
9088   case Instruction::AShr:
9089     return Context->getNullValue(I->getType());
9090   case Instruction::And:
9091     return Context->getAllOnesValue(I->getType());
9092   case Instruction::Mul:
9093     return Context->getConstantInt(I->getType(), 1);
9094   }
9095 }
9096
9097 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9098 /// have the same opcode and only one use each.  Try to simplify this.
9099 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9100                                           Instruction *FI) {
9101   if (TI->getNumOperands() == 1) {
9102     // If this is a non-volatile load or a cast from the same type,
9103     // merge.
9104     if (TI->isCast()) {
9105       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9106         return 0;
9107     } else {
9108       return 0;  // unknown unary op.
9109     }
9110
9111     // Fold this by inserting a select from the input values.
9112     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9113                                            FI->getOperand(0), SI.getName()+".v");
9114     InsertNewInstBefore(NewSI, SI);
9115     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9116                             TI->getType());
9117   }
9118
9119   // Only handle binary operators here.
9120   if (!isa<BinaryOperator>(TI))
9121     return 0;
9122
9123   // Figure out if the operations have any operands in common.
9124   Value *MatchOp, *OtherOpT, *OtherOpF;
9125   bool MatchIsOpZero;
9126   if (TI->getOperand(0) == FI->getOperand(0)) {
9127     MatchOp  = TI->getOperand(0);
9128     OtherOpT = TI->getOperand(1);
9129     OtherOpF = FI->getOperand(1);
9130     MatchIsOpZero = true;
9131   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9132     MatchOp  = TI->getOperand(1);
9133     OtherOpT = TI->getOperand(0);
9134     OtherOpF = FI->getOperand(0);
9135     MatchIsOpZero = false;
9136   } else if (!TI->isCommutative()) {
9137     return 0;
9138   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9139     MatchOp  = TI->getOperand(0);
9140     OtherOpT = TI->getOperand(1);
9141     OtherOpF = FI->getOperand(0);
9142     MatchIsOpZero = true;
9143   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9144     MatchOp  = TI->getOperand(1);
9145     OtherOpT = TI->getOperand(0);
9146     OtherOpF = FI->getOperand(1);
9147     MatchIsOpZero = true;
9148   } else {
9149     return 0;
9150   }
9151
9152   // If we reach here, they do have operations in common.
9153   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9154                                          OtherOpF, SI.getName()+".v");
9155   InsertNewInstBefore(NewSI, SI);
9156
9157   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9158     if (MatchIsOpZero)
9159       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9160     else
9161       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9162   }
9163   assert(0 && "Shouldn't get here");
9164   return 0;
9165 }
9166
9167 static bool isSelect01(Constant *C1, Constant *C2) {
9168   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9169   if (!C1I)
9170     return false;
9171   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9172   if (!C2I)
9173     return false;
9174   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9175 }
9176
9177 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9178 /// facilitate further optimization.
9179 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9180                                             Value *FalseVal) {
9181   // See the comment above GetSelectFoldableOperands for a description of the
9182   // transformation we are doing here.
9183   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9184     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9185         !isa<Constant>(FalseVal)) {
9186       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9187         unsigned OpToFold = 0;
9188         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9189           OpToFold = 1;
9190         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9191           OpToFold = 2;
9192         }
9193
9194         if (OpToFold) {
9195           Constant *C = GetSelectFoldableConstant(TVI, Context);
9196           Value *OOp = TVI->getOperand(2-OpToFold);
9197           // Avoid creating select between 2 constants unless it's selecting
9198           // between 0 and 1.
9199           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9200             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9201             InsertNewInstBefore(NewSel, SI);
9202             NewSel->takeName(TVI);
9203             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9204               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9205             assert(0 && "Unknown instruction!!");
9206           }
9207         }
9208       }
9209     }
9210   }
9211
9212   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9213     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9214         !isa<Constant>(TrueVal)) {
9215       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9216         unsigned OpToFold = 0;
9217         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9218           OpToFold = 1;
9219         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9220           OpToFold = 2;
9221         }
9222
9223         if (OpToFold) {
9224           Constant *C = GetSelectFoldableConstant(FVI, Context);
9225           Value *OOp = FVI->getOperand(2-OpToFold);
9226           // Avoid creating select between 2 constants unless it's selecting
9227           // between 0 and 1.
9228           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9229             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9230             InsertNewInstBefore(NewSel, SI);
9231             NewSel->takeName(FVI);
9232             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9233               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9234             assert(0 && "Unknown instruction!!");
9235           }
9236         }
9237       }
9238     }
9239   }
9240
9241   return 0;
9242 }
9243
9244 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9245 /// ICmpInst as its first operand.
9246 ///
9247 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9248                                                    ICmpInst *ICI) {
9249   bool Changed = false;
9250   ICmpInst::Predicate Pred = ICI->getPredicate();
9251   Value *CmpLHS = ICI->getOperand(0);
9252   Value *CmpRHS = ICI->getOperand(1);
9253   Value *TrueVal = SI.getTrueValue();
9254   Value *FalseVal = SI.getFalseValue();
9255
9256   // Check cases where the comparison is with a constant that
9257   // can be adjusted to fit the min/max idiom. We may edit ICI in
9258   // place here, so make sure the select is the only user.
9259   if (ICI->hasOneUse())
9260     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9261       switch (Pred) {
9262       default: break;
9263       case ICmpInst::ICMP_ULT:
9264       case ICmpInst::ICMP_SLT: {
9265         // X < MIN ? T : F  -->  F
9266         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9267           return ReplaceInstUsesWith(SI, FalseVal);
9268         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9269         Constant *AdjustedRHS = SubOne(CI, Context);
9270         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9271             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9272           Pred = ICmpInst::getSwappedPredicate(Pred);
9273           CmpRHS = AdjustedRHS;
9274           std::swap(FalseVal, TrueVal);
9275           ICI->setPredicate(Pred);
9276           ICI->setOperand(1, CmpRHS);
9277           SI.setOperand(1, TrueVal);
9278           SI.setOperand(2, FalseVal);
9279           Changed = true;
9280         }
9281         break;
9282       }
9283       case ICmpInst::ICMP_UGT:
9284       case ICmpInst::ICMP_SGT: {
9285         // X > MAX ? T : F  -->  F
9286         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9287           return ReplaceInstUsesWith(SI, FalseVal);
9288         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9289         Constant *AdjustedRHS = AddOne(CI, Context);
9290         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9291             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9292           Pred = ICmpInst::getSwappedPredicate(Pred);
9293           CmpRHS = AdjustedRHS;
9294           std::swap(FalseVal, TrueVal);
9295           ICI->setPredicate(Pred);
9296           ICI->setOperand(1, CmpRHS);
9297           SI.setOperand(1, TrueVal);
9298           SI.setOperand(2, FalseVal);
9299           Changed = true;
9300         }
9301         break;
9302       }
9303       }
9304
9305       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9306       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9307       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9308       if (match(TrueVal, m_ConstantInt<-1>()) &&
9309           match(FalseVal, m_ConstantInt<0>()))
9310         Pred = ICI->getPredicate();
9311       else if (match(TrueVal, m_ConstantInt<0>()) &&
9312                match(FalseVal, m_ConstantInt<-1>()))
9313         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9314       
9315       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9316         // If we are just checking for a icmp eq of a single bit and zext'ing it
9317         // to an integer, then shift the bit to the appropriate place and then
9318         // cast to integer to avoid the comparison.
9319         const APInt &Op1CV = CI->getValue();
9320     
9321         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9322         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9323         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9324             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9325           Value *In = ICI->getOperand(0);
9326           Value *Sh = Context->getConstantInt(In->getType(),
9327                                        In->getType()->getScalarSizeInBits()-1);
9328           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9329                                                           In->getName()+".lobit"),
9330                                    *ICI);
9331           if (In->getType() != SI.getType())
9332             In = CastInst::CreateIntegerCast(In, SI.getType(),
9333                                              true/*SExt*/, "tmp", ICI);
9334     
9335           if (Pred == ICmpInst::ICMP_SGT)
9336             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9337                                        In->getName()+".not"), *ICI);
9338     
9339           return ReplaceInstUsesWith(SI, In);
9340         }
9341       }
9342     }
9343
9344   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9345     // Transform (X == Y) ? X : Y  -> Y
9346     if (Pred == ICmpInst::ICMP_EQ)
9347       return ReplaceInstUsesWith(SI, FalseVal);
9348     // Transform (X != Y) ? X : Y  -> X
9349     if (Pred == ICmpInst::ICMP_NE)
9350       return ReplaceInstUsesWith(SI, TrueVal);
9351     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9352
9353   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9354     // Transform (X == Y) ? Y : X  -> X
9355     if (Pred == ICmpInst::ICMP_EQ)
9356       return ReplaceInstUsesWith(SI, FalseVal);
9357     // Transform (X != Y) ? Y : X  -> Y
9358     if (Pred == ICmpInst::ICMP_NE)
9359       return ReplaceInstUsesWith(SI, TrueVal);
9360     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9361   }
9362
9363   /// NOTE: if we wanted to, this is where to detect integer ABS
9364
9365   return Changed ? &SI : 0;
9366 }
9367
9368 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9369   Value *CondVal = SI.getCondition();
9370   Value *TrueVal = SI.getTrueValue();
9371   Value *FalseVal = SI.getFalseValue();
9372
9373   // select true, X, Y  -> X
9374   // select false, X, Y -> Y
9375   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9376     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9377
9378   // select C, X, X -> X
9379   if (TrueVal == FalseVal)
9380     return ReplaceInstUsesWith(SI, TrueVal);
9381
9382   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9383     return ReplaceInstUsesWith(SI, FalseVal);
9384   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9385     return ReplaceInstUsesWith(SI, TrueVal);
9386   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9387     if (isa<Constant>(TrueVal))
9388       return ReplaceInstUsesWith(SI, TrueVal);
9389     else
9390       return ReplaceInstUsesWith(SI, FalseVal);
9391   }
9392
9393   if (SI.getType() == Type::Int1Ty) {
9394     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9395       if (C->getZExtValue()) {
9396         // Change: A = select B, true, C --> A = or B, C
9397         return BinaryOperator::CreateOr(CondVal, FalseVal);
9398       } else {
9399         // Change: A = select B, false, C --> A = and !B, C
9400         Value *NotCond =
9401           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9402                                              "not."+CondVal->getName()), SI);
9403         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9404       }
9405     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9406       if (C->getZExtValue() == false) {
9407         // Change: A = select B, C, false --> A = and B, C
9408         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9409       } else {
9410         // Change: A = select B, C, true --> A = or !B, C
9411         Value *NotCond =
9412           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9413                                              "not."+CondVal->getName()), SI);
9414         return BinaryOperator::CreateOr(NotCond, TrueVal);
9415       }
9416     }
9417     
9418     // select a, b, a  -> a&b
9419     // select a, a, b  -> a|b
9420     if (CondVal == TrueVal)
9421       return BinaryOperator::CreateOr(CondVal, FalseVal);
9422     else if (CondVal == FalseVal)
9423       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9424   }
9425
9426   // Selecting between two integer constants?
9427   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9428     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9429       // select C, 1, 0 -> zext C to int
9430       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9431         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9432       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9433         // select C, 0, 1 -> zext !C to int
9434         Value *NotCond =
9435           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9436                                                "not."+CondVal->getName()), SI);
9437         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9438       }
9439
9440       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9441
9442         // (x <s 0) ? -1 : 0 -> ashr x, 31
9443         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9444           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9445             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9446               // The comparison constant and the result are not neccessarily the
9447               // same width. Make an all-ones value by inserting a AShr.
9448               Value *X = IC->getOperand(0);
9449               uint32_t Bits = X->getType()->getScalarSizeInBits();
9450               Constant *ShAmt = Context->getConstantInt(X->getType(), Bits-1);
9451               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9452                                                         ShAmt, "ones");
9453               InsertNewInstBefore(SRA, SI);
9454
9455               // Then cast to the appropriate width.
9456               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9457             }
9458           }
9459
9460
9461         // If one of the constants is zero (we know they can't both be) and we
9462         // have an icmp instruction with zero, and we have an 'and' with the
9463         // non-constant value, eliminate this whole mess.  This corresponds to
9464         // cases like this: ((X & 27) ? 27 : 0)
9465         if (TrueValC->isZero() || FalseValC->isZero())
9466           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9467               cast<Constant>(IC->getOperand(1))->isNullValue())
9468             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9469               if (ICA->getOpcode() == Instruction::And &&
9470                   isa<ConstantInt>(ICA->getOperand(1)) &&
9471                   (ICA->getOperand(1) == TrueValC ||
9472                    ICA->getOperand(1) == FalseValC) &&
9473                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9474                 // Okay, now we know that everything is set up, we just don't
9475                 // know whether we have a icmp_ne or icmp_eq and whether the 
9476                 // true or false val is the zero.
9477                 bool ShouldNotVal = !TrueValC->isZero();
9478                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9479                 Value *V = ICA;
9480                 if (ShouldNotVal)
9481                   V = InsertNewInstBefore(BinaryOperator::Create(
9482                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9483                 return ReplaceInstUsesWith(SI, V);
9484               }
9485       }
9486     }
9487
9488   // See if we are selecting two values based on a comparison of the two values.
9489   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9490     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9491       // Transform (X == Y) ? X : Y  -> Y
9492       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9493         // This is not safe in general for floating point:  
9494         // consider X== -0, Y== +0.
9495         // It becomes safe if either operand is a nonzero constant.
9496         ConstantFP *CFPt, *CFPf;
9497         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9498               !CFPt->getValueAPF().isZero()) ||
9499             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9500              !CFPf->getValueAPF().isZero()))
9501         return ReplaceInstUsesWith(SI, FalseVal);
9502       }
9503       // Transform (X != Y) ? X : Y  -> X
9504       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9505         return ReplaceInstUsesWith(SI, TrueVal);
9506       // NOTE: if we wanted to, this is where to detect MIN/MAX
9507
9508     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9509       // Transform (X == Y) ? Y : X  -> X
9510       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9511         // This is not safe in general for floating point:  
9512         // consider X== -0, Y== +0.
9513         // It becomes safe if either operand is a nonzero constant.
9514         ConstantFP *CFPt, *CFPf;
9515         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9516               !CFPt->getValueAPF().isZero()) ||
9517             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9518              !CFPf->getValueAPF().isZero()))
9519           return ReplaceInstUsesWith(SI, FalseVal);
9520       }
9521       // Transform (X != Y) ? Y : X  -> Y
9522       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9523         return ReplaceInstUsesWith(SI, TrueVal);
9524       // NOTE: if we wanted to, this is where to detect MIN/MAX
9525     }
9526     // NOTE: if we wanted to, this is where to detect ABS
9527   }
9528
9529   // See if we are selecting two values based on a comparison of the two values.
9530   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9531     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9532       return Result;
9533
9534   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9535     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9536       if (TI->hasOneUse() && FI->hasOneUse()) {
9537         Instruction *AddOp = 0, *SubOp = 0;
9538
9539         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9540         if (TI->getOpcode() == FI->getOpcode())
9541           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9542             return IV;
9543
9544         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9545         // even legal for FP.
9546         if ((TI->getOpcode() == Instruction::Sub &&
9547              FI->getOpcode() == Instruction::Add) ||
9548             (TI->getOpcode() == Instruction::FSub &&
9549              FI->getOpcode() == Instruction::FAdd)) {
9550           AddOp = FI; SubOp = TI;
9551         } else if ((FI->getOpcode() == Instruction::Sub &&
9552                     TI->getOpcode() == Instruction::Add) ||
9553                    (FI->getOpcode() == Instruction::FSub &&
9554                     TI->getOpcode() == Instruction::FAdd)) {
9555           AddOp = TI; SubOp = FI;
9556         }
9557
9558         if (AddOp) {
9559           Value *OtherAddOp = 0;
9560           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9561             OtherAddOp = AddOp->getOperand(1);
9562           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9563             OtherAddOp = AddOp->getOperand(0);
9564           }
9565
9566           if (OtherAddOp) {
9567             // So at this point we know we have (Y -> OtherAddOp):
9568             //        select C, (add X, Y), (sub X, Z)
9569             Value *NegVal;  // Compute -Z
9570             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9571               NegVal = Context->getConstantExprNeg(C);
9572             } else {
9573               NegVal = InsertNewInstBefore(
9574                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9575             }
9576
9577             Value *NewTrueOp = OtherAddOp;
9578             Value *NewFalseOp = NegVal;
9579             if (AddOp != TI)
9580               std::swap(NewTrueOp, NewFalseOp);
9581             Instruction *NewSel =
9582               SelectInst::Create(CondVal, NewTrueOp,
9583                                  NewFalseOp, SI.getName() + ".p");
9584
9585             NewSel = InsertNewInstBefore(NewSel, SI);
9586             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9587           }
9588         }
9589       }
9590
9591   // See if we can fold the select into one of our operands.
9592   if (SI.getType()->isInteger()) {
9593     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9594     if (FoldI)
9595       return FoldI;
9596   }
9597
9598   if (BinaryOperator::isNot(CondVal)) {
9599     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9600     SI.setOperand(1, FalseVal);
9601     SI.setOperand(2, TrueVal);
9602     return &SI;
9603   }
9604
9605   return 0;
9606 }
9607
9608 /// EnforceKnownAlignment - If the specified pointer points to an object that
9609 /// we control, modify the object's alignment to PrefAlign. This isn't
9610 /// often possible though. If alignment is important, a more reliable approach
9611 /// is to simply align all global variables and allocation instructions to
9612 /// their preferred alignment from the beginning.
9613 ///
9614 static unsigned EnforceKnownAlignment(Value *V,
9615                                       unsigned Align, unsigned PrefAlign) {
9616
9617   User *U = dyn_cast<User>(V);
9618   if (!U) return Align;
9619
9620   switch (getOpcode(U)) {
9621   default: break;
9622   case Instruction::BitCast:
9623     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9624   case Instruction::GetElementPtr: {
9625     // If all indexes are zero, it is just the alignment of the base pointer.
9626     bool AllZeroOperands = true;
9627     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9628       if (!isa<Constant>(*i) ||
9629           !cast<Constant>(*i)->isNullValue()) {
9630         AllZeroOperands = false;
9631         break;
9632       }
9633
9634     if (AllZeroOperands) {
9635       // Treat this like a bitcast.
9636       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9637     }
9638     break;
9639   }
9640   }
9641
9642   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9643     // If there is a large requested alignment and we can, bump up the alignment
9644     // of the global.
9645     if (!GV->isDeclaration()) {
9646       if (GV->getAlignment() >= PrefAlign)
9647         Align = GV->getAlignment();
9648       else {
9649         GV->setAlignment(PrefAlign);
9650         Align = PrefAlign;
9651       }
9652     }
9653   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9654     // If there is a requested alignment and if this is an alloca, round up.  We
9655     // don't do this for malloc, because some systems can't respect the request.
9656     if (isa<AllocaInst>(AI)) {
9657       if (AI->getAlignment() >= PrefAlign)
9658         Align = AI->getAlignment();
9659       else {
9660         AI->setAlignment(PrefAlign);
9661         Align = PrefAlign;
9662       }
9663     }
9664   }
9665
9666   return Align;
9667 }
9668
9669 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9670 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9671 /// and it is more than the alignment of the ultimate object, see if we can
9672 /// increase the alignment of the ultimate object, making this check succeed.
9673 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9674                                                   unsigned PrefAlign) {
9675   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9676                       sizeof(PrefAlign) * CHAR_BIT;
9677   APInt Mask = APInt::getAllOnesValue(BitWidth);
9678   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9679   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9680   unsigned TrailZ = KnownZero.countTrailingOnes();
9681   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9682
9683   if (PrefAlign > Align)
9684     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9685   
9686     // We don't need to make any adjustment.
9687   return Align;
9688 }
9689
9690 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9691   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9692   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9693   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9694   unsigned CopyAlign = MI->getAlignment();
9695
9696   if (CopyAlign < MinAlign) {
9697     MI->setAlignment(MinAlign);
9698     return MI;
9699   }
9700   
9701   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9702   // load/store.
9703   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9704   if (MemOpLength == 0) return 0;
9705   
9706   // Source and destination pointer types are always "i8*" for intrinsic.  See
9707   // if the size is something we can handle with a single primitive load/store.
9708   // A single load+store correctly handles overlapping memory in the memmove
9709   // case.
9710   unsigned Size = MemOpLength->getZExtValue();
9711   if (Size == 0) return MI;  // Delete this mem transfer.
9712   
9713   if (Size > 8 || (Size&(Size-1)))
9714     return 0;  // If not 1/2/4/8 bytes, exit.
9715   
9716   // Use an integer load+store unless we can find something better.
9717   Type *NewPtrTy =
9718                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9719   
9720   // Memcpy forces the use of i8* for the source and destination.  That means
9721   // that if you're using memcpy to move one double around, you'll get a cast
9722   // from double* to i8*.  We'd much rather use a double load+store rather than
9723   // an i64 load+store, here because this improves the odds that the source or
9724   // dest address will be promotable.  See if we can find a better type than the
9725   // integer datatype.
9726   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9727     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9728     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9729       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9730       // down through these levels if so.
9731       while (!SrcETy->isSingleValueType()) {
9732         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9733           if (STy->getNumElements() == 1)
9734             SrcETy = STy->getElementType(0);
9735           else
9736             break;
9737         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9738           if (ATy->getNumElements() == 1)
9739             SrcETy = ATy->getElementType();
9740           else
9741             break;
9742         } else
9743           break;
9744       }
9745       
9746       if (SrcETy->isSingleValueType())
9747         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9748     }
9749   }
9750   
9751   
9752   // If the memcpy/memmove provides better alignment info than we can
9753   // infer, use it.
9754   SrcAlign = std::max(SrcAlign, CopyAlign);
9755   DstAlign = std::max(DstAlign, CopyAlign);
9756   
9757   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9758   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9759   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9760   InsertNewInstBefore(L, *MI);
9761   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9762
9763   // Set the size of the copy to 0, it will be deleted on the next iteration.
9764   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9765   return MI;
9766 }
9767
9768 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9769   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9770   if (MI->getAlignment() < Alignment) {
9771     MI->setAlignment(Alignment);
9772     return MI;
9773   }
9774   
9775   // Extract the length and alignment and fill if they are constant.
9776   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9777   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9778   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9779     return 0;
9780   uint64_t Len = LenC->getZExtValue();
9781   Alignment = MI->getAlignment();
9782   
9783   // If the length is zero, this is a no-op
9784   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9785   
9786   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9787   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9788     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9789     
9790     Value *Dest = MI->getDest();
9791     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9792
9793     // Alignment 0 is identity for alignment 1 for memset, but not store.
9794     if (Alignment == 0) Alignment = 1;
9795     
9796     // Extract the fill value and store.
9797     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9798     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9799                                       Dest, false, Alignment), *MI);
9800     
9801     // Set the size of the copy to 0, it will be deleted on the next iteration.
9802     MI->setLength(Context->getNullValue(LenC->getType()));
9803     return MI;
9804   }
9805
9806   return 0;
9807 }
9808
9809
9810 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9811 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9812 /// the heavy lifting.
9813 ///
9814 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9815   // If the caller function is nounwind, mark the call as nounwind, even if the
9816   // callee isn't.
9817   if (CI.getParent()->getParent()->doesNotThrow() &&
9818       !CI.doesNotThrow()) {
9819     CI.setDoesNotThrow();
9820     return &CI;
9821   }
9822   
9823   
9824   
9825   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9826   if (!II) return visitCallSite(&CI);
9827   
9828   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9829   // visitCallSite.
9830   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9831     bool Changed = false;
9832
9833     // memmove/cpy/set of zero bytes is a noop.
9834     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9835       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9836
9837       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9838         if (CI->getZExtValue() == 1) {
9839           // Replace the instruction with just byte operations.  We would
9840           // transform other cases to loads/stores, but we don't know if
9841           // alignment is sufficient.
9842         }
9843     }
9844
9845     // If we have a memmove and the source operation is a constant global,
9846     // then the source and dest pointers can't alias, so we can change this
9847     // into a call to memcpy.
9848     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9849       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9850         if (GVSrc->isConstant()) {
9851           Module *M = CI.getParent()->getParent()->getParent();
9852           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9853           const Type *Tys[1];
9854           Tys[0] = CI.getOperand(3)->getType();
9855           CI.setOperand(0, 
9856                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9857           Changed = true;
9858         }
9859
9860       // memmove(x,x,size) -> noop.
9861       if (MMI->getSource() == MMI->getDest())
9862         return EraseInstFromFunction(CI);
9863     }
9864
9865     // If we can determine a pointer alignment that is bigger than currently
9866     // set, update the alignment.
9867     if (isa<MemTransferInst>(MI)) {
9868       if (Instruction *I = SimplifyMemTransfer(MI))
9869         return I;
9870     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9871       if (Instruction *I = SimplifyMemSet(MSI))
9872         return I;
9873     }
9874           
9875     if (Changed) return II;
9876   }
9877   
9878   switch (II->getIntrinsicID()) {
9879   default: break;
9880   case Intrinsic::bswap:
9881     // bswap(bswap(x)) -> x
9882     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9883       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9884         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9885     break;
9886   case Intrinsic::ppc_altivec_lvx:
9887   case Intrinsic::ppc_altivec_lvxl:
9888   case Intrinsic::x86_sse_loadu_ps:
9889   case Intrinsic::x86_sse2_loadu_pd:
9890   case Intrinsic::x86_sse2_loadu_dq:
9891     // Turn PPC lvx     -> load if the pointer is known aligned.
9892     // Turn X86 loadups -> load if the pointer is known aligned.
9893     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9894       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9895                                    Context->getPointerTypeUnqual(II->getType()),
9896                                        CI);
9897       return new LoadInst(Ptr);
9898     }
9899     break;
9900   case Intrinsic::ppc_altivec_stvx:
9901   case Intrinsic::ppc_altivec_stvxl:
9902     // Turn stvx -> store if the pointer is known aligned.
9903     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9904       const Type *OpPtrTy = 
9905         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9906       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9907       return new StoreInst(II->getOperand(1), Ptr);
9908     }
9909     break;
9910   case Intrinsic::x86_sse_storeu_ps:
9911   case Intrinsic::x86_sse2_storeu_pd:
9912   case Intrinsic::x86_sse2_storeu_dq:
9913     // Turn X86 storeu -> store if the pointer is known aligned.
9914     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9915       const Type *OpPtrTy = 
9916         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9917       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9918       return new StoreInst(II->getOperand(2), Ptr);
9919     }
9920     break;
9921     
9922   case Intrinsic::x86_sse_cvttss2si: {
9923     // These intrinsics only demands the 0th element of its input vector.  If
9924     // we can simplify the input based on that, do so now.
9925     unsigned VWidth =
9926       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9927     APInt DemandedElts(VWidth, 1);
9928     APInt UndefElts(VWidth, 0);
9929     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9930                                               UndefElts)) {
9931       II->setOperand(1, V);
9932       return II;
9933     }
9934     break;
9935   }
9936     
9937   case Intrinsic::ppc_altivec_vperm:
9938     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9939     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9940       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9941       
9942       // Check that all of the elements are integer constants or undefs.
9943       bool AllEltsOk = true;
9944       for (unsigned i = 0; i != 16; ++i) {
9945         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9946             !isa<UndefValue>(Mask->getOperand(i))) {
9947           AllEltsOk = false;
9948           break;
9949         }
9950       }
9951       
9952       if (AllEltsOk) {
9953         // Cast the input vectors to byte vectors.
9954         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9955         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9956         Value *Result = Context->getUndef(Op0->getType());
9957         
9958         // Only extract each element once.
9959         Value *ExtractedElts[32];
9960         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9961         
9962         for (unsigned i = 0; i != 16; ++i) {
9963           if (isa<UndefValue>(Mask->getOperand(i)))
9964             continue;
9965           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9966           Idx &= 31;  // Match the hardware behavior.
9967           
9968           if (ExtractedElts[Idx] == 0) {
9969             Instruction *Elt = 
9970               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9971             InsertNewInstBefore(Elt, CI);
9972             ExtractedElts[Idx] = Elt;
9973           }
9974         
9975           // Insert this value into the result vector.
9976           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9977                                              i, "tmp");
9978           InsertNewInstBefore(cast<Instruction>(Result), CI);
9979         }
9980         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9981       }
9982     }
9983     break;
9984
9985   case Intrinsic::stackrestore: {
9986     // If the save is right next to the restore, remove the restore.  This can
9987     // happen when variable allocas are DCE'd.
9988     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9989       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9990         BasicBlock::iterator BI = SS;
9991         if (&*++BI == II)
9992           return EraseInstFromFunction(CI);
9993       }
9994     }
9995     
9996     // Scan down this block to see if there is another stack restore in the
9997     // same block without an intervening call/alloca.
9998     BasicBlock::iterator BI = II;
9999     TerminatorInst *TI = II->getParent()->getTerminator();
10000     bool CannotRemove = false;
10001     for (++BI; &*BI != TI; ++BI) {
10002       if (isa<AllocaInst>(BI)) {
10003         CannotRemove = true;
10004         break;
10005       }
10006       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10007         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10008           // If there is a stackrestore below this one, remove this one.
10009           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10010             return EraseInstFromFunction(CI);
10011           // Otherwise, ignore the intrinsic.
10012         } else {
10013           // If we found a non-intrinsic call, we can't remove the stack
10014           // restore.
10015           CannotRemove = true;
10016           break;
10017         }
10018       }
10019     }
10020     
10021     // If the stack restore is in a return/unwind block and if there are no
10022     // allocas or calls between the restore and the return, nuke the restore.
10023     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10024       return EraseInstFromFunction(CI);
10025     break;
10026   }
10027   }
10028
10029   return visitCallSite(II);
10030 }
10031
10032 // InvokeInst simplification
10033 //
10034 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10035   return visitCallSite(&II);
10036 }
10037
10038 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10039 /// passed through the varargs area, we can eliminate the use of the cast.
10040 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10041                                          const CastInst * const CI,
10042                                          const TargetData * const TD,
10043                                          const int ix) {
10044   if (!CI->isLosslessCast())
10045     return false;
10046
10047   // The size of ByVal arguments is derived from the type, so we
10048   // can't change to a type with a different size.  If the size were
10049   // passed explicitly we could avoid this check.
10050   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10051     return true;
10052
10053   const Type* SrcTy = 
10054             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10055   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10056   if (!SrcTy->isSized() || !DstTy->isSized())
10057     return false;
10058   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10059     return false;
10060   return true;
10061 }
10062
10063 // visitCallSite - Improvements for call and invoke instructions.
10064 //
10065 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10066   bool Changed = false;
10067
10068   // If the callee is a constexpr cast of a function, attempt to move the cast
10069   // to the arguments of the call/invoke.
10070   if (transformConstExprCastCall(CS)) return 0;
10071
10072   Value *Callee = CS.getCalledValue();
10073
10074   if (Function *CalleeF = dyn_cast<Function>(Callee))
10075     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10076       Instruction *OldCall = CS.getInstruction();
10077       // If the call and callee calling conventions don't match, this call must
10078       // be unreachable, as the call is undefined.
10079       new StoreInst(Context->getConstantIntTrue(),
10080                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10081                                   OldCall);
10082       if (!OldCall->use_empty())
10083         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10084       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10085         return EraseInstFromFunction(*OldCall);
10086       return 0;
10087     }
10088
10089   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10090     // This instruction is not reachable, just remove it.  We insert a store to
10091     // undef so that we know that this code is not reachable, despite the fact
10092     // that we can't modify the CFG here.
10093     new StoreInst(Context->getConstantIntTrue(),
10094                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10095                   CS.getInstruction());
10096
10097     if (!CS.getInstruction()->use_empty())
10098       CS.getInstruction()->
10099         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10100
10101     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10102       // Don't break the CFG, insert a dummy cond branch.
10103       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10104                          Context->getConstantIntTrue(), II);
10105     }
10106     return EraseInstFromFunction(*CS.getInstruction());
10107   }
10108
10109   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10110     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10111       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10112         return transformCallThroughTrampoline(CS);
10113
10114   const PointerType *PTy = cast<PointerType>(Callee->getType());
10115   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10116   if (FTy->isVarArg()) {
10117     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10118     // See if we can optimize any arguments passed through the varargs area of
10119     // the call.
10120     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10121            E = CS.arg_end(); I != E; ++I, ++ix) {
10122       CastInst *CI = dyn_cast<CastInst>(*I);
10123       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10124         *I = CI->getOperand(0);
10125         Changed = true;
10126       }
10127     }
10128   }
10129
10130   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10131     // Inline asm calls cannot throw - mark them 'nounwind'.
10132     CS.setDoesNotThrow();
10133     Changed = true;
10134   }
10135
10136   return Changed ? CS.getInstruction() : 0;
10137 }
10138
10139 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10140 // attempt to move the cast to the arguments of the call/invoke.
10141 //
10142 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10143   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10144   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10145   if (CE->getOpcode() != Instruction::BitCast || 
10146       !isa<Function>(CE->getOperand(0)))
10147     return false;
10148   Function *Callee = cast<Function>(CE->getOperand(0));
10149   Instruction *Caller = CS.getInstruction();
10150   const AttrListPtr &CallerPAL = CS.getAttributes();
10151
10152   // Okay, this is a cast from a function to a different type.  Unless doing so
10153   // would cause a type conversion of one of our arguments, change this call to
10154   // be a direct call with arguments casted to the appropriate types.
10155   //
10156   const FunctionType *FT = Callee->getFunctionType();
10157   const Type *OldRetTy = Caller->getType();
10158   const Type *NewRetTy = FT->getReturnType();
10159
10160   if (isa<StructType>(NewRetTy))
10161     return false; // TODO: Handle multiple return values.
10162
10163   // Check to see if we are changing the return type...
10164   if (OldRetTy != NewRetTy) {
10165     if (Callee->isDeclaration() &&
10166         // Conversion is ok if changing from one pointer type to another or from
10167         // a pointer to an integer of the same size.
10168         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10169           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10170       return false;   // Cannot transform this return value.
10171
10172     if (!Caller->use_empty() &&
10173         // void -> non-void is handled specially
10174         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10175       return false;   // Cannot transform this return value.
10176
10177     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10178       Attributes RAttrs = CallerPAL.getRetAttributes();
10179       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10180         return false;   // Attribute not compatible with transformed value.
10181     }
10182
10183     // If the callsite is an invoke instruction, and the return value is used by
10184     // a PHI node in a successor, we cannot change the return type of the call
10185     // because there is no place to put the cast instruction (without breaking
10186     // the critical edge).  Bail out in this case.
10187     if (!Caller->use_empty())
10188       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10189         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10190              UI != E; ++UI)
10191           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10192             if (PN->getParent() == II->getNormalDest() ||
10193                 PN->getParent() == II->getUnwindDest())
10194               return false;
10195   }
10196
10197   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10198   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10199
10200   CallSite::arg_iterator AI = CS.arg_begin();
10201   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10202     const Type *ParamTy = FT->getParamType(i);
10203     const Type *ActTy = (*AI)->getType();
10204
10205     if (!CastInst::isCastable(ActTy, ParamTy))
10206       return false;   // Cannot transform this parameter value.
10207
10208     if (CallerPAL.getParamAttributes(i + 1) 
10209         & Attribute::typeIncompatible(ParamTy))
10210       return false;   // Attribute not compatible with transformed value.
10211
10212     // Converting from one pointer type to another or between a pointer and an
10213     // integer of the same size is safe even if we do not have a body.
10214     bool isConvertible = ActTy == ParamTy ||
10215       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10216        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10217     if (Callee->isDeclaration() && !isConvertible) return false;
10218   }
10219
10220   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10221       Callee->isDeclaration())
10222     return false;   // Do not delete arguments unless we have a function body.
10223
10224   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10225       !CallerPAL.isEmpty())
10226     // In this case we have more arguments than the new function type, but we
10227     // won't be dropping them.  Check that these extra arguments have attributes
10228     // that are compatible with being a vararg call argument.
10229     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10230       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10231         break;
10232       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10233       if (PAttrs & Attribute::VarArgsIncompatible)
10234         return false;
10235     }
10236
10237   // Okay, we decided that this is a safe thing to do: go ahead and start
10238   // inserting cast instructions as necessary...
10239   std::vector<Value*> Args;
10240   Args.reserve(NumActualArgs);
10241   SmallVector<AttributeWithIndex, 8> attrVec;
10242   attrVec.reserve(NumCommonArgs);
10243
10244   // Get any return attributes.
10245   Attributes RAttrs = CallerPAL.getRetAttributes();
10246
10247   // If the return value is not being used, the type may not be compatible
10248   // with the existing attributes.  Wipe out any problematic attributes.
10249   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10250
10251   // Add the new return attributes.
10252   if (RAttrs)
10253     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10254
10255   AI = CS.arg_begin();
10256   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10257     const Type *ParamTy = FT->getParamType(i);
10258     if ((*AI)->getType() == ParamTy) {
10259       Args.push_back(*AI);
10260     } else {
10261       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10262           false, ParamTy, false);
10263       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10264       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10265     }
10266
10267     // Add any parameter attributes.
10268     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10269       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10270   }
10271
10272   // If the function takes more arguments than the call was taking, add them
10273   // now...
10274   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10275     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10276
10277   // If we are removing arguments to the function, emit an obnoxious warning...
10278   if (FT->getNumParams() < NumActualArgs) {
10279     if (!FT->isVarArg()) {
10280       cerr << "WARNING: While resolving call to function '"
10281            << Callee->getName() << "' arguments were dropped!\n";
10282     } else {
10283       // Add all of the arguments in their promoted form to the arg list...
10284       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10285         const Type *PTy = getPromotedType((*AI)->getType());
10286         if (PTy != (*AI)->getType()) {
10287           // Must promote to pass through va_arg area!
10288           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10289                                                                 PTy, false);
10290           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10291           InsertNewInstBefore(Cast, *Caller);
10292           Args.push_back(Cast);
10293         } else {
10294           Args.push_back(*AI);
10295         }
10296
10297         // Add any parameter attributes.
10298         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10299           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10300       }
10301     }
10302   }
10303
10304   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10305     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10306
10307   if (NewRetTy == Type::VoidTy)
10308     Caller->setName("");   // Void type should not have a name.
10309
10310   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10311
10312   Instruction *NC;
10313   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10314     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10315                             Args.begin(), Args.end(),
10316                             Caller->getName(), Caller);
10317     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10318     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10319   } else {
10320     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10321                           Caller->getName(), Caller);
10322     CallInst *CI = cast<CallInst>(Caller);
10323     if (CI->isTailCall())
10324       cast<CallInst>(NC)->setTailCall();
10325     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10326     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10327   }
10328
10329   // Insert a cast of the return type as necessary.
10330   Value *NV = NC;
10331   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10332     if (NV->getType() != Type::VoidTy) {
10333       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10334                                                             OldRetTy, false);
10335       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10336
10337       // If this is an invoke instruction, we should insert it after the first
10338       // non-phi, instruction in the normal successor block.
10339       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10340         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10341         InsertNewInstBefore(NC, *I);
10342       } else {
10343         // Otherwise, it's a call, just insert cast right after the call instr
10344         InsertNewInstBefore(NC, *Caller);
10345       }
10346       AddUsersToWorkList(*Caller);
10347     } else {
10348       NV = Context->getUndef(Caller->getType());
10349     }
10350   }
10351
10352   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10353     Caller->replaceAllUsesWith(NV);
10354   Caller->eraseFromParent();
10355   RemoveFromWorkList(Caller);
10356   return true;
10357 }
10358
10359 // transformCallThroughTrampoline - Turn a call to a function created by the
10360 // init_trampoline intrinsic into a direct call to the underlying function.
10361 //
10362 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10363   Value *Callee = CS.getCalledValue();
10364   const PointerType *PTy = cast<PointerType>(Callee->getType());
10365   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10366   const AttrListPtr &Attrs = CS.getAttributes();
10367
10368   // If the call already has the 'nest' attribute somewhere then give up -
10369   // otherwise 'nest' would occur twice after splicing in the chain.
10370   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10371     return 0;
10372
10373   IntrinsicInst *Tramp =
10374     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10375
10376   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10377   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10378   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10379
10380   const AttrListPtr &NestAttrs = NestF->getAttributes();
10381   if (!NestAttrs.isEmpty()) {
10382     unsigned NestIdx = 1;
10383     const Type *NestTy = 0;
10384     Attributes NestAttr = Attribute::None;
10385
10386     // Look for a parameter marked with the 'nest' attribute.
10387     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10388          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10389       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10390         // Record the parameter type and any other attributes.
10391         NestTy = *I;
10392         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10393         break;
10394       }
10395
10396     if (NestTy) {
10397       Instruction *Caller = CS.getInstruction();
10398       std::vector<Value*> NewArgs;
10399       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10400
10401       SmallVector<AttributeWithIndex, 8> NewAttrs;
10402       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10403
10404       // Insert the nest argument into the call argument list, which may
10405       // mean appending it.  Likewise for attributes.
10406
10407       // Add any result attributes.
10408       if (Attributes Attr = Attrs.getRetAttributes())
10409         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10410
10411       {
10412         unsigned Idx = 1;
10413         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10414         do {
10415           if (Idx == NestIdx) {
10416             // Add the chain argument and attributes.
10417             Value *NestVal = Tramp->getOperand(3);
10418             if (NestVal->getType() != NestTy)
10419               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10420             NewArgs.push_back(NestVal);
10421             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10422           }
10423
10424           if (I == E)
10425             break;
10426
10427           // Add the original argument and attributes.
10428           NewArgs.push_back(*I);
10429           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10430             NewAttrs.push_back
10431               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10432
10433           ++Idx, ++I;
10434         } while (1);
10435       }
10436
10437       // Add any function attributes.
10438       if (Attributes Attr = Attrs.getFnAttributes())
10439         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10440
10441       // The trampoline may have been bitcast to a bogus type (FTy).
10442       // Handle this by synthesizing a new function type, equal to FTy
10443       // with the chain parameter inserted.
10444
10445       std::vector<const Type*> NewTypes;
10446       NewTypes.reserve(FTy->getNumParams()+1);
10447
10448       // Insert the chain's type into the list of parameter types, which may
10449       // mean appending it.
10450       {
10451         unsigned Idx = 1;
10452         FunctionType::param_iterator I = FTy->param_begin(),
10453           E = FTy->param_end();
10454
10455         do {
10456           if (Idx == NestIdx)
10457             // Add the chain's type.
10458             NewTypes.push_back(NestTy);
10459
10460           if (I == E)
10461             break;
10462
10463           // Add the original type.
10464           NewTypes.push_back(*I);
10465
10466           ++Idx, ++I;
10467         } while (1);
10468       }
10469
10470       // Replace the trampoline call with a direct call.  Let the generic
10471       // code sort out any function type mismatches.
10472       FunctionType *NewFTy =
10473                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10474                                                 FTy->isVarArg());
10475       Constant *NewCallee =
10476         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10477         NestF : Context->getConstantExprBitCast(NestF, 
10478                                          Context->getPointerTypeUnqual(NewFTy));
10479       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10480
10481       Instruction *NewCaller;
10482       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10483         NewCaller = InvokeInst::Create(NewCallee,
10484                                        II->getNormalDest(), II->getUnwindDest(),
10485                                        NewArgs.begin(), NewArgs.end(),
10486                                        Caller->getName(), Caller);
10487         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10488         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10489       } else {
10490         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10491                                      Caller->getName(), Caller);
10492         if (cast<CallInst>(Caller)->isTailCall())
10493           cast<CallInst>(NewCaller)->setTailCall();
10494         cast<CallInst>(NewCaller)->
10495           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10496         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10497       }
10498       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10499         Caller->replaceAllUsesWith(NewCaller);
10500       Caller->eraseFromParent();
10501       RemoveFromWorkList(Caller);
10502       return 0;
10503     }
10504   }
10505
10506   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10507   // parameter, there is no need to adjust the argument list.  Let the generic
10508   // code sort out any function type mismatches.
10509   Constant *NewCallee =
10510     NestF->getType() == PTy ? NestF : 
10511                               Context->getConstantExprBitCast(NestF, PTy);
10512   CS.setCalledFunction(NewCallee);
10513   return CS.getInstruction();
10514 }
10515
10516 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10517 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10518 /// and a single binop.
10519 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10520   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10521   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10522   unsigned Opc = FirstInst->getOpcode();
10523   Value *LHSVal = FirstInst->getOperand(0);
10524   Value *RHSVal = FirstInst->getOperand(1);
10525     
10526   const Type *LHSType = LHSVal->getType();
10527   const Type *RHSType = RHSVal->getType();
10528   
10529   // Scan to see if all operands are the same opcode, all have one use, and all
10530   // kill their operands (i.e. the operands have one use).
10531   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10532     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10533     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10534         // Verify type of the LHS matches so we don't fold cmp's of different
10535         // types or GEP's with different index types.
10536         I->getOperand(0)->getType() != LHSType ||
10537         I->getOperand(1)->getType() != RHSType)
10538       return 0;
10539
10540     // If they are CmpInst instructions, check their predicates
10541     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10542       if (cast<CmpInst>(I)->getPredicate() !=
10543           cast<CmpInst>(FirstInst)->getPredicate())
10544         return 0;
10545     
10546     // Keep track of which operand needs a phi node.
10547     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10548     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10549   }
10550   
10551   // Otherwise, this is safe to transform!
10552   
10553   Value *InLHS = FirstInst->getOperand(0);
10554   Value *InRHS = FirstInst->getOperand(1);
10555   PHINode *NewLHS = 0, *NewRHS = 0;
10556   if (LHSVal == 0) {
10557     NewLHS = PHINode::Create(LHSType,
10558                              FirstInst->getOperand(0)->getName() + ".pn");
10559     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10560     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10561     InsertNewInstBefore(NewLHS, PN);
10562     LHSVal = NewLHS;
10563   }
10564   
10565   if (RHSVal == 0) {
10566     NewRHS = PHINode::Create(RHSType,
10567                              FirstInst->getOperand(1)->getName() + ".pn");
10568     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10569     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10570     InsertNewInstBefore(NewRHS, PN);
10571     RHSVal = NewRHS;
10572   }
10573   
10574   // Add all operands to the new PHIs.
10575   if (NewLHS || NewRHS) {
10576     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10577       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10578       if (NewLHS) {
10579         Value *NewInLHS = InInst->getOperand(0);
10580         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10581       }
10582       if (NewRHS) {
10583         Value *NewInRHS = InInst->getOperand(1);
10584         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10585       }
10586     }
10587   }
10588     
10589   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10590     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10591   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10592   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10593                          RHSVal);
10594 }
10595
10596 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10597   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10598   
10599   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10600                                         FirstInst->op_end());
10601   // This is true if all GEP bases are allocas and if all indices into them are
10602   // constants.
10603   bool AllBasePointersAreAllocas = true;
10604   
10605   // Scan to see if all operands are the same opcode, all have one use, and all
10606   // kill their operands (i.e. the operands have one use).
10607   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10608     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10609     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10610       GEP->getNumOperands() != FirstInst->getNumOperands())
10611       return 0;
10612
10613     // Keep track of whether or not all GEPs are of alloca pointers.
10614     if (AllBasePointersAreAllocas &&
10615         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10616          !GEP->hasAllConstantIndices()))
10617       AllBasePointersAreAllocas = false;
10618     
10619     // Compare the operand lists.
10620     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10621       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10622         continue;
10623       
10624       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10625       // if one of the PHIs has a constant for the index.  The index may be
10626       // substantially cheaper to compute for the constants, so making it a
10627       // variable index could pessimize the path.  This also handles the case
10628       // for struct indices, which must always be constant.
10629       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10630           isa<ConstantInt>(GEP->getOperand(op)))
10631         return 0;
10632       
10633       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10634         return 0;
10635       FixedOperands[op] = 0;  // Needs a PHI.
10636     }
10637   }
10638   
10639   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10640   // bother doing this transformation.  At best, this will just save a bit of
10641   // offset calculation, but all the predecessors will have to materialize the
10642   // stack address into a register anyway.  We'd actually rather *clone* the
10643   // load up into the predecessors so that we have a load of a gep of an alloca,
10644   // which can usually all be folded into the load.
10645   if (AllBasePointersAreAllocas)
10646     return 0;
10647   
10648   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10649   // that is variable.
10650   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10651   
10652   bool HasAnyPHIs = false;
10653   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10654     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10655     Value *FirstOp = FirstInst->getOperand(i);
10656     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10657                                      FirstOp->getName()+".pn");
10658     InsertNewInstBefore(NewPN, PN);
10659     
10660     NewPN->reserveOperandSpace(e);
10661     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10662     OperandPhis[i] = NewPN;
10663     FixedOperands[i] = NewPN;
10664     HasAnyPHIs = true;
10665   }
10666
10667   
10668   // Add all operands to the new PHIs.
10669   if (HasAnyPHIs) {
10670     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10671       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10672       BasicBlock *InBB = PN.getIncomingBlock(i);
10673       
10674       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10675         if (PHINode *OpPhi = OperandPhis[op])
10676           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10677     }
10678   }
10679   
10680   Value *Base = FixedOperands[0];
10681   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10682                                    FixedOperands.end());
10683 }
10684
10685
10686 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10687 /// sink the load out of the block that defines it.  This means that it must be
10688 /// obvious the value of the load is not changed from the point of the load to
10689 /// the end of the block it is in.
10690 ///
10691 /// Finally, it is safe, but not profitable, to sink a load targetting a
10692 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10693 /// to a register.
10694 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10695   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10696   
10697   for (++BBI; BBI != E; ++BBI)
10698     if (BBI->mayWriteToMemory())
10699       return false;
10700   
10701   // Check for non-address taken alloca.  If not address-taken already, it isn't
10702   // profitable to do this xform.
10703   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10704     bool isAddressTaken = false;
10705     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10706          UI != E; ++UI) {
10707       if (isa<LoadInst>(UI)) continue;
10708       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10709         // If storing TO the alloca, then the address isn't taken.
10710         if (SI->getOperand(1) == AI) continue;
10711       }
10712       isAddressTaken = true;
10713       break;
10714     }
10715     
10716     if (!isAddressTaken && AI->isStaticAlloca())
10717       return false;
10718   }
10719   
10720   // If this load is a load from a GEP with a constant offset from an alloca,
10721   // then we don't want to sink it.  In its present form, it will be
10722   // load [constant stack offset].  Sinking it will cause us to have to
10723   // materialize the stack addresses in each predecessor in a register only to
10724   // do a shared load from register in the successor.
10725   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10726     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10727       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10728         return false;
10729   
10730   return true;
10731 }
10732
10733
10734 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10735 // operator and they all are only used by the PHI, PHI together their
10736 // inputs, and do the operation once, to the result of the PHI.
10737 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10738   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10739
10740   // Scan the instruction, looking for input operations that can be folded away.
10741   // If all input operands to the phi are the same instruction (e.g. a cast from
10742   // the same type or "+42") we can pull the operation through the PHI, reducing
10743   // code size and simplifying code.
10744   Constant *ConstantOp = 0;
10745   const Type *CastSrcTy = 0;
10746   bool isVolatile = false;
10747   if (isa<CastInst>(FirstInst)) {
10748     CastSrcTy = FirstInst->getOperand(0)->getType();
10749   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10750     // Can fold binop, compare or shift here if the RHS is a constant, 
10751     // otherwise call FoldPHIArgBinOpIntoPHI.
10752     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10753     if (ConstantOp == 0)
10754       return FoldPHIArgBinOpIntoPHI(PN);
10755   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10756     isVolatile = LI->isVolatile();
10757     // We can't sink the load if the loaded value could be modified between the
10758     // load and the PHI.
10759     if (LI->getParent() != PN.getIncomingBlock(0) ||
10760         !isSafeAndProfitableToSinkLoad(LI))
10761       return 0;
10762     
10763     // If the PHI is of volatile loads and the load block has multiple
10764     // successors, sinking it would remove a load of the volatile value from
10765     // the path through the other successor.
10766     if (isVolatile &&
10767         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10768       return 0;
10769     
10770   } else if (isa<GetElementPtrInst>(FirstInst)) {
10771     return FoldPHIArgGEPIntoPHI(PN);
10772   } else {
10773     return 0;  // Cannot fold this operation.
10774   }
10775
10776   // Check to see if all arguments are the same operation.
10777   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10778     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10779     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10780     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10781       return 0;
10782     if (CastSrcTy) {
10783       if (I->getOperand(0)->getType() != CastSrcTy)
10784         return 0;  // Cast operation must match.
10785     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10786       // We can't sink the load if the loaded value could be modified between 
10787       // the load and the PHI.
10788       if (LI->isVolatile() != isVolatile ||
10789           LI->getParent() != PN.getIncomingBlock(i) ||
10790           !isSafeAndProfitableToSinkLoad(LI))
10791         return 0;
10792       
10793       // If the PHI is of volatile loads and the load block has multiple
10794       // successors, sinking it would remove a load of the volatile value from
10795       // the path through the other successor.
10796       if (isVolatile &&
10797           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10798         return 0;
10799       
10800     } else if (I->getOperand(1) != ConstantOp) {
10801       return 0;
10802     }
10803   }
10804
10805   // Okay, they are all the same operation.  Create a new PHI node of the
10806   // correct type, and PHI together all of the LHS's of the instructions.
10807   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10808                                    PN.getName()+".in");
10809   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10810
10811   Value *InVal = FirstInst->getOperand(0);
10812   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10813
10814   // Add all operands to the new PHI.
10815   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10816     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10817     if (NewInVal != InVal)
10818       InVal = 0;
10819     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10820   }
10821
10822   Value *PhiVal;
10823   if (InVal) {
10824     // The new PHI unions all of the same values together.  This is really
10825     // common, so we handle it intelligently here for compile-time speed.
10826     PhiVal = InVal;
10827     delete NewPN;
10828   } else {
10829     InsertNewInstBefore(NewPN, PN);
10830     PhiVal = NewPN;
10831   }
10832
10833   // Insert and return the new operation.
10834   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10835     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10836   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10837     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10838   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10839     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10840                            PhiVal, ConstantOp);
10841   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10842   
10843   // If this was a volatile load that we are merging, make sure to loop through
10844   // and mark all the input loads as non-volatile.  If we don't do this, we will
10845   // insert a new volatile load and the old ones will not be deletable.
10846   if (isVolatile)
10847     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10848       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10849   
10850   return new LoadInst(PhiVal, "", isVolatile);
10851 }
10852
10853 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10854 /// that is dead.
10855 static bool DeadPHICycle(PHINode *PN,
10856                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10857   if (PN->use_empty()) return true;
10858   if (!PN->hasOneUse()) return false;
10859
10860   // Remember this node, and if we find the cycle, return.
10861   if (!PotentiallyDeadPHIs.insert(PN))
10862     return true;
10863   
10864   // Don't scan crazily complex things.
10865   if (PotentiallyDeadPHIs.size() == 16)
10866     return false;
10867
10868   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10869     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10870
10871   return false;
10872 }
10873
10874 /// PHIsEqualValue - Return true if this phi node is always equal to
10875 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10876 ///   z = some value; x = phi (y, z); y = phi (x, z)
10877 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10878                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10879   // See if we already saw this PHI node.
10880   if (!ValueEqualPHIs.insert(PN))
10881     return true;
10882   
10883   // Don't scan crazily complex things.
10884   if (ValueEqualPHIs.size() == 16)
10885     return false;
10886  
10887   // Scan the operands to see if they are either phi nodes or are equal to
10888   // the value.
10889   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10890     Value *Op = PN->getIncomingValue(i);
10891     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10892       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10893         return false;
10894     } else if (Op != NonPhiInVal)
10895       return false;
10896   }
10897   
10898   return true;
10899 }
10900
10901
10902 // PHINode simplification
10903 //
10904 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10905   // If LCSSA is around, don't mess with Phi nodes
10906   if (MustPreserveLCSSA) return 0;
10907   
10908   if (Value *V = PN.hasConstantValue())
10909     return ReplaceInstUsesWith(PN, V);
10910
10911   // If all PHI operands are the same operation, pull them through the PHI,
10912   // reducing code size.
10913   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10914       isa<Instruction>(PN.getIncomingValue(1)) &&
10915       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10916       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10917       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10918       // than themselves more than once.
10919       PN.getIncomingValue(0)->hasOneUse())
10920     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10921       return Result;
10922
10923   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10924   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10925   // PHI)... break the cycle.
10926   if (PN.hasOneUse()) {
10927     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10928     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10929       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10930       PotentiallyDeadPHIs.insert(&PN);
10931       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10932         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10933     }
10934    
10935     // If this phi has a single use, and if that use just computes a value for
10936     // the next iteration of a loop, delete the phi.  This occurs with unused
10937     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10938     // common case here is good because the only other things that catch this
10939     // are induction variable analysis (sometimes) and ADCE, which is only run
10940     // late.
10941     if (PHIUser->hasOneUse() &&
10942         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10943         PHIUser->use_back() == &PN) {
10944       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10945     }
10946   }
10947
10948   // We sometimes end up with phi cycles that non-obviously end up being the
10949   // same value, for example:
10950   //   z = some value; x = phi (y, z); y = phi (x, z)
10951   // where the phi nodes don't necessarily need to be in the same block.  Do a
10952   // quick check to see if the PHI node only contains a single non-phi value, if
10953   // so, scan to see if the phi cycle is actually equal to that value.
10954   {
10955     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10956     // Scan for the first non-phi operand.
10957     while (InValNo != NumOperandVals && 
10958            isa<PHINode>(PN.getIncomingValue(InValNo)))
10959       ++InValNo;
10960
10961     if (InValNo != NumOperandVals) {
10962       Value *NonPhiInVal = PN.getOperand(InValNo);
10963       
10964       // Scan the rest of the operands to see if there are any conflicts, if so
10965       // there is no need to recursively scan other phis.
10966       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10967         Value *OpVal = PN.getIncomingValue(InValNo);
10968         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10969           break;
10970       }
10971       
10972       // If we scanned over all operands, then we have one unique value plus
10973       // phi values.  Scan PHI nodes to see if they all merge in each other or
10974       // the value.
10975       if (InValNo == NumOperandVals) {
10976         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10977         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10978           return ReplaceInstUsesWith(PN, NonPhiInVal);
10979       }
10980     }
10981   }
10982   return 0;
10983 }
10984
10985 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10986                                    Instruction *InsertPoint,
10987                                    InstCombiner *IC) {
10988   unsigned PtrSize = DTy->getScalarSizeInBits();
10989   unsigned VTySize = V->getType()->getScalarSizeInBits();
10990   // We must cast correctly to the pointer type. Ensure that we
10991   // sign extend the integer value if it is smaller as this is
10992   // used for address computation.
10993   Instruction::CastOps opcode = 
10994      (VTySize < PtrSize ? Instruction::SExt :
10995       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10996   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10997 }
10998
10999
11000 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11001   Value *PtrOp = GEP.getOperand(0);
11002   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11003   // If so, eliminate the noop.
11004   if (GEP.getNumOperands() == 1)
11005     return ReplaceInstUsesWith(GEP, PtrOp);
11006
11007   if (isa<UndefValue>(GEP.getOperand(0)))
11008     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11009
11010   bool HasZeroPointerIndex = false;
11011   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11012     HasZeroPointerIndex = C->isNullValue();
11013
11014   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11015     return ReplaceInstUsesWith(GEP, PtrOp);
11016
11017   // Eliminate unneeded casts for indices.
11018   bool MadeChange = false;
11019   
11020   gep_type_iterator GTI = gep_type_begin(GEP);
11021   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11022        i != e; ++i, ++GTI) {
11023     if (isa<SequentialType>(*GTI)) {
11024       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11025         if (CI->getOpcode() == Instruction::ZExt ||
11026             CI->getOpcode() == Instruction::SExt) {
11027           const Type *SrcTy = CI->getOperand(0)->getType();
11028           // We can eliminate a cast from i32 to i64 iff the target 
11029           // is a 32-bit pointer target.
11030           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11031             MadeChange = true;
11032             *i = CI->getOperand(0);
11033           }
11034         }
11035       }
11036       // If we are using a wider index than needed for this platform, shrink it
11037       // to what we need.  If narrower, sign-extend it to what we need.
11038       // If the incoming value needs a cast instruction,
11039       // insert it.  This explicit cast can make subsequent optimizations more
11040       // obvious.
11041       Value *Op = *i;
11042       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11043         if (Constant *C = dyn_cast<Constant>(Op)) {
11044           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11045           MadeChange = true;
11046         } else {
11047           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11048                                 GEP);
11049           *i = Op;
11050           MadeChange = true;
11051         }
11052       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11053         if (Constant *C = dyn_cast<Constant>(Op)) {
11054           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11055           MadeChange = true;
11056         } else {
11057           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11058                                 GEP);
11059           *i = Op;
11060           MadeChange = true;
11061         }
11062       }
11063     }
11064   }
11065   if (MadeChange) return &GEP;
11066
11067   // Combine Indices - If the source pointer to this getelementptr instruction
11068   // is a getelementptr instruction, combine the indices of the two
11069   // getelementptr instructions into a single instruction.
11070   //
11071   SmallVector<Value*, 8> SrcGEPOperands;
11072   if (User *Src = dyn_castGetElementPtr(PtrOp))
11073     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11074
11075   if (!SrcGEPOperands.empty()) {
11076     // Note that if our source is a gep chain itself that we wait for that
11077     // chain to be resolved before we perform this transformation.  This
11078     // avoids us creating a TON of code in some cases.
11079     //
11080     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11081         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11082       return 0;   // Wait until our source is folded to completion.
11083
11084     SmallVector<Value*, 8> Indices;
11085
11086     // Find out whether the last index in the source GEP is a sequential idx.
11087     bool EndsWithSequential = false;
11088     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11089            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11090       EndsWithSequential = !isa<StructType>(*I);
11091
11092     // Can we combine the two pointer arithmetics offsets?
11093     if (EndsWithSequential) {
11094       // Replace: gep (gep %P, long B), long A, ...
11095       // With:    T = long A+B; gep %P, T, ...
11096       //
11097       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11098       if (SO1 == Context->getNullValue(SO1->getType())) {
11099         Sum = GO1;
11100       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11101         Sum = SO1;
11102       } else {
11103         // If they aren't the same type, convert both to an integer of the
11104         // target's pointer size.
11105         if (SO1->getType() != GO1->getType()) {
11106           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11107             SO1 =
11108                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11109           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11110             GO1 =
11111                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11112           } else {
11113             unsigned PS = TD->getPointerSizeInBits();
11114             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11115               // Convert GO1 to SO1's type.
11116               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11117
11118             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11119               // Convert SO1 to GO1's type.
11120               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11121             } else {
11122               const Type *PT = TD->getIntPtrType();
11123               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11124               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11125             }
11126           }
11127         }
11128         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11129           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11130                                             cast<Constant>(GO1));
11131         else {
11132           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11133           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11134         }
11135       }
11136
11137       // Recycle the GEP we already have if possible.
11138       if (SrcGEPOperands.size() == 2) {
11139         GEP.setOperand(0, SrcGEPOperands[0]);
11140         GEP.setOperand(1, Sum);
11141         return &GEP;
11142       } else {
11143         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11144                        SrcGEPOperands.end()-1);
11145         Indices.push_back(Sum);
11146         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11147       }
11148     } else if (isa<Constant>(*GEP.idx_begin()) &&
11149                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11150                SrcGEPOperands.size() != 1) {
11151       // Otherwise we can do the fold if the first index of the GEP is a zero
11152       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11153                      SrcGEPOperands.end());
11154       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11155     }
11156
11157     if (!Indices.empty())
11158       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11159                                        Indices.end(), GEP.getName());
11160
11161   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11162     // GEP of global variable.  If all of the indices for this GEP are
11163     // constants, we can promote this to a constexpr instead of an instruction.
11164
11165     // Scan for nonconstants...
11166     SmallVector<Constant*, 8> Indices;
11167     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11168     for (; I != E && isa<Constant>(*I); ++I)
11169       Indices.push_back(cast<Constant>(*I));
11170
11171     if (I == E) {  // If they are all constants...
11172       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11173                                                     &Indices[0],Indices.size());
11174
11175       // Replace all uses of the GEP with the new constexpr...
11176       return ReplaceInstUsesWith(GEP, CE);
11177     }
11178   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11179     if (!isa<PointerType>(X->getType())) {
11180       // Not interesting.  Source pointer must be a cast from pointer.
11181     } else if (HasZeroPointerIndex) {
11182       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11183       // into     : GEP [10 x i8]* X, i32 0, ...
11184       //
11185       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11186       //           into     : GEP i8* X, ...
11187       // 
11188       // This occurs when the program declares an array extern like "int X[];"
11189       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11190       const PointerType *XTy = cast<PointerType>(X->getType());
11191       if (const ArrayType *CATy =
11192           dyn_cast<ArrayType>(CPTy->getElementType())) {
11193         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11194         if (CATy->getElementType() == XTy->getElementType()) {
11195           // -> GEP i8* X, ...
11196           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11197           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11198                                            GEP.getName());
11199         } else if (const ArrayType *XATy =
11200                  dyn_cast<ArrayType>(XTy->getElementType())) {
11201           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11202           if (CATy->getElementType() == XATy->getElementType()) {
11203             // -> GEP [10 x i8]* X, i32 0, ...
11204             // At this point, we know that the cast source type is a pointer
11205             // to an array of the same type as the destination pointer
11206             // array.  Because the array type is never stepped over (there
11207             // is a leading zero) we can fold the cast into this GEP.
11208             GEP.setOperand(0, X);
11209             return &GEP;
11210           }
11211         }
11212       }
11213     } else if (GEP.getNumOperands() == 2) {
11214       // Transform things like:
11215       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11216       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11217       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11218       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11219       if (isa<ArrayType>(SrcElTy) &&
11220           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11221           TD->getTypeAllocSize(ResElTy)) {
11222         Value *Idx[2];
11223         Idx[0] = Context->getNullValue(Type::Int32Ty);
11224         Idx[1] = GEP.getOperand(1);
11225         Value *V = InsertNewInstBefore(
11226                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11227         // V and GEP are both pointer types --> BitCast
11228         return new BitCastInst(V, GEP.getType());
11229       }
11230       
11231       // Transform things like:
11232       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11233       //   (where tmp = 8*tmp2) into:
11234       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11235       
11236       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11237         uint64_t ArrayEltSize =
11238             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11239         
11240         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11241         // allow either a mul, shift, or constant here.
11242         Value *NewIdx = 0;
11243         ConstantInt *Scale = 0;
11244         if (ArrayEltSize == 1) {
11245           NewIdx = GEP.getOperand(1);
11246           Scale = 
11247                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11248         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11249           NewIdx = Context->getConstantInt(CI->getType(), 1);
11250           Scale = CI;
11251         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11252           if (Inst->getOpcode() == Instruction::Shl &&
11253               isa<ConstantInt>(Inst->getOperand(1))) {
11254             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11255             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11256             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11257                                      1ULL << ShAmtVal);
11258             NewIdx = Inst->getOperand(0);
11259           } else if (Inst->getOpcode() == Instruction::Mul &&
11260                      isa<ConstantInt>(Inst->getOperand(1))) {
11261             Scale = cast<ConstantInt>(Inst->getOperand(1));
11262             NewIdx = Inst->getOperand(0);
11263           }
11264         }
11265         
11266         // If the index will be to exactly the right offset with the scale taken
11267         // out, perform the transformation. Note, we don't know whether Scale is
11268         // signed or not. We'll use unsigned version of division/modulo
11269         // operation after making sure Scale doesn't have the sign bit set.
11270         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11271             Scale->getZExtValue() % ArrayEltSize == 0) {
11272           Scale = Context->getConstantInt(Scale->getType(),
11273                                    Scale->getZExtValue() / ArrayEltSize);
11274           if (Scale->getZExtValue() != 1) {
11275             Constant *C =
11276                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11277                                                        false /*ZExt*/);
11278             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11279             NewIdx = InsertNewInstBefore(Sc, GEP);
11280           }
11281
11282           // Insert the new GEP instruction.
11283           Value *Idx[2];
11284           Idx[0] = Context->getNullValue(Type::Int32Ty);
11285           Idx[1] = NewIdx;
11286           Instruction *NewGEP =
11287             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11288           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11289           // The NewGEP must be pointer typed, so must the old one -> BitCast
11290           return new BitCastInst(NewGEP, GEP.getType());
11291         }
11292       }
11293     }
11294   }
11295   
11296   /// See if we can simplify:
11297   ///   X = bitcast A to B*
11298   ///   Y = gep X, <...constant indices...>
11299   /// into a gep of the original struct.  This is important for SROA and alias
11300   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11301   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11302     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11303       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11304       // a constant back from EmitGEPOffset.
11305       ConstantInt *OffsetV =
11306                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11307       int64_t Offset = OffsetV->getSExtValue();
11308       
11309       // If this GEP instruction doesn't move the pointer, just replace the GEP
11310       // with a bitcast of the real input to the dest type.
11311       if (Offset == 0) {
11312         // If the bitcast is of an allocation, and the allocation will be
11313         // converted to match the type of the cast, don't touch this.
11314         if (isa<AllocationInst>(BCI->getOperand(0))) {
11315           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11316           if (Instruction *I = visitBitCast(*BCI)) {
11317             if (I != BCI) {
11318               I->takeName(BCI);
11319               BCI->getParent()->getInstList().insert(BCI, I);
11320               ReplaceInstUsesWith(*BCI, I);
11321             }
11322             return &GEP;
11323           }
11324         }
11325         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11326       }
11327       
11328       // Otherwise, if the offset is non-zero, we need to find out if there is a
11329       // field at Offset in 'A's type.  If so, we can pull the cast through the
11330       // GEP.
11331       SmallVector<Value*, 8> NewIndices;
11332       const Type *InTy =
11333         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11334       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11335         Instruction *NGEP =
11336            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11337                                      NewIndices.end());
11338         if (NGEP->getType() == GEP.getType()) return NGEP;
11339         InsertNewInstBefore(NGEP, GEP);
11340         NGEP->takeName(&GEP);
11341         return new BitCastInst(NGEP, GEP.getType());
11342       }
11343     }
11344   }    
11345     
11346   return 0;
11347 }
11348
11349 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11350   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11351   if (AI.isArrayAllocation()) {  // Check C != 1
11352     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11353       const Type *NewTy = 
11354         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11355       AllocationInst *New = 0;
11356
11357       // Create and insert the replacement instruction...
11358       if (isa<MallocInst>(AI))
11359         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11360       else {
11361         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11362         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11363       }
11364
11365       InsertNewInstBefore(New, AI);
11366
11367       // Scan to the end of the allocation instructions, to skip over a block of
11368       // allocas if possible...also skip interleaved debug info
11369       //
11370       BasicBlock::iterator It = New;
11371       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11372
11373       // Now that I is pointing to the first non-allocation-inst in the block,
11374       // insert our getelementptr instruction...
11375       //
11376       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11377       Value *Idx[2];
11378       Idx[0] = NullIdx;
11379       Idx[1] = NullIdx;
11380       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11381                                            New->getName()+".sub", It);
11382
11383       // Now make everything use the getelementptr instead of the original
11384       // allocation.
11385       return ReplaceInstUsesWith(AI, V);
11386     } else if (isa<UndefValue>(AI.getArraySize())) {
11387       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11388     }
11389   }
11390
11391   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11392     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11393     // Note that we only do this for alloca's, because malloc should allocate
11394     // and return a unique pointer, even for a zero byte allocation.
11395     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11396       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11397
11398     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11399     if (AI.getAlignment() == 0)
11400       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11401   }
11402
11403   return 0;
11404 }
11405
11406 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11407   Value *Op = FI.getOperand(0);
11408
11409   // free undef -> unreachable.
11410   if (isa<UndefValue>(Op)) {
11411     // Insert a new store to null because we cannot modify the CFG here.
11412     new StoreInst(Context->getConstantIntTrue(),
11413            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11414     return EraseInstFromFunction(FI);
11415   }
11416   
11417   // If we have 'free null' delete the instruction.  This can happen in stl code
11418   // when lots of inlining happens.
11419   if (isa<ConstantPointerNull>(Op))
11420     return EraseInstFromFunction(FI);
11421   
11422   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11423   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11424     FI.setOperand(0, CI->getOperand(0));
11425     return &FI;
11426   }
11427   
11428   // Change free (gep X, 0,0,0,0) into free(X)
11429   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11430     if (GEPI->hasAllZeroIndices()) {
11431       AddToWorkList(GEPI);
11432       FI.setOperand(0, GEPI->getOperand(0));
11433       return &FI;
11434     }
11435   }
11436   
11437   // Change free(malloc) into nothing, if the malloc has a single use.
11438   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11439     if (MI->hasOneUse()) {
11440       EraseInstFromFunction(FI);
11441       return EraseInstFromFunction(*MI);
11442     }
11443
11444   return 0;
11445 }
11446
11447
11448 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11449 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11450                                         const TargetData *TD) {
11451   User *CI = cast<User>(LI.getOperand(0));
11452   Value *CastOp = CI->getOperand(0);
11453   LLVMContext *Context = IC.getContext();
11454
11455   if (TD) {
11456     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11457       // Instead of loading constant c string, use corresponding integer value
11458       // directly if string length is small enough.
11459       std::string Str;
11460       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11461         unsigned len = Str.length();
11462         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11463         unsigned numBits = Ty->getPrimitiveSizeInBits();
11464         // Replace LI with immediate integer store.
11465         if ((numBits >> 3) == len + 1) {
11466           APInt StrVal(numBits, 0);
11467           APInt SingleChar(numBits, 0);
11468           if (TD->isLittleEndian()) {
11469             for (signed i = len-1; i >= 0; i--) {
11470               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11471               StrVal = (StrVal << 8) | SingleChar;
11472             }
11473           } else {
11474             for (unsigned i = 0; i < len; i++) {
11475               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11476               StrVal = (StrVal << 8) | SingleChar;
11477             }
11478             // Append NULL at the end.
11479             SingleChar = 0;
11480             StrVal = (StrVal << 8) | SingleChar;
11481           }
11482           Value *NL = Context->getConstantInt(StrVal);
11483           return IC.ReplaceInstUsesWith(LI, NL);
11484         }
11485       }
11486     }
11487   }
11488
11489   const PointerType *DestTy = cast<PointerType>(CI->getType());
11490   const Type *DestPTy = DestTy->getElementType();
11491   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11492
11493     // If the address spaces don't match, don't eliminate the cast.
11494     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11495       return 0;
11496
11497     const Type *SrcPTy = SrcTy->getElementType();
11498
11499     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11500          isa<VectorType>(DestPTy)) {
11501       // If the source is an array, the code below will not succeed.  Check to
11502       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11503       // constants.
11504       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11505         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11506           if (ASrcTy->getNumElements() != 0) {
11507             Value *Idxs[2];
11508             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11509             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11510             SrcTy = cast<PointerType>(CastOp->getType());
11511             SrcPTy = SrcTy->getElementType();
11512           }
11513
11514       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11515             isa<VectorType>(SrcPTy)) &&
11516           // Do not allow turning this into a load of an integer, which is then
11517           // casted to a pointer, this pessimizes pointer analysis a lot.
11518           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11519           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11520                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11521
11522         // Okay, we are casting from one integer or pointer type to another of
11523         // the same size.  Instead of casting the pointer before the load, cast
11524         // the result of the loaded value.
11525         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11526                                                              CI->getName(),
11527                                                          LI.isVolatile()),LI);
11528         // Now cast the result of the load.
11529         return new BitCastInst(NewLoad, LI.getType());
11530       }
11531     }
11532   }
11533   return 0;
11534 }
11535
11536 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11537   Value *Op = LI.getOperand(0);
11538
11539   // Attempt to improve the alignment.
11540   unsigned KnownAlign =
11541     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11542   if (KnownAlign >
11543       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11544                                 LI.getAlignment()))
11545     LI.setAlignment(KnownAlign);
11546
11547   // load (cast X) --> cast (load X) iff safe
11548   if (isa<CastInst>(Op))
11549     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11550       return Res;
11551
11552   // None of the following transforms are legal for volatile loads.
11553   if (LI.isVolatile()) return 0;
11554   
11555   // Do really simple store-to-load forwarding and load CSE, to catch cases
11556   // where there are several consequtive memory accesses to the same location,
11557   // separated by a few arithmetic operations.
11558   BasicBlock::iterator BBI = &LI;
11559   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11560     return ReplaceInstUsesWith(LI, AvailableVal);
11561
11562   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11563     const Value *GEPI0 = GEPI->getOperand(0);
11564     // TODO: Consider a target hook for valid address spaces for this xform.
11565     if (isa<ConstantPointerNull>(GEPI0) &&
11566         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11567       // Insert a new store to null instruction before the load to indicate
11568       // that this code is not reachable.  We do this instead of inserting
11569       // an unreachable instruction directly because we cannot modify the
11570       // CFG.
11571       new StoreInst(Context->getUndef(LI.getType()),
11572                     Context->getNullValue(Op->getType()), &LI);
11573       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11574     }
11575   } 
11576
11577   if (Constant *C = dyn_cast<Constant>(Op)) {
11578     // load null/undef -> undef
11579     // TODO: Consider a target hook for valid address spaces for this xform.
11580     if (isa<UndefValue>(C) || (C->isNullValue() && 
11581         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11582       // Insert a new store to null instruction before the load to indicate that
11583       // this code is not reachable.  We do this instead of inserting an
11584       // unreachable instruction directly because we cannot modify the CFG.
11585       new StoreInst(Context->getUndef(LI.getType()),
11586                     Context->getNullValue(Op->getType()), &LI);
11587       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11588     }
11589
11590     // Instcombine load (constant global) into the value loaded.
11591     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11592       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11593         return ReplaceInstUsesWith(LI, GV->getInitializer());
11594
11595     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11596     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11597       if (CE->getOpcode() == Instruction::GetElementPtr) {
11598         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11599           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11600             if (Constant *V = 
11601                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11602                                                       Context))
11603               return ReplaceInstUsesWith(LI, V);
11604         if (CE->getOperand(0)->isNullValue()) {
11605           // Insert a new store to null instruction before the load to indicate
11606           // that this code is not reachable.  We do this instead of inserting
11607           // an unreachable instruction directly because we cannot modify the
11608           // CFG.
11609           new StoreInst(Context->getUndef(LI.getType()),
11610                         Context->getNullValue(Op->getType()), &LI);
11611           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11612         }
11613
11614       } else if (CE->isCast()) {
11615         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11616           return Res;
11617       }
11618     }
11619   }
11620     
11621   // If this load comes from anywhere in a constant global, and if the global
11622   // is all undef or zero, we know what it loads.
11623   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11624     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11625       if (GV->getInitializer()->isNullValue())
11626         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11627       else if (isa<UndefValue>(GV->getInitializer()))
11628         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11629     }
11630   }
11631
11632   if (Op->hasOneUse()) {
11633     // Change select and PHI nodes to select values instead of addresses: this
11634     // helps alias analysis out a lot, allows many others simplifications, and
11635     // exposes redundancy in the code.
11636     //
11637     // Note that we cannot do the transformation unless we know that the
11638     // introduced loads cannot trap!  Something like this is valid as long as
11639     // the condition is always false: load (select bool %C, int* null, int* %G),
11640     // but it would not be valid if we transformed it to load from null
11641     // unconditionally.
11642     //
11643     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11644       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11645       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11646           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11647         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11648                                      SI->getOperand(1)->getName()+".val"), LI);
11649         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11650                                      SI->getOperand(2)->getName()+".val"), LI);
11651         return SelectInst::Create(SI->getCondition(), V1, V2);
11652       }
11653
11654       // load (select (cond, null, P)) -> load P
11655       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11656         if (C->isNullValue()) {
11657           LI.setOperand(0, SI->getOperand(2));
11658           return &LI;
11659         }
11660
11661       // load (select (cond, P, null)) -> load P
11662       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11663         if (C->isNullValue()) {
11664           LI.setOperand(0, SI->getOperand(1));
11665           return &LI;
11666         }
11667     }
11668   }
11669   return 0;
11670 }
11671
11672 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11673 /// when possible.  This makes it generally easy to do alias analysis and/or
11674 /// SROA/mem2reg of the memory object.
11675 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11676   User *CI = cast<User>(SI.getOperand(1));
11677   Value *CastOp = CI->getOperand(0);
11678   LLVMContext *Context = IC.getContext();
11679
11680   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11681   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11682   if (SrcTy == 0) return 0;
11683   
11684   const Type *SrcPTy = SrcTy->getElementType();
11685
11686   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11687     return 0;
11688   
11689   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11690   /// to its first element.  This allows us to handle things like:
11691   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11692   /// on 32-bit hosts.
11693   SmallVector<Value*, 4> NewGEPIndices;
11694   
11695   // If the source is an array, the code below will not succeed.  Check to
11696   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11697   // constants.
11698   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11699     // Index through pointer.
11700     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11701     NewGEPIndices.push_back(Zero);
11702     
11703     while (1) {
11704       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11705         if (!STy->getNumElements()) /* Struct can be empty {} */
11706           break;
11707         NewGEPIndices.push_back(Zero);
11708         SrcPTy = STy->getElementType(0);
11709       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11710         NewGEPIndices.push_back(Zero);
11711         SrcPTy = ATy->getElementType();
11712       } else {
11713         break;
11714       }
11715     }
11716     
11717     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11718   }
11719
11720   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11721     return 0;
11722   
11723   // If the pointers point into different address spaces or if they point to
11724   // values with different sizes, we can't do the transformation.
11725   if (SrcTy->getAddressSpace() != 
11726         cast<PointerType>(CI->getType())->getAddressSpace() ||
11727       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11728       IC.getTargetData().getTypeSizeInBits(DestPTy))
11729     return 0;
11730
11731   // Okay, we are casting from one integer or pointer type to another of
11732   // the same size.  Instead of casting the pointer before 
11733   // the store, cast the value to be stored.
11734   Value *NewCast;
11735   Value *SIOp0 = SI.getOperand(0);
11736   Instruction::CastOps opcode = Instruction::BitCast;
11737   const Type* CastSrcTy = SIOp0->getType();
11738   const Type* CastDstTy = SrcPTy;
11739   if (isa<PointerType>(CastDstTy)) {
11740     if (CastSrcTy->isInteger())
11741       opcode = Instruction::IntToPtr;
11742   } else if (isa<IntegerType>(CastDstTy)) {
11743     if (isa<PointerType>(SIOp0->getType()))
11744       opcode = Instruction::PtrToInt;
11745   }
11746   
11747   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11748   // emit a GEP to index into its first field.
11749   if (!NewGEPIndices.empty()) {
11750     if (Constant *C = dyn_cast<Constant>(CastOp))
11751       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11752                                               NewGEPIndices.size());
11753     else
11754       CastOp = IC.InsertNewInstBefore(
11755               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11756                                         NewGEPIndices.end()), SI);
11757   }
11758   
11759   if (Constant *C = dyn_cast<Constant>(SIOp0))
11760     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11761   else
11762     NewCast = IC.InsertNewInstBefore(
11763       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11764       SI);
11765   return new StoreInst(NewCast, CastOp);
11766 }
11767
11768 /// equivalentAddressValues - Test if A and B will obviously have the same
11769 /// value. This includes recognizing that %t0 and %t1 will have the same
11770 /// value in code like this:
11771 ///   %t0 = getelementptr \@a, 0, 3
11772 ///   store i32 0, i32* %t0
11773 ///   %t1 = getelementptr \@a, 0, 3
11774 ///   %t2 = load i32* %t1
11775 ///
11776 static bool equivalentAddressValues(Value *A, Value *B) {
11777   // Test if the values are trivially equivalent.
11778   if (A == B) return true;
11779   
11780   // Test if the values come form identical arithmetic instructions.
11781   if (isa<BinaryOperator>(A) ||
11782       isa<CastInst>(A) ||
11783       isa<PHINode>(A) ||
11784       isa<GetElementPtrInst>(A))
11785     if (Instruction *BI = dyn_cast<Instruction>(B))
11786       if (cast<Instruction>(A)->isIdenticalTo(BI))
11787         return true;
11788   
11789   // Otherwise they may not be equivalent.
11790   return false;
11791 }
11792
11793 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11794 // return the llvm.dbg.declare.
11795 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11796   if (!V->hasNUses(2))
11797     return 0;
11798   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11799        UI != E; ++UI) {
11800     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11801       return DI;
11802     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11803       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11804         return DI;
11805       }
11806   }
11807   return 0;
11808 }
11809
11810 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11811   Value *Val = SI.getOperand(0);
11812   Value *Ptr = SI.getOperand(1);
11813
11814   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11815     EraseInstFromFunction(SI);
11816     ++NumCombined;
11817     return 0;
11818   }
11819   
11820   // If the RHS is an alloca with a single use, zapify the store, making the
11821   // alloca dead.
11822   // If the RHS is an alloca with a two uses, the other one being a 
11823   // llvm.dbg.declare, zapify the store and the declare, making the
11824   // alloca dead.  We must do this to prevent declare's from affecting
11825   // codegen.
11826   if (!SI.isVolatile()) {
11827     if (Ptr->hasOneUse()) {
11828       if (isa<AllocaInst>(Ptr)) {
11829         EraseInstFromFunction(SI);
11830         ++NumCombined;
11831         return 0;
11832       }
11833       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11834         if (isa<AllocaInst>(GEP->getOperand(0))) {
11835           if (GEP->getOperand(0)->hasOneUse()) {
11836             EraseInstFromFunction(SI);
11837             ++NumCombined;
11838             return 0;
11839           }
11840           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11841             EraseInstFromFunction(*DI);
11842             EraseInstFromFunction(SI);
11843             ++NumCombined;
11844             return 0;
11845           }
11846         }
11847       }
11848     }
11849     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11850       EraseInstFromFunction(*DI);
11851       EraseInstFromFunction(SI);
11852       ++NumCombined;
11853       return 0;
11854     }
11855   }
11856
11857   // Attempt to improve the alignment.
11858   unsigned KnownAlign =
11859     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11860   if (KnownAlign >
11861       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11862                                 SI.getAlignment()))
11863     SI.setAlignment(KnownAlign);
11864
11865   // Do really simple DSE, to catch cases where there are several consecutive
11866   // stores to the same location, separated by a few arithmetic operations. This
11867   // situation often occurs with bitfield accesses.
11868   BasicBlock::iterator BBI = &SI;
11869   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11870        --ScanInsts) {
11871     --BBI;
11872     // Don't count debug info directives, lest they affect codegen,
11873     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11874     // It is necessary for correctness to skip those that feed into a
11875     // llvm.dbg.declare, as these are not present when debugging is off.
11876     if (isa<DbgInfoIntrinsic>(BBI) ||
11877         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11878       ScanInsts++;
11879       continue;
11880     }    
11881     
11882     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11883       // Prev store isn't volatile, and stores to the same location?
11884       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11885                                                           SI.getOperand(1))) {
11886         ++NumDeadStore;
11887         ++BBI;
11888         EraseInstFromFunction(*PrevSI);
11889         continue;
11890       }
11891       break;
11892     }
11893     
11894     // If this is a load, we have to stop.  However, if the loaded value is from
11895     // the pointer we're loading and is producing the pointer we're storing,
11896     // then *this* store is dead (X = load P; store X -> P).
11897     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11898       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11899           !SI.isVolatile()) {
11900         EraseInstFromFunction(SI);
11901         ++NumCombined;
11902         return 0;
11903       }
11904       // Otherwise, this is a load from some other location.  Stores before it
11905       // may not be dead.
11906       break;
11907     }
11908     
11909     // Don't skip over loads or things that can modify memory.
11910     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11911       break;
11912   }
11913   
11914   
11915   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11916
11917   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11918   if (isa<ConstantPointerNull>(Ptr) &&
11919       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11920     if (!isa<UndefValue>(Val)) {
11921       SI.setOperand(0, Context->getUndef(Val->getType()));
11922       if (Instruction *U = dyn_cast<Instruction>(Val))
11923         AddToWorkList(U);  // Dropped a use.
11924       ++NumCombined;
11925     }
11926     return 0;  // Do not modify these!
11927   }
11928
11929   // store undef, Ptr -> noop
11930   if (isa<UndefValue>(Val)) {
11931     EraseInstFromFunction(SI);
11932     ++NumCombined;
11933     return 0;
11934   }
11935
11936   // If the pointer destination is a cast, see if we can fold the cast into the
11937   // source instead.
11938   if (isa<CastInst>(Ptr))
11939     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11940       return Res;
11941   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11942     if (CE->isCast())
11943       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11944         return Res;
11945
11946   
11947   // If this store is the last instruction in the basic block (possibly
11948   // excepting debug info instructions and the pointer bitcasts that feed
11949   // into them), and if the block ends with an unconditional branch, try
11950   // to move it to the successor block.
11951   BBI = &SI; 
11952   do {
11953     ++BBI;
11954   } while (isa<DbgInfoIntrinsic>(BBI) ||
11955            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11956   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11957     if (BI->isUnconditional())
11958       if (SimplifyStoreAtEndOfBlock(SI))
11959         return 0;  // xform done!
11960   
11961   return 0;
11962 }
11963
11964 /// SimplifyStoreAtEndOfBlock - Turn things like:
11965 ///   if () { *P = v1; } else { *P = v2 }
11966 /// into a phi node with a store in the successor.
11967 ///
11968 /// Simplify things like:
11969 ///   *P = v1; if () { *P = v2; }
11970 /// into a phi node with a store in the successor.
11971 ///
11972 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11973   BasicBlock *StoreBB = SI.getParent();
11974   
11975   // Check to see if the successor block has exactly two incoming edges.  If
11976   // so, see if the other predecessor contains a store to the same location.
11977   // if so, insert a PHI node (if needed) and move the stores down.
11978   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11979   
11980   // Determine whether Dest has exactly two predecessors and, if so, compute
11981   // the other predecessor.
11982   pred_iterator PI = pred_begin(DestBB);
11983   BasicBlock *OtherBB = 0;
11984   if (*PI != StoreBB)
11985     OtherBB = *PI;
11986   ++PI;
11987   if (PI == pred_end(DestBB))
11988     return false;
11989   
11990   if (*PI != StoreBB) {
11991     if (OtherBB)
11992       return false;
11993     OtherBB = *PI;
11994   }
11995   if (++PI != pred_end(DestBB))
11996     return false;
11997
11998   // Bail out if all the relevant blocks aren't distinct (this can happen,
11999   // for example, if SI is in an infinite loop)
12000   if (StoreBB == DestBB || OtherBB == DestBB)
12001     return false;
12002
12003   // Verify that the other block ends in a branch and is not otherwise empty.
12004   BasicBlock::iterator BBI = OtherBB->getTerminator();
12005   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12006   if (!OtherBr || BBI == OtherBB->begin())
12007     return false;
12008   
12009   // If the other block ends in an unconditional branch, check for the 'if then
12010   // else' case.  there is an instruction before the branch.
12011   StoreInst *OtherStore = 0;
12012   if (OtherBr->isUnconditional()) {
12013     --BBI;
12014     // Skip over debugging info.
12015     while (isa<DbgInfoIntrinsic>(BBI) ||
12016            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12017       if (BBI==OtherBB->begin())
12018         return false;
12019       --BBI;
12020     }
12021     // If this isn't a store, or isn't a store to the same location, bail out.
12022     OtherStore = dyn_cast<StoreInst>(BBI);
12023     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12024       return false;
12025   } else {
12026     // Otherwise, the other block ended with a conditional branch. If one of the
12027     // destinations is StoreBB, then we have the if/then case.
12028     if (OtherBr->getSuccessor(0) != StoreBB && 
12029         OtherBr->getSuccessor(1) != StoreBB)
12030       return false;
12031     
12032     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12033     // if/then triangle.  See if there is a store to the same ptr as SI that
12034     // lives in OtherBB.
12035     for (;; --BBI) {
12036       // Check to see if we find the matching store.
12037       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12038         if (OtherStore->getOperand(1) != SI.getOperand(1))
12039           return false;
12040         break;
12041       }
12042       // If we find something that may be using or overwriting the stored
12043       // value, or if we run out of instructions, we can't do the xform.
12044       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12045           BBI == OtherBB->begin())
12046         return false;
12047     }
12048     
12049     // In order to eliminate the store in OtherBr, we have to
12050     // make sure nothing reads or overwrites the stored value in
12051     // StoreBB.
12052     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12053       // FIXME: This should really be AA driven.
12054       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12055         return false;
12056     }
12057   }
12058   
12059   // Insert a PHI node now if we need it.
12060   Value *MergedVal = OtherStore->getOperand(0);
12061   if (MergedVal != SI.getOperand(0)) {
12062     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12063     PN->reserveOperandSpace(2);
12064     PN->addIncoming(SI.getOperand(0), SI.getParent());
12065     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12066     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12067   }
12068   
12069   // Advance to a place where it is safe to insert the new store and
12070   // insert it.
12071   BBI = DestBB->getFirstNonPHI();
12072   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12073                                     OtherStore->isVolatile()), *BBI);
12074   
12075   // Nuke the old stores.
12076   EraseInstFromFunction(SI);
12077   EraseInstFromFunction(*OtherStore);
12078   ++NumCombined;
12079   return true;
12080 }
12081
12082
12083 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12084   // Change br (not X), label True, label False to: br X, label False, True
12085   Value *X = 0;
12086   BasicBlock *TrueDest;
12087   BasicBlock *FalseDest;
12088   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12089       !isa<Constant>(X)) {
12090     // Swap Destinations and condition...
12091     BI.setCondition(X);
12092     BI.setSuccessor(0, FalseDest);
12093     BI.setSuccessor(1, TrueDest);
12094     return &BI;
12095   }
12096
12097   // Cannonicalize fcmp_one -> fcmp_oeq
12098   FCmpInst::Predicate FPred; Value *Y;
12099   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12100                              TrueDest, FalseDest)))
12101     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12102          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12103       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12104       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12105       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12106       NewSCC->takeName(I);
12107       // Swap Destinations and condition...
12108       BI.setCondition(NewSCC);
12109       BI.setSuccessor(0, FalseDest);
12110       BI.setSuccessor(1, TrueDest);
12111       RemoveFromWorkList(I);
12112       I->eraseFromParent();
12113       AddToWorkList(NewSCC);
12114       return &BI;
12115     }
12116
12117   // Cannonicalize icmp_ne -> icmp_eq
12118   ICmpInst::Predicate IPred;
12119   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12120                       TrueDest, FalseDest)))
12121     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12122          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12123          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12124       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12125       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12126       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12127       NewSCC->takeName(I);
12128       // Swap Destinations and condition...
12129       BI.setCondition(NewSCC);
12130       BI.setSuccessor(0, FalseDest);
12131       BI.setSuccessor(1, TrueDest);
12132       RemoveFromWorkList(I);
12133       I->eraseFromParent();;
12134       AddToWorkList(NewSCC);
12135       return &BI;
12136     }
12137
12138   return 0;
12139 }
12140
12141 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12142   Value *Cond = SI.getCondition();
12143   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12144     if (I->getOpcode() == Instruction::Add)
12145       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12146         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12147         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12148           SI.setOperand(i,
12149                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12150                                                 AddRHS));
12151         SI.setOperand(0, I->getOperand(0));
12152         AddToWorkList(I);
12153         return &SI;
12154       }
12155   }
12156   return 0;
12157 }
12158
12159 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12160   Value *Agg = EV.getAggregateOperand();
12161
12162   if (!EV.hasIndices())
12163     return ReplaceInstUsesWith(EV, Agg);
12164
12165   if (Constant *C = dyn_cast<Constant>(Agg)) {
12166     if (isa<UndefValue>(C))
12167       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12168       
12169     if (isa<ConstantAggregateZero>(C))
12170       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12171
12172     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12173       // Extract the element indexed by the first index out of the constant
12174       Value *V = C->getOperand(*EV.idx_begin());
12175       if (EV.getNumIndices() > 1)
12176         // Extract the remaining indices out of the constant indexed by the
12177         // first index
12178         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12179       else
12180         return ReplaceInstUsesWith(EV, V);
12181     }
12182     return 0; // Can't handle other constants
12183   } 
12184   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12185     // We're extracting from an insertvalue instruction, compare the indices
12186     const unsigned *exti, *exte, *insi, *inse;
12187     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12188          exte = EV.idx_end(), inse = IV->idx_end();
12189          exti != exte && insi != inse;
12190          ++exti, ++insi) {
12191       if (*insi != *exti)
12192         // The insert and extract both reference distinctly different elements.
12193         // This means the extract is not influenced by the insert, and we can
12194         // replace the aggregate operand of the extract with the aggregate
12195         // operand of the insert. i.e., replace
12196         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12197         // %E = extractvalue { i32, { i32 } } %I, 0
12198         // with
12199         // %E = extractvalue { i32, { i32 } } %A, 0
12200         return ExtractValueInst::Create(IV->getAggregateOperand(),
12201                                         EV.idx_begin(), EV.idx_end());
12202     }
12203     if (exti == exte && insi == inse)
12204       // Both iterators are at the end: Index lists are identical. Replace
12205       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12206       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12207       // with "i32 42"
12208       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12209     if (exti == exte) {
12210       // The extract list is a prefix of the insert list. i.e. replace
12211       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12212       // %E = extractvalue { i32, { i32 } } %I, 1
12213       // with
12214       // %X = extractvalue { i32, { i32 } } %A, 1
12215       // %E = insertvalue { i32 } %X, i32 42, 0
12216       // by switching the order of the insert and extract (though the
12217       // insertvalue should be left in, since it may have other uses).
12218       Value *NewEV = InsertNewInstBefore(
12219         ExtractValueInst::Create(IV->getAggregateOperand(),
12220                                  EV.idx_begin(), EV.idx_end()),
12221         EV);
12222       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12223                                      insi, inse);
12224     }
12225     if (insi == inse)
12226       // The insert list is a prefix of the extract list
12227       // We can simply remove the common indices from the extract and make it
12228       // operate on the inserted value instead of the insertvalue result.
12229       // i.e., replace
12230       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12231       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12232       // with
12233       // %E extractvalue { i32 } { i32 42 }, 0
12234       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12235                                       exti, exte);
12236   }
12237   // Can't simplify extracts from other values. Note that nested extracts are
12238   // already simplified implicitely by the above (extract ( extract (insert) )
12239   // will be translated into extract ( insert ( extract ) ) first and then just
12240   // the value inserted, if appropriate).
12241   return 0;
12242 }
12243
12244 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12245 /// is to leave as a vector operation.
12246 static bool CheapToScalarize(Value *V, bool isConstant) {
12247   if (isa<ConstantAggregateZero>(V)) 
12248     return true;
12249   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12250     if (isConstant) return true;
12251     // If all elts are the same, we can extract.
12252     Constant *Op0 = C->getOperand(0);
12253     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12254       if (C->getOperand(i) != Op0)
12255         return false;
12256     return true;
12257   }
12258   Instruction *I = dyn_cast<Instruction>(V);
12259   if (!I) return false;
12260   
12261   // Insert element gets simplified to the inserted element or is deleted if
12262   // this is constant idx extract element and its a constant idx insertelt.
12263   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12264       isa<ConstantInt>(I->getOperand(2)))
12265     return true;
12266   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12267     return true;
12268   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12269     if (BO->hasOneUse() &&
12270         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12271          CheapToScalarize(BO->getOperand(1), isConstant)))
12272       return true;
12273   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12274     if (CI->hasOneUse() &&
12275         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12276          CheapToScalarize(CI->getOperand(1), isConstant)))
12277       return true;
12278   
12279   return false;
12280 }
12281
12282 /// Read and decode a shufflevector mask.
12283 ///
12284 /// It turns undef elements into values that are larger than the number of
12285 /// elements in the input.
12286 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12287   unsigned NElts = SVI->getType()->getNumElements();
12288   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12289     return std::vector<unsigned>(NElts, 0);
12290   if (isa<UndefValue>(SVI->getOperand(2)))
12291     return std::vector<unsigned>(NElts, 2*NElts);
12292
12293   std::vector<unsigned> Result;
12294   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12295   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12296     if (isa<UndefValue>(*i))
12297       Result.push_back(NElts*2);  // undef -> 8
12298     else
12299       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12300   return Result;
12301 }
12302
12303 /// FindScalarElement - Given a vector and an element number, see if the scalar
12304 /// value is already around as a register, for example if it were inserted then
12305 /// extracted from the vector.
12306 static Value *FindScalarElement(Value *V, unsigned EltNo,
12307                                 LLVMContext *Context) {
12308   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12309   const VectorType *PTy = cast<VectorType>(V->getType());
12310   unsigned Width = PTy->getNumElements();
12311   if (EltNo >= Width)  // Out of range access.
12312     return Context->getUndef(PTy->getElementType());
12313   
12314   if (isa<UndefValue>(V))
12315     return Context->getUndef(PTy->getElementType());
12316   else if (isa<ConstantAggregateZero>(V))
12317     return Context->getNullValue(PTy->getElementType());
12318   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12319     return CP->getOperand(EltNo);
12320   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12321     // If this is an insert to a variable element, we don't know what it is.
12322     if (!isa<ConstantInt>(III->getOperand(2))) 
12323       return 0;
12324     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12325     
12326     // If this is an insert to the element we are looking for, return the
12327     // inserted value.
12328     if (EltNo == IIElt) 
12329       return III->getOperand(1);
12330     
12331     // Otherwise, the insertelement doesn't modify the value, recurse on its
12332     // vector input.
12333     return FindScalarElement(III->getOperand(0), EltNo, Context);
12334   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12335     unsigned LHSWidth =
12336       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12337     unsigned InEl = getShuffleMask(SVI)[EltNo];
12338     if (InEl < LHSWidth)
12339       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12340     else if (InEl < LHSWidth*2)
12341       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12342     else
12343       return Context->getUndef(PTy->getElementType());
12344   }
12345   
12346   // Otherwise, we don't know.
12347   return 0;
12348 }
12349
12350 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12351   // If vector val is undef, replace extract with scalar undef.
12352   if (isa<UndefValue>(EI.getOperand(0)))
12353     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12354
12355   // If vector val is constant 0, replace extract with scalar 0.
12356   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12357     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12358   
12359   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12360     // If vector val is constant with all elements the same, replace EI with
12361     // that element. When the elements are not identical, we cannot replace yet
12362     // (we do that below, but only when the index is constant).
12363     Constant *op0 = C->getOperand(0);
12364     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12365       if (C->getOperand(i) != op0) {
12366         op0 = 0; 
12367         break;
12368       }
12369     if (op0)
12370       return ReplaceInstUsesWith(EI, op0);
12371   }
12372   
12373   // If extracting a specified index from the vector, see if we can recursively
12374   // find a previously computed scalar that was inserted into the vector.
12375   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12376     unsigned IndexVal = IdxC->getZExtValue();
12377     unsigned VectorWidth = 
12378       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12379       
12380     // If this is extracting an invalid index, turn this into undef, to avoid
12381     // crashing the code below.
12382     if (IndexVal >= VectorWidth)
12383       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12384     
12385     // This instruction only demands the single element from the input vector.
12386     // If the input vector has a single use, simplify it based on this use
12387     // property.
12388     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12389       APInt UndefElts(VectorWidth, 0);
12390       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12391       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12392                                                 DemandedMask, UndefElts)) {
12393         EI.setOperand(0, V);
12394         return &EI;
12395       }
12396     }
12397     
12398     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12399       return ReplaceInstUsesWith(EI, Elt);
12400     
12401     // If the this extractelement is directly using a bitcast from a vector of
12402     // the same number of elements, see if we can find the source element from
12403     // it.  In this case, we will end up needing to bitcast the scalars.
12404     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12405       if (const VectorType *VT = 
12406               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12407         if (VT->getNumElements() == VectorWidth)
12408           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12409                                              IndexVal, Context))
12410             return new BitCastInst(Elt, EI.getType());
12411     }
12412   }
12413   
12414   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12415     if (I->hasOneUse()) {
12416       // Push extractelement into predecessor operation if legal and
12417       // profitable to do so
12418       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12419         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12420         if (CheapToScalarize(BO, isConstantElt)) {
12421           ExtractElementInst *newEI0 = 
12422             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12423                                    EI.getName()+".lhs");
12424           ExtractElementInst *newEI1 =
12425             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12426                                    EI.getName()+".rhs");
12427           InsertNewInstBefore(newEI0, EI);
12428           InsertNewInstBefore(newEI1, EI);
12429           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12430         }
12431       } else if (isa<LoadInst>(I)) {
12432         unsigned AS = 
12433           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12434         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12435                                   Context->getPointerType(EI.getType(), AS),EI);
12436         GetElementPtrInst *GEP =
12437           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12438         InsertNewInstBefore(GEP, EI);
12439         return new LoadInst(GEP);
12440       }
12441     }
12442     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12443       // Extracting the inserted element?
12444       if (IE->getOperand(2) == EI.getOperand(1))
12445         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12446       // If the inserted and extracted elements are constants, they must not
12447       // be the same value, extract from the pre-inserted value instead.
12448       if (isa<Constant>(IE->getOperand(2)) &&
12449           isa<Constant>(EI.getOperand(1))) {
12450         AddUsesToWorkList(EI);
12451         EI.setOperand(0, IE->getOperand(0));
12452         return &EI;
12453       }
12454     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12455       // If this is extracting an element from a shufflevector, figure out where
12456       // it came from and extract from the appropriate input element instead.
12457       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12458         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12459         Value *Src;
12460         unsigned LHSWidth =
12461           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12462
12463         if (SrcIdx < LHSWidth)
12464           Src = SVI->getOperand(0);
12465         else if (SrcIdx < LHSWidth*2) {
12466           SrcIdx -= LHSWidth;
12467           Src = SVI->getOperand(1);
12468         } else {
12469           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12470         }
12471         return new ExtractElementInst(Src, SrcIdx);
12472       }
12473     }
12474   }
12475   return 0;
12476 }
12477
12478 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12479 /// elements from either LHS or RHS, return the shuffle mask and true. 
12480 /// Otherwise, return false.
12481 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12482                                          std::vector<Constant*> &Mask,
12483                                          LLVMContext *Context) {
12484   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12485          "Invalid CollectSingleShuffleElements");
12486   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12487
12488   if (isa<UndefValue>(V)) {
12489     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12490     return true;
12491   } else if (V == LHS) {
12492     for (unsigned i = 0; i != NumElts; ++i)
12493       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12494     return true;
12495   } else if (V == RHS) {
12496     for (unsigned i = 0; i != NumElts; ++i)
12497       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12498     return true;
12499   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12500     // If this is an insert of an extract from some other vector, include it.
12501     Value *VecOp    = IEI->getOperand(0);
12502     Value *ScalarOp = IEI->getOperand(1);
12503     Value *IdxOp    = IEI->getOperand(2);
12504     
12505     if (!isa<ConstantInt>(IdxOp))
12506       return false;
12507     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12508     
12509     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12510       // Okay, we can handle this if the vector we are insertinting into is
12511       // transitively ok.
12512       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12513         // If so, update the mask to reflect the inserted undef.
12514         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12515         return true;
12516       }      
12517     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12518       if (isa<ConstantInt>(EI->getOperand(1)) &&
12519           EI->getOperand(0)->getType() == V->getType()) {
12520         unsigned ExtractedIdx =
12521           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12522         
12523         // This must be extracting from either LHS or RHS.
12524         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12525           // Okay, we can handle this if the vector we are insertinting into is
12526           // transitively ok.
12527           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12528             // If so, update the mask to reflect the inserted value.
12529             if (EI->getOperand(0) == LHS) {
12530               Mask[InsertedIdx % NumElts] = 
12531                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12532             } else {
12533               assert(EI->getOperand(0) == RHS);
12534               Mask[InsertedIdx % NumElts] = 
12535                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12536               
12537             }
12538             return true;
12539           }
12540         }
12541       }
12542     }
12543   }
12544   // TODO: Handle shufflevector here!
12545   
12546   return false;
12547 }
12548
12549 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12550 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12551 /// that computes V and the LHS value of the shuffle.
12552 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12553                                      Value *&RHS, LLVMContext *Context) {
12554   assert(isa<VectorType>(V->getType()) && 
12555          (RHS == 0 || V->getType() == RHS->getType()) &&
12556          "Invalid shuffle!");
12557   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12558
12559   if (isa<UndefValue>(V)) {
12560     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12561     return V;
12562   } else if (isa<ConstantAggregateZero>(V)) {
12563     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12564     return V;
12565   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12566     // If this is an insert of an extract from some other vector, include it.
12567     Value *VecOp    = IEI->getOperand(0);
12568     Value *ScalarOp = IEI->getOperand(1);
12569     Value *IdxOp    = IEI->getOperand(2);
12570     
12571     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12572       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12573           EI->getOperand(0)->getType() == V->getType()) {
12574         unsigned ExtractedIdx =
12575           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12576         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12577         
12578         // Either the extracted from or inserted into vector must be RHSVec,
12579         // otherwise we'd end up with a shuffle of three inputs.
12580         if (EI->getOperand(0) == RHS || RHS == 0) {
12581           RHS = EI->getOperand(0);
12582           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12583           Mask[InsertedIdx % NumElts] = 
12584             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12585           return V;
12586         }
12587         
12588         if (VecOp == RHS) {
12589           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12590                                             RHS, Context);
12591           // Everything but the extracted element is replaced with the RHS.
12592           for (unsigned i = 0; i != NumElts; ++i) {
12593             if (i != InsertedIdx)
12594               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12595           }
12596           return V;
12597         }
12598         
12599         // If this insertelement is a chain that comes from exactly these two
12600         // vectors, return the vector and the effective shuffle.
12601         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12602                                          Context))
12603           return EI->getOperand(0);
12604         
12605       }
12606     }
12607   }
12608   // TODO: Handle shufflevector here!
12609   
12610   // Otherwise, can't do anything fancy.  Return an identity vector.
12611   for (unsigned i = 0; i != NumElts; ++i)
12612     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12613   return V;
12614 }
12615
12616 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12617   Value *VecOp    = IE.getOperand(0);
12618   Value *ScalarOp = IE.getOperand(1);
12619   Value *IdxOp    = IE.getOperand(2);
12620   
12621   // Inserting an undef or into an undefined place, remove this.
12622   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12623     ReplaceInstUsesWith(IE, VecOp);
12624   
12625   // If the inserted element was extracted from some other vector, and if the 
12626   // indexes are constant, try to turn this into a shufflevector operation.
12627   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12628     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12629         EI->getOperand(0)->getType() == IE.getType()) {
12630       unsigned NumVectorElts = IE.getType()->getNumElements();
12631       unsigned ExtractedIdx =
12632         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12633       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12634       
12635       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12636         return ReplaceInstUsesWith(IE, VecOp);
12637       
12638       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12639         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12640       
12641       // If we are extracting a value from a vector, then inserting it right
12642       // back into the same place, just use the input vector.
12643       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12644         return ReplaceInstUsesWith(IE, VecOp);      
12645       
12646       // We could theoretically do this for ANY input.  However, doing so could
12647       // turn chains of insertelement instructions into a chain of shufflevector
12648       // instructions, and right now we do not merge shufflevectors.  As such,
12649       // only do this in a situation where it is clear that there is benefit.
12650       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12651         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12652         // the values of VecOp, except then one read from EIOp0.
12653         // Build a new shuffle mask.
12654         std::vector<Constant*> Mask;
12655         if (isa<UndefValue>(VecOp))
12656           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12657         else {
12658           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12659           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12660                                                        NumVectorElts));
12661         } 
12662         Mask[InsertedIdx] = 
12663                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12664         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12665                                      Context->getConstantVector(Mask));
12666       }
12667       
12668       // If this insertelement isn't used by some other insertelement, turn it
12669       // (and any insertelements it points to), into one big shuffle.
12670       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12671         std::vector<Constant*> Mask;
12672         Value *RHS = 0;
12673         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12674         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12675         // We now have a shuffle of LHS, RHS, Mask.
12676         return new ShuffleVectorInst(LHS, RHS,
12677                                      Context->getConstantVector(Mask));
12678       }
12679     }
12680   }
12681
12682   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12683   APInt UndefElts(VWidth, 0);
12684   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12685   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12686     return &IE;
12687
12688   return 0;
12689 }
12690
12691
12692 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12693   Value *LHS = SVI.getOperand(0);
12694   Value *RHS = SVI.getOperand(1);
12695   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12696
12697   bool MadeChange = false;
12698
12699   // Undefined shuffle mask -> undefined value.
12700   if (isa<UndefValue>(SVI.getOperand(2)))
12701     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12702
12703   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12704
12705   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12706     return 0;
12707
12708   APInt UndefElts(VWidth, 0);
12709   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12710   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12711     LHS = SVI.getOperand(0);
12712     RHS = SVI.getOperand(1);
12713     MadeChange = true;
12714   }
12715   
12716   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12717   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12718   if (LHS == RHS || isa<UndefValue>(LHS)) {
12719     if (isa<UndefValue>(LHS) && LHS == RHS) {
12720       // shuffle(undef,undef,mask) -> undef.
12721       return ReplaceInstUsesWith(SVI, LHS);
12722     }
12723     
12724     // Remap any references to RHS to use LHS.
12725     std::vector<Constant*> Elts;
12726     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12727       if (Mask[i] >= 2*e)
12728         Elts.push_back(Context->getUndef(Type::Int32Ty));
12729       else {
12730         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12731             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12732           Mask[i] = 2*e;     // Turn into undef.
12733           Elts.push_back(Context->getUndef(Type::Int32Ty));
12734         } else {
12735           Mask[i] = Mask[i] % e;  // Force to LHS.
12736           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12737         }
12738       }
12739     }
12740     SVI.setOperand(0, SVI.getOperand(1));
12741     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12742     SVI.setOperand(2, Context->getConstantVector(Elts));
12743     LHS = SVI.getOperand(0);
12744     RHS = SVI.getOperand(1);
12745     MadeChange = true;
12746   }
12747   
12748   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12749   bool isLHSID = true, isRHSID = true;
12750     
12751   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12752     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12753     // Is this an identity shuffle of the LHS value?
12754     isLHSID &= (Mask[i] == i);
12755       
12756     // Is this an identity shuffle of the RHS value?
12757     isRHSID &= (Mask[i]-e == i);
12758   }
12759
12760   // Eliminate identity shuffles.
12761   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12762   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12763   
12764   // If the LHS is a shufflevector itself, see if we can combine it with this
12765   // one without producing an unusual shuffle.  Here we are really conservative:
12766   // we are absolutely afraid of producing a shuffle mask not in the input
12767   // program, because the code gen may not be smart enough to turn a merged
12768   // shuffle into two specific shuffles: it may produce worse code.  As such,
12769   // we only merge two shuffles if the result is one of the two input shuffle
12770   // masks.  In this case, merging the shuffles just removes one instruction,
12771   // which we know is safe.  This is good for things like turning:
12772   // (splat(splat)) -> splat.
12773   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12774     if (isa<UndefValue>(RHS)) {
12775       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12776
12777       std::vector<unsigned> NewMask;
12778       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12779         if (Mask[i] >= 2*e)
12780           NewMask.push_back(2*e);
12781         else
12782           NewMask.push_back(LHSMask[Mask[i]]);
12783       
12784       // If the result mask is equal to the src shuffle or this shuffle mask, do
12785       // the replacement.
12786       if (NewMask == LHSMask || NewMask == Mask) {
12787         unsigned LHSInNElts =
12788           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12789         std::vector<Constant*> Elts;
12790         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12791           if (NewMask[i] >= LHSInNElts*2) {
12792             Elts.push_back(Context->getUndef(Type::Int32Ty));
12793           } else {
12794             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12795           }
12796         }
12797         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12798                                      LHSSVI->getOperand(1),
12799                                      Context->getConstantVector(Elts));
12800       }
12801     }
12802   }
12803
12804   return MadeChange ? &SVI : 0;
12805 }
12806
12807
12808
12809
12810 /// TryToSinkInstruction - Try to move the specified instruction from its
12811 /// current block into the beginning of DestBlock, which can only happen if it's
12812 /// safe to move the instruction past all of the instructions between it and the
12813 /// end of its block.
12814 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12815   assert(I->hasOneUse() && "Invariants didn't hold!");
12816
12817   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12818   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12819     return false;
12820
12821   // Do not sink alloca instructions out of the entry block.
12822   if (isa<AllocaInst>(I) && I->getParent() ==
12823         &DestBlock->getParent()->getEntryBlock())
12824     return false;
12825
12826   // We can only sink load instructions if there is nothing between the load and
12827   // the end of block that could change the value.
12828   if (I->mayReadFromMemory()) {
12829     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12830          Scan != E; ++Scan)
12831       if (Scan->mayWriteToMemory())
12832         return false;
12833   }
12834
12835   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12836
12837   CopyPrecedingStopPoint(I, InsertPos);
12838   I->moveBefore(InsertPos);
12839   ++NumSunkInst;
12840   return true;
12841 }
12842
12843
12844 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12845 /// all reachable code to the worklist.
12846 ///
12847 /// This has a couple of tricks to make the code faster and more powerful.  In
12848 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12849 /// them to the worklist (this significantly speeds up instcombine on code where
12850 /// many instructions are dead or constant).  Additionally, if we find a branch
12851 /// whose condition is a known constant, we only visit the reachable successors.
12852 ///
12853 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12854                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12855                                        InstCombiner &IC,
12856                                        const TargetData *TD) {
12857   SmallVector<BasicBlock*, 256> Worklist;
12858   Worklist.push_back(BB);
12859
12860   while (!Worklist.empty()) {
12861     BB = Worklist.back();
12862     Worklist.pop_back();
12863     
12864     // We have now visited this block!  If we've already been here, ignore it.
12865     if (!Visited.insert(BB)) continue;
12866
12867     DbgInfoIntrinsic *DBI_Prev = NULL;
12868     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12869       Instruction *Inst = BBI++;
12870       
12871       // DCE instruction if trivially dead.
12872       if (isInstructionTriviallyDead(Inst)) {
12873         ++NumDeadInst;
12874         DOUT << "IC: DCE: " << *Inst;
12875         Inst->eraseFromParent();
12876         continue;
12877       }
12878       
12879       // ConstantProp instruction if trivially constant.
12880       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12881         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12882         Inst->replaceAllUsesWith(C);
12883         ++NumConstProp;
12884         Inst->eraseFromParent();
12885         continue;
12886       }
12887      
12888       // If there are two consecutive llvm.dbg.stoppoint calls then
12889       // it is likely that the optimizer deleted code in between these
12890       // two intrinsics. 
12891       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12892       if (DBI_Next) {
12893         if (DBI_Prev
12894             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12895             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12896           IC.RemoveFromWorkList(DBI_Prev);
12897           DBI_Prev->eraseFromParent();
12898         }
12899         DBI_Prev = DBI_Next;
12900       } else {
12901         DBI_Prev = 0;
12902       }
12903
12904       IC.AddToWorkList(Inst);
12905     }
12906
12907     // Recursively visit successors.  If this is a branch or switch on a
12908     // constant, only visit the reachable successor.
12909     TerminatorInst *TI = BB->getTerminator();
12910     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12911       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12912         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12913         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12914         Worklist.push_back(ReachableBB);
12915         continue;
12916       }
12917     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12918       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12919         // See if this is an explicit destination.
12920         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12921           if (SI->getCaseValue(i) == Cond) {
12922             BasicBlock *ReachableBB = SI->getSuccessor(i);
12923             Worklist.push_back(ReachableBB);
12924             continue;
12925           }
12926         
12927         // Otherwise it is the default destination.
12928         Worklist.push_back(SI->getSuccessor(0));
12929         continue;
12930       }
12931     }
12932     
12933     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12934       Worklist.push_back(TI->getSuccessor(i));
12935   }
12936 }
12937
12938 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12939   bool Changed = false;
12940   TD = &getAnalysis<TargetData>();
12941   
12942   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12943              << F.getNameStr() << "\n");
12944
12945   {
12946     // Do a depth-first traversal of the function, populate the worklist with
12947     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12948     // track of which blocks we visit.
12949     SmallPtrSet<BasicBlock*, 64> Visited;
12950     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12951
12952     // Do a quick scan over the function.  If we find any blocks that are
12953     // unreachable, remove any instructions inside of them.  This prevents
12954     // the instcombine code from having to deal with some bad special cases.
12955     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12956       if (!Visited.count(BB)) {
12957         Instruction *Term = BB->getTerminator();
12958         while (Term != BB->begin()) {   // Remove instrs bottom-up
12959           BasicBlock::iterator I = Term; --I;
12960
12961           DOUT << "IC: DCE: " << *I;
12962           // A debug intrinsic shouldn't force another iteration if we weren't
12963           // going to do one without it.
12964           if (!isa<DbgInfoIntrinsic>(I)) {
12965             ++NumDeadInst;
12966             Changed = true;
12967           }
12968           if (!I->use_empty())
12969             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12970           I->eraseFromParent();
12971         }
12972       }
12973   }
12974
12975   while (!Worklist.empty()) {
12976     Instruction *I = RemoveOneFromWorkList();
12977     if (I == 0) continue;  // skip null values.
12978
12979     // Check to see if we can DCE the instruction.
12980     if (isInstructionTriviallyDead(I)) {
12981       // Add operands to the worklist.
12982       if (I->getNumOperands() < 4)
12983         AddUsesToWorkList(*I);
12984       ++NumDeadInst;
12985
12986       DOUT << "IC: DCE: " << *I;
12987
12988       I->eraseFromParent();
12989       RemoveFromWorkList(I);
12990       Changed = true;
12991       continue;
12992     }
12993
12994     // Instruction isn't dead, see if we can constant propagate it.
12995     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12996       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12997
12998       // Add operands to the worklist.
12999       AddUsesToWorkList(*I);
13000       ReplaceInstUsesWith(*I, C);
13001
13002       ++NumConstProp;
13003       I->eraseFromParent();
13004       RemoveFromWorkList(I);
13005       Changed = true;
13006       continue;
13007     }
13008
13009     if (TD &&
13010         (I->getType()->getTypeID() == Type::VoidTyID ||
13011          I->isTrapping())) {
13012       // See if we can constant fold its operands.
13013       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13014         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13015           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13016                                   F.getContext(), TD))
13017             if (NewC != CE) {
13018               i->set(NewC);
13019               Changed = true;
13020             }
13021     }
13022
13023     // See if we can trivially sink this instruction to a successor basic block.
13024     if (I->hasOneUse()) {
13025       BasicBlock *BB = I->getParent();
13026       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13027       if (UserParent != BB) {
13028         bool UserIsSuccessor = false;
13029         // See if the user is one of our successors.
13030         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13031           if (*SI == UserParent) {
13032             UserIsSuccessor = true;
13033             break;
13034           }
13035
13036         // If the user is one of our immediate successors, and if that successor
13037         // only has us as a predecessors (we'd have to split the critical edge
13038         // otherwise), we can keep going.
13039         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13040             next(pred_begin(UserParent)) == pred_end(UserParent))
13041           // Okay, the CFG is simple enough, try to sink this instruction.
13042           Changed |= TryToSinkInstruction(I, UserParent);
13043       }
13044     }
13045
13046     // Now that we have an instruction, try combining it to simplify it...
13047 #ifndef NDEBUG
13048     std::string OrigI;
13049 #endif
13050     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13051     if (Instruction *Result = visit(*I)) {
13052       ++NumCombined;
13053       // Should we replace the old instruction with a new one?
13054       if (Result != I) {
13055         DOUT << "IC: Old = " << *I
13056              << "    New = " << *Result;
13057
13058         // Everything uses the new instruction now.
13059         I->replaceAllUsesWith(Result);
13060
13061         // Push the new instruction and any users onto the worklist.
13062         AddToWorkList(Result);
13063         AddUsersToWorkList(*Result);
13064
13065         // Move the name to the new instruction first.
13066         Result->takeName(I);
13067
13068         // Insert the new instruction into the basic block...
13069         BasicBlock *InstParent = I->getParent();
13070         BasicBlock::iterator InsertPos = I;
13071
13072         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13073           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13074             ++InsertPos;
13075
13076         InstParent->getInstList().insert(InsertPos, Result);
13077
13078         // Make sure that we reprocess all operands now that we reduced their
13079         // use counts.
13080         AddUsesToWorkList(*I);
13081
13082         // Instructions can end up on the worklist more than once.  Make sure
13083         // we do not process an instruction that has been deleted.
13084         RemoveFromWorkList(I);
13085
13086         // Erase the old instruction.
13087         InstParent->getInstList().erase(I);
13088       } else {
13089 #ifndef NDEBUG
13090         DOUT << "IC: Mod = " << OrigI
13091              << "    New = " << *I;
13092 #endif
13093
13094         // If the instruction was modified, it's possible that it is now dead.
13095         // if so, remove it.
13096         if (isInstructionTriviallyDead(I)) {
13097           // Make sure we process all operands now that we are reducing their
13098           // use counts.
13099           AddUsesToWorkList(*I);
13100
13101           // Instructions may end up in the worklist more than once.  Erase all
13102           // occurrences of this instruction.
13103           RemoveFromWorkList(I);
13104           I->eraseFromParent();
13105         } else {
13106           AddToWorkList(I);
13107           AddUsersToWorkList(*I);
13108         }
13109       }
13110       Changed = true;
13111     }
13112   }
13113
13114   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13115     
13116   // Do an explicit clear, this shrinks the map if needed.
13117   WorklistMap.clear();
13118   return Changed;
13119 }
13120
13121
13122 bool InstCombiner::runOnFunction(Function &F) {
13123   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13124   
13125   bool EverMadeChange = false;
13126
13127   // Iterate while there is work to do.
13128   unsigned Iteration = 0;
13129   while (DoOneIteration(F, Iteration++))
13130     EverMadeChange = true;
13131   return EverMadeChange;
13132 }
13133
13134 FunctionPass *llvm::createInstructionCombiningPass() {
13135   return new InstCombiner();
13136 }