79de4432d8c2a0872c86b0ff455fe53b6cf52df8
[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)), *Context) &&
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(*Context, CI->getOpcode(), CI->getPredicate(),
1928                           Op0, Op1, 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(*Context, 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)), *Context)) {
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)), *Context))
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)), *Context) &&
2248         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
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)), *Context))    // ~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() &&
2275         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2276       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2277       if (Anded == CRHS) {
2278         // See if all bits from the first bit set in the Add RHS up are included
2279         // in the mask.  First, get the rightmost bit.
2280         const APInt& AddRHSV = CRHS->getValue();
2281
2282         // Form a mask of all bits from the lowest bit added through the top.
2283         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2284
2285         // See if the and mask includes all of these bits.
2286         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2287
2288         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2289           // Okay, the xform is safe.  Insert the new add pronto.
2290           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2291                                                             LHS->getName()), I);
2292           return BinaryOperator::CreateAnd(NewAdd, C2);
2293         }
2294       }
2295     }
2296
2297     // Try to fold constant add into select arguments.
2298     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2299       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2300         return R;
2301   }
2302
2303   // add (cast *A to intptrtype) B -> 
2304   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2305   {
2306     CastInst *CI = dyn_cast<CastInst>(LHS);
2307     Value *Other = RHS;
2308     if (!CI) {
2309       CI = dyn_cast<CastInst>(RHS);
2310       Other = LHS;
2311     }
2312     if (CI && CI->getType()->isSized() && 
2313         (CI->getType()->getScalarSizeInBits() ==
2314          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2315         && isa<PointerType>(CI->getOperand(0)->getType())) {
2316       unsigned AS =
2317         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2318       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2319                                   Context->getPointerType(Type::Int8Ty, AS), I);
2320       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2321       return new PtrToIntInst(I2, CI->getType());
2322     }
2323   }
2324   
2325   // add (select X 0 (sub n A)) A  -->  select X A n
2326   {
2327     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2328     Value *A = RHS;
2329     if (!SI) {
2330       SI = dyn_cast<SelectInst>(RHS);
2331       A = LHS;
2332     }
2333     if (SI && SI->hasOneUse()) {
2334       Value *TV = SI->getTrueValue();
2335       Value *FV = SI->getFalseValue();
2336       Value *N;
2337
2338       // Can we fold the add into the argument of the select?
2339       // We check both true and false select arguments for a matching subtract.
2340       if (match(FV, m_Zero(), *Context) &&
2341           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2342         // Fold the add into the true select value.
2343         return SelectInst::Create(SI->getCondition(), N, A);
2344       if (match(TV, m_Zero(), *Context) &&
2345           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2346         // Fold the add into the false select value.
2347         return SelectInst::Create(SI->getCondition(), A, N);
2348     }
2349   }
2350
2351   // Check for (add (sext x), y), see if we can merge this into an
2352   // integer add followed by a sext.
2353   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2354     // (add (sext x), cst) --> (sext (add x, cst'))
2355     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2356       Constant *CI = 
2357         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2358       if (LHSConv->hasOneUse() &&
2359           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2360           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2361         // Insert the new, smaller add.
2362         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2363                                                         CI, "addconv");
2364         InsertNewInstBefore(NewAdd, I);
2365         return new SExtInst(NewAdd, I.getType());
2366       }
2367     }
2368     
2369     // (add (sext x), (sext y)) --> (sext (add int x, y))
2370     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2371       // Only do this if x/y have the same type, if at last one of them has a
2372       // single use (so we don't increase the number of sexts), and if the
2373       // integer add will not overflow.
2374       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2375           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2376           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2377                                    RHSConv->getOperand(0))) {
2378         // Insert the new integer add.
2379         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2380                                                         RHSConv->getOperand(0),
2381                                                         "addconv");
2382         InsertNewInstBefore(NewAdd, I);
2383         return new SExtInst(NewAdd, I.getType());
2384       }
2385     }
2386   }
2387
2388   return Changed ? &I : 0;
2389 }
2390
2391 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2392   bool Changed = SimplifyCommutative(I);
2393   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2394
2395   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2396     // X + 0 --> X
2397     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2398       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2399                               (I.getType())->getValueAPF()))
2400         return ReplaceInstUsesWith(I, LHS);
2401     }
2402
2403     if (isa<PHINode>(LHS))
2404       if (Instruction *NV = FoldOpIntoPhi(I))
2405         return NV;
2406   }
2407
2408   // -A + B  -->  B - A
2409   // -A + -B  -->  -(A + B)
2410   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2411     return BinaryOperator::CreateFSub(RHS, LHSV);
2412
2413   // A + -B  -->  A - B
2414   if (!isa<Constant>(RHS))
2415     if (Value *V = dyn_castFNegVal(RHS, Context))
2416       return BinaryOperator::CreateFSub(LHS, V);
2417
2418   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2419   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2420     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2421       return ReplaceInstUsesWith(I, LHS);
2422
2423   // Check for (add double (sitofp x), y), see if we can merge this into an
2424   // integer add followed by a promotion.
2425   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2426     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2427     // ... if the constant fits in the integer value.  This is useful for things
2428     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2429     // requires a constant pool load, and generally allows the add to be better
2430     // instcombined.
2431     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2432       Constant *CI = 
2433       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2434       if (LHSConv->hasOneUse() &&
2435           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2436           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437         // Insert the new integer add.
2438         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2439                                                         CI, "addconv");
2440         InsertNewInstBefore(NewAdd, I);
2441         return new SIToFPInst(NewAdd, I.getType());
2442       }
2443     }
2444     
2445     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2446     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2447       // Only do this if x/y have the same type, if at last one of them has a
2448       // single use (so we don't increase the number of int->fp conversions),
2449       // and if the integer add will not overflow.
2450       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2451           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2452           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2453                                    RHSConv->getOperand(0))) {
2454         // Insert the new integer add.
2455         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2456                                                         RHSConv->getOperand(0),
2457                                                         "addconv");
2458         InsertNewInstBefore(NewAdd, I);
2459         return new SIToFPInst(NewAdd, I.getType());
2460       }
2461     }
2462   }
2463   
2464   return Changed ? &I : 0;
2465 }
2466
2467 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2468   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2469
2470   if (Op0 == Op1)                        // sub X, X  -> 0
2471     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2472
2473   // If this is a 'B = x-(-A)', change to B = x+A...
2474   if (Value *V = dyn_castNegVal(Op1, Context))
2475     return BinaryOperator::CreateAdd(Op0, V);
2476
2477   if (isa<UndefValue>(Op0))
2478     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2479   if (isa<UndefValue>(Op1))
2480     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2481
2482   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2483     // Replace (-1 - A) with (~A)...
2484     if (C->isAllOnesValue())
2485       return BinaryOperator::CreateNot(Op1);
2486
2487     // C - ~X == X + (1+C)
2488     Value *X = 0;
2489     if (match(Op1, m_Not(m_Value(X)), *Context))
2490       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2491
2492     // -(X >>u 31) -> (X >>s 31)
2493     // -(X >>s 31) -> (X >>u 31)
2494     if (C->isZero()) {
2495       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2496         if (SI->getOpcode() == Instruction::LShr) {
2497           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2498             // Check to see if we are shifting out everything but the sign bit.
2499             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2500                 SI->getType()->getPrimitiveSizeInBits()-1) {
2501               // Ok, the transformation is safe.  Insert AShr.
2502               return BinaryOperator::Create(Instruction::AShr, 
2503                                           SI->getOperand(0), CU, SI->getName());
2504             }
2505           }
2506         }
2507         else if (SI->getOpcode() == Instruction::AShr) {
2508           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2509             // Check to see if we are shifting out everything but the sign bit.
2510             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2511                 SI->getType()->getPrimitiveSizeInBits()-1) {
2512               // Ok, the transformation is safe.  Insert LShr. 
2513               return BinaryOperator::CreateLShr(
2514                                           SI->getOperand(0), CU, SI->getName());
2515             }
2516           }
2517         }
2518       }
2519     }
2520
2521     // Try to fold constant sub into select arguments.
2522     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2523       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524         return R;
2525   }
2526
2527   if (I.getType() == Type::Int1Ty)
2528     return BinaryOperator::CreateXor(Op0, Op1);
2529
2530   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2531     if (Op1I->getOpcode() == Instruction::Add) {
2532       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2533         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2534       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2535         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2536       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2537         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2538           // C1-(X+C2) --> (C1-C2)-X
2539           return BinaryOperator::CreateSub(
2540             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2541       }
2542     }
2543
2544     if (Op1I->hasOneUse()) {
2545       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2546       // is not used by anyone else...
2547       //
2548       if (Op1I->getOpcode() == Instruction::Sub) {
2549         // Swap the two operands of the subexpr...
2550         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2551         Op1I->setOperand(0, IIOp1);
2552         Op1I->setOperand(1, IIOp0);
2553
2554         // Create the new top level add instruction...
2555         return BinaryOperator::CreateAdd(Op0, Op1);
2556       }
2557
2558       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2559       //
2560       if (Op1I->getOpcode() == Instruction::And &&
2561           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2562         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2563
2564         Value *NewNot =
2565           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2566         return BinaryOperator::CreateAnd(Op0, NewNot);
2567       }
2568
2569       // 0 - (X sdiv C)  -> (X sdiv -C)
2570       if (Op1I->getOpcode() == Instruction::SDiv)
2571         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2572           if (CSI->isZero())
2573             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2574               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2575                                           Context->getConstantExprNeg(DivRHS));
2576
2577       // X - X*C --> X * (1-C)
2578       ConstantInt *C2 = 0;
2579       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2580         Constant *CP1 = 
2581           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2582                                              C2);
2583         return BinaryOperator::CreateMul(Op0, CP1);
2584       }
2585     }
2586   }
2587
2588   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2589     if (Op0I->getOpcode() == Instruction::Add) {
2590       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2591         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2592       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2593         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2594     } else if (Op0I->getOpcode() == Instruction::Sub) {
2595       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2596         return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2597     }
2598   }
2599
2600   ConstantInt *C1;
2601   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2602     if (X == Op1)  // X*C - X --> X * (C-1)
2603       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2604
2605     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2606     if (X == dyn_castFoldableMul(Op1, C2, Context))
2607       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2608   }
2609   return 0;
2610 }
2611
2612 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2613   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2614
2615   // If this is a 'B = x-(-A)', change to B = x+A...
2616   if (Value *V = dyn_castFNegVal(Op1, Context))
2617     return BinaryOperator::CreateFAdd(Op0, V);
2618
2619   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2620     if (Op1I->getOpcode() == Instruction::FAdd) {
2621       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2622         return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2623       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2624         return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2625     }
2626   }
2627
2628   return 0;
2629 }
2630
2631 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2632 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2633 /// TrueIfSigned if the result of the comparison is true when the input value is
2634 /// signed.
2635 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2636                            bool &TrueIfSigned) {
2637   switch (pred) {
2638   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2639     TrueIfSigned = true;
2640     return RHS->isZero();
2641   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2642     TrueIfSigned = true;
2643     return RHS->isAllOnesValue();
2644   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2645     TrueIfSigned = false;
2646     return RHS->isAllOnesValue();
2647   case ICmpInst::ICMP_UGT:
2648     // True if LHS u> RHS and RHS == high-bit-mask - 1
2649     TrueIfSigned = true;
2650     return RHS->getValue() ==
2651       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2652   case ICmpInst::ICMP_UGE: 
2653     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2654     TrueIfSigned = true;
2655     return RHS->getValue().isSignBit();
2656   default:
2657     return false;
2658   }
2659 }
2660
2661 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2662   bool Changed = SimplifyCommutative(I);
2663   Value *Op0 = I.getOperand(0);
2664
2665   // TODO: If Op1 is undef and Op0 is finite, return zero.
2666   if (!I.getType()->isFPOrFPVector() &&
2667       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2668     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2669
2670   // Simplify mul instructions with a constant RHS...
2671   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2672     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2673
2674       // ((X << C1)*C2) == (X * (C2 << C1))
2675       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2676         if (SI->getOpcode() == Instruction::Shl)
2677           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2678             return BinaryOperator::CreateMul(SI->getOperand(0),
2679                                         Context->getConstantExprShl(CI, ShOp));
2680
2681       if (CI->isZero())
2682         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2683       if (CI->equalsInt(1))                  // X * 1  == X
2684         return ReplaceInstUsesWith(I, Op0);
2685       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2686         return BinaryOperator::CreateNeg(Op0, I.getName());
2687
2688       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2689       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2690         return BinaryOperator::CreateShl(Op0,
2691                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2692       }
2693     } else if (isa<VectorType>(Op1->getType())) {
2694       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2695
2696       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2697         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2698           return BinaryOperator::CreateNeg(Op0, I.getName());
2699
2700         // As above, vector X*splat(1.0) -> X in all defined cases.
2701         if (Constant *Splat = Op1V->getSplatValue()) {
2702           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2703             if (CI->equalsInt(1))
2704               return ReplaceInstUsesWith(I, Op0);
2705         }
2706       }
2707     }
2708     
2709     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2710       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2711           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2712         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2713         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2714                                                      Op1, "tmp");
2715         InsertNewInstBefore(Add, I);
2716         Value *C1C2 = Context->getConstantExprMul(Op1, 
2717                                            cast<Constant>(Op0I->getOperand(1)));
2718         return BinaryOperator::CreateAdd(Add, C1C2);
2719         
2720       }
2721
2722     // Try to fold constant mul into select arguments.
2723     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2724       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2725         return R;
2726
2727     if (isa<PHINode>(Op0))
2728       if (Instruction *NV = FoldOpIntoPhi(I))
2729         return NV;
2730   }
2731
2732   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2733     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2734       return BinaryOperator::CreateMul(Op0v, Op1v);
2735
2736   // (X / Y) *  Y = X - (X % Y)
2737   // (X / Y) * -Y = (X % Y) - X
2738   {
2739     Value *Op1 = I.getOperand(1);
2740     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2741     if (!BO ||
2742         (BO->getOpcode() != Instruction::UDiv && 
2743          BO->getOpcode() != Instruction::SDiv)) {
2744       Op1 = Op0;
2745       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2746     }
2747     Value *Neg = dyn_castNegVal(Op1, Context);
2748     if (BO && BO->hasOneUse() &&
2749         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2750         (BO->getOpcode() == Instruction::UDiv ||
2751          BO->getOpcode() == Instruction::SDiv)) {
2752       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2753
2754       Instruction *Rem;
2755       if (BO->getOpcode() == Instruction::UDiv)
2756         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2757       else
2758         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2759
2760       InsertNewInstBefore(Rem, I);
2761       Rem->takeName(BO);
2762
2763       if (Op1BO == Op1)
2764         return BinaryOperator::CreateSub(Op0BO, Rem);
2765       else
2766         return BinaryOperator::CreateSub(Rem, Op0BO);
2767     }
2768   }
2769
2770   if (I.getType() == Type::Int1Ty)
2771     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2772
2773   // If one of the operands of the multiply is a cast from a boolean value, then
2774   // we know the bool is either zero or one, so this is a 'masking' multiply.
2775   // See if we can simplify things based on how the boolean was originally
2776   // formed.
2777   CastInst *BoolCast = 0;
2778   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2779     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2780       BoolCast = CI;
2781   if (!BoolCast)
2782     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2783       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2784         BoolCast = CI;
2785   if (BoolCast) {
2786     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2787       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2788       const Type *SCOpTy = SCIOp0->getType();
2789       bool TIS = false;
2790       
2791       // If the icmp is true iff the sign bit of X is set, then convert this
2792       // multiply into a shift/and combination.
2793       if (isa<ConstantInt>(SCIOp1) &&
2794           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2795           TIS) {
2796         // Shift the X value right to turn it into "all signbits".
2797         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2798                                           SCOpTy->getPrimitiveSizeInBits()-1);
2799         Value *V =
2800           InsertNewInstBefore(
2801             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2802                                             BoolCast->getOperand(0)->getName()+
2803                                             ".mask"), I);
2804
2805         // If the multiply type is not the same as the source type, sign extend
2806         // or truncate to the multiply type.
2807         if (I.getType() != V->getType()) {
2808           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2809           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2810           Instruction::CastOps opcode = 
2811             (SrcBits == DstBits ? Instruction::BitCast : 
2812              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2813           V = InsertCastBefore(opcode, V, I.getType(), I);
2814         }
2815
2816         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2817         return BinaryOperator::CreateAnd(V, OtherOp);
2818       }
2819     }
2820   }
2821
2822   return Changed ? &I : 0;
2823 }
2824
2825 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2826   bool Changed = SimplifyCommutative(I);
2827   Value *Op0 = I.getOperand(0);
2828
2829   // Simplify mul instructions with a constant RHS...
2830   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2831     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2832       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2833       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2834       if (Op1F->isExactlyValue(1.0))
2835         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2836     } else if (isa<VectorType>(Op1->getType())) {
2837       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2838         // As above, vector X*splat(1.0) -> X in all defined cases.
2839         if (Constant *Splat = Op1V->getSplatValue()) {
2840           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2841             if (F->isExactlyValue(1.0))
2842               return ReplaceInstUsesWith(I, Op0);
2843         }
2844       }
2845     }
2846
2847     // Try to fold constant mul into select arguments.
2848     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2849       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2850         return R;
2851
2852     if (isa<PHINode>(Op0))
2853       if (Instruction *NV = FoldOpIntoPhi(I))
2854         return NV;
2855   }
2856
2857   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2858     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2859       return BinaryOperator::CreateFMul(Op0v, Op1v);
2860
2861   return Changed ? &I : 0;
2862 }
2863
2864 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2865 /// instruction.
2866 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2867   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2868   
2869   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2870   int NonNullOperand = -1;
2871   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2872     if (ST->isNullValue())
2873       NonNullOperand = 2;
2874   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2875   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2876     if (ST->isNullValue())
2877       NonNullOperand = 1;
2878   
2879   if (NonNullOperand == -1)
2880     return false;
2881   
2882   Value *SelectCond = SI->getOperand(0);
2883   
2884   // Change the div/rem to use 'Y' instead of the select.
2885   I.setOperand(1, SI->getOperand(NonNullOperand));
2886   
2887   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2888   // problem.  However, the select, or the condition of the select may have
2889   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2890   // propagate the known value for the select into other uses of it, and
2891   // propagate a known value of the condition into its other users.
2892   
2893   // If the select and condition only have a single use, don't bother with this,
2894   // early exit.
2895   if (SI->use_empty() && SelectCond->hasOneUse())
2896     return true;
2897   
2898   // Scan the current block backward, looking for other uses of SI.
2899   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2900   
2901   while (BBI != BBFront) {
2902     --BBI;
2903     // If we found a call to a function, we can't assume it will return, so
2904     // information from below it cannot be propagated above it.
2905     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2906       break;
2907     
2908     // Replace uses of the select or its condition with the known values.
2909     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2910          I != E; ++I) {
2911       if (*I == SI) {
2912         *I = SI->getOperand(NonNullOperand);
2913         AddToWorkList(BBI);
2914       } else if (*I == SelectCond) {
2915         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2916                                    Context->getConstantIntFalse();
2917         AddToWorkList(BBI);
2918       }
2919     }
2920     
2921     // If we past the instruction, quit looking for it.
2922     if (&*BBI == SI)
2923       SI = 0;
2924     if (&*BBI == SelectCond)
2925       SelectCond = 0;
2926     
2927     // If we ran out of things to eliminate, break out of the loop.
2928     if (SelectCond == 0 && SI == 0)
2929       break;
2930     
2931   }
2932   return true;
2933 }
2934
2935
2936 /// This function implements the transforms on div instructions that work
2937 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2938 /// used by the visitors to those instructions.
2939 /// @brief Transforms common to all three div instructions
2940 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2941   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2942
2943   // undef / X -> 0        for integer.
2944   // undef / X -> undef    for FP (the undef could be a snan).
2945   if (isa<UndefValue>(Op0)) {
2946     if (Op0->getType()->isFPOrFPVector())
2947       return ReplaceInstUsesWith(I, Op0);
2948     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2949   }
2950
2951   // X / undef -> undef
2952   if (isa<UndefValue>(Op1))
2953     return ReplaceInstUsesWith(I, Op1);
2954
2955   return 0;
2956 }
2957
2958 /// This function implements the transforms common to both integer division
2959 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2960 /// division instructions.
2961 /// @brief Common integer divide transforms
2962 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2963   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
2965   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2966   if (Op0 == Op1) {
2967     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2968       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2969       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2970       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2971     }
2972
2973     Constant *CI = Context->getConstantInt(I.getType(), 1);
2974     return ReplaceInstUsesWith(I, CI);
2975   }
2976   
2977   if (Instruction *Common = commonDivTransforms(I))
2978     return Common;
2979   
2980   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2981   // This does not apply for fdiv.
2982   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2983     return &I;
2984
2985   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2986     // div X, 1 == X
2987     if (RHS->equalsInt(1))
2988       return ReplaceInstUsesWith(I, Op0);
2989
2990     // (X / C1) / C2  -> X / (C1*C2)
2991     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2992       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2993         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2994           if (MultiplyOverflows(RHS, LHSRHS,
2995                                 I.getOpcode()==Instruction::SDiv, Context))
2996             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2997           else 
2998             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2999                                       Context->getConstantExprMul(RHS, LHSRHS));
3000         }
3001
3002     if (!RHS->isZero()) { // avoid X udiv 0
3003       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3004         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3005           return R;
3006       if (isa<PHINode>(Op0))
3007         if (Instruction *NV = FoldOpIntoPhi(I))
3008           return NV;
3009     }
3010   }
3011
3012   // 0 / X == 0, we don't need to preserve faults!
3013   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3014     if (LHS->equalsInt(0))
3015       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3016
3017   // It can't be division by zero, hence it must be division by one.
3018   if (I.getType() == Type::Int1Ty)
3019     return ReplaceInstUsesWith(I, Op0);
3020
3021   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3022     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3023       // div X, 1 == X
3024       if (X->isOne())
3025         return ReplaceInstUsesWith(I, Op0);
3026   }
3027
3028   return 0;
3029 }
3030
3031 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3032   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3033
3034   // Handle the integer div common cases
3035   if (Instruction *Common = commonIDivTransforms(I))
3036     return Common;
3037
3038   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3039     // X udiv C^2 -> X >> C
3040     // Check to see if this is an unsigned division with an exact power of 2,
3041     // if so, convert to a right shift.
3042     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3043       return BinaryOperator::CreateLShr(Op0, 
3044             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3045
3046     // X udiv C, where C >= signbit
3047     if (C->getValue().isNegative()) {
3048       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3049                                                     ICmpInst::ICMP_ULT, Op0, C),
3050                                       I);
3051       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3052                                 Context->getConstantInt(I.getType(), 1));
3053     }
3054   }
3055
3056   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3057   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3058     if (RHSI->getOpcode() == Instruction::Shl &&
3059         isa<ConstantInt>(RHSI->getOperand(0))) {
3060       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3061       if (C1.isPowerOf2()) {
3062         Value *N = RHSI->getOperand(1);
3063         const Type *NTy = N->getType();
3064         if (uint32_t C2 = C1.logBase2()) {
3065           Constant *C2V = Context->getConstantInt(NTy, C2);
3066           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3067         }
3068         return BinaryOperator::CreateLShr(Op0, N);
3069       }
3070     }
3071   }
3072   
3073   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3074   // where C1&C2 are powers of two.
3075   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3076     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3077       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3078         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3079         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3080           // Compute the shift amounts
3081           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3082           // Construct the "on true" case of the select
3083           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3084           Instruction *TSI = BinaryOperator::CreateLShr(
3085                                                  Op0, TC, SI->getName()+".t");
3086           TSI = InsertNewInstBefore(TSI, I);
3087   
3088           // Construct the "on false" case of the select
3089           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3090           Instruction *FSI = BinaryOperator::CreateLShr(
3091                                                  Op0, FC, SI->getName()+".f");
3092           FSI = InsertNewInstBefore(FSI, I);
3093
3094           // construct the select instruction and return it.
3095           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3096         }
3097       }
3098   return 0;
3099 }
3100
3101 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3102   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3103
3104   // Handle the integer div common cases
3105   if (Instruction *Common = commonIDivTransforms(I))
3106     return Common;
3107
3108   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3109     // sdiv X, -1 == -X
3110     if (RHS->isAllOnesValue())
3111       return BinaryOperator::CreateNeg(Op0);
3112   }
3113
3114   // If the sign bits of both operands are zero (i.e. we can prove they are
3115   // unsigned inputs), turn this into a udiv.
3116   if (I.getType()->isInteger()) {
3117     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3118     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3119       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3120       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3121     }
3122   }      
3123   
3124   return 0;
3125 }
3126
3127 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3128   return commonDivTransforms(I);
3129 }
3130
3131 /// This function implements the transforms on rem instructions that work
3132 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3133 /// is used by the visitors to those instructions.
3134 /// @brief Transforms common to all three rem instructions
3135 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3136   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3137
3138   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3139     if (I.getType()->isFPOrFPVector())
3140       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3141     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3142   }
3143   if (isa<UndefValue>(Op1))
3144     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3145
3146   // Handle cases involving: rem X, (select Cond, Y, Z)
3147   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3148     return &I;
3149
3150   return 0;
3151 }
3152
3153 /// This function implements the transforms common to both integer remainder
3154 /// instructions (urem and srem). It is called by the visitors to those integer
3155 /// remainder instructions.
3156 /// @brief Common integer remainder transforms
3157 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3158   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3159
3160   if (Instruction *common = commonRemTransforms(I))
3161     return common;
3162
3163   // 0 % X == 0 for integer, we don't need to preserve faults!
3164   if (Constant *LHS = dyn_cast<Constant>(Op0))
3165     if (LHS->isNullValue())
3166       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3167
3168   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3169     // X % 0 == undef, we don't need to preserve faults!
3170     if (RHS->equalsInt(0))
3171       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3172     
3173     if (RHS->equalsInt(1))  // X % 1 == 0
3174       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3175
3176     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3177       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3178         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3179           return R;
3180       } else if (isa<PHINode>(Op0I)) {
3181         if (Instruction *NV = FoldOpIntoPhi(I))
3182           return NV;
3183       }
3184
3185       // See if we can fold away this rem instruction.
3186       if (SimplifyDemandedInstructionBits(I))
3187         return &I;
3188     }
3189   }
3190
3191   return 0;
3192 }
3193
3194 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3195   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3196
3197   if (Instruction *common = commonIRemTransforms(I))
3198     return common;
3199   
3200   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3201     // X urem C^2 -> X and C
3202     // Check to see if this is an unsigned remainder with an exact power of 2,
3203     // if so, convert to a bitwise and.
3204     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3205       if (C->getValue().isPowerOf2())
3206         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3207   }
3208
3209   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3210     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3211     if (RHSI->getOpcode() == Instruction::Shl &&
3212         isa<ConstantInt>(RHSI->getOperand(0))) {
3213       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3214         Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
3215         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3216                                                                    "tmp"), I);
3217         return BinaryOperator::CreateAnd(Op0, Add);
3218       }
3219     }
3220   }
3221
3222   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3223   // where C1&C2 are powers of two.
3224   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3225     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3226       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3227         // STO == 0 and SFO == 0 handled above.
3228         if ((STO->getValue().isPowerOf2()) && 
3229             (SFO->getValue().isPowerOf2())) {
3230           Value *TrueAnd = InsertNewInstBefore(
3231             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3232                                       SI->getName()+".t"), I);
3233           Value *FalseAnd = InsertNewInstBefore(
3234             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3235                                       SI->getName()+".f"), I);
3236           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3237         }
3238       }
3239   }
3240   
3241   return 0;
3242 }
3243
3244 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3245   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3246
3247   // Handle the integer rem common cases
3248   if (Instruction *common = commonIRemTransforms(I))
3249     return common;
3250   
3251   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3252     if (!isa<Constant>(RHSNeg) ||
3253         (isa<ConstantInt>(RHSNeg) &&
3254          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3255       // X % -Y -> X % Y
3256       AddUsesToWorkList(I);
3257       I.setOperand(1, RHSNeg);
3258       return &I;
3259     }
3260
3261   // If the sign bits of both operands are zero (i.e. we can prove they are
3262   // unsigned inputs), turn this into a urem.
3263   if (I.getType()->isInteger()) {
3264     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3265     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3266       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3267       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3268     }
3269   }
3270
3271   // If it's a constant vector, flip any negative values positive.
3272   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3273     unsigned VWidth = RHSV->getNumOperands();
3274
3275     bool hasNegative = false;
3276     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3277       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3278         if (RHS->getValue().isNegative())
3279           hasNegative = true;
3280
3281     if (hasNegative) {
3282       std::vector<Constant *> Elts(VWidth);
3283       for (unsigned i = 0; i != VWidth; ++i) {
3284         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3285           if (RHS->getValue().isNegative())
3286             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3287           else
3288             Elts[i] = RHS;
3289         }
3290       }
3291
3292       Constant *NewRHSV = Context->getConstantVector(Elts);
3293       if (NewRHSV != RHSV) {
3294         AddUsesToWorkList(I);
3295         I.setOperand(1, NewRHSV);
3296         return &I;
3297       }
3298     }
3299   }
3300
3301   return 0;
3302 }
3303
3304 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3305   return commonRemTransforms(I);
3306 }
3307
3308 // isOneBitSet - Return true if there is exactly one bit set in the specified
3309 // constant.
3310 static bool isOneBitSet(const ConstantInt *CI) {
3311   return CI->getValue().isPowerOf2();
3312 }
3313
3314 // isHighOnes - Return true if the constant is of the form 1+0+.
3315 // This is the same as lowones(~X).
3316 static bool isHighOnes(const ConstantInt *CI) {
3317   return (~CI->getValue() + 1).isPowerOf2();
3318 }
3319
3320 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3321 /// are carefully arranged to allow folding of expressions such as:
3322 ///
3323 ///      (A < B) | (A > B) --> (A != B)
3324 ///
3325 /// Note that this is only valid if the first and second predicates have the
3326 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3327 ///
3328 /// Three bits are used to represent the condition, as follows:
3329 ///   0  A > B
3330 ///   1  A == B
3331 ///   2  A < B
3332 ///
3333 /// <=>  Value  Definition
3334 /// 000     0   Always false
3335 /// 001     1   A >  B
3336 /// 010     2   A == B
3337 /// 011     3   A >= B
3338 /// 100     4   A <  B
3339 /// 101     5   A != B
3340 /// 110     6   A <= B
3341 /// 111     7   Always true
3342 ///  
3343 static unsigned getICmpCode(const ICmpInst *ICI) {
3344   switch (ICI->getPredicate()) {
3345     // False -> 0
3346   case ICmpInst::ICMP_UGT: return 1;  // 001
3347   case ICmpInst::ICMP_SGT: return 1;  // 001
3348   case ICmpInst::ICMP_EQ:  return 2;  // 010
3349   case ICmpInst::ICMP_UGE: return 3;  // 011
3350   case ICmpInst::ICMP_SGE: return 3;  // 011
3351   case ICmpInst::ICMP_ULT: return 4;  // 100
3352   case ICmpInst::ICMP_SLT: return 4;  // 100
3353   case ICmpInst::ICMP_NE:  return 5;  // 101
3354   case ICmpInst::ICMP_ULE: return 6;  // 110
3355   case ICmpInst::ICMP_SLE: return 6;  // 110
3356     // True -> 7
3357   default:
3358     assert(0 && "Invalid ICmp predicate!");
3359     return 0;
3360   }
3361 }
3362
3363 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3364 /// predicate into a three bit mask. It also returns whether it is an ordered
3365 /// predicate by reference.
3366 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3367   isOrdered = false;
3368   switch (CC) {
3369   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3370   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3371   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3372   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3373   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3374   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3375   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3376   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3377   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3378   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3379   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3380   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3381   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3382   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3383     // True -> 7
3384   default:
3385     // Not expecting FCMP_FALSE and FCMP_TRUE;
3386     assert(0 && "Unexpected FCmp predicate!");
3387     return 0;
3388   }
3389 }
3390
3391 /// getICmpValue - This is the complement of getICmpCode, which turns an
3392 /// opcode and two operands into either a constant true or false, or a brand 
3393 /// new ICmp instruction. The sign is passed in to determine which kind
3394 /// of predicate to use in the new icmp instruction.
3395 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3396                            LLVMContext *Context) {
3397   switch (code) {
3398   default: assert(0 && "Illegal ICmp code!");
3399   case  0: return Context->getConstantIntFalse();
3400   case  1: 
3401     if (sign)
3402       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3403     else
3404       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3405   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3406   case  3: 
3407     if (sign)
3408       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3409     else
3410       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3411   case  4: 
3412     if (sign)
3413       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3414     else
3415       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3416   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3417   case  6: 
3418     if (sign)
3419       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3420     else
3421       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3422   case  7: return Context->getConstantIntTrue();
3423   }
3424 }
3425
3426 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3427 /// opcode and two operands into either a FCmp instruction. isordered is passed
3428 /// in to determine which kind of predicate to use in the new fcmp instruction.
3429 static Value *getFCmpValue(bool isordered, unsigned code,
3430                            Value *LHS, Value *RHS, LLVMContext *Context) {
3431   switch (code) {
3432   default: assert(0 && "Illegal FCmp code!");
3433   case  0:
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3438   case  1: 
3439     if (isordered)
3440       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3441     else
3442       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3443   case  2: 
3444     if (isordered)
3445       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3446     else
3447       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3448   case  3: 
3449     if (isordered)
3450       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3451     else
3452       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3453   case  4: 
3454     if (isordered)
3455       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3456     else
3457       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3458   case  5: 
3459     if (isordered)
3460       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3461     else
3462       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3463   case  6: 
3464     if (isordered)
3465       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3466     else
3467       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3468   case  7: return Context->getConstantIntTrue();
3469   }
3470 }
3471
3472 /// PredicatesFoldable - Return true if both predicates match sign or if at
3473 /// least one of them is an equality comparison (which is signless).
3474 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3475   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3476          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3477          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3478 }
3479
3480 namespace { 
3481 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3482 struct FoldICmpLogical {
3483   InstCombiner &IC;
3484   Value *LHS, *RHS;
3485   ICmpInst::Predicate pred;
3486   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3487     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3488       pred(ICI->getPredicate()) {}
3489   bool shouldApply(Value *V) const {
3490     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3491       if (PredicatesFoldable(pred, ICI->getPredicate()))
3492         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3493                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3494     return false;
3495   }
3496   Instruction *apply(Instruction &Log) const {
3497     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3498     if (ICI->getOperand(0) != LHS) {
3499       assert(ICI->getOperand(1) == LHS);
3500       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3501     }
3502
3503     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3504     unsigned LHSCode = getICmpCode(ICI);
3505     unsigned RHSCode = getICmpCode(RHSICI);
3506     unsigned Code;
3507     switch (Log.getOpcode()) {
3508     case Instruction::And: Code = LHSCode & RHSCode; break;
3509     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3510     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3511     default: assert(0 && "Illegal logical opcode!"); return 0;
3512     }
3513
3514     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3515                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3516       
3517     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3518     if (Instruction *I = dyn_cast<Instruction>(RV))
3519       return I;
3520     // Otherwise, it's a constant boolean value...
3521     return IC.ReplaceInstUsesWith(Log, RV);
3522   }
3523 };
3524 } // end anonymous namespace
3525
3526 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3527 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3528 // guaranteed to be a binary operator.
3529 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3530                                     ConstantInt *OpRHS,
3531                                     ConstantInt *AndRHS,
3532                                     BinaryOperator &TheAnd) {
3533   Value *X = Op->getOperand(0);
3534   Constant *Together = 0;
3535   if (!Op->isShift())
3536     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3537
3538   switch (Op->getOpcode()) {
3539   case Instruction::Xor:
3540     if (Op->hasOneUse()) {
3541       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3542       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3543       InsertNewInstBefore(And, TheAnd);
3544       And->takeName(Op);
3545       return BinaryOperator::CreateXor(And, Together);
3546     }
3547     break;
3548   case Instruction::Or:
3549     if (Together == AndRHS) // (X | C) & C --> C
3550       return ReplaceInstUsesWith(TheAnd, AndRHS);
3551
3552     if (Op->hasOneUse() && Together != OpRHS) {
3553       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3554       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3555       InsertNewInstBefore(Or, TheAnd);
3556       Or->takeName(Op);
3557       return BinaryOperator::CreateAnd(Or, AndRHS);
3558     }
3559     break;
3560   case Instruction::Add:
3561     if (Op->hasOneUse()) {
3562       // Adding a one to a single bit bit-field should be turned into an XOR
3563       // of the bit.  First thing to check is to see if this AND is with a
3564       // single bit constant.
3565       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3566
3567       // If there is only one bit set...
3568       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3569         // Ok, at this point, we know that we are masking the result of the
3570         // ADD down to exactly one bit.  If the constant we are adding has
3571         // no bits set below this bit, then we can eliminate the ADD.
3572         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3573
3574         // Check to see if any bits below the one bit set in AndRHSV are set.
3575         if ((AddRHS & (AndRHSV-1)) == 0) {
3576           // If not, the only thing that can effect the output of the AND is
3577           // the bit specified by AndRHSV.  If that bit is set, the effect of
3578           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3579           // no effect.
3580           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3581             TheAnd.setOperand(0, X);
3582             return &TheAnd;
3583           } else {
3584             // Pull the XOR out of the AND.
3585             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3586             InsertNewInstBefore(NewAnd, TheAnd);
3587             NewAnd->takeName(Op);
3588             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3589           }
3590         }
3591       }
3592     }
3593     break;
3594
3595   case Instruction::Shl: {
3596     // We know that the AND will not produce any of the bits shifted in, so if
3597     // the anded constant includes them, clear them now!
3598     //
3599     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3602     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3603
3604     if (CI->getValue() == ShlMask) { 
3605     // Masking out bits that the shift already masks
3606       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3607     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3608       TheAnd.setOperand(1, CI);
3609       return &TheAnd;
3610     }
3611     break;
3612   }
3613   case Instruction::LShr:
3614   {
3615     // We know that the AND will not produce any of the bits shifted in, so if
3616     // the anded constant includes them, clear them now!  This only applies to
3617     // unsigned shifts, because a signed shr may bring in set bits!
3618     //
3619     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3620     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3621     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3622     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3623
3624     if (CI->getValue() == ShrMask) {   
3625     // Masking out bits that the shift already masks.
3626       return ReplaceInstUsesWith(TheAnd, Op);
3627     } else if (CI != AndRHS) {
3628       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3629       return &TheAnd;
3630     }
3631     break;
3632   }
3633   case Instruction::AShr:
3634     // Signed shr.
3635     // See if this is shifting in some sign extension, then masking it out
3636     // with an and.
3637     if (Op->hasOneUse()) {
3638       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3639       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3640       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3641       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3642       if (C == AndRHS) {          // Masking out bits shifted in.
3643         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3644         // Make the argument unsigned.
3645         Value *ShVal = Op->getOperand(0);
3646         ShVal = InsertNewInstBefore(
3647             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3648                                    Op->getName()), TheAnd);
3649         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3650       }
3651     }
3652     break;
3653   }
3654   return 0;
3655 }
3656
3657
3658 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3659 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3660 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3661 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3662 /// insert new instructions.
3663 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3664                                            bool isSigned, bool Inside, 
3665                                            Instruction &IB) {
3666   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3667             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3668          "Lo is not <= Hi in range emission code!");
3669     
3670   if (Inside) {
3671     if (Lo == Hi)  // Trivially false.
3672       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3673
3674     // V >= Min && V < Hi --> V < Hi
3675     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3676       ICmpInst::Predicate pred = (isSigned ? 
3677         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3678       return new ICmpInst(*Context, pred, V, Hi);
3679     }
3680
3681     // Emit V-Lo <u Hi-Lo
3682     Constant *NegLo = Context->getConstantExprNeg(Lo);
3683     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3684     InsertNewInstBefore(Add, IB);
3685     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3686     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3687   }
3688
3689   if (Lo == Hi)  // Trivially true.
3690     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3691
3692   // V < Min || V >= Hi -> V > Hi-1
3693   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3694   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3695     ICmpInst::Predicate pred = (isSigned ? 
3696         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3697     return new ICmpInst(*Context, pred, V, Hi);
3698   }
3699
3700   // Emit V-Lo >u Hi-1-Lo
3701   // Note that Hi has already had one subtracted from it, above.
3702   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3703   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3704   InsertNewInstBefore(Add, IB);
3705   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3706   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3707 }
3708
3709 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3710 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3711 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3712 // not, since all 1s are not contiguous.
3713 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3714   const APInt& V = Val->getValue();
3715   uint32_t BitWidth = Val->getType()->getBitWidth();
3716   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3717
3718   // look for the first zero bit after the run of ones
3719   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3720   // look for the first non-zero bit
3721   ME = V.getActiveBits(); 
3722   return true;
3723 }
3724
3725 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3726 /// where isSub determines whether the operator is a sub.  If we can fold one of
3727 /// the following xforms:
3728 /// 
3729 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3730 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3731 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3732 ///
3733 /// return (A +/- B).
3734 ///
3735 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3736                                         ConstantInt *Mask, bool isSub,
3737                                         Instruction &I) {
3738   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3739   if (!LHSI || LHSI->getNumOperands() != 2 ||
3740       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3741
3742   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3743
3744   switch (LHSI->getOpcode()) {
3745   default: return 0;
3746   case Instruction::And:
3747     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3748       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3749       if ((Mask->getValue().countLeadingZeros() + 
3750            Mask->getValue().countPopulation()) == 
3751           Mask->getValue().getBitWidth())
3752         break;
3753
3754       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3755       // part, we don't need any explicit masks to take them out of A.  If that
3756       // is all N is, ignore it.
3757       uint32_t MB = 0, ME = 0;
3758       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3759         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3760         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3761         if (MaskedValueIsZero(RHS, Mask))
3762           break;
3763       }
3764     }
3765     return 0;
3766   case Instruction::Or:
3767   case Instruction::Xor:
3768     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3769     if ((Mask->getValue().countLeadingZeros() + 
3770          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3771         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3772       break;
3773     return 0;
3774   }
3775   
3776   Instruction *New;
3777   if (isSub)
3778     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3779   else
3780     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3781   return InsertNewInstBefore(New, I);
3782 }
3783
3784 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3785 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3786                                           ICmpInst *LHS, ICmpInst *RHS) {
3787   Value *Val, *Val2;
3788   ConstantInt *LHSCst, *RHSCst;
3789   ICmpInst::Predicate LHSCC, RHSCC;
3790   
3791   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3792   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3793                          m_ConstantInt(LHSCst)), *Context) ||
3794       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3795                          m_ConstantInt(RHSCst)), *Context))
3796     return 0;
3797   
3798   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3799   // where C is a power of 2
3800   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3801       LHSCst->getValue().isPowerOf2()) {
3802     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3803     InsertNewInstBefore(NewOr, I);
3804     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3805   }
3806   
3807   // From here on, we only handle:
3808   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3809   if (Val != Val2) return 0;
3810   
3811   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3812   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3813       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3814       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3815       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3816     return 0;
3817   
3818   // We can't fold (ugt x, C) & (sgt x, C2).
3819   if (!PredicatesFoldable(LHSCC, RHSCC))
3820     return 0;
3821     
3822   // Ensure that the larger constant is on the RHS.
3823   bool ShouldSwap;
3824   if (ICmpInst::isSignedPredicate(LHSCC) ||
3825       (ICmpInst::isEquality(LHSCC) && 
3826        ICmpInst::isSignedPredicate(RHSCC)))
3827     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3828   else
3829     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3830     
3831   if (ShouldSwap) {
3832     std::swap(LHS, RHS);
3833     std::swap(LHSCst, RHSCst);
3834     std::swap(LHSCC, RHSCC);
3835   }
3836
3837   // At this point, we know we have have two icmp instructions
3838   // comparing a value against two constants and and'ing the result
3839   // together.  Because of the above check, we know that we only have
3840   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3841   // (from the FoldICmpLogical check above), that the two constants 
3842   // are not equal and that the larger constant is on the RHS
3843   assert(LHSCst != RHSCst && "Compares not folded above?");
3844
3845   switch (LHSCC) {
3846   default: assert(0 && "Unknown integer condition code!");
3847   case ICmpInst::ICMP_EQ:
3848     switch (RHSCC) {
3849     default: assert(0 && "Unknown integer condition code!");
3850     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3851     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3852     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3853       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3854     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3855     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3856     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3857       return ReplaceInstUsesWith(I, LHS);
3858     }
3859   case ICmpInst::ICMP_NE:
3860     switch (RHSCC) {
3861     default: assert(0 && "Unknown integer condition code!");
3862     case ICmpInst::ICMP_ULT:
3863       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3864         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3865       break;                        // (X != 13 & X u< 15) -> no change
3866     case ICmpInst::ICMP_SLT:
3867       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3868         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3869       break;                        // (X != 13 & X s< 15) -> no change
3870     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3871     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3872     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3873       return ReplaceInstUsesWith(I, RHS);
3874     case ICmpInst::ICMP_NE:
3875       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3876         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3877         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3878                                                      Val->getName()+".off");
3879         InsertNewInstBefore(Add, I);
3880         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3881                             Context->getConstantInt(Add->getType(), 1));
3882       }
3883       break;                        // (X != 13 & X != 15) -> no change
3884     }
3885     break;
3886   case ICmpInst::ICMP_ULT:
3887     switch (RHSCC) {
3888     default: assert(0 && "Unknown integer condition code!");
3889     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3890     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3891       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3892     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3893       break;
3894     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3895     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3896       return ReplaceInstUsesWith(I, LHS);
3897     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3898       break;
3899     }
3900     break;
3901   case ICmpInst::ICMP_SLT:
3902     switch (RHSCC) {
3903     default: assert(0 && "Unknown integer condition code!");
3904     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3905     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3906       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3907     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3908       break;
3909     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3910     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3911       return ReplaceInstUsesWith(I, LHS);
3912     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3913       break;
3914     }
3915     break;
3916   case ICmpInst::ICMP_UGT:
3917     switch (RHSCC) {
3918     default: assert(0 && "Unknown integer condition code!");
3919     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3920     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3921       return ReplaceInstUsesWith(I, RHS);
3922     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3923       break;
3924     case ICmpInst::ICMP_NE:
3925       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3926         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3927       break;                        // (X u> 13 & X != 15) -> no change
3928     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3929       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3930                              RHSCst, false, true, I);
3931     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3932       break;
3933     }
3934     break;
3935   case ICmpInst::ICMP_SGT:
3936     switch (RHSCC) {
3937     default: assert(0 && "Unknown integer condition code!");
3938     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3939     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3940       return ReplaceInstUsesWith(I, RHS);
3941     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3942       break;
3943     case ICmpInst::ICMP_NE:
3944       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3945         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3946       break;                        // (X s> 13 & X != 15) -> no change
3947     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3948       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3949                              RHSCst, true, true, I);
3950     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3951       break;
3952     }
3953     break;
3954   }
3955  
3956   return 0;
3957 }
3958
3959
3960 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3961   bool Changed = SimplifyCommutative(I);
3962   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3963
3964   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3965     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3966
3967   // and X, X = X
3968   if (Op0 == Op1)
3969     return ReplaceInstUsesWith(I, Op1);
3970
3971   // See if we can simplify any instructions used by the instruction whose sole 
3972   // purpose is to compute bits we don't care about.
3973   if (SimplifyDemandedInstructionBits(I))
3974     return &I;
3975   if (isa<VectorType>(I.getType())) {
3976     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3977       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3978         return ReplaceInstUsesWith(I, I.getOperand(0));
3979     } else if (isa<ConstantAggregateZero>(Op1)) {
3980       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3981     }
3982   }
3983
3984   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3985     const APInt& AndRHSMask = AndRHS->getValue();
3986     APInt NotAndRHS(~AndRHSMask);
3987
3988     // Optimize a variety of ((val OP C1) & C2) combinations...
3989     if (isa<BinaryOperator>(Op0)) {
3990       Instruction *Op0I = cast<Instruction>(Op0);
3991       Value *Op0LHS = Op0I->getOperand(0);
3992       Value *Op0RHS = Op0I->getOperand(1);
3993       switch (Op0I->getOpcode()) {
3994       case Instruction::Xor:
3995       case Instruction::Or:
3996         // If the mask is only needed on one incoming arm, push it up.
3997         if (Op0I->hasOneUse()) {
3998           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3999             // Not masking anything out for the LHS, move to RHS.
4000             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4001                                                    Op0RHS->getName()+".masked");
4002             InsertNewInstBefore(NewRHS, I);
4003             return BinaryOperator::Create(
4004                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4005           }
4006           if (!isa<Constant>(Op0RHS) &&
4007               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4008             // Not masking anything out for the RHS, move to LHS.
4009             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4010                                                    Op0LHS->getName()+".masked");
4011             InsertNewInstBefore(NewLHS, I);
4012             return BinaryOperator::Create(
4013                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4014           }
4015         }
4016
4017         break;
4018       case Instruction::Add:
4019         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4020         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4021         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4022         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4023           return BinaryOperator::CreateAnd(V, AndRHS);
4024         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4025           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4026         break;
4027
4028       case Instruction::Sub:
4029         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4030         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4031         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4032         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4033           return BinaryOperator::CreateAnd(V, AndRHS);
4034
4035         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4036         // has 1's for all bits that the subtraction with A might affect.
4037         if (Op0I->hasOneUse()) {
4038           uint32_t BitWidth = AndRHSMask.getBitWidth();
4039           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4040           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4041
4042           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4043           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4044               MaskedValueIsZero(Op0LHS, Mask)) {
4045             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4046             InsertNewInstBefore(NewNeg, I);
4047             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4048           }
4049         }
4050         break;
4051
4052       case Instruction::Shl:
4053       case Instruction::LShr:
4054         // (1 << x) & 1 --> zext(x == 0)
4055         // (1 >> x) & 1 --> zext(x == 0)
4056         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4057           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4058                                     Op0RHS, Context->getNullValue(I.getType()));
4059           InsertNewInstBefore(NewICmp, I);
4060           return new ZExtInst(NewICmp, I.getType());
4061         }
4062         break;
4063       }
4064
4065       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4066         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4067           return Res;
4068     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4069       // If this is an integer truncation or change from signed-to-unsigned, and
4070       // if the source is an and/or with immediate, transform it.  This
4071       // frequently occurs for bitfield accesses.
4072       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4073         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4074             CastOp->getNumOperands() == 2)
4075           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4076             if (CastOp->getOpcode() == Instruction::And) {
4077               // Change: and (cast (and X, C1) to T), C2
4078               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4079               // This will fold the two constants together, which may allow 
4080               // other simplifications.
4081               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4082                 CastOp->getOperand(0), I.getType(), 
4083                 CastOp->getName()+".shrunk");
4084               NewCast = InsertNewInstBefore(NewCast, I);
4085               // trunc_or_bitcast(C1)&C2
4086               Constant *C3 =
4087                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4088               C3 = Context->getConstantExprAnd(C3, AndRHS);
4089               return BinaryOperator::CreateAnd(NewCast, C3);
4090             } else if (CastOp->getOpcode() == Instruction::Or) {
4091               // Change: and (cast (or X, C1) to T), C2
4092               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4093               Constant *C3 =
4094                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4095               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4096                 // trunc(C1)&C2
4097                 return ReplaceInstUsesWith(I, AndRHS);
4098             }
4099           }
4100       }
4101     }
4102
4103     // Try to fold constant and into select arguments.
4104     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4105       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4106         return R;
4107     if (isa<PHINode>(Op0))
4108       if (Instruction *NV = FoldOpIntoPhi(I))
4109         return NV;
4110   }
4111
4112   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4113   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4114
4115   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4116     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4117
4118   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4119   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4120     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4121                                                I.getName()+".demorgan");
4122     InsertNewInstBefore(Or, I);
4123     return BinaryOperator::CreateNot(Or);
4124   }
4125   
4126   {
4127     Value *A = 0, *B = 0, *C = 0, *D = 0;
4128     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4129       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4130         return ReplaceInstUsesWith(I, Op1);
4131     
4132       // (A|B) & ~(A&B) -> A^B
4133       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4134         if ((A == C && B == D) || (A == D && B == C))
4135           return BinaryOperator::CreateXor(A, B);
4136       }
4137     }
4138     
4139     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4140       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4141         return ReplaceInstUsesWith(I, Op0);
4142
4143       // ~(A&B) & (A|B) -> A^B
4144       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4145         if ((A == C && B == D) || (A == D && B == C))
4146           return BinaryOperator::CreateXor(A, B);
4147       }
4148     }
4149     
4150     if (Op0->hasOneUse() &&
4151         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4152       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4153         I.swapOperands();     // Simplify below
4154         std::swap(Op0, Op1);
4155       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4156         cast<BinaryOperator>(Op0)->swapOperands();
4157         I.swapOperands();     // Simplify below
4158         std::swap(Op0, Op1);
4159       }
4160     }
4161
4162     if (Op1->hasOneUse() &&
4163         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4164       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4165         cast<BinaryOperator>(Op1)->swapOperands();
4166         std::swap(A, B);
4167       }
4168       if (A == Op0) {                                // A&(A^B) -> A & ~B
4169         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4170         InsertNewInstBefore(NotB, I);
4171         return BinaryOperator::CreateAnd(A, NotB);
4172       }
4173     }
4174
4175     // (A&((~A)|B)) -> A&B
4176     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4177         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4178       return BinaryOperator::CreateAnd(A, Op1);
4179     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4180         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4181       return BinaryOperator::CreateAnd(A, Op0);
4182   }
4183   
4184   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4185     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4186     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4187       return R;
4188
4189     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4190       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4191         return Res;
4192   }
4193
4194   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4195   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4196     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4197       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4198         const Type *SrcTy = Op0C->getOperand(0)->getType();
4199         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4200             // Only do this if the casts both really cause code to be generated.
4201             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4202                               I.getType(), TD) &&
4203             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4204                               I.getType(), TD)) {
4205           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4206                                                          Op1C->getOperand(0),
4207                                                          I.getName());
4208           InsertNewInstBefore(NewOp, I);
4209           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4210         }
4211       }
4212     
4213   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4214   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4215     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4216       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4217           SI0->getOperand(1) == SI1->getOperand(1) &&
4218           (SI0->hasOneUse() || SI1->hasOneUse())) {
4219         Instruction *NewOp =
4220           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4221                                                         SI1->getOperand(0),
4222                                                         SI0->getName()), I);
4223         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4224                                       SI1->getOperand(1));
4225       }
4226   }
4227
4228   // If and'ing two fcmp, try combine them into one.
4229   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4230     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4231       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4232           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4233         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4234         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4235           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4236             // If either of the constants are nans, then the whole thing returns
4237             // false.
4238             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4239               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4240             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4241                                 LHS->getOperand(0), RHS->getOperand(0));
4242           }
4243       } else {
4244         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4245         FCmpInst::Predicate Op0CC, Op1CC;
4246         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4247                   m_Value(Op0RHS)), *Context) &&
4248             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4249                   m_Value(Op1RHS)), *Context)) {
4250           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4251             // Swap RHS operands to match LHS.
4252             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4253             std::swap(Op1LHS, Op1RHS);
4254           }
4255           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4256             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4257             if (Op0CC == Op1CC)
4258               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4259                                   Op0LHS, Op0RHS);
4260             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4261                      Op1CC == FCmpInst::FCMP_FALSE)
4262               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4263             else if (Op0CC == FCmpInst::FCMP_TRUE)
4264               return ReplaceInstUsesWith(I, Op1);
4265             else if (Op1CC == FCmpInst::FCMP_TRUE)
4266               return ReplaceInstUsesWith(I, Op0);
4267             bool Op0Ordered;
4268             bool Op1Ordered;
4269             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4270             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4271             if (Op1Pred == 0) {
4272               std::swap(Op0, Op1);
4273               std::swap(Op0Pred, Op1Pred);
4274               std::swap(Op0Ordered, Op1Ordered);
4275             }
4276             if (Op0Pred == 0) {
4277               // uno && ueq -> uno && (uno || eq) -> ueq
4278               // ord && olt -> ord && (ord && lt) -> olt
4279               if (Op0Ordered == Op1Ordered)
4280                 return ReplaceInstUsesWith(I, Op1);
4281               // uno && oeq -> uno && (ord && eq) -> false
4282               // uno && ord -> false
4283               if (!Op0Ordered)
4284                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4285               // ord && ueq -> ord && (uno || eq) -> oeq
4286               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4287                                                     Op0LHS, Op0RHS, Context));
4288             }
4289           }
4290         }
4291       }
4292     }
4293   }
4294
4295   return Changed ? &I : 0;
4296 }
4297
4298 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4299 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4300 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4301 /// the expression came from the corresponding "byte swapped" byte in some other
4302 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4303 /// we know that the expression deposits the low byte of %X into the high byte
4304 /// of the bswap result and that all other bytes are zero.  This expression is
4305 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4306 /// match.
4307 ///
4308 /// This function returns true if the match was unsuccessful and false if so.
4309 /// On entry to the function the "OverallLeftShift" is a signed integer value
4310 /// indicating the number of bytes that the subexpression is later shifted.  For
4311 /// example, if the expression is later right shifted by 16 bits, the
4312 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4313 /// byte of ByteValues is actually being set.
4314 ///
4315 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4316 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4317 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4318 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4319 /// always in the local (OverallLeftShift) coordinate space.
4320 ///
4321 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4322                               SmallVector<Value*, 8> &ByteValues) {
4323   if (Instruction *I = dyn_cast<Instruction>(V)) {
4324     // If this is an or instruction, it may be an inner node of the bswap.
4325     if (I->getOpcode() == Instruction::Or) {
4326       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4327                                ByteValues) ||
4328              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4329                                ByteValues);
4330     }
4331   
4332     // If this is a logical shift by a constant multiple of 8, recurse with
4333     // OverallLeftShift and ByteMask adjusted.
4334     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4335       unsigned ShAmt = 
4336         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4337       // Ensure the shift amount is defined and of a byte value.
4338       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4339         return true;
4340
4341       unsigned ByteShift = ShAmt >> 3;
4342       if (I->getOpcode() == Instruction::Shl) {
4343         // X << 2 -> collect(X, +2)
4344         OverallLeftShift += ByteShift;
4345         ByteMask >>= ByteShift;
4346       } else {
4347         // X >>u 2 -> collect(X, -2)
4348         OverallLeftShift -= ByteShift;
4349         ByteMask <<= ByteShift;
4350         ByteMask &= (~0U >> (32-ByteValues.size()));
4351       }
4352
4353       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4354       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4355
4356       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4357                                ByteValues);
4358     }
4359
4360     // If this is a logical 'and' with a mask that clears bytes, clear the
4361     // corresponding bytes in ByteMask.
4362     if (I->getOpcode() == Instruction::And &&
4363         isa<ConstantInt>(I->getOperand(1))) {
4364       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4365       unsigned NumBytes = ByteValues.size();
4366       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4367       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4368       
4369       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4370         // If this byte is masked out by a later operation, we don't care what
4371         // the and mask is.
4372         if ((ByteMask & (1 << i)) == 0)
4373           continue;
4374         
4375         // If the AndMask is all zeros for this byte, clear the bit.
4376         APInt MaskB = AndMask & Byte;
4377         if (MaskB == 0) {
4378           ByteMask &= ~(1U << i);
4379           continue;
4380         }
4381         
4382         // If the AndMask is not all ones for this byte, it's not a bytezap.
4383         if (MaskB != Byte)
4384           return true;
4385
4386         // Otherwise, this byte is kept.
4387       }
4388
4389       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4390                                ByteValues);
4391     }
4392   }
4393   
4394   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4395   // the input value to the bswap.  Some observations: 1) if more than one byte
4396   // is demanded from this input, then it could not be successfully assembled
4397   // into a byteswap.  At least one of the two bytes would not be aligned with
4398   // their ultimate destination.
4399   if (!isPowerOf2_32(ByteMask)) return true;
4400   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4401   
4402   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4403   // is demanded, it needs to go into byte 0 of the result.  This means that the
4404   // byte needs to be shifted until it lands in the right byte bucket.  The
4405   // shift amount depends on the position: if the byte is coming from the high
4406   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4407   // low part, it must be shifted left.
4408   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4409   if (InputByteNo < ByteValues.size()/2) {
4410     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411       return true;
4412   } else {
4413     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4414       return true;
4415   }
4416   
4417   // If the destination byte value is already defined, the values are or'd
4418   // together, which isn't a bswap (unless it's an or of the same bits).
4419   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4420     return true;
4421   ByteValues[DestByteNo] = V;
4422   return false;
4423 }
4424
4425 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4426 /// If so, insert the new bswap intrinsic and return it.
4427 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4428   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4429   if (!ITy || ITy->getBitWidth() % 16 || 
4430       // ByteMask only allows up to 32-byte values.
4431       ITy->getBitWidth() > 32*8) 
4432     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4433   
4434   /// ByteValues - For each byte of the result, we keep track of which value
4435   /// defines each byte.
4436   SmallVector<Value*, 8> ByteValues;
4437   ByteValues.resize(ITy->getBitWidth()/8);
4438     
4439   // Try to find all the pieces corresponding to the bswap.
4440   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4441   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4442     return 0;
4443   
4444   // Check to see if all of the bytes come from the same value.
4445   Value *V = ByteValues[0];
4446   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4447   
4448   // Check to make sure that all of the bytes come from the same value.
4449   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4450     if (ByteValues[i] != V)
4451       return 0;
4452   const Type *Tys[] = { ITy };
4453   Module *M = I.getParent()->getParent()->getParent();
4454   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4455   return CallInst::Create(F, V);
4456 }
4457
4458 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4459 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4460 /// we can simplify this expression to "cond ? C : D or B".
4461 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4462                                          Value *C, Value *D,
4463                                          LLVMContext *Context) {
4464   // If A is not a select of -1/0, this cannot match.
4465   Value *Cond = 0;
4466   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4467     return 0;
4468
4469   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4470   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4471     return SelectInst::Create(Cond, C, B);
4472   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4473     return SelectInst::Create(Cond, C, B);
4474   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4475   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4476     return SelectInst::Create(Cond, C, D);
4477   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4478     return SelectInst::Create(Cond, C, D);
4479   return 0;
4480 }
4481
4482 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4483 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4484                                          ICmpInst *LHS, ICmpInst *RHS) {
4485   Value *Val, *Val2;
4486   ConstantInt *LHSCst, *RHSCst;
4487   ICmpInst::Predicate LHSCC, RHSCC;
4488   
4489   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4490   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4491              m_ConstantInt(LHSCst)), *Context) ||
4492       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4493              m_ConstantInt(RHSCst)), *Context))
4494     return 0;
4495   
4496   // From here on, we only handle:
4497   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4498   if (Val != Val2) return 0;
4499   
4500   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4501   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4502       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4503       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4504       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4505     return 0;
4506   
4507   // We can't fold (ugt x, C) | (sgt x, C2).
4508   if (!PredicatesFoldable(LHSCC, RHSCC))
4509     return 0;
4510   
4511   // Ensure that the larger constant is on the RHS.
4512   bool ShouldSwap;
4513   if (ICmpInst::isSignedPredicate(LHSCC) ||
4514       (ICmpInst::isEquality(LHSCC) && 
4515        ICmpInst::isSignedPredicate(RHSCC)))
4516     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4517   else
4518     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4519   
4520   if (ShouldSwap) {
4521     std::swap(LHS, RHS);
4522     std::swap(LHSCst, RHSCst);
4523     std::swap(LHSCC, RHSCC);
4524   }
4525   
4526   // At this point, we know we have have two icmp instructions
4527   // comparing a value against two constants and or'ing the result
4528   // together.  Because of the above check, we know that we only have
4529   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4530   // FoldICmpLogical check above), that the two constants are not
4531   // equal.
4532   assert(LHSCst != RHSCst && "Compares not folded above?");
4533
4534   switch (LHSCC) {
4535   default: assert(0 && "Unknown integer condition code!");
4536   case ICmpInst::ICMP_EQ:
4537     switch (RHSCC) {
4538     default: assert(0 && "Unknown integer condition code!");
4539     case ICmpInst::ICMP_EQ:
4540       if (LHSCst == SubOne(RHSCst, Context)) {
4541         // (X == 13 | X == 14) -> X-13 <u 2
4542         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4543         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4544                                                      Val->getName()+".off");
4545         InsertNewInstBefore(Add, I);
4546         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4547         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4548       }
4549       break;                         // (X == 13 | X == 15) -> no change
4550     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4551     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4552       break;
4553     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4554     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4555     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4556       return ReplaceInstUsesWith(I, RHS);
4557     }
4558     break;
4559   case ICmpInst::ICMP_NE:
4560     switch (RHSCC) {
4561     default: assert(0 && "Unknown integer condition code!");
4562     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4563     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4564     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4565       return ReplaceInstUsesWith(I, LHS);
4566     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4567     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4568     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4569       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4570     }
4571     break;
4572   case ICmpInst::ICMP_ULT:
4573     switch (RHSCC) {
4574     default: assert(0 && "Unknown integer condition code!");
4575     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4576       break;
4577     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4578       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4579       // this can cause overflow.
4580       if (RHSCst->isMaxValue(false))
4581         return ReplaceInstUsesWith(I, LHS);
4582       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4583                              false, false, I);
4584     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4585       break;
4586     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4587     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4588       return ReplaceInstUsesWith(I, RHS);
4589     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4590       break;
4591     }
4592     break;
4593   case ICmpInst::ICMP_SLT:
4594     switch (RHSCC) {
4595     default: assert(0 && "Unknown integer condition code!");
4596     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4597       break;
4598     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4599       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4600       // this can cause overflow.
4601       if (RHSCst->isMaxValue(true))
4602         return ReplaceInstUsesWith(I, LHS);
4603       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4604                              true, false, I);
4605     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4606       break;
4607     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4608     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4609       return ReplaceInstUsesWith(I, RHS);
4610     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4611       break;
4612     }
4613     break;
4614   case ICmpInst::ICMP_UGT:
4615     switch (RHSCC) {
4616     default: assert(0 && "Unknown integer condition code!");
4617     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4618     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4619       return ReplaceInstUsesWith(I, LHS);
4620     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4621       break;
4622     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4623     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4624       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4625     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4626       break;
4627     }
4628     break;
4629   case ICmpInst::ICMP_SGT:
4630     switch (RHSCC) {
4631     default: assert(0 && "Unknown integer condition code!");
4632     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4633     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4634       return ReplaceInstUsesWith(I, LHS);
4635     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4636       break;
4637     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4638     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4639       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4640     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4641       break;
4642     }
4643     break;
4644   }
4645   return 0;
4646 }
4647
4648 /// FoldOrWithConstants - This helper function folds:
4649 ///
4650 ///     ((A | B) & C1) | (B & C2)
4651 ///
4652 /// into:
4653 /// 
4654 ///     (A & C1) | B
4655 ///
4656 /// when the XOR of the two constants is "all ones" (-1).
4657 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4658                                                Value *A, Value *B, Value *C) {
4659   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4660   if (!CI1) return 0;
4661
4662   Value *V1 = 0;
4663   ConstantInt *CI2 = 0;
4664   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4665
4666   APInt Xor = CI1->getValue() ^ CI2->getValue();
4667   if (!Xor.isAllOnesValue()) return 0;
4668
4669   if (V1 == A || V1 == B) {
4670     Instruction *NewOp =
4671       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4672     return BinaryOperator::CreateOr(NewOp, V1);
4673   }
4674
4675   return 0;
4676 }
4677
4678 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4679   bool Changed = SimplifyCommutative(I);
4680   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4681
4682   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4683     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4684
4685   // or X, X = X
4686   if (Op0 == Op1)
4687     return ReplaceInstUsesWith(I, Op0);
4688
4689   // See if we can simplify any instructions used by the instruction whose sole 
4690   // purpose is to compute bits we don't care about.
4691   if (SimplifyDemandedInstructionBits(I))
4692     return &I;
4693   if (isa<VectorType>(I.getType())) {
4694     if (isa<ConstantAggregateZero>(Op1)) {
4695       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4696     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4697       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4698         return ReplaceInstUsesWith(I, I.getOperand(1));
4699     }
4700   }
4701
4702   // or X, -1 == -1
4703   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4704     ConstantInt *C1 = 0; Value *X = 0;
4705     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4706     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4707         isOnlyUse(Op0)) {
4708       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4709       InsertNewInstBefore(Or, I);
4710       Or->takeName(Op0);
4711       return BinaryOperator::CreateAnd(Or, 
4712                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4713     }
4714
4715     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4716     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4717         isOnlyUse(Op0)) {
4718       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4719       InsertNewInstBefore(Or, I);
4720       Or->takeName(Op0);
4721       return BinaryOperator::CreateXor(Or,
4722                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4723     }
4724
4725     // Try to fold constant and into select arguments.
4726     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4727       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4728         return R;
4729     if (isa<PHINode>(Op0))
4730       if (Instruction *NV = FoldOpIntoPhi(I))
4731         return NV;
4732   }
4733
4734   Value *A = 0, *B = 0;
4735   ConstantInt *C1 = 0, *C2 = 0;
4736
4737   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4738     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4739       return ReplaceInstUsesWith(I, Op1);
4740   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4741     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4742       return ReplaceInstUsesWith(I, Op0);
4743
4744   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4745   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4746   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4747       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4748       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4749        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4750     if (Instruction *BSwap = MatchBSwap(I))
4751       return BSwap;
4752   }
4753   
4754   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4755   if (Op0->hasOneUse() &&
4756       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4757       MaskedValueIsZero(Op1, C1->getValue())) {
4758     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4759     InsertNewInstBefore(NOr, I);
4760     NOr->takeName(Op0);
4761     return BinaryOperator::CreateXor(NOr, C1);
4762   }
4763
4764   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4765   if (Op1->hasOneUse() &&
4766       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4767       MaskedValueIsZero(Op0, C1->getValue())) {
4768     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4769     InsertNewInstBefore(NOr, I);
4770     NOr->takeName(Op0);
4771     return BinaryOperator::CreateXor(NOr, C1);
4772   }
4773
4774   // (A & C)|(B & D)
4775   Value *C = 0, *D = 0;
4776   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4777       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4778     Value *V1 = 0, *V2 = 0, *V3 = 0;
4779     C1 = dyn_cast<ConstantInt>(C);
4780     C2 = dyn_cast<ConstantInt>(D);
4781     if (C1 && C2) {  // (A & C1)|(B & C2)
4782       // If we have: ((V + N) & C1) | (V & C2)
4783       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4784       // replace with V+N.
4785       if (C1->getValue() == ~C2->getValue()) {
4786         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4787             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4788           // Add commutes, try both ways.
4789           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4790             return ReplaceInstUsesWith(I, A);
4791           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4792             return ReplaceInstUsesWith(I, A);
4793         }
4794         // Or commutes, try both ways.
4795         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4796             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4797           // Add commutes, try both ways.
4798           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4799             return ReplaceInstUsesWith(I, B);
4800           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4801             return ReplaceInstUsesWith(I, B);
4802         }
4803       }
4804       V1 = 0; V2 = 0; V3 = 0;
4805     }
4806     
4807     // Check to see if we have any common things being and'ed.  If so, find the
4808     // terms for V1 & (V2|V3).
4809     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4810       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4811         V1 = A, V2 = C, V3 = D;
4812       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4813         V1 = A, V2 = B, V3 = C;
4814       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4815         V1 = C, V2 = A, V3 = D;
4816       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4817         V1 = C, V2 = A, V3 = B;
4818       
4819       if (V1) {
4820         Value *Or =
4821           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4822         return BinaryOperator::CreateAnd(V1, Or);
4823       }
4824     }
4825
4826     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4827     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4828       return Match;
4829     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4830       return Match;
4831     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4832       return Match;
4833     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4834       return Match;
4835
4836     // ((A&~B)|(~A&B)) -> A^B
4837     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4838          match(B, m_Not(m_Specific(A)), *Context)))
4839       return BinaryOperator::CreateXor(A, D);
4840     // ((~B&A)|(~A&B)) -> A^B
4841     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4842          match(B, m_Not(m_Specific(C)), *Context)))
4843       return BinaryOperator::CreateXor(C, D);
4844     // ((A&~B)|(B&~A)) -> A^B
4845     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4846          match(D, m_Not(m_Specific(A)), *Context)))
4847       return BinaryOperator::CreateXor(A, B);
4848     // ((~B&A)|(B&~A)) -> A^B
4849     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4850          match(D, m_Not(m_Specific(C)), *Context)))
4851       return BinaryOperator::CreateXor(C, B);
4852   }
4853   
4854   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4855   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4856     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4857       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4858           SI0->getOperand(1) == SI1->getOperand(1) &&
4859           (SI0->hasOneUse() || SI1->hasOneUse())) {
4860         Instruction *NewOp =
4861         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4862                                                      SI1->getOperand(0),
4863                                                      SI0->getName()), I);
4864         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4865                                       SI1->getOperand(1));
4866       }
4867   }
4868
4869   // ((A|B)&1)|(B&-2) -> (A&1) | B
4870   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4871       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4872     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4873     if (Ret) return Ret;
4874   }
4875   // (B&-2)|((A|B)&1) -> (A&1) | B
4876   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4877       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4878     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4879     if (Ret) return Ret;
4880   }
4881
4882   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4883     if (A == Op1)   // ~A | A == -1
4884       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4885   } else {
4886     A = 0;
4887   }
4888   // Note, A is still live here!
4889   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4890     if (Op0 == B)
4891       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4892
4893     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4894     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4895       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4896                                               I.getName()+".demorgan"), I);
4897       return BinaryOperator::CreateNot(And);
4898     }
4899   }
4900
4901   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4902   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4903     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4904       return R;
4905
4906     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4907       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4908         return Res;
4909   }
4910     
4911   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4912   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4913     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4914       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4915         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4916             !isa<ICmpInst>(Op1C->getOperand(0))) {
4917           const Type *SrcTy = Op0C->getOperand(0)->getType();
4918           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4919               // Only do this if the casts both really cause code to be
4920               // generated.
4921               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4922                                 I.getType(), TD) &&
4923               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4924                                 I.getType(), TD)) {
4925             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4926                                                           Op1C->getOperand(0),
4927                                                           I.getName());
4928             InsertNewInstBefore(NewOp, I);
4929             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4930           }
4931         }
4932       }
4933   }
4934   
4935     
4936   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4937   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4938     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4939       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4940           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4941           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4942         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4943           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4944             // If either of the constants are nans, then the whole thing returns
4945             // true.
4946             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4947               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4948             
4949             // Otherwise, no need to compare the two constants, compare the
4950             // rest.
4951             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4952                                 LHS->getOperand(0), RHS->getOperand(0));
4953           }
4954       } else {
4955         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4956         FCmpInst::Predicate Op0CC, Op1CC;
4957         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4958                   m_Value(Op0RHS)), *Context) &&
4959             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4960                   m_Value(Op1RHS)), *Context)) {
4961           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4962             // Swap RHS operands to match LHS.
4963             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4964             std::swap(Op1LHS, Op1RHS);
4965           }
4966           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4967             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4968             if (Op0CC == Op1CC)
4969               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4970                                   Op0LHS, Op0RHS);
4971             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4972                      Op1CC == FCmpInst::FCMP_TRUE)
4973               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4974             else if (Op0CC == FCmpInst::FCMP_FALSE)
4975               return ReplaceInstUsesWith(I, Op1);
4976             else if (Op1CC == FCmpInst::FCMP_FALSE)
4977               return ReplaceInstUsesWith(I, Op0);
4978             bool Op0Ordered;
4979             bool Op1Ordered;
4980             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4981             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4982             if (Op0Ordered == Op1Ordered) {
4983               // If both are ordered or unordered, return a new fcmp with
4984               // or'ed predicates.
4985               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4986                                        Op0LHS, Op0RHS, Context);
4987               if (Instruction *I = dyn_cast<Instruction>(RV))
4988                 return I;
4989               // Otherwise, it's a constant boolean value...
4990               return ReplaceInstUsesWith(I, RV);
4991             }
4992           }
4993         }
4994       }
4995     }
4996   }
4997
4998   return Changed ? &I : 0;
4999 }
5000
5001 namespace {
5002
5003 // XorSelf - Implements: X ^ X --> 0
5004 struct XorSelf {
5005   Value *RHS;
5006   XorSelf(Value *rhs) : RHS(rhs) {}
5007   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5008   Instruction *apply(BinaryOperator &Xor) const {
5009     return &Xor;
5010   }
5011 };
5012
5013 }
5014
5015 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5016   bool Changed = SimplifyCommutative(I);
5017   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5018
5019   if (isa<UndefValue>(Op1)) {
5020     if (isa<UndefValue>(Op0))
5021       // Handle undef ^ undef -> 0 special case. This is a common
5022       // idiom (misuse).
5023       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5024     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5025   }
5026
5027   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5028   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5029     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5030     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5031   }
5032   
5033   // See if we can simplify any instructions used by the instruction whose sole 
5034   // purpose is to compute bits we don't care about.
5035   if (SimplifyDemandedInstructionBits(I))
5036     return &I;
5037   if (isa<VectorType>(I.getType()))
5038     if (isa<ConstantAggregateZero>(Op1))
5039       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5040
5041   // Is this a ~ operation?
5042   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5043     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5044     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5045     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5046       if (Op0I->getOpcode() == Instruction::And || 
5047           Op0I->getOpcode() == Instruction::Or) {
5048         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5049         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5050           Instruction *NotY =
5051             BinaryOperator::CreateNot(Op0I->getOperand(1),
5052                                       Op0I->getOperand(1)->getName()+".not");
5053           InsertNewInstBefore(NotY, I);
5054           if (Op0I->getOpcode() == Instruction::And)
5055             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5056           else
5057             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5058         }
5059       }
5060     }
5061   }
5062   
5063   
5064   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5065     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5066       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5067       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5068         return new ICmpInst(*Context, ICI->getInversePredicate(),
5069                             ICI->getOperand(0), ICI->getOperand(1));
5070
5071       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5072         return new FCmpInst(*Context, FCI->getInversePredicate(),
5073                             FCI->getOperand(0), FCI->getOperand(1));
5074     }
5075
5076     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5077     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5078       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5079         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5080           Instruction::CastOps Opcode = Op0C->getOpcode();
5081           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5082             if (RHS == Context->getConstantExprCast(Opcode, 
5083                                              Context->getConstantIntTrue(),
5084                                              Op0C->getDestTy())) {
5085               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5086                                      *Context,
5087                                      CI->getOpcode(), CI->getInversePredicate(),
5088                                      CI->getOperand(0), CI->getOperand(1)), I);
5089               NewCI->takeName(CI);
5090               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5091             }
5092           }
5093         }
5094       }
5095     }
5096
5097     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5098       // ~(c-X) == X-c-1 == X+(-c-1)
5099       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5100         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5101           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5102           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5103                                       Context->getConstantInt(I.getType(), 1));
5104           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5105         }
5106           
5107       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5108         if (Op0I->getOpcode() == Instruction::Add) {
5109           // ~(X-c) --> (-c-1)-X
5110           if (RHS->isAllOnesValue()) {
5111             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5112             return BinaryOperator::CreateSub(
5113                            Context->getConstantExprSub(NegOp0CI,
5114                                       Context->getConstantInt(I.getType(), 1)),
5115                                       Op0I->getOperand(0));
5116           } else if (RHS->getValue().isSignBit()) {
5117             // (X + C) ^ signbit -> (X + C + signbit)
5118             Constant *C =
5119                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5120             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5121
5122           }
5123         } else if (Op0I->getOpcode() == Instruction::Or) {
5124           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5125           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5126             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5127             // Anything in both C1 and C2 is known to be zero, remove it from
5128             // NewRHS.
5129             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5130             NewRHS = Context->getConstantExprAnd(NewRHS, 
5131                                        Context->getConstantExprNot(CommonBits));
5132             AddToWorkList(Op0I);
5133             I.setOperand(0, Op0I->getOperand(0));
5134             I.setOperand(1, NewRHS);
5135             return &I;
5136           }
5137         }
5138       }
5139     }
5140
5141     // Try to fold constant and into select arguments.
5142     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5143       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5144         return R;
5145     if (isa<PHINode>(Op0))
5146       if (Instruction *NV = FoldOpIntoPhi(I))
5147         return NV;
5148   }
5149
5150   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5151     if (X == Op1)
5152       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5153
5154   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5155     if (X == Op0)
5156       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5157
5158   
5159   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5160   if (Op1I) {
5161     Value *A, *B;
5162     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5163       if (A == Op0) {              // B^(B|A) == (A|B)^B
5164         Op1I->swapOperands();
5165         I.swapOperands();
5166         std::swap(Op0, Op1);
5167       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5168         I.swapOperands();     // Simplified below.
5169         std::swap(Op0, Op1);
5170       }
5171     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5172       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5173     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5174       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5175     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5176                Op1I->hasOneUse()){
5177       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5178         Op1I->swapOperands();
5179         std::swap(A, B);
5180       }
5181       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5182         I.swapOperands();     // Simplified below.
5183         std::swap(Op0, Op1);
5184       }
5185     }
5186   }
5187   
5188   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5189   if (Op0I) {
5190     Value *A, *B;
5191     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5192         Op0I->hasOneUse()) {
5193       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5194         std::swap(A, B);
5195       if (B == Op1) {                                // (A|B)^B == A & ~B
5196         Instruction *NotB =
5197           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5198         return BinaryOperator::CreateAnd(A, NotB);
5199       }
5200     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5201       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5202     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5203       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5204     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5205                Op0I->hasOneUse()){
5206       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5207         std::swap(A, B);
5208       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5209           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5210         Instruction *N =
5211           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5212         return BinaryOperator::CreateAnd(N, Op1);
5213       }
5214     }
5215   }
5216   
5217   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5218   if (Op0I && Op1I && Op0I->isShift() && 
5219       Op0I->getOpcode() == Op1I->getOpcode() && 
5220       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5221       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5222     Instruction *NewOp =
5223       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5224                                                     Op1I->getOperand(0),
5225                                                     Op0I->getName()), I);
5226     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5227                                   Op1I->getOperand(1));
5228   }
5229     
5230   if (Op0I && Op1I) {
5231     Value *A, *B, *C, *D;
5232     // (A & B)^(A | B) -> A ^ B
5233     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5234         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5235       if ((A == C && B == D) || (A == D && B == C)) 
5236         return BinaryOperator::CreateXor(A, B);
5237     }
5238     // (A | B)^(A & B) -> A ^ B
5239     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5240         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5241       if ((A == C && B == D) || (A == D && B == C)) 
5242         return BinaryOperator::CreateXor(A, B);
5243     }
5244     
5245     // (A & B)^(C & D)
5246     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5247         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5248         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5249       // (X & Y)^(X & Y) -> (Y^Z) & X
5250       Value *X = 0, *Y = 0, *Z = 0;
5251       if (A == C)
5252         X = A, Y = B, Z = D;
5253       else if (A == D)
5254         X = A, Y = B, Z = C;
5255       else if (B == C)
5256         X = B, Y = A, Z = D;
5257       else if (B == D)
5258         X = B, Y = A, Z = C;
5259       
5260       if (X) {
5261         Instruction *NewOp =
5262         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5263         return BinaryOperator::CreateAnd(NewOp, X);
5264       }
5265     }
5266   }
5267     
5268   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5269   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5270     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5271       return R;
5272
5273   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5274   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5275     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5276       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5277         const Type *SrcTy = Op0C->getOperand(0)->getType();
5278         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5279             // Only do this if the casts both really cause code to be generated.
5280             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5281                               I.getType(), TD) &&
5282             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5283                               I.getType(), TD)) {
5284           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5285                                                          Op1C->getOperand(0),
5286                                                          I.getName());
5287           InsertNewInstBefore(NewOp, I);
5288           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5289         }
5290       }
5291   }
5292
5293   return Changed ? &I : 0;
5294 }
5295
5296 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5297                                    LLVMContext *Context) {
5298   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5299 }
5300
5301 static bool HasAddOverflow(ConstantInt *Result,
5302                            ConstantInt *In1, ConstantInt *In2,
5303                            bool IsSigned) {
5304   if (IsSigned)
5305     if (In2->getValue().isNegative())
5306       return Result->getValue().sgt(In1->getValue());
5307     else
5308       return Result->getValue().slt(In1->getValue());
5309   else
5310     return Result->getValue().ult(In1->getValue());
5311 }
5312
5313 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5314 /// overflowed for this type.
5315 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5316                             Constant *In2, LLVMContext *Context,
5317                             bool IsSigned = false) {
5318   Result = Context->getConstantExprAdd(In1, In2);
5319
5320   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5321     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5322       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5323       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5324                          ExtractElement(In1, Idx, Context),
5325                          ExtractElement(In2, Idx, Context),
5326                          IsSigned))
5327         return true;
5328     }
5329     return false;
5330   }
5331
5332   return HasAddOverflow(cast<ConstantInt>(Result),
5333                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5334                         IsSigned);
5335 }
5336
5337 static bool HasSubOverflow(ConstantInt *Result,
5338                            ConstantInt *In1, ConstantInt *In2,
5339                            bool IsSigned) {
5340   if (IsSigned)
5341     if (In2->getValue().isNegative())
5342       return Result->getValue().slt(In1->getValue());
5343     else
5344       return Result->getValue().sgt(In1->getValue());
5345   else
5346     return Result->getValue().ugt(In1->getValue());
5347 }
5348
5349 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5350 /// overflowed for this type.
5351 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5352                             Constant *In2, LLVMContext *Context,
5353                             bool IsSigned = false) {
5354   Result = Context->getConstantExprSub(In1, In2);
5355
5356   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5357     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5358       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5359       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5360                          ExtractElement(In1, Idx, Context),
5361                          ExtractElement(In2, Idx, Context),
5362                          IsSigned))
5363         return true;
5364     }
5365     return false;
5366   }
5367
5368   return HasSubOverflow(cast<ConstantInt>(Result),
5369                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5370                         IsSigned);
5371 }
5372
5373 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5374 /// code necessary to compute the offset from the base pointer (without adding
5375 /// in the base pointer).  Return the result as a signed integer of intptr size.
5376 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5377   TargetData &TD = IC.getTargetData();
5378   gep_type_iterator GTI = gep_type_begin(GEP);
5379   const Type *IntPtrTy = TD.getIntPtrType();
5380   LLVMContext *Context = IC.getContext();
5381   Value *Result = Context->getNullValue(IntPtrTy);
5382
5383   // Build a mask for high order bits.
5384   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5385   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5386
5387   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5388        ++i, ++GTI) {
5389     Value *Op = *i;
5390     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5391     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5392       if (OpC->isZero()) continue;
5393       
5394       // Handle a struct index, which adds its field offset to the pointer.
5395       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5396         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5397         
5398         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5399           Result = 
5400              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5401         else
5402           Result = IC.InsertNewInstBefore(
5403                    BinaryOperator::CreateAdd(Result,
5404                                         Context->getConstantInt(IntPtrTy, Size),
5405                                              GEP->getName()+".offs"), I);
5406         continue;
5407       }
5408       
5409       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5410       Constant *OC =
5411               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5412       Scale = Context->getConstantExprMul(OC, Scale);
5413       if (Constant *RC = dyn_cast<Constant>(Result))
5414         Result = Context->getConstantExprAdd(RC, Scale);
5415       else {
5416         // Emit an add instruction.
5417         Result = IC.InsertNewInstBefore(
5418            BinaryOperator::CreateAdd(Result, Scale,
5419                                      GEP->getName()+".offs"), I);
5420       }
5421       continue;
5422     }
5423     // Convert to correct type.
5424     if (Op->getType() != IntPtrTy) {
5425       if (Constant *OpC = dyn_cast<Constant>(Op))
5426         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5427       else
5428         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5429                                                                 true,
5430                                                       Op->getName()+".c"), I);
5431     }
5432     if (Size != 1) {
5433       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5434       if (Constant *OpC = dyn_cast<Constant>(Op))
5435         Op = Context->getConstantExprMul(OpC, Scale);
5436       else    // We'll let instcombine(mul) convert this to a shl if possible.
5437         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5438                                                   GEP->getName()+".idx"), I);
5439     }
5440
5441     // Emit an add instruction.
5442     if (isa<Constant>(Op) && isa<Constant>(Result))
5443       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5444                                     cast<Constant>(Result));
5445     else
5446       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5447                                                   GEP->getName()+".offs"), I);
5448   }
5449   return Result;
5450 }
5451
5452
5453 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5454 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5455 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5456 /// complex, and scales are involved.  The above expression would also be legal
5457 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5458 /// later form is less amenable to optimization though, and we are allowed to
5459 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5460 ///
5461 /// If we can't emit an optimized form for this expression, this returns null.
5462 /// 
5463 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5464                                           InstCombiner &IC) {
5465   TargetData &TD = IC.getTargetData();
5466   gep_type_iterator GTI = gep_type_begin(GEP);
5467
5468   // Check to see if this gep only has a single variable index.  If so, and if
5469   // any constant indices are a multiple of its scale, then we can compute this
5470   // in terms of the scale of the variable index.  For example, if the GEP
5471   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5472   // because the expression will cross zero at the same point.
5473   unsigned i, e = GEP->getNumOperands();
5474   int64_t Offset = 0;
5475   for (i = 1; i != e; ++i, ++GTI) {
5476     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5477       // Compute the aggregate offset of constant indices.
5478       if (CI->isZero()) continue;
5479
5480       // Handle a struct index, which adds its field offset to the pointer.
5481       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5482         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5483       } else {
5484         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5485         Offset += Size*CI->getSExtValue();
5486       }
5487     } else {
5488       // Found our variable index.
5489       break;
5490     }
5491   }
5492   
5493   // If there are no variable indices, we must have a constant offset, just
5494   // evaluate it the general way.
5495   if (i == e) return 0;
5496   
5497   Value *VariableIdx = GEP->getOperand(i);
5498   // Determine the scale factor of the variable element.  For example, this is
5499   // 4 if the variable index is into an array of i32.
5500   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5501   
5502   // Verify that there are no other variable indices.  If so, emit the hard way.
5503   for (++i, ++GTI; i != e; ++i, ++GTI) {
5504     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5505     if (!CI) return 0;
5506    
5507     // Compute the aggregate offset of constant indices.
5508     if (CI->isZero()) continue;
5509     
5510     // Handle a struct index, which adds its field offset to the pointer.
5511     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5512       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5513     } else {
5514       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5515       Offset += Size*CI->getSExtValue();
5516     }
5517   }
5518   
5519   // Okay, we know we have a single variable index, which must be a
5520   // pointer/array/vector index.  If there is no offset, life is simple, return
5521   // the index.
5522   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5523   if (Offset == 0) {
5524     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5525     // we don't need to bother extending: the extension won't affect where the
5526     // computation crosses zero.
5527     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5528       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5529                                   VariableIdx->getNameStart(), &I);
5530     return VariableIdx;
5531   }
5532   
5533   // Otherwise, there is an index.  The computation we will do will be modulo
5534   // the pointer size, so get it.
5535   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5536   
5537   Offset &= PtrSizeMask;
5538   VariableScale &= PtrSizeMask;
5539
5540   // To do this transformation, any constant index must be a multiple of the
5541   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5542   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5543   // multiple of the variable scale.
5544   int64_t NewOffs = Offset / (int64_t)VariableScale;
5545   if (Offset != NewOffs*(int64_t)VariableScale)
5546     return 0;
5547
5548   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5549   const Type *IntPtrTy = TD.getIntPtrType();
5550   if (VariableIdx->getType() != IntPtrTy)
5551     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5552                                               true /*SExt*/, 
5553                                               VariableIdx->getNameStart(), &I);
5554   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5555   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5556 }
5557
5558
5559 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5560 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5561 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5562                                        ICmpInst::Predicate Cond,
5563                                        Instruction &I) {
5564   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5565
5566   // Look through bitcasts.
5567   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5568     RHS = BCI->getOperand(0);
5569
5570   Value *PtrBase = GEPLHS->getOperand(0);
5571   if (PtrBase == RHS) {
5572     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5573     // This transformation (ignoring the base and scales) is valid because we
5574     // know pointers can't overflow.  See if we can output an optimized form.
5575     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5576     
5577     // If not, synthesize the offset the hard way.
5578     if (Offset == 0)
5579       Offset = EmitGEPOffset(GEPLHS, I, *this);
5580     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5581                         Context->getNullValue(Offset->getType()));
5582   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5583     // If the base pointers are different, but the indices are the same, just
5584     // compare the base pointer.
5585     if (PtrBase != GEPRHS->getOperand(0)) {
5586       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5587       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5588                         GEPRHS->getOperand(0)->getType();
5589       if (IndicesTheSame)
5590         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5592             IndicesTheSame = false;
5593             break;
5594           }
5595
5596       // If all indices are the same, just compare the base pointers.
5597       if (IndicesTheSame)
5598         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5599                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5600
5601       // Otherwise, the base pointers are different and the indices are
5602       // different, bail out.
5603       return 0;
5604     }
5605
5606     // If one of the GEPs has all zero indices, recurse.
5607     bool AllZeros = true;
5608     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5609       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5610           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5611         AllZeros = false;
5612         break;
5613       }
5614     if (AllZeros)
5615       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5616                           ICmpInst::getSwappedPredicate(Cond), I);
5617
5618     // If the other GEP has all zero indices, recurse.
5619     AllZeros = true;
5620     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5621       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5622           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5623         AllZeros = false;
5624         break;
5625       }
5626     if (AllZeros)
5627       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5628
5629     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5630       // If the GEPs only differ by one index, compare it.
5631       unsigned NumDifferences = 0;  // Keep track of # differences.
5632       unsigned DiffOperand = 0;     // The operand that differs.
5633       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5635           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5636                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5637             // Irreconcilable differences.
5638             NumDifferences = 2;
5639             break;
5640           } else {
5641             if (NumDifferences++) break;
5642             DiffOperand = i;
5643           }
5644         }
5645
5646       if (NumDifferences == 0)   // SAME GEP?
5647         return ReplaceInstUsesWith(I, // No comparison is needed here.
5648                                    Context->getConstantInt(Type::Int1Ty,
5649                                              ICmpInst::isTrueWhenEqual(Cond)));
5650
5651       else if (NumDifferences == 1) {
5652         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5653         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5654         // Make sure we do a signed comparison here.
5655         return new ICmpInst(*Context,
5656                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5657       }
5658     }
5659
5660     // Only lower this if the icmp is the only user of the GEP or if we expect
5661     // the result to fold to a constant!
5662     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5663         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5664       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5665       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5666       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5667       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5668     }
5669   }
5670   return 0;
5671 }
5672
5673 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5674 ///
5675 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5676                                                 Instruction *LHSI,
5677                                                 Constant *RHSC) {
5678   if (!isa<ConstantFP>(RHSC)) return 0;
5679   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5680   
5681   // Get the width of the mantissa.  We don't want to hack on conversions that
5682   // might lose information from the integer, e.g. "i64 -> float"
5683   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5684   if (MantissaWidth == -1) return 0;  // Unknown.
5685   
5686   // Check to see that the input is converted from an integer type that is small
5687   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5688   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5689   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5690   
5691   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5692   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5693   if (LHSUnsigned)
5694     ++InputSize;
5695   
5696   // If the conversion would lose info, don't hack on this.
5697   if ((int)InputSize > MantissaWidth)
5698     return 0;
5699   
5700   // Otherwise, we can potentially simplify the comparison.  We know that it
5701   // will always come through as an integer value and we know the constant is
5702   // not a NAN (it would have been previously simplified).
5703   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5704   
5705   ICmpInst::Predicate Pred;
5706   switch (I.getPredicate()) {
5707   default: assert(0 && "Unexpected predicate!");
5708   case FCmpInst::FCMP_UEQ:
5709   case FCmpInst::FCMP_OEQ:
5710     Pred = ICmpInst::ICMP_EQ;
5711     break;
5712   case FCmpInst::FCMP_UGT:
5713   case FCmpInst::FCMP_OGT:
5714     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5715     break;
5716   case FCmpInst::FCMP_UGE:
5717   case FCmpInst::FCMP_OGE:
5718     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5719     break;
5720   case FCmpInst::FCMP_ULT:
5721   case FCmpInst::FCMP_OLT:
5722     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5723     break;
5724   case FCmpInst::FCMP_ULE:
5725   case FCmpInst::FCMP_OLE:
5726     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5727     break;
5728   case FCmpInst::FCMP_UNE:
5729   case FCmpInst::FCMP_ONE:
5730     Pred = ICmpInst::ICMP_NE;
5731     break;
5732   case FCmpInst::FCMP_ORD:
5733     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5734   case FCmpInst::FCMP_UNO:
5735     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5736   }
5737   
5738   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5739   
5740   // Now we know that the APFloat is a normal number, zero or inf.
5741   
5742   // See if the FP constant is too large for the integer.  For example,
5743   // comparing an i8 to 300.0.
5744   unsigned IntWidth = IntTy->getScalarSizeInBits();
5745   
5746   if (!LHSUnsigned) {
5747     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5748     // and large values.
5749     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5750     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5751                           APFloat::rmNearestTiesToEven);
5752     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5753       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5754           Pred == ICmpInst::ICMP_SLE)
5755         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5756       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5757     }
5758   } else {
5759     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5760     // +INF and large values.
5761     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5762     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5763                           APFloat::rmNearestTiesToEven);
5764     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5765       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5766           Pred == ICmpInst::ICMP_ULE)
5767         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5768       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5769     }
5770   }
5771   
5772   if (!LHSUnsigned) {
5773     // See if the RHS value is < SignedMin.
5774     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5775     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5776                           APFloat::rmNearestTiesToEven);
5777     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5778       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5779           Pred == ICmpInst::ICMP_SGE)
5780         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5781       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5782     }
5783   }
5784
5785   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5786   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5787   // casting the FP value to the integer value and back, checking for equality.
5788   // Don't do this for zero, because -0.0 is not fractional.
5789   Constant *RHSInt = LHSUnsigned
5790     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5791     : Context->getConstantExprFPToSI(RHSC, IntTy);
5792   if (!RHS.isZero()) {
5793     bool Equal = LHSUnsigned
5794       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5795       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5796     if (!Equal) {
5797       // If we had a comparison against a fractional value, we have to adjust
5798       // the compare predicate and sometimes the value.  RHSC is rounded towards
5799       // zero at this point.
5800       switch (Pred) {
5801       default: assert(0 && "Unexpected integer comparison!");
5802       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5803         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5804       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5805         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5806       case ICmpInst::ICMP_ULE:
5807         // (float)int <= 4.4   --> int <= 4
5808         // (float)int <= -4.4  --> false
5809         if (RHS.isNegative())
5810           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5811         break;
5812       case ICmpInst::ICMP_SLE:
5813         // (float)int <= 4.4   --> int <= 4
5814         // (float)int <= -4.4  --> int < -4
5815         if (RHS.isNegative())
5816           Pred = ICmpInst::ICMP_SLT;
5817         break;
5818       case ICmpInst::ICMP_ULT:
5819         // (float)int < -4.4   --> false
5820         // (float)int < 4.4    --> int <= 4
5821         if (RHS.isNegative())
5822           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5823         Pred = ICmpInst::ICMP_ULE;
5824         break;
5825       case ICmpInst::ICMP_SLT:
5826         // (float)int < -4.4   --> int < -4
5827         // (float)int < 4.4    --> int <= 4
5828         if (!RHS.isNegative())
5829           Pred = ICmpInst::ICMP_SLE;
5830         break;
5831       case ICmpInst::ICMP_UGT:
5832         // (float)int > 4.4    --> int > 4
5833         // (float)int > -4.4   --> true
5834         if (RHS.isNegative())
5835           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5836         break;
5837       case ICmpInst::ICMP_SGT:
5838         // (float)int > 4.4    --> int > 4
5839         // (float)int > -4.4   --> int >= -4
5840         if (RHS.isNegative())
5841           Pred = ICmpInst::ICMP_SGE;
5842         break;
5843       case ICmpInst::ICMP_UGE:
5844         // (float)int >= -4.4   --> true
5845         // (float)int >= 4.4    --> int > 4
5846         if (!RHS.isNegative())
5847           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5848         Pred = ICmpInst::ICMP_UGT;
5849         break;
5850       case ICmpInst::ICMP_SGE:
5851         // (float)int >= -4.4   --> int >= -4
5852         // (float)int >= 4.4    --> int > 4
5853         if (!RHS.isNegative())
5854           Pred = ICmpInst::ICMP_SGT;
5855         break;
5856       }
5857     }
5858   }
5859
5860   // Lower this FP comparison into an appropriate integer version of the
5861   // comparison.
5862   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5863 }
5864
5865 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5866   bool Changed = SimplifyCompare(I);
5867   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5868
5869   // Fold trivial predicates.
5870   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5871     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5872   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5873     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5874   
5875   // Simplify 'fcmp pred X, X'
5876   if (Op0 == Op1) {
5877     switch (I.getPredicate()) {
5878     default: assert(0 && "Unknown predicate!");
5879     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5880     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5881     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5882       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5883     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5884     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5885     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5886       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5887       
5888     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5889     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5890     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5891     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5892       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5893       I.setPredicate(FCmpInst::FCMP_UNO);
5894       I.setOperand(1, Context->getNullValue(Op0->getType()));
5895       return &I;
5896       
5897     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5898     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5899     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5900     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5901       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5902       I.setPredicate(FCmpInst::FCMP_ORD);
5903       I.setOperand(1, Context->getNullValue(Op0->getType()));
5904       return &I;
5905     }
5906   }
5907     
5908   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5909     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5910
5911   // Handle fcmp with constant RHS
5912   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5913     // If the constant is a nan, see if we can fold the comparison based on it.
5914     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5915       if (CFP->getValueAPF().isNaN()) {
5916         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5917           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5918         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5919                "Comparison must be either ordered or unordered!");
5920         // True if unordered.
5921         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5922       }
5923     }
5924     
5925     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5926       switch (LHSI->getOpcode()) {
5927       case Instruction::PHI:
5928         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5929         // block.  If in the same block, we're encouraging jump threading.  If
5930         // not, we are just pessimizing the code by making an i1 phi.
5931         if (LHSI->getParent() == I.getParent())
5932           if (Instruction *NV = FoldOpIntoPhi(I))
5933             return NV;
5934         break;
5935       case Instruction::SIToFP:
5936       case Instruction::UIToFP:
5937         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5938           return NV;
5939         break;
5940       case Instruction::Select:
5941         // If either operand of the select is a constant, we can fold the
5942         // comparison into the select arms, which will cause one to be
5943         // constant folded and the select turned into a bitwise or.
5944         Value *Op1 = 0, *Op2 = 0;
5945         if (LHSI->hasOneUse()) {
5946           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5947             // Fold the known value into the constant operand.
5948             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5949             // Insert a new FCmp of the other select operand.
5950             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5951                                                       LHSI->getOperand(2), RHSC,
5952                                                       I.getName()), I);
5953           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5954             // Fold the known value into the constant operand.
5955             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5956             // Insert a new FCmp of the other select operand.
5957             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5958                                                       LHSI->getOperand(1), RHSC,
5959                                                       I.getName()), I);
5960           }
5961         }
5962
5963         if (Op1)
5964           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5965         break;
5966       }
5967   }
5968
5969   return Changed ? &I : 0;
5970 }
5971
5972 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5973   bool Changed = SimplifyCompare(I);
5974   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5975   const Type *Ty = Op0->getType();
5976
5977   // icmp X, X
5978   if (Op0 == Op1)
5979     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5980                                                    I.isTrueWhenEqual()));
5981
5982   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5983     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5984   
5985   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5986   // addresses never equal each other!  We already know that Op0 != Op1.
5987   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5988        isa<ConstantPointerNull>(Op0)) &&
5989       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5990        isa<ConstantPointerNull>(Op1)))
5991     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5992                                                    !I.isTrueWhenEqual()));
5993
5994   // icmp's with boolean values can always be turned into bitwise operations
5995   if (Ty == Type::Int1Ty) {
5996     switch (I.getPredicate()) {
5997     default: assert(0 && "Invalid icmp instruction!");
5998     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5999       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6000       InsertNewInstBefore(Xor, I);
6001       return BinaryOperator::CreateNot(Xor);
6002     }
6003     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6004       return BinaryOperator::CreateXor(Op0, Op1);
6005
6006     case ICmpInst::ICMP_UGT:
6007       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6008       // FALL THROUGH
6009     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6010       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6011       InsertNewInstBefore(Not, I);
6012       return BinaryOperator::CreateAnd(Not, Op1);
6013     }
6014     case ICmpInst::ICMP_SGT:
6015       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6016       // FALL THROUGH
6017     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6018       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6019       InsertNewInstBefore(Not, I);
6020       return BinaryOperator::CreateAnd(Not, Op0);
6021     }
6022     case ICmpInst::ICMP_UGE:
6023       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6024       // FALL THROUGH
6025     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6026       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6027       InsertNewInstBefore(Not, I);
6028       return BinaryOperator::CreateOr(Not, Op1);
6029     }
6030     case ICmpInst::ICMP_SGE:
6031       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6032       // FALL THROUGH
6033     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6034       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6035       InsertNewInstBefore(Not, I);
6036       return BinaryOperator::CreateOr(Not, Op0);
6037     }
6038     }
6039   }
6040
6041   unsigned BitWidth = 0;
6042   if (TD)
6043     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6044   else if (Ty->isIntOrIntVector())
6045     BitWidth = Ty->getScalarSizeInBits();
6046
6047   bool isSignBit = false;
6048
6049   // See if we are doing a comparison with a constant.
6050   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6051     Value *A = 0, *B = 0;
6052     
6053     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6054     if (I.isEquality() && CI->isNullValue() &&
6055         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6056       // (icmp cond A B) if cond is equality
6057       return new ICmpInst(*Context, I.getPredicate(), A, B);
6058     }
6059     
6060     // If we have an icmp le or icmp ge instruction, turn it into the
6061     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6062     // them being folded in the code below.
6063     switch (I.getPredicate()) {
6064     default: break;
6065     case ICmpInst::ICMP_ULE:
6066       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6067         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6068       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6069                           AddOne(CI, Context));
6070     case ICmpInst::ICMP_SLE:
6071       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6072         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6073       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6074                           AddOne(CI, Context));
6075     case ICmpInst::ICMP_UGE:
6076       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6077         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6078       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6079                           SubOne(CI, Context));
6080     case ICmpInst::ICMP_SGE:
6081       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6082         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6083       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6084                           SubOne(CI, Context));
6085     }
6086     
6087     // If this comparison is a normal comparison, it demands all
6088     // bits, if it is a sign bit comparison, it only demands the sign bit.
6089     bool UnusedBit;
6090     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6091   }
6092
6093   // See if we can fold the comparison based on range information we can get
6094   // by checking whether bits are known to be zero or one in the input.
6095   if (BitWidth != 0) {
6096     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6097     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6098
6099     if (SimplifyDemandedBits(I.getOperandUse(0),
6100                              isSignBit ? APInt::getSignBit(BitWidth)
6101                                        : APInt::getAllOnesValue(BitWidth),
6102                              Op0KnownZero, Op0KnownOne, 0))
6103       return &I;
6104     if (SimplifyDemandedBits(I.getOperandUse(1),
6105                              APInt::getAllOnesValue(BitWidth),
6106                              Op1KnownZero, Op1KnownOne, 0))
6107       return &I;
6108
6109     // Given the known and unknown bits, compute a range that the LHS could be
6110     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6111     // EQ and NE we use unsigned values.
6112     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6113     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6114     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6115       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6116                                              Op0Min, Op0Max);
6117       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118                                              Op1Min, Op1Max);
6119     } else {
6120       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121                                                Op0Min, Op0Max);
6122       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123                                                Op1Min, Op1Max);
6124     }
6125
6126     // If Min and Max are known to be the same, then SimplifyDemandedBits
6127     // figured out that the LHS is a constant.  Just constant fold this now so
6128     // that code below can assume that Min != Max.
6129     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6130       return new ICmpInst(*Context, I.getPredicate(),
6131                           Context->getConstantInt(Op0Min), Op1);
6132     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6133       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6134                           Context->getConstantInt(Op1Min));
6135
6136     // Based on the range information we know about the LHS, see if we can
6137     // simplify this comparison.  For example, (x&4) < 8  is always true.
6138     switch (I.getPredicate()) {
6139     default: assert(0 && "Unknown icmp opcode!");
6140     case ICmpInst::ICMP_EQ:
6141       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6142         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6143       break;
6144     case ICmpInst::ICMP_NE:
6145       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6146         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6147       break;
6148     case ICmpInst::ICMP_ULT:
6149       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6150         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6151       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6152         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6153       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6154         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6155       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6157           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158                               SubOne(CI, Context));
6159
6160         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6161         if (CI->isMinValue(true))
6162           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6163                            Context->getConstantIntAllOnesValue(Op0->getType()));
6164       }
6165       break;
6166     case ICmpInst::ICMP_UGT:
6167       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6168         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6169       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6170         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6171
6172       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6173         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6174       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6176           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177                               AddOne(CI, Context));
6178
6179         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6180         if (CI->isMaxValue(true))
6181           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6182                               Context->getNullValue(Op0->getType()));
6183       }
6184       break;
6185     case ICmpInst::ICMP_SLT:
6186       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6187         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6188       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6189         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6190       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6191         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6192       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6193         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6194           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6195                               SubOne(CI, Context));
6196       }
6197       break;
6198     case ICmpInst::ICMP_SGT:
6199       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6200         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6201       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6202         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6203
6204       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6205         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6206       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6208           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209                               AddOne(CI, Context));
6210       }
6211       break;
6212     case ICmpInst::ICMP_SGE:
6213       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6214       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6215         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6216       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6217         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6218       break;
6219     case ICmpInst::ICMP_SLE:
6220       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6221       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6222         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6223       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6224         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6225       break;
6226     case ICmpInst::ICMP_UGE:
6227       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6228       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6229         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6230       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6231         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6232       break;
6233     case ICmpInst::ICMP_ULE:
6234       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6236         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6237       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6238         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6239       break;
6240     }
6241
6242     // Turn a signed comparison into an unsigned one if both operands
6243     // are known to have the same sign.
6244     if (I.isSignedPredicate() &&
6245         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6246          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6247       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6248   }
6249
6250   // Test if the ICmpInst instruction is used exclusively by a select as
6251   // part of a minimum or maximum operation. If so, refrain from doing
6252   // any other folding. This helps out other analyses which understand
6253   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6254   // and CodeGen. And in this case, at least one of the comparison
6255   // operands has at least one user besides the compare (the select),
6256   // which would often largely negate the benefit of folding anyway.
6257   if (I.hasOneUse())
6258     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6259       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6260           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6261         return 0;
6262
6263   // See if we are doing a comparison between a constant and an instruction that
6264   // can be folded into the comparison.
6265   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6266     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6267     // instruction, see if that instruction also has constants so that the 
6268     // instruction can be folded into the icmp 
6269     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6270       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6271         return Res;
6272   }
6273
6274   // Handle icmp with constant (but not simple integer constant) RHS
6275   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6276     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6277       switch (LHSI->getOpcode()) {
6278       case Instruction::GetElementPtr:
6279         if (RHSC->isNullValue()) {
6280           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6281           bool isAllZeros = true;
6282           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6283             if (!isa<Constant>(LHSI->getOperand(i)) ||
6284                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6285               isAllZeros = false;
6286               break;
6287             }
6288           if (isAllZeros)
6289             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6290                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6291         }
6292         break;
6293
6294       case Instruction::PHI:
6295         // Only fold icmp into the PHI if the phi and fcmp are in the same
6296         // block.  If in the same block, we're encouraging jump threading.  If
6297         // not, we are just pessimizing the code by making an i1 phi.
6298         if (LHSI->getParent() == I.getParent())
6299           if (Instruction *NV = FoldOpIntoPhi(I))
6300             return NV;
6301         break;
6302       case Instruction::Select: {
6303         // If either operand of the select is a constant, we can fold the
6304         // comparison into the select arms, which will cause one to be
6305         // constant folded and the select turned into a bitwise or.
6306         Value *Op1 = 0, *Op2 = 0;
6307         if (LHSI->hasOneUse()) {
6308           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6309             // Fold the known value into the constant operand.
6310             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6311             // Insert a new ICmp of the other select operand.
6312             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6313                                                    LHSI->getOperand(2), RHSC,
6314                                                    I.getName()), I);
6315           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6316             // Fold the known value into the constant operand.
6317             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6318             // Insert a new ICmp of the other select operand.
6319             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6320                                                    LHSI->getOperand(1), RHSC,
6321                                                    I.getName()), I);
6322           }
6323         }
6324
6325         if (Op1)
6326           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6327         break;
6328       }
6329       case Instruction::Malloc:
6330         // If we have (malloc != null), and if the malloc has a single use, we
6331         // can assume it is successful and remove the malloc.
6332         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6333           AddToWorkList(LHSI);
6334           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6335                                                          !I.isTrueWhenEqual()));
6336         }
6337         break;
6338       }
6339   }
6340
6341   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6342   if (User *GEP = dyn_castGetElementPtr(Op0))
6343     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6344       return NI;
6345   if (User *GEP = dyn_castGetElementPtr(Op1))
6346     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6347                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6348       return NI;
6349
6350   // Test to see if the operands of the icmp are casted versions of other
6351   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6352   // now.
6353   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6354     if (isa<PointerType>(Op0->getType()) && 
6355         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6356       // We keep moving the cast from the left operand over to the right
6357       // operand, where it can often be eliminated completely.
6358       Op0 = CI->getOperand(0);
6359
6360       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6361       // so eliminate it as well.
6362       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6363         Op1 = CI2->getOperand(0);
6364
6365       // If Op1 is a constant, we can fold the cast into the constant.
6366       if (Op0->getType() != Op1->getType()) {
6367         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6368           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6369         } else {
6370           // Otherwise, cast the RHS right before the icmp
6371           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6372         }
6373       }
6374       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6375     }
6376   }
6377   
6378   if (isa<CastInst>(Op0)) {
6379     // Handle the special case of: icmp (cast bool to X), <cst>
6380     // This comes up when you have code like
6381     //   int X = A < B;
6382     //   if (X) ...
6383     // For generality, we handle any zero-extension of any operand comparison
6384     // with a constant or another cast from the same type.
6385     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6386       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6387         return R;
6388   }
6389   
6390   // See if it's the same type of instruction on the left and right.
6391   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6392     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6393       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6394           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6395         switch (Op0I->getOpcode()) {
6396         default: break;
6397         case Instruction::Add:
6398         case Instruction::Sub:
6399         case Instruction::Xor:
6400           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6401             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6402                                 Op1I->getOperand(0));
6403           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6404           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6405             if (CI->getValue().isSignBit()) {
6406               ICmpInst::Predicate Pred = I.isSignedPredicate()
6407                                              ? I.getUnsignedPredicate()
6408                                              : I.getSignedPredicate();
6409               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6410                                   Op1I->getOperand(0));
6411             }
6412             
6413             if (CI->getValue().isMaxSignedValue()) {
6414               ICmpInst::Predicate Pred = I.isSignedPredicate()
6415                                              ? I.getUnsignedPredicate()
6416                                              : I.getSignedPredicate();
6417               Pred = I.getSwappedPredicate(Pred);
6418               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6419                                   Op1I->getOperand(0));
6420             }
6421           }
6422           break;
6423         case Instruction::Mul:
6424           if (!I.isEquality())
6425             break;
6426
6427           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6429             // Mask = -1 >> count-trailing-zeros(Cst).
6430             if (!CI->isZero() && !CI->isOne()) {
6431               const APInt &AP = CI->getValue();
6432               ConstantInt *Mask = Context->getConstantInt(
6433                                       APInt::getLowBitsSet(AP.getBitWidth(),
6434                                                            AP.getBitWidth() -
6435                                                       AP.countTrailingZeros()));
6436               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6437                                                             Mask);
6438               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6439                                                             Mask);
6440               InsertNewInstBefore(And1, I);
6441               InsertNewInstBefore(And2, I);
6442               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6443             }
6444           }
6445           break;
6446         }
6447       }
6448     }
6449   }
6450   
6451   // ~x < ~y --> y < x
6452   { Value *A, *B;
6453     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6454         match(Op1, m_Not(m_Value(B)), *Context))
6455       return new ICmpInst(*Context, I.getPredicate(), B, A);
6456   }
6457   
6458   if (I.isEquality()) {
6459     Value *A, *B, *C, *D;
6460     
6461     // -x == -y --> x == y
6462     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6463         match(Op1, m_Neg(m_Value(B)), *Context))
6464       return new ICmpInst(*Context, I.getPredicate(), A, B);
6465     
6466     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6467       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6468         Value *OtherVal = A == Op1 ? B : A;
6469         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6470                             Context->getNullValue(A->getType()));
6471       }
6472
6473       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6474         // A^c1 == C^c2 --> A == C^(c1^c2)
6475         ConstantInt *C1, *C2;
6476         if (match(B, m_ConstantInt(C1), *Context) &&
6477             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6478           Constant *NC = 
6479                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6480           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6481           return new ICmpInst(*Context, I.getPredicate(), A,
6482                               InsertNewInstBefore(Xor, I));
6483         }
6484         
6485         // A^B == A^D -> B == D
6486         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6487         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6488         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6489         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6490       }
6491     }
6492     
6493     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6494         (A == Op0 || B == Op0)) {
6495       // A == (A^B)  ->  B == 0
6496       Value *OtherVal = A == Op0 ? B : A;
6497       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6498                           Context->getNullValue(A->getType()));
6499     }
6500
6501     // (A-B) == A  ->  B == 0
6502     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6503       return new ICmpInst(*Context, I.getPredicate(), B, 
6504                           Context->getNullValue(B->getType()));
6505
6506     // A == (A-B)  ->  B == 0
6507     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6508       return new ICmpInst(*Context, I.getPredicate(), B,
6509                           Context->getNullValue(B->getType()));
6510     
6511     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6512     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6513         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6514         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6515       Value *X = 0, *Y = 0, *Z = 0;
6516       
6517       if (A == C) {
6518         X = B; Y = D; Z = A;
6519       } else if (A == D) {
6520         X = B; Y = C; Z = A;
6521       } else if (B == C) {
6522         X = A; Y = D; Z = B;
6523       } else if (B == D) {
6524         X = A; Y = C; Z = B;
6525       }
6526       
6527       if (X) {   // Build (X^Y) & Z
6528         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6529         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6530         I.setOperand(0, Op1);
6531         I.setOperand(1, Context->getNullValue(Op1->getType()));
6532         return &I;
6533       }
6534     }
6535   }
6536   return Changed ? &I : 0;
6537 }
6538
6539
6540 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6541 /// and CmpRHS are both known to be integer constants.
6542 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6543                                           ConstantInt *DivRHS) {
6544   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6545   const APInt &CmpRHSV = CmpRHS->getValue();
6546   
6547   // FIXME: If the operand types don't match the type of the divide 
6548   // then don't attempt this transform. The code below doesn't have the
6549   // logic to deal with a signed divide and an unsigned compare (and
6550   // vice versa). This is because (x /s C1) <s C2  produces different 
6551   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6552   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6553   // work. :(  The if statement below tests that condition and bails 
6554   // if it finds it. 
6555   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6556   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6557     return 0;
6558   if (DivRHS->isZero())
6559     return 0; // The ProdOV computation fails on divide by zero.
6560   if (DivIsSigned && DivRHS->isAllOnesValue())
6561     return 0; // The overflow computation also screws up here
6562   if (DivRHS->isOne())
6563     return 0; // Not worth bothering, and eliminates some funny cases
6564               // with INT_MIN.
6565
6566   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6567   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6568   // C2 (CI). By solving for X we can turn this into a range check 
6569   // instead of computing a divide. 
6570   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6571
6572   // Determine if the product overflows by seeing if the product is
6573   // not equal to the divide. Make sure we do the same kind of divide
6574   // as in the LHS instruction that we're folding. 
6575   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6576                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6577
6578   // Get the ICmp opcode
6579   ICmpInst::Predicate Pred = ICI.getPredicate();
6580
6581   // Figure out the interval that is being checked.  For example, a comparison
6582   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6583   // Compute this interval based on the constants involved and the signedness of
6584   // the compare/divide.  This computes a half-open interval, keeping track of
6585   // whether either value in the interval overflows.  After analysis each
6586   // overflow variable is set to 0 if it's corresponding bound variable is valid
6587   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6588   int LoOverflow = 0, HiOverflow = 0;
6589   Constant *LoBound = 0, *HiBound = 0;
6590   
6591   if (!DivIsSigned) {  // udiv
6592     // e.g. X/5 op 3  --> [15, 20)
6593     LoBound = Prod;
6594     HiOverflow = LoOverflow = ProdOV;
6595     if (!HiOverflow)
6596       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6597   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6598     if (CmpRHSV == 0) {       // (X / pos) op 0
6599       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6600       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6601                                                                     Context)));
6602       HiBound = DivRHS;
6603     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6604       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6605       HiOverflow = LoOverflow = ProdOV;
6606       if (!HiOverflow)
6607         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6608     } else {                       // (X / pos) op neg
6609       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6610       HiBound = AddOne(Prod, Context);
6611       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6612       if (!LoOverflow) {
6613         ConstantInt* DivNeg =
6614                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6615         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6616                                      true) ? -1 : 0;
6617        }
6618     }
6619   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6620     if (CmpRHSV == 0) {       // (X / neg) op 0
6621       // e.g. X/-5 op 0  --> [-4, 5)
6622       LoBound = AddOne(DivRHS, Context);
6623       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6624       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6625         HiOverflow = 1;            // [INTMIN+1, overflow)
6626         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6627       }
6628     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6629       // e.g. X/-5 op 3  --> [-19, -14)
6630       HiBound = AddOne(Prod, Context);
6631       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6632       if (!LoOverflow)
6633         LoOverflow = AddWithOverflow(LoBound, HiBound,
6634                                      DivRHS, Context, true) ? -1 : 0;
6635     } else {                       // (X / neg) op neg
6636       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6637       LoOverflow = HiOverflow = ProdOV;
6638       if (!HiOverflow)
6639         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6640     }
6641     
6642     // Dividing by a negative swaps the condition.  LT <-> GT
6643     Pred = ICmpInst::getSwappedPredicate(Pred);
6644   }
6645
6646   Value *X = DivI->getOperand(0);
6647   switch (Pred) {
6648   default: assert(0 && "Unhandled icmp opcode!");
6649   case ICmpInst::ICMP_EQ:
6650     if (LoOverflow && HiOverflow)
6651       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6652     else if (HiOverflow)
6653       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6654                           ICmpInst::ICMP_UGE, X, LoBound);
6655     else if (LoOverflow)
6656       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6657                           ICmpInst::ICMP_ULT, X, HiBound);
6658     else
6659       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6660   case ICmpInst::ICMP_NE:
6661     if (LoOverflow && HiOverflow)
6662       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6663     else if (HiOverflow)
6664       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6665                           ICmpInst::ICMP_ULT, X, LoBound);
6666     else if (LoOverflow)
6667       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6668                           ICmpInst::ICMP_UGE, X, HiBound);
6669     else
6670       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6671   case ICmpInst::ICMP_ULT:
6672   case ICmpInst::ICMP_SLT:
6673     if (LoOverflow == +1)   // Low bound is greater than input range.
6674       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6675     if (LoOverflow == -1)   // Low bound is less than input range.
6676       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6677     return new ICmpInst(*Context, Pred, X, LoBound);
6678   case ICmpInst::ICMP_UGT:
6679   case ICmpInst::ICMP_SGT:
6680     if (HiOverflow == +1)       // High bound greater than input range.
6681       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6682     else if (HiOverflow == -1)  // High bound less than input range.
6683       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6684     if (Pred == ICmpInst::ICMP_UGT)
6685       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6686     else
6687       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6688   }
6689 }
6690
6691
6692 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6693 ///
6694 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6695                                                           Instruction *LHSI,
6696                                                           ConstantInt *RHS) {
6697   const APInt &RHSV = RHS->getValue();
6698   
6699   switch (LHSI->getOpcode()) {
6700   case Instruction::Trunc:
6701     if (ICI.isEquality() && LHSI->hasOneUse()) {
6702       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6703       // of the high bits truncated out of x are known.
6704       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6705              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6706       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6707       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6708       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6709       
6710       // If all the high bits are known, we can do this xform.
6711       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6712         // Pull in the high bits from known-ones set.
6713         APInt NewRHS(RHS->getValue());
6714         NewRHS.zext(SrcBits);
6715         NewRHS |= KnownOne;
6716         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6717                             Context->getConstantInt(NewRHS));
6718       }
6719     }
6720     break;
6721       
6722   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6723     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6724       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6725       // fold the xor.
6726       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6727           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6728         Value *CompareVal = LHSI->getOperand(0);
6729         
6730         // If the sign bit of the XorCST is not set, there is no change to
6731         // the operation, just stop using the Xor.
6732         if (!XorCST->getValue().isNegative()) {
6733           ICI.setOperand(0, CompareVal);
6734           AddToWorkList(LHSI);
6735           return &ICI;
6736         }
6737         
6738         // Was the old condition true if the operand is positive?
6739         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6740         
6741         // If so, the new one isn't.
6742         isTrueIfPositive ^= true;
6743         
6744         if (isTrueIfPositive)
6745           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6746                               SubOne(RHS, Context));
6747         else
6748           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6749                               AddOne(RHS, Context));
6750       }
6751
6752       if (LHSI->hasOneUse()) {
6753         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6754         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6755           const APInt &SignBit = XorCST->getValue();
6756           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6757                                          ? ICI.getUnsignedPredicate()
6758                                          : ICI.getSignedPredicate();
6759           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6760                               Context->getConstantInt(RHSV ^ SignBit));
6761         }
6762
6763         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6764         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6765           const APInt &NotSignBit = XorCST->getValue();
6766           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767                                          ? ICI.getUnsignedPredicate()
6768                                          : ICI.getSignedPredicate();
6769           Pred = ICI.getSwappedPredicate(Pred);
6770           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6771                               Context->getConstantInt(RHSV ^ NotSignBit));
6772         }
6773       }
6774     }
6775     break;
6776   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6777     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6778         LHSI->getOperand(0)->hasOneUse()) {
6779       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6780       
6781       // If the LHS is an AND of a truncating cast, we can widen the
6782       // and/compare to be the input width without changing the value
6783       // produced, eliminating a cast.
6784       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6785         // We can do this transformation if either the AND constant does not
6786         // have its sign bit set or if it is an equality comparison. 
6787         // Extending a relational comparison when we're checking the sign
6788         // bit would not work.
6789         if (Cast->hasOneUse() &&
6790             (ICI.isEquality() ||
6791              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6792           uint32_t BitWidth = 
6793             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6794           APInt NewCST = AndCST->getValue();
6795           NewCST.zext(BitWidth);
6796           APInt NewCI = RHSV;
6797           NewCI.zext(BitWidth);
6798           Instruction *NewAnd = 
6799             BinaryOperator::CreateAnd(Cast->getOperand(0),
6800                                Context->getConstantInt(NewCST),LHSI->getName());
6801           InsertNewInstBefore(NewAnd, ICI);
6802           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6803                               Context->getConstantInt(NewCI));
6804         }
6805       }
6806       
6807       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6808       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6809       // happens a LOT in code produced by the C front-end, for bitfield
6810       // access.
6811       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6812       if (Shift && !Shift->isShift())
6813         Shift = 0;
6814       
6815       ConstantInt *ShAmt;
6816       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6817       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6818       const Type *AndTy = AndCST->getType();          // Type of the and.
6819       
6820       // We can fold this as long as we can't shift unknown bits
6821       // into the mask.  This can only happen with signed shift
6822       // rights, as they sign-extend.
6823       if (ShAmt) {
6824         bool CanFold = Shift->isLogicalShift();
6825         if (!CanFold) {
6826           // To test for the bad case of the signed shr, see if any
6827           // of the bits shifted in could be tested after the mask.
6828           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6829           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6830           
6831           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6832           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6833                AndCST->getValue()) == 0)
6834             CanFold = true;
6835         }
6836         
6837         if (CanFold) {
6838           Constant *NewCst;
6839           if (Shift->getOpcode() == Instruction::Shl)
6840             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6841           else
6842             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6843           
6844           // Check to see if we are shifting out any of the bits being
6845           // compared.
6846           if (Context->getConstantExpr(Shift->getOpcode(),
6847                                        NewCst, ShAmt) != RHS) {
6848             // If we shifted bits out, the fold is not going to work out.
6849             // As a special case, check to see if this means that the
6850             // result is always true or false now.
6851             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6852               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6853             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6854               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6855           } else {
6856             ICI.setOperand(1, NewCst);
6857             Constant *NewAndCST;
6858             if (Shift->getOpcode() == Instruction::Shl)
6859               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6860             else
6861               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6862             LHSI->setOperand(1, NewAndCST);
6863             LHSI->setOperand(0, Shift->getOperand(0));
6864             AddToWorkList(Shift); // Shift is dead.
6865             AddUsesToWorkList(ICI);
6866             return &ICI;
6867           }
6868         }
6869       }
6870       
6871       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6872       // preferable because it allows the C<<Y expression to be hoisted out
6873       // of a loop if Y is invariant and X is not.
6874       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6875           ICI.isEquality() && !Shift->isArithmeticShift() &&
6876           !isa<Constant>(Shift->getOperand(0))) {
6877         // Compute C << Y.
6878         Value *NS;
6879         if (Shift->getOpcode() == Instruction::LShr) {
6880           NS = BinaryOperator::CreateShl(AndCST, 
6881                                          Shift->getOperand(1), "tmp");
6882         } else {
6883           // Insert a logical shift.
6884           NS = BinaryOperator::CreateLShr(AndCST,
6885                                           Shift->getOperand(1), "tmp");
6886         }
6887         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6888         
6889         // Compute X & (C << Y).
6890         Instruction *NewAnd = 
6891           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6892         InsertNewInstBefore(NewAnd, ICI);
6893         
6894         ICI.setOperand(0, NewAnd);
6895         return &ICI;
6896       }
6897     }
6898     break;
6899     
6900   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6901     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6902     if (!ShAmt) break;
6903     
6904     uint32_t TypeBits = RHSV.getBitWidth();
6905     
6906     // Check that the shift amount is in range.  If not, don't perform
6907     // undefined shifts.  When the shift is visited it will be
6908     // simplified.
6909     if (ShAmt->uge(TypeBits))
6910       break;
6911     
6912     if (ICI.isEquality()) {
6913       // If we are comparing against bits always shifted out, the
6914       // comparison cannot succeed.
6915       Constant *Comp =
6916         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6917                                                                  ShAmt);
6918       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6919         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6920         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6921         return ReplaceInstUsesWith(ICI, Cst);
6922       }
6923       
6924       if (LHSI->hasOneUse()) {
6925         // Otherwise strength reduce the shift into an and.
6926         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6927         Constant *Mask =
6928           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6929                                                        TypeBits-ShAmtVal));
6930         
6931         Instruction *AndI =
6932           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6933                                     Mask, LHSI->getName()+".mask");
6934         Value *And = InsertNewInstBefore(AndI, ICI);
6935         return new ICmpInst(*Context, ICI.getPredicate(), And,
6936                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6937       }
6938     }
6939     
6940     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6941     bool TrueIfSigned = false;
6942     if (LHSI->hasOneUse() &&
6943         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6944       // (X << 31) <s 0  --> (X&1) != 0
6945       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6946                                            (TypeBits-ShAmt->getZExtValue()-1));
6947       Instruction *AndI =
6948         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6949                                   Mask, LHSI->getName()+".mask");
6950       Value *And = InsertNewInstBefore(AndI, ICI);
6951       
6952       return new ICmpInst(*Context,
6953                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6954                           And, Context->getNullValue(And->getType()));
6955     }
6956     break;
6957   }
6958     
6959   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6960   case Instruction::AShr: {
6961     // Only handle equality comparisons of shift-by-constant.
6962     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6963     if (!ShAmt || !ICI.isEquality()) break;
6964
6965     // Check that the shift amount is in range.  If not, don't perform
6966     // undefined shifts.  When the shift is visited it will be
6967     // simplified.
6968     uint32_t TypeBits = RHSV.getBitWidth();
6969     if (ShAmt->uge(TypeBits))
6970       break;
6971     
6972     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6973       
6974     // If we are comparing against bits always shifted out, the
6975     // comparison cannot succeed.
6976     APInt Comp = RHSV << ShAmtVal;
6977     if (LHSI->getOpcode() == Instruction::LShr)
6978       Comp = Comp.lshr(ShAmtVal);
6979     else
6980       Comp = Comp.ashr(ShAmtVal);
6981     
6982     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6983       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6984       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6985       return ReplaceInstUsesWith(ICI, Cst);
6986     }
6987     
6988     // Otherwise, check to see if the bits shifted out are known to be zero.
6989     // If so, we can compare against the unshifted value:
6990     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6991     if (LHSI->hasOneUse() &&
6992         MaskedValueIsZero(LHSI->getOperand(0), 
6993                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6994       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6995                           Context->getConstantExprShl(RHS, ShAmt));
6996     }
6997       
6998     if (LHSI->hasOneUse()) {
6999       // Otherwise strength reduce the shift into an and.
7000       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7001       Constant *Mask = Context->getConstantInt(Val);
7002       
7003       Instruction *AndI =
7004         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7005                                   Mask, LHSI->getName()+".mask");
7006       Value *And = InsertNewInstBefore(AndI, ICI);
7007       return new ICmpInst(*Context, ICI.getPredicate(), And,
7008                           Context->getConstantExprShl(RHS, ShAmt));
7009     }
7010     break;
7011   }
7012     
7013   case Instruction::SDiv:
7014   case Instruction::UDiv:
7015     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7016     // Fold this div into the comparison, producing a range check. 
7017     // Determine, based on the divide type, what the range is being 
7018     // checked.  If there is an overflow on the low or high side, remember 
7019     // it, otherwise compute the range [low, hi) bounding the new value.
7020     // See: InsertRangeTest above for the kinds of replacements possible.
7021     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7022       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7023                                           DivRHS))
7024         return R;
7025     break;
7026
7027   case Instruction::Add:
7028     // Fold: icmp pred (add, X, C1), C2
7029
7030     if (!ICI.isEquality()) {
7031       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7032       if (!LHSC) break;
7033       const APInt &LHSV = LHSC->getValue();
7034
7035       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7036                             .subtract(LHSV);
7037
7038       if (ICI.isSignedPredicate()) {
7039         if (CR.getLower().isSignBit()) {
7040           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7041                               Context->getConstantInt(CR.getUpper()));
7042         } else if (CR.getUpper().isSignBit()) {
7043           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7044                               Context->getConstantInt(CR.getLower()));
7045         }
7046       } else {
7047         if (CR.getLower().isMinValue()) {
7048           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7049                               Context->getConstantInt(CR.getUpper()));
7050         } else if (CR.getUpper().isMinValue()) {
7051           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7052                               Context->getConstantInt(CR.getLower()));
7053         }
7054       }
7055     }
7056     break;
7057   }
7058   
7059   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7060   if (ICI.isEquality()) {
7061     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7062     
7063     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7064     // the second operand is a constant, simplify a bit.
7065     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7066       switch (BO->getOpcode()) {
7067       case Instruction::SRem:
7068         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7069         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7070           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7071           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7072             Instruction *NewRem =
7073               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7074                                          BO->getName());
7075             InsertNewInstBefore(NewRem, ICI);
7076             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7077                                 Context->getNullValue(BO->getType()));
7078           }
7079         }
7080         break;
7081       case Instruction::Add:
7082         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7083         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7084           if (BO->hasOneUse())
7085             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7086                                 Context->getConstantExprSub(RHS, BOp1C));
7087         } else if (RHSV == 0) {
7088           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7089           // efficiently invertible, or if the add has just this one use.
7090           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7091           
7092           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7093             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7094           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7095             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7096           else if (BO->hasOneUse()) {
7097             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7098             InsertNewInstBefore(Neg, ICI);
7099             Neg->takeName(BO);
7100             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7101           }
7102         }
7103         break;
7104       case Instruction::Xor:
7105         // For the xor case, we can xor two constants together, eliminating
7106         // the explicit xor.
7107         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7108           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7109                               Context->getConstantExprXor(RHS, BOC));
7110         
7111         // FALLTHROUGH
7112       case Instruction::Sub:
7113         // Replace (([sub|xor] A, B) != 0) with (A != B)
7114         if (RHSV == 0)
7115           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7116                               BO->getOperand(1));
7117         break;
7118         
7119       case Instruction::Or:
7120         // If bits are being or'd in that are not present in the constant we
7121         // are comparing against, then the comparison could never succeed!
7122         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7123           Constant *NotCI = Context->getConstantExprNot(RHS);
7124           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7125             return ReplaceInstUsesWith(ICI,
7126                                        Context->getConstantInt(Type::Int1Ty, 
7127                                        isICMP_NE));
7128         }
7129         break;
7130         
7131       case Instruction::And:
7132         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7133           // If bits are being compared against that are and'd out, then the
7134           // comparison can never succeed!
7135           if ((RHSV & ~BOC->getValue()) != 0)
7136             return ReplaceInstUsesWith(ICI,
7137                                        Context->getConstantInt(Type::Int1Ty,
7138                                        isICMP_NE));
7139           
7140           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7141           if (RHS == BOC && RHSV.isPowerOf2())
7142             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7143                                 ICmpInst::ICMP_NE, LHSI,
7144                                 Context->getNullValue(RHS->getType()));
7145           
7146           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7147           if (BOC->getValue().isSignBit()) {
7148             Value *X = BO->getOperand(0);
7149             Constant *Zero = Context->getNullValue(X->getType());
7150             ICmpInst::Predicate pred = isICMP_NE ? 
7151               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7152             return new ICmpInst(*Context, pred, X, Zero);
7153           }
7154           
7155           // ((X & ~7) == 0) --> X < 8
7156           if (RHSV == 0 && isHighOnes(BOC)) {
7157             Value *X = BO->getOperand(0);
7158             Constant *NegX = Context->getConstantExprNeg(BOC);
7159             ICmpInst::Predicate pred = isICMP_NE ? 
7160               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7161             return new ICmpInst(*Context, pred, X, NegX);
7162           }
7163         }
7164       default: break;
7165       }
7166     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7167       // Handle icmp {eq|ne} <intrinsic>, intcst.
7168       if (II->getIntrinsicID() == Intrinsic::bswap) {
7169         AddToWorkList(II);
7170         ICI.setOperand(0, II->getOperand(1));
7171         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7172         return &ICI;
7173       }
7174     }
7175   }
7176   return 0;
7177 }
7178
7179 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7180 /// We only handle extending casts so far.
7181 ///
7182 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7183   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7184   Value *LHSCIOp        = LHSCI->getOperand(0);
7185   const Type *SrcTy     = LHSCIOp->getType();
7186   const Type *DestTy    = LHSCI->getType();
7187   Value *RHSCIOp;
7188
7189   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7190   // integer type is the same size as the pointer type.
7191   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7192       getTargetData().getPointerSizeInBits() == 
7193          cast<IntegerType>(DestTy)->getBitWidth()) {
7194     Value *RHSOp = 0;
7195     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7196       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7197     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7198       RHSOp = RHSC->getOperand(0);
7199       // If the pointer types don't match, insert a bitcast.
7200       if (LHSCIOp->getType() != RHSOp->getType())
7201         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7202     }
7203
7204     if (RHSOp)
7205       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7206   }
7207   
7208   // The code below only handles extension cast instructions, so far.
7209   // Enforce this.
7210   if (LHSCI->getOpcode() != Instruction::ZExt &&
7211       LHSCI->getOpcode() != Instruction::SExt)
7212     return 0;
7213
7214   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7215   bool isSignedCmp = ICI.isSignedPredicate();
7216
7217   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7218     // Not an extension from the same type?
7219     RHSCIOp = CI->getOperand(0);
7220     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7221       return 0;
7222     
7223     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7224     // and the other is a zext), then we can't handle this.
7225     if (CI->getOpcode() != LHSCI->getOpcode())
7226       return 0;
7227
7228     // Deal with equality cases early.
7229     if (ICI.isEquality())
7230       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7231
7232     // A signed comparison of sign extended values simplifies into a
7233     // signed comparison.
7234     if (isSignedCmp && isSignedExt)
7235       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7236
7237     // The other three cases all fold into an unsigned comparison.
7238     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7239   }
7240
7241   // If we aren't dealing with a constant on the RHS, exit early
7242   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7243   if (!CI)
7244     return 0;
7245
7246   // Compute the constant that would happen if we truncated to SrcTy then
7247   // reextended to DestTy.
7248   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7249   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7250                                                 Res1, DestTy);
7251
7252   // If the re-extended constant didn't change...
7253   if (Res2 == CI) {
7254     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7255     // For example, we might have:
7256     //    %A = sext i16 %X to i32
7257     //    %B = icmp ugt i32 %A, 1330
7258     // It is incorrect to transform this into 
7259     //    %B = icmp ugt i16 %X, 1330
7260     // because %A may have negative value. 
7261     //
7262     // However, we allow this when the compare is EQ/NE, because they are
7263     // signless.
7264     if (isSignedExt == isSignedCmp || ICI.isEquality())
7265       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7266     return 0;
7267   }
7268
7269   // The re-extended constant changed so the constant cannot be represented 
7270   // in the shorter type. Consequently, we cannot emit a simple comparison.
7271
7272   // First, handle some easy cases. We know the result cannot be equal at this
7273   // point so handle the ICI.isEquality() cases
7274   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7275     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7276   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7277     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7278
7279   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7280   // should have been folded away previously and not enter in here.
7281   Value *Result;
7282   if (isSignedCmp) {
7283     // We're performing a signed comparison.
7284     if (cast<ConstantInt>(CI)->getValue().isNegative())
7285       Result = Context->getConstantIntFalse();          // X < (small) --> false
7286     else
7287       Result = Context->getConstantIntTrue();           // X < (large) --> true
7288   } else {
7289     // We're performing an unsigned comparison.
7290     if (isSignedExt) {
7291       // We're performing an unsigned comp with a sign extended value.
7292       // This is true if the input is >= 0. [aka >s -1]
7293       Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
7294       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7295                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7296     } else {
7297       // Unsigned extend & unsigned compare -> always true.
7298       Result = Context->getConstantIntTrue();
7299     }
7300   }
7301
7302   // Finally, return the value computed.
7303   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7304       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7305     return ReplaceInstUsesWith(ICI, Result);
7306
7307   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7308           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7309          "ICmp should be folded!");
7310   if (Constant *CI = dyn_cast<Constant>(Result))
7311     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7312   return BinaryOperator::CreateNot(Result);
7313 }
7314
7315 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7316   return commonShiftTransforms(I);
7317 }
7318
7319 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7320   return commonShiftTransforms(I);
7321 }
7322
7323 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7324   if (Instruction *R = commonShiftTransforms(I))
7325     return R;
7326   
7327   Value *Op0 = I.getOperand(0);
7328   
7329   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7330   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7331     if (CSI->isAllOnesValue())
7332       return ReplaceInstUsesWith(I, CSI);
7333
7334   // See if we can turn a signed shr into an unsigned shr.
7335   if (MaskedValueIsZero(Op0,
7336                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7337     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7338
7339   // Arithmetic shifting an all-sign-bit value is a no-op.
7340   unsigned NumSignBits = ComputeNumSignBits(Op0);
7341   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7342     return ReplaceInstUsesWith(I, Op0);
7343
7344   return 0;
7345 }
7346
7347 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7348   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7349   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7350
7351   // shl X, 0 == X and shr X, 0 == X
7352   // shl 0, X == 0 and shr 0, X == 0
7353   if (Op1 == Context->getNullValue(Op1->getType()) ||
7354       Op0 == Context->getNullValue(Op0->getType()))
7355     return ReplaceInstUsesWith(I, Op0);
7356   
7357   if (isa<UndefValue>(Op0)) {            
7358     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7359       return ReplaceInstUsesWith(I, Op0);
7360     else                                    // undef << X -> 0, undef >>u X -> 0
7361       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7362   }
7363   if (isa<UndefValue>(Op1)) {
7364     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7365       return ReplaceInstUsesWith(I, Op0);          
7366     else                                     // X << undef, X >>u undef -> 0
7367       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7368   }
7369
7370   // See if we can fold away this shift.
7371   if (SimplifyDemandedInstructionBits(I))
7372     return &I;
7373
7374   // Try to fold constant and into select arguments.
7375   if (isa<Constant>(Op0))
7376     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7377       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7378         return R;
7379
7380   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7381     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7382       return Res;
7383   return 0;
7384 }
7385
7386 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7387                                                BinaryOperator &I) {
7388   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7389
7390   // See if we can simplify any instructions used by the instruction whose sole 
7391   // purpose is to compute bits we don't care about.
7392   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7393   
7394   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7395   // a signed shift.
7396   //
7397   if (Op1->uge(TypeBits)) {
7398     if (I.getOpcode() != Instruction::AShr)
7399       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7400     else {
7401       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7402       return &I;
7403     }
7404   }
7405   
7406   // ((X*C1) << C2) == (X * (C1 << C2))
7407   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7408     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7409       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7410         return BinaryOperator::CreateMul(BO->getOperand(0),
7411                                         Context->getConstantExprShl(BOOp, Op1));
7412   
7413   // Try to fold constant and into select arguments.
7414   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7415     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7416       return R;
7417   if (isa<PHINode>(Op0))
7418     if (Instruction *NV = FoldOpIntoPhi(I))
7419       return NV;
7420   
7421   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7422   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7423     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7424     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7425     // place.  Don't try to do this transformation in this case.  Also, we
7426     // require that the input operand is a shift-by-constant so that we have
7427     // confidence that the shifts will get folded together.  We could do this
7428     // xform in more cases, but it is unlikely to be profitable.
7429     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7430         isa<ConstantInt>(TrOp->getOperand(1))) {
7431       // Okay, we'll do this xform.  Make the shift of shift.
7432       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7433       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7434                                                 I.getName());
7435       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7436
7437       // For logical shifts, the truncation has the effect of making the high
7438       // part of the register be zeros.  Emulate this by inserting an AND to
7439       // clear the top bits as needed.  This 'and' will usually be zapped by
7440       // other xforms later if dead.
7441       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7442       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7443       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7444       
7445       // The mask we constructed says what the trunc would do if occurring
7446       // between the shifts.  We want to know the effect *after* the second
7447       // shift.  We know that it is a logical shift by a constant, so adjust the
7448       // mask as appropriate.
7449       if (I.getOpcode() == Instruction::Shl)
7450         MaskV <<= Op1->getZExtValue();
7451       else {
7452         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7453         MaskV = MaskV.lshr(Op1->getZExtValue());
7454       }
7455
7456       Instruction *And =
7457         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7458                                   TI->getName());
7459       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7460
7461       // Return the value truncated to the interesting size.
7462       return new TruncInst(And, I.getType());
7463     }
7464   }
7465   
7466   if (Op0->hasOneUse()) {
7467     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7468       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7469       Value *V1, *V2;
7470       ConstantInt *CC;
7471       switch (Op0BO->getOpcode()) {
7472         default: break;
7473         case Instruction::Add:
7474         case Instruction::And:
7475         case Instruction::Or:
7476         case Instruction::Xor: {
7477           // These operators commute.
7478           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7479           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7480               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7481                     m_Specific(Op1)), *Context)){
7482             Instruction *YS = BinaryOperator::CreateShl(
7483                                             Op0BO->getOperand(0), Op1,
7484                                             Op0BO->getName());
7485             InsertNewInstBefore(YS, I); // (Y << C)
7486             Instruction *X = 
7487               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7488                                      Op0BO->getOperand(1)->getName());
7489             InsertNewInstBefore(X, I);  // (X + (Y << C))
7490             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7491             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7492                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7493           }
7494           
7495           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7496           Value *Op0BOOp1 = Op0BO->getOperand(1);
7497           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7498               match(Op0BOOp1, 
7499                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7500                           m_ConstantInt(CC)), *Context) &&
7501               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7502             Instruction *YS = BinaryOperator::CreateShl(
7503                                                      Op0BO->getOperand(0), Op1,
7504                                                      Op0BO->getName());
7505             InsertNewInstBefore(YS, I); // (Y << C)
7506             Instruction *XM =
7507               BinaryOperator::CreateAnd(V1,
7508                                         Context->getConstantExprShl(CC, Op1),
7509                                         V1->getName()+".mask");
7510             InsertNewInstBefore(XM, I); // X & (CC << C)
7511             
7512             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7513           }
7514         }
7515           
7516         // FALL THROUGH.
7517         case Instruction::Sub: {
7518           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7519           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7520               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7521                     m_Specific(Op1)), *Context)){
7522             Instruction *YS = BinaryOperator::CreateShl(
7523                                                      Op0BO->getOperand(1), Op1,
7524                                                      Op0BO->getName());
7525             InsertNewInstBefore(YS, I); // (Y << C)
7526             Instruction *X =
7527               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7528                                      Op0BO->getOperand(0)->getName());
7529             InsertNewInstBefore(X, I);  // (X + (Y << C))
7530             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7531             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7532                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7533           }
7534           
7535           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7536           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7537               match(Op0BO->getOperand(0),
7538                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7539                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7540               cast<BinaryOperator>(Op0BO->getOperand(0))
7541                   ->getOperand(0)->hasOneUse()) {
7542             Instruction *YS = BinaryOperator::CreateShl(
7543                                                      Op0BO->getOperand(1), Op1,
7544                                                      Op0BO->getName());
7545             InsertNewInstBefore(YS, I); // (Y << C)
7546             Instruction *XM =
7547               BinaryOperator::CreateAnd(V1, 
7548                                         Context->getConstantExprShl(CC, Op1),
7549                                         V1->getName()+".mask");
7550             InsertNewInstBefore(XM, I); // X & (CC << C)
7551             
7552             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7553           }
7554           
7555           break;
7556         }
7557       }
7558       
7559       
7560       // If the operand is an bitwise operator with a constant RHS, and the
7561       // shift is the only use, we can pull it out of the shift.
7562       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7563         bool isValid = true;     // Valid only for And, Or, Xor
7564         bool highBitSet = false; // Transform if high bit of constant set?
7565         
7566         switch (Op0BO->getOpcode()) {
7567           default: isValid = false; break;   // Do not perform transform!
7568           case Instruction::Add:
7569             isValid = isLeftShift;
7570             break;
7571           case Instruction::Or:
7572           case Instruction::Xor:
7573             highBitSet = false;
7574             break;
7575           case Instruction::And:
7576             highBitSet = true;
7577             break;
7578         }
7579         
7580         // If this is a signed shift right, and the high bit is modified
7581         // by the logical operation, do not perform the transformation.
7582         // The highBitSet boolean indicates the value of the high bit of
7583         // the constant which would cause it to be modified for this
7584         // operation.
7585         //
7586         if (isValid && I.getOpcode() == Instruction::AShr)
7587           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7588         
7589         if (isValid) {
7590           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7591           
7592           Instruction *NewShift =
7593             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7594           InsertNewInstBefore(NewShift, I);
7595           NewShift->takeName(Op0BO);
7596           
7597           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7598                                         NewRHS);
7599         }
7600       }
7601     }
7602   }
7603   
7604   // Find out if this is a shift of a shift by a constant.
7605   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7606   if (ShiftOp && !ShiftOp->isShift())
7607     ShiftOp = 0;
7608   
7609   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7610     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7611     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7612     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7613     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7614     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7615     Value *X = ShiftOp->getOperand(0);
7616     
7617     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7618     
7619     const IntegerType *Ty = cast<IntegerType>(I.getType());
7620     
7621     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7622     if (I.getOpcode() == ShiftOp->getOpcode()) {
7623       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7624       // saturates.
7625       if (AmtSum >= TypeBits) {
7626         if (I.getOpcode() != Instruction::AShr)
7627           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7628         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7629       }
7630       
7631       return BinaryOperator::Create(I.getOpcode(), X,
7632                                     Context->getConstantInt(Ty, AmtSum));
7633     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7634                I.getOpcode() == Instruction::AShr) {
7635       if (AmtSum >= TypeBits)
7636         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7637       
7638       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7639       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7640     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7641                I.getOpcode() == Instruction::LShr) {
7642       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7643       if (AmtSum >= TypeBits)
7644         AmtSum = TypeBits-1;
7645       
7646       Instruction *Shift =
7647         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7648       InsertNewInstBefore(Shift, I);
7649
7650       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7651       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7652     }
7653     
7654     // Okay, if we get here, one shift must be left, and the other shift must be
7655     // right.  See if the amounts are equal.
7656     if (ShiftAmt1 == ShiftAmt2) {
7657       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7658       if (I.getOpcode() == Instruction::Shl) {
7659         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7660         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7661       }
7662       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7663       if (I.getOpcode() == Instruction::LShr) {
7664         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7665         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7666       }
7667       // We can simplify ((X << C) >>s C) into a trunc + sext.
7668       // NOTE: we could do this for any C, but that would make 'unusual' integer
7669       // types.  For now, just stick to ones well-supported by the code
7670       // generators.
7671       const Type *SExtType = 0;
7672       switch (Ty->getBitWidth() - ShiftAmt1) {
7673       case 1  :
7674       case 8  :
7675       case 16 :
7676       case 32 :
7677       case 64 :
7678       case 128:
7679         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7680         break;
7681       default: break;
7682       }
7683       if (SExtType) {
7684         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7685         InsertNewInstBefore(NewTrunc, I);
7686         return new SExtInst(NewTrunc, Ty);
7687       }
7688       // Otherwise, we can't handle it yet.
7689     } else if (ShiftAmt1 < ShiftAmt2) {
7690       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7691       
7692       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7693       if (I.getOpcode() == Instruction::Shl) {
7694         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7695                ShiftOp->getOpcode() == Instruction::AShr);
7696         Instruction *Shift =
7697           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7698         InsertNewInstBefore(Shift, I);
7699         
7700         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7701         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7702       }
7703       
7704       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7705       if (I.getOpcode() == Instruction::LShr) {
7706         assert(ShiftOp->getOpcode() == Instruction::Shl);
7707         Instruction *Shift =
7708           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7709         InsertNewInstBefore(Shift, I);
7710         
7711         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7712         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7713       }
7714       
7715       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7716     } else {
7717       assert(ShiftAmt2 < ShiftAmt1);
7718       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7719
7720       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7721       if (I.getOpcode() == Instruction::Shl) {
7722         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7723                ShiftOp->getOpcode() == Instruction::AShr);
7724         Instruction *Shift =
7725           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7726                                  Context->getConstantInt(Ty, ShiftDiff));
7727         InsertNewInstBefore(Shift, I);
7728         
7729         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7730         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7731       }
7732       
7733       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7734       if (I.getOpcode() == Instruction::LShr) {
7735         assert(ShiftOp->getOpcode() == Instruction::Shl);
7736         Instruction *Shift =
7737           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7738         InsertNewInstBefore(Shift, I);
7739         
7740         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7741         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7742       }
7743       
7744       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7745     }
7746   }
7747   return 0;
7748 }
7749
7750
7751 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7752 /// expression.  If so, decompose it, returning some value X, such that Val is
7753 /// X*Scale+Offset.
7754 ///
7755 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7756                                         int &Offset, LLVMContext *Context) {
7757   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7758   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7759     Offset = CI->getZExtValue();
7760     Scale  = 0;
7761     return Context->getConstantInt(Type::Int32Ty, 0);
7762   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7763     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7764       if (I->getOpcode() == Instruction::Shl) {
7765         // This is a value scaled by '1 << the shift amt'.
7766         Scale = 1U << RHS->getZExtValue();
7767         Offset = 0;
7768         return I->getOperand(0);
7769       } else if (I->getOpcode() == Instruction::Mul) {
7770         // This value is scaled by 'RHS'.
7771         Scale = RHS->getZExtValue();
7772         Offset = 0;
7773         return I->getOperand(0);
7774       } else if (I->getOpcode() == Instruction::Add) {
7775         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7776         // where C1 is divisible by C2.
7777         unsigned SubScale;
7778         Value *SubVal = 
7779           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7780                                     Offset, Context);
7781         Offset += RHS->getZExtValue();
7782         Scale = SubScale;
7783         return SubVal;
7784       }
7785     }
7786   }
7787
7788   // Otherwise, we can't look past this.
7789   Scale = 1;
7790   Offset = 0;
7791   return Val;
7792 }
7793
7794
7795 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7796 /// try to eliminate the cast by moving the type information into the alloc.
7797 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7798                                                    AllocationInst &AI) {
7799   const PointerType *PTy = cast<PointerType>(CI.getType());
7800   
7801   // Remove any uses of AI that are dead.
7802   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7803   
7804   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7805     Instruction *User = cast<Instruction>(*UI++);
7806     if (isInstructionTriviallyDead(User)) {
7807       while (UI != E && *UI == User)
7808         ++UI; // If this instruction uses AI more than once, don't break UI.
7809       
7810       ++NumDeadInst;
7811       DOUT << "IC: DCE: " << *User;
7812       EraseInstFromFunction(*User);
7813     }
7814   }
7815   
7816   // Get the type really allocated and the type casted to.
7817   const Type *AllocElTy = AI.getAllocatedType();
7818   const Type *CastElTy = PTy->getElementType();
7819   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7820
7821   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7822   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7823   if (CastElTyAlign < AllocElTyAlign) return 0;
7824
7825   // If the allocation has multiple uses, only promote it if we are strictly
7826   // increasing the alignment of the resultant allocation.  If we keep it the
7827   // same, we open the door to infinite loops of various kinds.  (A reference
7828   // from a dbg.declare doesn't count as a use for this purpose.)
7829   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7830       CastElTyAlign == AllocElTyAlign) return 0;
7831
7832   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7833   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7834   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7835
7836   // See if we can satisfy the modulus by pulling a scale out of the array
7837   // size argument.
7838   unsigned ArraySizeScale;
7839   int ArrayOffset;
7840   Value *NumElements = // See if the array size is a decomposable linear expr.
7841     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7842                               ArrayOffset, Context);
7843  
7844   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7845   // do the xform.
7846   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7847       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7848
7849   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7850   Value *Amt = 0;
7851   if (Scale == 1) {
7852     Amt = NumElements;
7853   } else {
7854     // If the allocation size is constant, form a constant mul expression
7855     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7856     if (isa<ConstantInt>(NumElements))
7857       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7858                                  cast<ConstantInt>(Amt));
7859     // otherwise multiply the amount and the number of elements
7860     else {
7861       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7862       Amt = InsertNewInstBefore(Tmp, AI);
7863     }
7864   }
7865   
7866   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7867     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7868     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7869     Amt = InsertNewInstBefore(Tmp, AI);
7870   }
7871   
7872   AllocationInst *New;
7873   if (isa<MallocInst>(AI))
7874     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7875   else
7876     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7877   InsertNewInstBefore(New, AI);
7878   New->takeName(&AI);
7879   
7880   // If the allocation has one real use plus a dbg.declare, just remove the
7881   // declare.
7882   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7883     EraseInstFromFunction(*DI);
7884   }
7885   // If the allocation has multiple real uses, insert a cast and change all
7886   // things that used it to use the new cast.  This will also hack on CI, but it
7887   // will die soon.
7888   else if (!AI.hasOneUse()) {
7889     AddUsesToWorkList(AI);
7890     // New is the allocation instruction, pointer typed. AI is the original
7891     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7892     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7893     InsertNewInstBefore(NewCast, AI);
7894     AI.replaceAllUsesWith(NewCast);
7895   }
7896   return ReplaceInstUsesWith(CI, New);
7897 }
7898
7899 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7900 /// and return it as type Ty without inserting any new casts and without
7901 /// changing the computed value.  This is used by code that tries to decide
7902 /// whether promoting or shrinking integer operations to wider or smaller types
7903 /// will allow us to eliminate a truncate or extend.
7904 ///
7905 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7906 /// extension operation if Ty is larger.
7907 ///
7908 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7909 /// should return true if trunc(V) can be computed by computing V in the smaller
7910 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7911 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7912 /// efficiently truncated.
7913 ///
7914 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7915 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7916 /// the final result.
7917 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7918                                               unsigned CastOpc,
7919                                               int &NumCastsRemoved){
7920   // We can always evaluate constants in another type.
7921   if (isa<Constant>(V))
7922     return true;
7923   
7924   Instruction *I = dyn_cast<Instruction>(V);
7925   if (!I) return false;
7926   
7927   const Type *OrigTy = V->getType();
7928   
7929   // If this is an extension or truncate, we can often eliminate it.
7930   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7931     // If this is a cast from the destination type, we can trivially eliminate
7932     // it, and this will remove a cast overall.
7933     if (I->getOperand(0)->getType() == Ty) {
7934       // If the first operand is itself a cast, and is eliminable, do not count
7935       // this as an eliminable cast.  We would prefer to eliminate those two
7936       // casts first.
7937       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7938         ++NumCastsRemoved;
7939       return true;
7940     }
7941   }
7942
7943   // We can't extend or shrink something that has multiple uses: doing so would
7944   // require duplicating the instruction in general, which isn't profitable.
7945   if (!I->hasOneUse()) return false;
7946
7947   unsigned Opc = I->getOpcode();
7948   switch (Opc) {
7949   case Instruction::Add:
7950   case Instruction::Sub:
7951   case Instruction::Mul:
7952   case Instruction::And:
7953   case Instruction::Or:
7954   case Instruction::Xor:
7955     // These operators can all arbitrarily be extended or truncated.
7956     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7957                                       NumCastsRemoved) &&
7958            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7959                                       NumCastsRemoved);
7960
7961   case Instruction::Shl:
7962     // If we are truncating the result of this SHL, and if it's a shift of a
7963     // constant amount, we can always perform a SHL in a smaller type.
7964     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7965       uint32_t BitWidth = Ty->getScalarSizeInBits();
7966       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7967           CI->getLimitedValue(BitWidth) < BitWidth)
7968         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7969                                           NumCastsRemoved);
7970     }
7971     break;
7972   case Instruction::LShr:
7973     // If this is a truncate of a logical shr, we can truncate it to a smaller
7974     // lshr iff we know that the bits we would otherwise be shifting in are
7975     // already zeros.
7976     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7977       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7978       uint32_t BitWidth = Ty->getScalarSizeInBits();
7979       if (BitWidth < OrigBitWidth &&
7980           MaskedValueIsZero(I->getOperand(0),
7981             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7982           CI->getLimitedValue(BitWidth) < BitWidth) {
7983         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7984                                           NumCastsRemoved);
7985       }
7986     }
7987     break;
7988   case Instruction::ZExt:
7989   case Instruction::SExt:
7990   case Instruction::Trunc:
7991     // If this is the same kind of case as our original (e.g. zext+zext), we
7992     // can safely replace it.  Note that replacing it does not reduce the number
7993     // of casts in the input.
7994     if (Opc == CastOpc)
7995       return true;
7996
7997     // sext (zext ty1), ty2 -> zext ty2
7998     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7999       return true;
8000     break;
8001   case Instruction::Select: {
8002     SelectInst *SI = cast<SelectInst>(I);
8003     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8004                                       NumCastsRemoved) &&
8005            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8006                                       NumCastsRemoved);
8007   }
8008   case Instruction::PHI: {
8009     // We can change a phi if we can change all operands.
8010     PHINode *PN = cast<PHINode>(I);
8011     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8012       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8013                                       NumCastsRemoved))
8014         return false;
8015     return true;
8016   }
8017   default:
8018     // TODO: Can handle more cases here.
8019     break;
8020   }
8021   
8022   return false;
8023 }
8024
8025 /// EvaluateInDifferentType - Given an expression that 
8026 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8027 /// evaluate the expression.
8028 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8029                                              bool isSigned) {
8030   if (Constant *C = dyn_cast<Constant>(V))
8031     return Context->getConstantExprIntegerCast(C, Ty,
8032                                                isSigned /*Sext or ZExt*/);
8033
8034   // Otherwise, it must be an instruction.
8035   Instruction *I = cast<Instruction>(V);
8036   Instruction *Res = 0;
8037   unsigned Opc = I->getOpcode();
8038   switch (Opc) {
8039   case Instruction::Add:
8040   case Instruction::Sub:
8041   case Instruction::Mul:
8042   case Instruction::And:
8043   case Instruction::Or:
8044   case Instruction::Xor:
8045   case Instruction::AShr:
8046   case Instruction::LShr:
8047   case Instruction::Shl: {
8048     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8049     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8050     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8051     break;
8052   }    
8053   case Instruction::Trunc:
8054   case Instruction::ZExt:
8055   case Instruction::SExt:
8056     // If the source type of the cast is the type we're trying for then we can
8057     // just return the source.  There's no need to insert it because it is not
8058     // new.
8059     if (I->getOperand(0)->getType() == Ty)
8060       return I->getOperand(0);
8061     
8062     // Otherwise, must be the same type of cast, so just reinsert a new one.
8063     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8064                            Ty);
8065     break;
8066   case Instruction::Select: {
8067     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8068     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8069     Res = SelectInst::Create(I->getOperand(0), True, False);
8070     break;
8071   }
8072   case Instruction::PHI: {
8073     PHINode *OPN = cast<PHINode>(I);
8074     PHINode *NPN = PHINode::Create(Ty);
8075     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8076       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8077       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8078     }
8079     Res = NPN;
8080     break;
8081   }
8082   default: 
8083     // TODO: Can handle more cases here.
8084     assert(0 && "Unreachable!");
8085     break;
8086   }
8087   
8088   Res->takeName(I);
8089   return InsertNewInstBefore(Res, *I);
8090 }
8091
8092 /// @brief Implement the transforms common to all CastInst visitors.
8093 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8094   Value *Src = CI.getOperand(0);
8095
8096   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8097   // eliminate it now.
8098   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8099     if (Instruction::CastOps opc = 
8100         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8101       // The first cast (CSrc) is eliminable so we need to fix up or replace
8102       // the second cast (CI). CSrc will then have a good chance of being dead.
8103       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8104     }
8105   }
8106
8107   // If we are casting a select then fold the cast into the select
8108   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8109     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8110       return NV;
8111
8112   // If we are casting a PHI then fold the cast into the PHI
8113   if (isa<PHINode>(Src))
8114     if (Instruction *NV = FoldOpIntoPhi(CI))
8115       return NV;
8116   
8117   return 0;
8118 }
8119
8120 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8121 /// or not there is a sequence of GEP indices into the type that will land us at
8122 /// the specified offset.  If so, fill them into NewIndices and return the
8123 /// resultant element type, otherwise return null.
8124 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8125                                        SmallVectorImpl<Value*> &NewIndices,
8126                                        const TargetData *TD,
8127                                        LLVMContext *Context) {
8128   if (!Ty->isSized()) return 0;
8129   
8130   // Start with the index over the outer type.  Note that the type size
8131   // might be zero (even if the offset isn't zero) if the indexed type
8132   // is something like [0 x {int, int}]
8133   const Type *IntPtrTy = TD->getIntPtrType();
8134   int64_t FirstIdx = 0;
8135   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8136     FirstIdx = Offset/TySize;
8137     Offset -= FirstIdx*TySize;
8138     
8139     // Handle hosts where % returns negative instead of values [0..TySize).
8140     if (Offset < 0) {
8141       --FirstIdx;
8142       Offset += TySize;
8143       assert(Offset >= 0);
8144     }
8145     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8146   }
8147   
8148   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8149     
8150   // Index into the types.  If we fail, set OrigBase to null.
8151   while (Offset) {
8152     // Indexing into tail padding between struct/array elements.
8153     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8154       return 0;
8155     
8156     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157       const StructLayout *SL = TD->getStructLayout(STy);
8158       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159              "Offset must stay within the indexed type");
8160       
8161       unsigned Elt = SL->getElementContainingOffset(Offset);
8162       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8163       
8164       Offset -= SL->getElementOffset(Elt);
8165       Ty = STy->getElementType(Elt);
8166     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8167       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8168       assert(EltSize && "Cannot index into a zero-sized array");
8169       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8170       Offset %= EltSize;
8171       Ty = AT->getElementType();
8172     } else {
8173       // Otherwise, we can't index into the middle of this atomic type, bail.
8174       return 0;
8175     }
8176   }
8177   
8178   return Ty;
8179 }
8180
8181 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183   Value *Src = CI.getOperand(0);
8184   
8185   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8186     // If casting the result of a getelementptr instruction with no offset, turn
8187     // this into a cast of the original pointer!
8188     if (GEP->hasAllZeroIndices()) {
8189       // Changing the cast operand is usually not a good idea but it is safe
8190       // here because the pointer operand is being replaced with another 
8191       // pointer operand so the opcode doesn't need to change.
8192       AddToWorkList(GEP);
8193       CI.setOperand(0, GEP->getOperand(0));
8194       return &CI;
8195     }
8196     
8197     // If the GEP has a single use, and the base pointer is a bitcast, and the
8198     // GEP computes a constant offset, see if we can convert these three
8199     // instructions into fewer.  This typically happens with unions and other
8200     // non-type-safe code.
8201     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8202       if (GEP->hasAllConstantIndices()) {
8203         // We are guaranteed to get a constant from EmitGEPOffset.
8204         ConstantInt *OffsetV =
8205                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8206         int64_t Offset = OffsetV->getSExtValue();
8207         
8208         // Get the base pointer input of the bitcast, and the type it points to.
8209         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210         const Type *GEPIdxTy =
8211           cast<PointerType>(OrigBase->getType())->getElementType();
8212         SmallVector<Value*, 8> NewIndices;
8213         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8214           // If we were able to index down into an element, create the GEP
8215           // and bitcast the result.  This eliminates one bitcast, potentially
8216           // two.
8217           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8218                                                         NewIndices.begin(),
8219                                                         NewIndices.end(), "");
8220           InsertNewInstBefore(NGEP, CI);
8221           NGEP->takeName(GEP);
8222           
8223           if (isa<BitCastInst>(CI))
8224             return new BitCastInst(NGEP, CI.getType());
8225           assert(isa<PtrToIntInst>(CI));
8226           return new PtrToIntInst(NGEP, CI.getType());
8227         }
8228       }      
8229     }
8230   }
8231     
8232   return commonCastTransforms(CI);
8233 }
8234
8235 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236 /// type like i42.  We don't want to introduce operations on random non-legal
8237 /// integer types where they don't already exist in the code.  In the future,
8238 /// we should consider making this based off target-data, so that 32-bit targets
8239 /// won't get i64 operations etc.
8240 static bool isSafeIntegerType(const Type *Ty) {
8241   switch (Ty->getPrimitiveSizeInBits()) {
8242   case 8:
8243   case 16:
8244   case 32:
8245   case 64:
8246     return true;
8247   default: 
8248     return false;
8249   }
8250 }
8251
8252 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8253 /// integer types. This function implements the common transforms for all those
8254 /// cases.
8255 /// @brief Implement the transforms common to CastInst with integer operands
8256 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8257   if (Instruction *Result = commonCastTransforms(CI))
8258     return Result;
8259
8260   Value *Src = CI.getOperand(0);
8261   const Type *SrcTy = Src->getType();
8262   const Type *DestTy = CI.getType();
8263   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8264   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8265
8266   // See if we can simplify any instructions used by the LHS whose sole 
8267   // purpose is to compute bits we don't care about.
8268   if (SimplifyDemandedInstructionBits(CI))
8269     return &CI;
8270
8271   // If the source isn't an instruction or has more than one use then we
8272   // can't do anything more. 
8273   Instruction *SrcI = dyn_cast<Instruction>(Src);
8274   if (!SrcI || !Src->hasOneUse())
8275     return 0;
8276
8277   // Attempt to propagate the cast into the instruction for int->int casts.
8278   int NumCastsRemoved = 0;
8279   if (!isa<BitCastInst>(CI) &&
8280       // Only do this if the dest type is a simple type, don't convert the
8281       // expression tree to something weird like i93 unless the source is also
8282       // strange.
8283       (isSafeIntegerType(DestTy->getScalarType()) ||
8284        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8285       CanEvaluateInDifferentType(SrcI, DestTy,
8286                                  CI.getOpcode(), NumCastsRemoved)) {
8287     // If this cast is a truncate, evaluting in a different type always
8288     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8289     // we need to do an AND to maintain the clear top-part of the computation,
8290     // so we require that the input have eliminated at least one cast.  If this
8291     // is a sign extension, we insert two new casts (to do the extension) so we
8292     // require that two casts have been eliminated.
8293     bool DoXForm = false;
8294     bool JustReplace = false;
8295     switch (CI.getOpcode()) {
8296     default:
8297       // All the others use floating point so we shouldn't actually 
8298       // get here because of the check above.
8299       assert(0 && "Unknown cast type");
8300     case Instruction::Trunc:
8301       DoXForm = true;
8302       break;
8303     case Instruction::ZExt: {
8304       DoXForm = NumCastsRemoved >= 1;
8305       if (!DoXForm && 0) {
8306         // If it's unnecessary to issue an AND to clear the high bits, it's
8307         // always profitable to do this xform.
8308         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8309         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8310         if (MaskedValueIsZero(TryRes, Mask))
8311           return ReplaceInstUsesWith(CI, TryRes);
8312         
8313         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8314           if (TryI->use_empty())
8315             EraseInstFromFunction(*TryI);
8316       }
8317       break;
8318     }
8319     case Instruction::SExt: {
8320       DoXForm = NumCastsRemoved >= 2;
8321       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8322         // If we do not have to emit the truncate + sext pair, then it's always
8323         // profitable to do this xform.
8324         //
8325         // It's not safe to eliminate the trunc + sext pair if one of the
8326         // eliminated cast is a truncate. e.g.
8327         // t2 = trunc i32 t1 to i16
8328         // t3 = sext i16 t2 to i32
8329         // !=
8330         // i32 t1
8331         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8332         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8333         if (NumSignBits > (DestBitSize - SrcBitSize))
8334           return ReplaceInstUsesWith(CI, TryRes);
8335         
8336         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8337           if (TryI->use_empty())
8338             EraseInstFromFunction(*TryI);
8339       }
8340       break;
8341     }
8342     }
8343     
8344     if (DoXForm) {
8345       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8346            << " cast: " << CI;
8347       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8348                                            CI.getOpcode() == Instruction::SExt);
8349       if (JustReplace)
8350         // Just replace this cast with the result.
8351         return ReplaceInstUsesWith(CI, Res);
8352
8353       assert(Res->getType() == DestTy);
8354       switch (CI.getOpcode()) {
8355       default: assert(0 && "Unknown cast type!");
8356       case Instruction::Trunc:
8357       case Instruction::BitCast:
8358         // Just replace this cast with the result.
8359         return ReplaceInstUsesWith(CI, Res);
8360       case Instruction::ZExt: {
8361         assert(SrcBitSize < DestBitSize && "Not a zext?");
8362
8363         // If the high bits are already zero, just replace this cast with the
8364         // result.
8365         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8366         if (MaskedValueIsZero(Res, Mask))
8367           return ReplaceInstUsesWith(CI, Res);
8368
8369         // We need to emit an AND to clear the high bits.
8370         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8371                                                             SrcBitSize));
8372         return BinaryOperator::CreateAnd(Res, C);
8373       }
8374       case Instruction::SExt: {
8375         // If the high bits are already filled with sign bit, just replace this
8376         // cast with the result.
8377         unsigned NumSignBits = ComputeNumSignBits(Res);
8378         if (NumSignBits > (DestBitSize - SrcBitSize))
8379           return ReplaceInstUsesWith(CI, Res);
8380
8381         // We need to emit a cast to truncate, then a cast to sext.
8382         return CastInst::Create(Instruction::SExt,
8383             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8384                              CI), DestTy);
8385       }
8386       }
8387     }
8388   }
8389   
8390   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8391   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8392
8393   switch (SrcI->getOpcode()) {
8394   case Instruction::Add:
8395   case Instruction::Mul:
8396   case Instruction::And:
8397   case Instruction::Or:
8398   case Instruction::Xor:
8399     // If we are discarding information, rewrite.
8400     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8401       // Don't insert two casts if they cannot be eliminated.  We allow 
8402       // two casts to be inserted if the sizes are the same.  This could 
8403       // only be converting signedness, which is a noop.
8404       if (DestBitSize == SrcBitSize || 
8405           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8406           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8407         Instruction::CastOps opcode = CI.getOpcode();
8408         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8409         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8410         return BinaryOperator::Create(
8411             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8412       }
8413     }
8414
8415     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8416     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8417         SrcI->getOpcode() == Instruction::Xor &&
8418         Op1 == Context->getConstantIntTrue() &&
8419         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8420       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8421       return BinaryOperator::CreateXor(New,
8422                                       Context->getConstantInt(CI.getType(), 1));
8423     }
8424     break;
8425   case Instruction::SDiv:
8426   case Instruction::UDiv:
8427   case Instruction::SRem:
8428   case Instruction::URem:
8429     // If we are just changing the sign, rewrite.
8430     if (DestBitSize == SrcBitSize) {
8431       // Don't insert two casts if they cannot be eliminated.  We allow 
8432       // two casts to be inserted if the sizes are the same.  This could 
8433       // only be converting signedness, which is a noop.
8434       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8435           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8436         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8437                                        Op0, DestTy, *SrcI);
8438         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8439                                        Op1, DestTy, *SrcI);
8440         return BinaryOperator::Create(
8441           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8442       }
8443     }
8444     break;
8445
8446   case Instruction::Shl:
8447     // Allow changing the sign of the source operand.  Do not allow 
8448     // changing the size of the shift, UNLESS the shift amount is a 
8449     // constant.  We must not change variable sized shifts to a smaller 
8450     // size, because it is undefined to shift more bits out than exist 
8451     // in the value.
8452     if (DestBitSize == SrcBitSize ||
8453         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8454       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8455           Instruction::BitCast : Instruction::Trunc);
8456       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8457       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8458       return BinaryOperator::CreateShl(Op0c, Op1c);
8459     }
8460     break;
8461   case Instruction::AShr:
8462     // If this is a signed shr, and if all bits shifted in are about to be
8463     // truncated off, turn it into an unsigned shr to allow greater
8464     // simplifications.
8465     if (DestBitSize < SrcBitSize &&
8466         isa<ConstantInt>(Op1)) {
8467       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8468       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8469         // Insert the new logical shift right.
8470         return BinaryOperator::CreateLShr(Op0, Op1);
8471       }
8472     }
8473     break;
8474   }
8475   return 0;
8476 }
8477
8478 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8479   if (Instruction *Result = commonIntCastTransforms(CI))
8480     return Result;
8481   
8482   Value *Src = CI.getOperand(0);
8483   const Type *Ty = CI.getType();
8484   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8485   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8486
8487   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8488   if (DestBitWidth == 1 &&
8489       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8490     Constant *One = Context->getConstantInt(Src->getType(), 1);
8491     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8492     Value *Zero = Context->getNullValue(Src->getType());
8493     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8494   }
8495
8496   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8497   ConstantInt *ShAmtV = 0;
8498   Value *ShiftOp = 0;
8499   if (Src->hasOneUse() &&
8500       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8501     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8502     
8503     // Get a mask for the bits shifting in.
8504     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8505     if (MaskedValueIsZero(ShiftOp, Mask)) {
8506       if (ShAmt >= DestBitWidth)        // All zeros.
8507         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8508       
8509       // Okay, we can shrink this.  Truncate the input, then return a new
8510       // shift.
8511       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8512       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8513       return BinaryOperator::CreateLShr(V1, V2);
8514     }
8515   }
8516   
8517   return 0;
8518 }
8519
8520 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8521 /// in order to eliminate the icmp.
8522 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8523                                              bool DoXform) {
8524   // If we are just checking for a icmp eq of a single bit and zext'ing it
8525   // to an integer, then shift the bit to the appropriate place and then
8526   // cast to integer to avoid the comparison.
8527   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8528     const APInt &Op1CV = Op1C->getValue();
8529       
8530     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8531     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8532     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8533         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8534       if (!DoXform) return ICI;
8535
8536       Value *In = ICI->getOperand(0);
8537       Value *Sh = Context->getConstantInt(In->getType(),
8538                                    In->getType()->getScalarSizeInBits()-1);
8539       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8540                                                         In->getName()+".lobit"),
8541                                CI);
8542       if (In->getType() != CI.getType())
8543         In = CastInst::CreateIntegerCast(In, CI.getType(),
8544                                          false/*ZExt*/, "tmp", &CI);
8545
8546       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8547         Constant *One = Context->getConstantInt(In->getType(), 1);
8548         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8549                                                          In->getName()+".not"),
8550                                  CI);
8551       }
8552
8553       return ReplaceInstUsesWith(CI, In);
8554     }
8555       
8556       
8557       
8558     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8559     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8560     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8561     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8562     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8563     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8564     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8565     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8566     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8567         // This only works for EQ and NE
8568         ICI->isEquality()) {
8569       // If Op1C some other power of two, convert:
8570       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8571       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8572       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8573       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8574         
8575       APInt KnownZeroMask(~KnownZero);
8576       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8577         if (!DoXform) return ICI;
8578
8579         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8580         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8581           // (X&4) == 2 --> false
8582           // (X&4) != 2 --> true
8583           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8584           Res = Context->getConstantExprZExt(Res, CI.getType());
8585           return ReplaceInstUsesWith(CI, Res);
8586         }
8587           
8588         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8589         Value *In = ICI->getOperand(0);
8590         if (ShiftAmt) {
8591           // Perform a logical shr by shiftamt.
8592           // Insert the shift to put the result in the low bit.
8593           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8594                               Context->getConstantInt(In->getType(), ShiftAmt),
8595                                                    In->getName()+".lobit"), CI);
8596         }
8597           
8598         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8599           Constant *One = Context->getConstantInt(In->getType(), 1);
8600           In = BinaryOperator::CreateXor(In, One, "tmp");
8601           InsertNewInstBefore(cast<Instruction>(In), CI);
8602         }
8603           
8604         if (CI.getType() == In->getType())
8605           return ReplaceInstUsesWith(CI, In);
8606         else
8607           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8608       }
8609     }
8610   }
8611
8612   return 0;
8613 }
8614
8615 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8616   // If one of the common conversion will work ..
8617   if (Instruction *Result = commonIntCastTransforms(CI))
8618     return Result;
8619
8620   Value *Src = CI.getOperand(0);
8621
8622   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8623   // types and if the sizes are just right we can convert this into a logical
8624   // 'and' which will be much cheaper than the pair of casts.
8625   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8626     // Get the sizes of the types involved.  We know that the intermediate type
8627     // will be smaller than A or C, but don't know the relation between A and C.
8628     Value *A = CSrc->getOperand(0);
8629     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8630     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8631     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8632     // If we're actually extending zero bits, then if
8633     // SrcSize <  DstSize: zext(a & mask)
8634     // SrcSize == DstSize: a & mask
8635     // SrcSize  > DstSize: trunc(a) & mask
8636     if (SrcSize < DstSize) {
8637       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8638       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8639       Instruction *And =
8640         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8641       InsertNewInstBefore(And, CI);
8642       return new ZExtInst(And, CI.getType());
8643     } else if (SrcSize == DstSize) {
8644       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8645       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8646                                                            AndValue));
8647     } else if (SrcSize > DstSize) {
8648       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8649       InsertNewInstBefore(Trunc, CI);
8650       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8651       return BinaryOperator::CreateAnd(Trunc, 
8652                                        Context->getConstantInt(Trunc->getType(),
8653                                                                AndValue));
8654     }
8655   }
8656
8657   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8658     return transformZExtICmp(ICI, CI);
8659
8660   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8661   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8662     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8663     // of the (zext icmp) will be transformed.
8664     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8665     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8666     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8667         (transformZExtICmp(LHS, CI, false) ||
8668          transformZExtICmp(RHS, CI, false))) {
8669       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8670       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8671       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8672     }
8673   }
8674
8675   // zext(trunc(t) & C) -> (t & zext(C)).
8676   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8677     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8678       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8679         Value *TI0 = TI->getOperand(0);
8680         if (TI0->getType() == CI.getType())
8681           return
8682             BinaryOperator::CreateAnd(TI0,
8683                                 Context->getConstantExprZExt(C, CI.getType()));
8684       }
8685
8686   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8687   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8688     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8689       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8690         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8691             And->getOperand(1) == C)
8692           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8693             Value *TI0 = TI->getOperand(0);
8694             if (TI0->getType() == CI.getType()) {
8695               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8696               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8697               InsertNewInstBefore(NewAnd, *And);
8698               return BinaryOperator::CreateXor(NewAnd, ZC);
8699             }
8700           }
8701
8702   return 0;
8703 }
8704
8705 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8706   if (Instruction *I = commonIntCastTransforms(CI))
8707     return I;
8708   
8709   Value *Src = CI.getOperand(0);
8710   
8711   // Canonicalize sign-extend from i1 to a select.
8712   if (Src->getType() == Type::Int1Ty)
8713     return SelectInst::Create(Src,
8714                               Context->getConstantIntAllOnesValue(CI.getType()),
8715                               Context->getNullValue(CI.getType()));
8716
8717   // See if the value being truncated is already sign extended.  If so, just
8718   // eliminate the trunc/sext pair.
8719   if (getOpcode(Src) == Instruction::Trunc) {
8720     Value *Op = cast<User>(Src)->getOperand(0);
8721     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8722     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8723     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8724     unsigned NumSignBits = ComputeNumSignBits(Op);
8725
8726     if (OpBits == DestBits) {
8727       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8728       // bits, it is already ready.
8729       if (NumSignBits > DestBits-MidBits)
8730         return ReplaceInstUsesWith(CI, Op);
8731     } else if (OpBits < DestBits) {
8732       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8733       // bits, just sext from i32.
8734       if (NumSignBits > OpBits-MidBits)
8735         return new SExtInst(Op, CI.getType(), "tmp");
8736     } else {
8737       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8738       // bits, just truncate to i32.
8739       if (NumSignBits > OpBits-MidBits)
8740         return new TruncInst(Op, CI.getType(), "tmp");
8741     }
8742   }
8743
8744   // If the input is a shl/ashr pair of a same constant, then this is a sign
8745   // extension from a smaller value.  If we could trust arbitrary bitwidth
8746   // integers, we could turn this into a truncate to the smaller bit and then
8747   // use a sext for the whole extension.  Since we don't, look deeper and check
8748   // for a truncate.  If the source and dest are the same type, eliminate the
8749   // trunc and extend and just do shifts.  For example, turn:
8750   //   %a = trunc i32 %i to i8
8751   //   %b = shl i8 %a, 6
8752   //   %c = ashr i8 %b, 6
8753   //   %d = sext i8 %c to i32
8754   // into:
8755   //   %a = shl i32 %i, 30
8756   //   %d = ashr i32 %a, 30
8757   Value *A = 0;
8758   ConstantInt *BA = 0, *CA = 0;
8759   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8760                         m_ConstantInt(CA)), *Context) &&
8761       BA == CA && isa<TruncInst>(A)) {
8762     Value *I = cast<TruncInst>(A)->getOperand(0);
8763     if (I->getType() == CI.getType()) {
8764       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8765       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8766       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8767       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8768       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8769                                                         CI.getName()), CI);
8770       return BinaryOperator::CreateAShr(I, ShAmtV);
8771     }
8772   }
8773   
8774   return 0;
8775 }
8776
8777 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8778 /// in the specified FP type without changing its value.
8779 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8780                               LLVMContext *Context) {
8781   bool losesInfo;
8782   APFloat F = CFP->getValueAPF();
8783   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8784   if (!losesInfo)
8785     return Context->getConstantFP(F);
8786   return 0;
8787 }
8788
8789 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8790 /// through it until we get the source value.
8791 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8792   if (Instruction *I = dyn_cast<Instruction>(V))
8793     if (I->getOpcode() == Instruction::FPExt)
8794       return LookThroughFPExtensions(I->getOperand(0), Context);
8795   
8796   // If this value is a constant, return the constant in the smallest FP type
8797   // that can accurately represent it.  This allows us to turn
8798   // (float)((double)X+2.0) into x+2.0f.
8799   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8800     if (CFP->getType() == Type::PPC_FP128Ty)
8801       return V;  // No constant folding of this.
8802     // See if the value can be truncated to float and then reextended.
8803     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8804       return V;
8805     if (CFP->getType() == Type::DoubleTy)
8806       return V;  // Won't shrink.
8807     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8808       return V;
8809     // Don't try to shrink to various long double types.
8810   }
8811   
8812   return V;
8813 }
8814
8815 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8816   if (Instruction *I = commonCastTransforms(CI))
8817     return I;
8818   
8819   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8820   // smaller than the destination type, we can eliminate the truncate by doing
8821   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8822   // many builtins (sqrt, etc).
8823   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8824   if (OpI && OpI->hasOneUse()) {
8825     switch (OpI->getOpcode()) {
8826     default: break;
8827     case Instruction::FAdd:
8828     case Instruction::FSub:
8829     case Instruction::FMul:
8830     case Instruction::FDiv:
8831     case Instruction::FRem:
8832       const Type *SrcTy = OpI->getType();
8833       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8834       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8835       if (LHSTrunc->getType() != SrcTy && 
8836           RHSTrunc->getType() != SrcTy) {
8837         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8838         // If the source types were both smaller than the destination type of
8839         // the cast, do this xform.
8840         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8841             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8842           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8843                                       CI.getType(), CI);
8844           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8845                                       CI.getType(), CI);
8846           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8847         }
8848       }
8849       break;  
8850     }
8851   }
8852   return 0;
8853 }
8854
8855 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8856   return commonCastTransforms(CI);
8857 }
8858
8859 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8860   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8861   if (OpI == 0)
8862     return commonCastTransforms(FI);
8863
8864   // fptoui(uitofp(X)) --> X
8865   // fptoui(sitofp(X)) --> X
8866   // This is safe if the intermediate type has enough bits in its mantissa to
8867   // accurately represent all values of X.  For example, do not do this with
8868   // i64->float->i64.  This is also safe for sitofp case, because any negative
8869   // 'X' value would cause an undefined result for the fptoui. 
8870   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8871       OpI->getOperand(0)->getType() == FI.getType() &&
8872       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8873                     OpI->getType()->getFPMantissaWidth())
8874     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8875
8876   return commonCastTransforms(FI);
8877 }
8878
8879 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8880   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8881   if (OpI == 0)
8882     return commonCastTransforms(FI);
8883   
8884   // fptosi(sitofp(X)) --> X
8885   // fptosi(uitofp(X)) --> X
8886   // This is safe if the intermediate type has enough bits in its mantissa to
8887   // accurately represent all values of X.  For example, do not do this with
8888   // i64->float->i64.  This is also safe for sitofp case, because any negative
8889   // 'X' value would cause an undefined result for the fptoui. 
8890   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8891       OpI->getOperand(0)->getType() == FI.getType() &&
8892       (int)FI.getType()->getScalarSizeInBits() <=
8893                     OpI->getType()->getFPMantissaWidth())
8894     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8895   
8896   return commonCastTransforms(FI);
8897 }
8898
8899 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8900   return commonCastTransforms(CI);
8901 }
8902
8903 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8904   return commonCastTransforms(CI);
8905 }
8906
8907 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8908   // If the destination integer type is smaller than the intptr_t type for
8909   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8910   // trunc to be exposed to other transforms.  Don't do this for extending
8911   // ptrtoint's, because we don't know if the target sign or zero extends its
8912   // pointers.
8913   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8914     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8915                                                     TD->getIntPtrType(),
8916                                                     "tmp"), CI);
8917     return new TruncInst(P, CI.getType());
8918   }
8919   
8920   return commonPointerCastTransforms(CI);
8921 }
8922
8923 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8924   // If the source integer type is larger than the intptr_t type for
8925   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8926   // allows the trunc to be exposed to other transforms.  Don't do this for
8927   // extending inttoptr's, because we don't know if the target sign or zero
8928   // extends to pointers.
8929   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8930       TD->getPointerSizeInBits()) {
8931     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8932                                                  TD->getIntPtrType(),
8933                                                  "tmp"), CI);
8934     return new IntToPtrInst(P, CI.getType());
8935   }
8936   
8937   if (Instruction *I = commonCastTransforms(CI))
8938     return I;
8939   
8940   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8941   if (!DestPointee->isSized()) return 0;
8942
8943   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8944   ConstantInt *Cst;
8945   Value *X;
8946   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8947                                     m_ConstantInt(Cst)), *Context)) {
8948     // If the source and destination operands have the same type, see if this
8949     // is a single-index GEP.
8950     if (X->getType() == CI.getType()) {
8951       // Get the size of the pointee type.
8952       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8953
8954       // Convert the constant to intptr type.
8955       APInt Offset = Cst->getValue();
8956       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8957
8958       // If Offset is evenly divisible by Size, we can do this xform.
8959       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8960         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8961         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8962       }
8963     }
8964     // TODO: Could handle other cases, e.g. where add is indexing into field of
8965     // struct etc.
8966   } else if (CI.getOperand(0)->hasOneUse() &&
8967              match(CI.getOperand(0), m_Add(m_Value(X),
8968                    m_ConstantInt(Cst)), *Context)) {
8969     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8970     // "inttoptr+GEP" instead of "add+intptr".
8971     
8972     // Get the size of the pointee type.
8973     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8974     
8975     // Convert the constant to intptr type.
8976     APInt Offset = Cst->getValue();
8977     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8978     
8979     // If Offset is evenly divisible by Size, we can do this xform.
8980     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8981       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8982       
8983       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8984                                                             "tmp"), CI);
8985       return GetElementPtrInst::Create(P,
8986                                        Context->getConstantInt(Offset), "tmp");
8987     }
8988   }
8989   return 0;
8990 }
8991
8992 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8993   // If the operands are integer typed then apply the integer transforms,
8994   // otherwise just apply the common ones.
8995   Value *Src = CI.getOperand(0);
8996   const Type *SrcTy = Src->getType();
8997   const Type *DestTy = CI.getType();
8998
8999   if (SrcTy->isInteger() && DestTy->isInteger()) {
9000     if (Instruction *Result = commonIntCastTransforms(CI))
9001       return Result;
9002   } else if (isa<PointerType>(SrcTy)) {
9003     if (Instruction *I = commonPointerCastTransforms(CI))
9004       return I;
9005   } else {
9006     if (Instruction *Result = commonCastTransforms(CI))
9007       return Result;
9008   }
9009
9010
9011   // Get rid of casts from one type to the same type. These are useless and can
9012   // be replaced by the operand.
9013   if (DestTy == Src->getType())
9014     return ReplaceInstUsesWith(CI, Src);
9015
9016   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9017     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9018     const Type *DstElTy = DstPTy->getElementType();
9019     const Type *SrcElTy = SrcPTy->getElementType();
9020     
9021     // If the address spaces don't match, don't eliminate the bitcast, which is
9022     // required for changing types.
9023     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9024       return 0;
9025     
9026     // If we are casting a malloc or alloca to a pointer to a type of the same
9027     // size, rewrite the allocation instruction to allocate the "right" type.
9028     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9029       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9030         return V;
9031     
9032     // If the source and destination are pointers, and this cast is equivalent
9033     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9034     // This can enhance SROA and other transforms that want type-safe pointers.
9035     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9036     unsigned NumZeros = 0;
9037     while (SrcElTy != DstElTy && 
9038            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9039            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9040       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9041       ++NumZeros;
9042     }
9043
9044     // If we found a path from the src to dest, create the getelementptr now.
9045     if (SrcElTy == DstElTy) {
9046       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9047       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9048                                        ((Instruction*) NULL));
9049     }
9050   }
9051
9052   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9053     if (SVI->hasOneUse()) {
9054       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9055       // a bitconvert to a vector with the same # elts.
9056       if (isa<VectorType>(DestTy) && 
9057           cast<VectorType>(DestTy)->getNumElements() ==
9058                 SVI->getType()->getNumElements() &&
9059           SVI->getType()->getNumElements() ==
9060             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9061         CastInst *Tmp;
9062         // If either of the operands is a cast from CI.getType(), then
9063         // evaluating the shuffle in the casted destination's type will allow
9064         // us to eliminate at least one cast.
9065         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9066              Tmp->getOperand(0)->getType() == DestTy) ||
9067             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9068              Tmp->getOperand(0)->getType() == DestTy)) {
9069           Value *LHS = InsertCastBefore(Instruction::BitCast,
9070                                         SVI->getOperand(0), DestTy, CI);
9071           Value *RHS = InsertCastBefore(Instruction::BitCast,
9072                                         SVI->getOperand(1), DestTy, CI);
9073           // Return a new shuffle vector.  Use the same element ID's, as we
9074           // know the vector types match #elts.
9075           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9076         }
9077       }
9078     }
9079   }
9080   return 0;
9081 }
9082
9083 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9084 ///   %C = or %A, %B
9085 ///   %D = select %cond, %C, %A
9086 /// into:
9087 ///   %C = select %cond, %B, 0
9088 ///   %D = or %A, %C
9089 ///
9090 /// Assuming that the specified instruction is an operand to the select, return
9091 /// a bitmask indicating which operands of this instruction are foldable if they
9092 /// equal the other incoming value of the select.
9093 ///
9094 static unsigned GetSelectFoldableOperands(Instruction *I) {
9095   switch (I->getOpcode()) {
9096   case Instruction::Add:
9097   case Instruction::Mul:
9098   case Instruction::And:
9099   case Instruction::Or:
9100   case Instruction::Xor:
9101     return 3;              // Can fold through either operand.
9102   case Instruction::Sub:   // Can only fold on the amount subtracted.
9103   case Instruction::Shl:   // Can only fold on the shift amount.
9104   case Instruction::LShr:
9105   case Instruction::AShr:
9106     return 1;
9107   default:
9108     return 0;              // Cannot fold
9109   }
9110 }
9111
9112 /// GetSelectFoldableConstant - For the same transformation as the previous
9113 /// function, return the identity constant that goes into the select.
9114 static Constant *GetSelectFoldableConstant(Instruction *I,
9115                                            LLVMContext *Context) {
9116   switch (I->getOpcode()) {
9117   default: assert(0 && "This cannot happen!"); abort();
9118   case Instruction::Add:
9119   case Instruction::Sub:
9120   case Instruction::Or:
9121   case Instruction::Xor:
9122   case Instruction::Shl:
9123   case Instruction::LShr:
9124   case Instruction::AShr:
9125     return Context->getNullValue(I->getType());
9126   case Instruction::And:
9127     return Context->getAllOnesValue(I->getType());
9128   case Instruction::Mul:
9129     return Context->getConstantInt(I->getType(), 1);
9130   }
9131 }
9132
9133 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9134 /// have the same opcode and only one use each.  Try to simplify this.
9135 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9136                                           Instruction *FI) {
9137   if (TI->getNumOperands() == 1) {
9138     // If this is a non-volatile load or a cast from the same type,
9139     // merge.
9140     if (TI->isCast()) {
9141       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9142         return 0;
9143     } else {
9144       return 0;  // unknown unary op.
9145     }
9146
9147     // Fold this by inserting a select from the input values.
9148     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9149                                            FI->getOperand(0), SI.getName()+".v");
9150     InsertNewInstBefore(NewSI, SI);
9151     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9152                             TI->getType());
9153   }
9154
9155   // Only handle binary operators here.
9156   if (!isa<BinaryOperator>(TI))
9157     return 0;
9158
9159   // Figure out if the operations have any operands in common.
9160   Value *MatchOp, *OtherOpT, *OtherOpF;
9161   bool MatchIsOpZero;
9162   if (TI->getOperand(0) == FI->getOperand(0)) {
9163     MatchOp  = TI->getOperand(0);
9164     OtherOpT = TI->getOperand(1);
9165     OtherOpF = FI->getOperand(1);
9166     MatchIsOpZero = true;
9167   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9168     MatchOp  = TI->getOperand(1);
9169     OtherOpT = TI->getOperand(0);
9170     OtherOpF = FI->getOperand(0);
9171     MatchIsOpZero = false;
9172   } else if (!TI->isCommutative()) {
9173     return 0;
9174   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9175     MatchOp  = TI->getOperand(0);
9176     OtherOpT = TI->getOperand(1);
9177     OtherOpF = FI->getOperand(0);
9178     MatchIsOpZero = true;
9179   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9180     MatchOp  = TI->getOperand(1);
9181     OtherOpT = TI->getOperand(0);
9182     OtherOpF = FI->getOperand(1);
9183     MatchIsOpZero = true;
9184   } else {
9185     return 0;
9186   }
9187
9188   // If we reach here, they do have operations in common.
9189   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9190                                          OtherOpF, SI.getName()+".v");
9191   InsertNewInstBefore(NewSI, SI);
9192
9193   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9194     if (MatchIsOpZero)
9195       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9196     else
9197       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9198   }
9199   assert(0 && "Shouldn't get here");
9200   return 0;
9201 }
9202
9203 static bool isSelect01(Constant *C1, Constant *C2) {
9204   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9205   if (!C1I)
9206     return false;
9207   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9208   if (!C2I)
9209     return false;
9210   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9211 }
9212
9213 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9214 /// facilitate further optimization.
9215 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9216                                             Value *FalseVal) {
9217   // See the comment above GetSelectFoldableOperands for a description of the
9218   // transformation we are doing here.
9219   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9220     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9221         !isa<Constant>(FalseVal)) {
9222       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9223         unsigned OpToFold = 0;
9224         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9225           OpToFold = 1;
9226         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9227           OpToFold = 2;
9228         }
9229
9230         if (OpToFold) {
9231           Constant *C = GetSelectFoldableConstant(TVI, Context);
9232           Value *OOp = TVI->getOperand(2-OpToFold);
9233           // Avoid creating select between 2 constants unless it's selecting
9234           // between 0 and 1.
9235           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9236             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9237             InsertNewInstBefore(NewSel, SI);
9238             NewSel->takeName(TVI);
9239             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9240               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9241             assert(0 && "Unknown instruction!!");
9242           }
9243         }
9244       }
9245     }
9246   }
9247
9248   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9249     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9250         !isa<Constant>(TrueVal)) {
9251       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9252         unsigned OpToFold = 0;
9253         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9254           OpToFold = 1;
9255         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9256           OpToFold = 2;
9257         }
9258
9259         if (OpToFold) {
9260           Constant *C = GetSelectFoldableConstant(FVI, Context);
9261           Value *OOp = FVI->getOperand(2-OpToFold);
9262           // Avoid creating select between 2 constants unless it's selecting
9263           // between 0 and 1.
9264           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9265             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9266             InsertNewInstBefore(NewSel, SI);
9267             NewSel->takeName(FVI);
9268             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9269               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9270             assert(0 && "Unknown instruction!!");
9271           }
9272         }
9273       }
9274     }
9275   }
9276
9277   return 0;
9278 }
9279
9280 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9281 /// ICmpInst as its first operand.
9282 ///
9283 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9284                                                    ICmpInst *ICI) {
9285   bool Changed = false;
9286   ICmpInst::Predicate Pred = ICI->getPredicate();
9287   Value *CmpLHS = ICI->getOperand(0);
9288   Value *CmpRHS = ICI->getOperand(1);
9289   Value *TrueVal = SI.getTrueValue();
9290   Value *FalseVal = SI.getFalseValue();
9291
9292   // Check cases where the comparison is with a constant that
9293   // can be adjusted to fit the min/max idiom. We may edit ICI in
9294   // place here, so make sure the select is the only user.
9295   if (ICI->hasOneUse())
9296     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9297       switch (Pred) {
9298       default: break;
9299       case ICmpInst::ICMP_ULT:
9300       case ICmpInst::ICMP_SLT: {
9301         // X < MIN ? T : F  -->  F
9302         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9303           return ReplaceInstUsesWith(SI, FalseVal);
9304         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9305         Constant *AdjustedRHS = SubOne(CI, Context);
9306         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9307             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9308           Pred = ICmpInst::getSwappedPredicate(Pred);
9309           CmpRHS = AdjustedRHS;
9310           std::swap(FalseVal, TrueVal);
9311           ICI->setPredicate(Pred);
9312           ICI->setOperand(1, CmpRHS);
9313           SI.setOperand(1, TrueVal);
9314           SI.setOperand(2, FalseVal);
9315           Changed = true;
9316         }
9317         break;
9318       }
9319       case ICmpInst::ICMP_UGT:
9320       case ICmpInst::ICMP_SGT: {
9321         // X > MAX ? T : F  -->  F
9322         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9323           return ReplaceInstUsesWith(SI, FalseVal);
9324         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9325         Constant *AdjustedRHS = AddOne(CI, Context);
9326         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9327             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9328           Pred = ICmpInst::getSwappedPredicate(Pred);
9329           CmpRHS = AdjustedRHS;
9330           std::swap(FalseVal, TrueVal);
9331           ICI->setPredicate(Pred);
9332           ICI->setOperand(1, CmpRHS);
9333           SI.setOperand(1, TrueVal);
9334           SI.setOperand(2, FalseVal);
9335           Changed = true;
9336         }
9337         break;
9338       }
9339       }
9340
9341       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9342       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9343       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9344       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9345           match(FalseVal, m_ConstantInt<0>(), *Context))
9346         Pred = ICI->getPredicate();
9347       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9348                match(FalseVal, m_ConstantInt<-1>(), *Context))
9349         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9350       
9351       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9352         // If we are just checking for a icmp eq of a single bit and zext'ing it
9353         // to an integer, then shift the bit to the appropriate place and then
9354         // cast to integer to avoid the comparison.
9355         const APInt &Op1CV = CI->getValue();
9356     
9357         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9358         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9359         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9360             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9361           Value *In = ICI->getOperand(0);
9362           Value *Sh = Context->getConstantInt(In->getType(),
9363                                        In->getType()->getScalarSizeInBits()-1);
9364           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9365                                                           In->getName()+".lobit"),
9366                                    *ICI);
9367           if (In->getType() != SI.getType())
9368             In = CastInst::CreateIntegerCast(In, SI.getType(),
9369                                              true/*SExt*/, "tmp", ICI);
9370     
9371           if (Pred == ICmpInst::ICMP_SGT)
9372             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9373                                        In->getName()+".not"), *ICI);
9374     
9375           return ReplaceInstUsesWith(SI, In);
9376         }
9377       }
9378     }
9379
9380   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9381     // Transform (X == Y) ? X : Y  -> Y
9382     if (Pred == ICmpInst::ICMP_EQ)
9383       return ReplaceInstUsesWith(SI, FalseVal);
9384     // Transform (X != Y) ? X : Y  -> X
9385     if (Pred == ICmpInst::ICMP_NE)
9386       return ReplaceInstUsesWith(SI, TrueVal);
9387     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9388
9389   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9390     // Transform (X == Y) ? Y : X  -> X
9391     if (Pred == ICmpInst::ICMP_EQ)
9392       return ReplaceInstUsesWith(SI, FalseVal);
9393     // Transform (X != Y) ? Y : X  -> Y
9394     if (Pred == ICmpInst::ICMP_NE)
9395       return ReplaceInstUsesWith(SI, TrueVal);
9396     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9397   }
9398
9399   /// NOTE: if we wanted to, this is where to detect integer ABS
9400
9401   return Changed ? &SI : 0;
9402 }
9403
9404 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9405   Value *CondVal = SI.getCondition();
9406   Value *TrueVal = SI.getTrueValue();
9407   Value *FalseVal = SI.getFalseValue();
9408
9409   // select true, X, Y  -> X
9410   // select false, X, Y -> Y
9411   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9412     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9413
9414   // select C, X, X -> X
9415   if (TrueVal == FalseVal)
9416     return ReplaceInstUsesWith(SI, TrueVal);
9417
9418   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9419     return ReplaceInstUsesWith(SI, FalseVal);
9420   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9421     return ReplaceInstUsesWith(SI, TrueVal);
9422   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9423     if (isa<Constant>(TrueVal))
9424       return ReplaceInstUsesWith(SI, TrueVal);
9425     else
9426       return ReplaceInstUsesWith(SI, FalseVal);
9427   }
9428
9429   if (SI.getType() == Type::Int1Ty) {
9430     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9431       if (C->getZExtValue()) {
9432         // Change: A = select B, true, C --> A = or B, C
9433         return BinaryOperator::CreateOr(CondVal, FalseVal);
9434       } else {
9435         // Change: A = select B, false, C --> A = and !B, C
9436         Value *NotCond =
9437           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9438                                              "not."+CondVal->getName()), SI);
9439         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9440       }
9441     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9442       if (C->getZExtValue() == false) {
9443         // Change: A = select B, C, false --> A = and B, C
9444         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9445       } else {
9446         // Change: A = select B, C, true --> A = or !B, C
9447         Value *NotCond =
9448           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9449                                              "not."+CondVal->getName()), SI);
9450         return BinaryOperator::CreateOr(NotCond, TrueVal);
9451       }
9452     }
9453     
9454     // select a, b, a  -> a&b
9455     // select a, a, b  -> a|b
9456     if (CondVal == TrueVal)
9457       return BinaryOperator::CreateOr(CondVal, FalseVal);
9458     else if (CondVal == FalseVal)
9459       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9460   }
9461
9462   // Selecting between two integer constants?
9463   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9464     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9465       // select C, 1, 0 -> zext C to int
9466       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9467         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9468       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9469         // select C, 0, 1 -> zext !C to int
9470         Value *NotCond =
9471           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9472                                                "not."+CondVal->getName()), SI);
9473         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9474       }
9475
9476       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9477
9478         // (x <s 0) ? -1 : 0 -> ashr x, 31
9479         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9480           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9481             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9482               // The comparison constant and the result are not neccessarily the
9483               // same width. Make an all-ones value by inserting a AShr.
9484               Value *X = IC->getOperand(0);
9485               uint32_t Bits = X->getType()->getScalarSizeInBits();
9486               Constant *ShAmt = Context->getConstantInt(X->getType(), Bits-1);
9487               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9488                                                         ShAmt, "ones");
9489               InsertNewInstBefore(SRA, SI);
9490
9491               // Then cast to the appropriate width.
9492               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9493             }
9494           }
9495
9496
9497         // If one of the constants is zero (we know they can't both be) and we
9498         // have an icmp instruction with zero, and we have an 'and' with the
9499         // non-constant value, eliminate this whole mess.  This corresponds to
9500         // cases like this: ((X & 27) ? 27 : 0)
9501         if (TrueValC->isZero() || FalseValC->isZero())
9502           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9503               cast<Constant>(IC->getOperand(1))->isNullValue())
9504             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9505               if (ICA->getOpcode() == Instruction::And &&
9506                   isa<ConstantInt>(ICA->getOperand(1)) &&
9507                   (ICA->getOperand(1) == TrueValC ||
9508                    ICA->getOperand(1) == FalseValC) &&
9509                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9510                 // Okay, now we know that everything is set up, we just don't
9511                 // know whether we have a icmp_ne or icmp_eq and whether the 
9512                 // true or false val is the zero.
9513                 bool ShouldNotVal = !TrueValC->isZero();
9514                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9515                 Value *V = ICA;
9516                 if (ShouldNotVal)
9517                   V = InsertNewInstBefore(BinaryOperator::Create(
9518                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9519                 return ReplaceInstUsesWith(SI, V);
9520               }
9521       }
9522     }
9523
9524   // See if we are selecting two values based on a comparison of the two values.
9525   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9526     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9527       // Transform (X == Y) ? X : Y  -> Y
9528       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9529         // This is not safe in general for floating point:  
9530         // consider X== -0, Y== +0.
9531         // It becomes safe if either operand is a nonzero constant.
9532         ConstantFP *CFPt, *CFPf;
9533         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9534               !CFPt->getValueAPF().isZero()) ||
9535             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9536              !CFPf->getValueAPF().isZero()))
9537         return ReplaceInstUsesWith(SI, FalseVal);
9538       }
9539       // Transform (X != Y) ? X : Y  -> X
9540       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9541         return ReplaceInstUsesWith(SI, TrueVal);
9542       // NOTE: if we wanted to, this is where to detect MIN/MAX
9543
9544     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9545       // Transform (X == Y) ? Y : X  -> X
9546       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9547         // This is not safe in general for floating point:  
9548         // consider X== -0, Y== +0.
9549         // It becomes safe if either operand is a nonzero constant.
9550         ConstantFP *CFPt, *CFPf;
9551         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9552               !CFPt->getValueAPF().isZero()) ||
9553             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9554              !CFPf->getValueAPF().isZero()))
9555           return ReplaceInstUsesWith(SI, FalseVal);
9556       }
9557       // Transform (X != Y) ? Y : X  -> Y
9558       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9559         return ReplaceInstUsesWith(SI, TrueVal);
9560       // NOTE: if we wanted to, this is where to detect MIN/MAX
9561     }
9562     // NOTE: if we wanted to, this is where to detect ABS
9563   }
9564
9565   // See if we are selecting two values based on a comparison of the two values.
9566   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9567     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9568       return Result;
9569
9570   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9571     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9572       if (TI->hasOneUse() && FI->hasOneUse()) {
9573         Instruction *AddOp = 0, *SubOp = 0;
9574
9575         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9576         if (TI->getOpcode() == FI->getOpcode())
9577           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9578             return IV;
9579
9580         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9581         // even legal for FP.
9582         if ((TI->getOpcode() == Instruction::Sub &&
9583              FI->getOpcode() == Instruction::Add) ||
9584             (TI->getOpcode() == Instruction::FSub &&
9585              FI->getOpcode() == Instruction::FAdd)) {
9586           AddOp = FI; SubOp = TI;
9587         } else if ((FI->getOpcode() == Instruction::Sub &&
9588                     TI->getOpcode() == Instruction::Add) ||
9589                    (FI->getOpcode() == Instruction::FSub &&
9590                     TI->getOpcode() == Instruction::FAdd)) {
9591           AddOp = TI; SubOp = FI;
9592         }
9593
9594         if (AddOp) {
9595           Value *OtherAddOp = 0;
9596           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9597             OtherAddOp = AddOp->getOperand(1);
9598           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9599             OtherAddOp = AddOp->getOperand(0);
9600           }
9601
9602           if (OtherAddOp) {
9603             // So at this point we know we have (Y -> OtherAddOp):
9604             //        select C, (add X, Y), (sub X, Z)
9605             Value *NegVal;  // Compute -Z
9606             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9607               NegVal = Context->getConstantExprNeg(C);
9608             } else {
9609               NegVal = InsertNewInstBefore(
9610                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9611             }
9612
9613             Value *NewTrueOp = OtherAddOp;
9614             Value *NewFalseOp = NegVal;
9615             if (AddOp != TI)
9616               std::swap(NewTrueOp, NewFalseOp);
9617             Instruction *NewSel =
9618               SelectInst::Create(CondVal, NewTrueOp,
9619                                  NewFalseOp, SI.getName() + ".p");
9620
9621             NewSel = InsertNewInstBefore(NewSel, SI);
9622             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9623           }
9624         }
9625       }
9626
9627   // See if we can fold the select into one of our operands.
9628   if (SI.getType()->isInteger()) {
9629     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9630     if (FoldI)
9631       return FoldI;
9632   }
9633
9634   if (BinaryOperator::isNot(CondVal)) {
9635     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9636     SI.setOperand(1, FalseVal);
9637     SI.setOperand(2, TrueVal);
9638     return &SI;
9639   }
9640
9641   return 0;
9642 }
9643
9644 /// EnforceKnownAlignment - If the specified pointer points to an object that
9645 /// we control, modify the object's alignment to PrefAlign. This isn't
9646 /// often possible though. If alignment is important, a more reliable approach
9647 /// is to simply align all global variables and allocation instructions to
9648 /// their preferred alignment from the beginning.
9649 ///
9650 static unsigned EnforceKnownAlignment(Value *V,
9651                                       unsigned Align, unsigned PrefAlign) {
9652
9653   User *U = dyn_cast<User>(V);
9654   if (!U) return Align;
9655
9656   switch (getOpcode(U)) {
9657   default: break;
9658   case Instruction::BitCast:
9659     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9660   case Instruction::GetElementPtr: {
9661     // If all indexes are zero, it is just the alignment of the base pointer.
9662     bool AllZeroOperands = true;
9663     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9664       if (!isa<Constant>(*i) ||
9665           !cast<Constant>(*i)->isNullValue()) {
9666         AllZeroOperands = false;
9667         break;
9668       }
9669
9670     if (AllZeroOperands) {
9671       // Treat this like a bitcast.
9672       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9673     }
9674     break;
9675   }
9676   }
9677
9678   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9679     // If there is a large requested alignment and we can, bump up the alignment
9680     // of the global.
9681     if (!GV->isDeclaration()) {
9682       if (GV->getAlignment() >= PrefAlign)
9683         Align = GV->getAlignment();
9684       else {
9685         GV->setAlignment(PrefAlign);
9686         Align = PrefAlign;
9687       }
9688     }
9689   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9690     // If there is a requested alignment and if this is an alloca, round up.  We
9691     // don't do this for malloc, because some systems can't respect the request.
9692     if (isa<AllocaInst>(AI)) {
9693       if (AI->getAlignment() >= PrefAlign)
9694         Align = AI->getAlignment();
9695       else {
9696         AI->setAlignment(PrefAlign);
9697         Align = PrefAlign;
9698       }
9699     }
9700   }
9701
9702   return Align;
9703 }
9704
9705 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9706 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9707 /// and it is more than the alignment of the ultimate object, see if we can
9708 /// increase the alignment of the ultimate object, making this check succeed.
9709 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9710                                                   unsigned PrefAlign) {
9711   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9712                       sizeof(PrefAlign) * CHAR_BIT;
9713   APInt Mask = APInt::getAllOnesValue(BitWidth);
9714   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9715   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9716   unsigned TrailZ = KnownZero.countTrailingOnes();
9717   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9718
9719   if (PrefAlign > Align)
9720     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9721   
9722     // We don't need to make any adjustment.
9723   return Align;
9724 }
9725
9726 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9727   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9728   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9729   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9730   unsigned CopyAlign = MI->getAlignment();
9731
9732   if (CopyAlign < MinAlign) {
9733     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9734                                              MinAlign, false));
9735     return MI;
9736   }
9737   
9738   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9739   // load/store.
9740   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9741   if (MemOpLength == 0) return 0;
9742   
9743   // Source and destination pointer types are always "i8*" for intrinsic.  See
9744   // if the size is something we can handle with a single primitive load/store.
9745   // A single load+store correctly handles overlapping memory in the memmove
9746   // case.
9747   unsigned Size = MemOpLength->getZExtValue();
9748   if (Size == 0) return MI;  // Delete this mem transfer.
9749   
9750   if (Size > 8 || (Size&(Size-1)))
9751     return 0;  // If not 1/2/4/8 bytes, exit.
9752   
9753   // Use an integer load+store unless we can find something better.
9754   Type *NewPtrTy =
9755                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9756   
9757   // Memcpy forces the use of i8* for the source and destination.  That means
9758   // that if you're using memcpy to move one double around, you'll get a cast
9759   // from double* to i8*.  We'd much rather use a double load+store rather than
9760   // an i64 load+store, here because this improves the odds that the source or
9761   // dest address will be promotable.  See if we can find a better type than the
9762   // integer datatype.
9763   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9764     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9765     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9766       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9767       // down through these levels if so.
9768       while (!SrcETy->isSingleValueType()) {
9769         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9770           if (STy->getNumElements() == 1)
9771             SrcETy = STy->getElementType(0);
9772           else
9773             break;
9774         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9775           if (ATy->getNumElements() == 1)
9776             SrcETy = ATy->getElementType();
9777           else
9778             break;
9779         } else
9780           break;
9781       }
9782       
9783       if (SrcETy->isSingleValueType())
9784         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9785     }
9786   }
9787   
9788   
9789   // If the memcpy/memmove provides better alignment info than we can
9790   // infer, use it.
9791   SrcAlign = std::max(SrcAlign, CopyAlign);
9792   DstAlign = std::max(DstAlign, CopyAlign);
9793   
9794   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9795   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9796   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9797   InsertNewInstBefore(L, *MI);
9798   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9799
9800   // Set the size of the copy to 0, it will be deleted on the next iteration.
9801   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9802   return MI;
9803 }
9804
9805 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9806   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9807   if (MI->getAlignment() < Alignment) {
9808     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9809                                              Alignment, false));
9810     return MI;
9811   }
9812   
9813   // Extract the length and alignment and fill if they are constant.
9814   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9815   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9816   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9817     return 0;
9818   uint64_t Len = LenC->getZExtValue();
9819   Alignment = MI->getAlignment();
9820   
9821   // If the length is zero, this is a no-op
9822   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9823   
9824   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9825   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9826     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9827     
9828     Value *Dest = MI->getDest();
9829     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9830
9831     // Alignment 0 is identity for alignment 1 for memset, but not store.
9832     if (Alignment == 0) Alignment = 1;
9833     
9834     // Extract the fill value and store.
9835     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9836     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9837                                       Dest, false, Alignment), *MI);
9838     
9839     // Set the size of the copy to 0, it will be deleted on the next iteration.
9840     MI->setLength(Context->getNullValue(LenC->getType()));
9841     return MI;
9842   }
9843
9844   return 0;
9845 }
9846
9847
9848 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9849 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9850 /// the heavy lifting.
9851 ///
9852 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9853   // If the caller function is nounwind, mark the call as nounwind, even if the
9854   // callee isn't.
9855   if (CI.getParent()->getParent()->doesNotThrow() &&
9856       !CI.doesNotThrow()) {
9857     CI.setDoesNotThrow();
9858     return &CI;
9859   }
9860   
9861   
9862   
9863   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9864   if (!II) return visitCallSite(&CI);
9865   
9866   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9867   // visitCallSite.
9868   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9869     bool Changed = false;
9870
9871     // memmove/cpy/set of zero bytes is a noop.
9872     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9873       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9874
9875       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9876         if (CI->getZExtValue() == 1) {
9877           // Replace the instruction with just byte operations.  We would
9878           // transform other cases to loads/stores, but we don't know if
9879           // alignment is sufficient.
9880         }
9881     }
9882
9883     // If we have a memmove and the source operation is a constant global,
9884     // then the source and dest pointers can't alias, so we can change this
9885     // into a call to memcpy.
9886     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9887       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9888         if (GVSrc->isConstant()) {
9889           Module *M = CI.getParent()->getParent()->getParent();
9890           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9891           const Type *Tys[1];
9892           Tys[0] = CI.getOperand(3)->getType();
9893           CI.setOperand(0, 
9894                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9895           Changed = true;
9896         }
9897
9898       // memmove(x,x,size) -> noop.
9899       if (MMI->getSource() == MMI->getDest())
9900         return EraseInstFromFunction(CI);
9901     }
9902
9903     // If we can determine a pointer alignment that is bigger than currently
9904     // set, update the alignment.
9905     if (isa<MemTransferInst>(MI)) {
9906       if (Instruction *I = SimplifyMemTransfer(MI))
9907         return I;
9908     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9909       if (Instruction *I = SimplifyMemSet(MSI))
9910         return I;
9911     }
9912           
9913     if (Changed) return II;
9914   }
9915   
9916   switch (II->getIntrinsicID()) {
9917   default: break;
9918   case Intrinsic::bswap:
9919     // bswap(bswap(x)) -> x
9920     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9921       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9922         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9923     break;
9924   case Intrinsic::ppc_altivec_lvx:
9925   case Intrinsic::ppc_altivec_lvxl:
9926   case Intrinsic::x86_sse_loadu_ps:
9927   case Intrinsic::x86_sse2_loadu_pd:
9928   case Intrinsic::x86_sse2_loadu_dq:
9929     // Turn PPC lvx     -> load if the pointer is known aligned.
9930     // Turn X86 loadups -> load if the pointer is known aligned.
9931     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9932       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9933                                    Context->getPointerTypeUnqual(II->getType()),
9934                                        CI);
9935       return new LoadInst(Ptr);
9936     }
9937     break;
9938   case Intrinsic::ppc_altivec_stvx:
9939   case Intrinsic::ppc_altivec_stvxl:
9940     // Turn stvx -> store if the pointer is known aligned.
9941     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9942       const Type *OpPtrTy = 
9943         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9944       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9945       return new StoreInst(II->getOperand(1), Ptr);
9946     }
9947     break;
9948   case Intrinsic::x86_sse_storeu_ps:
9949   case Intrinsic::x86_sse2_storeu_pd:
9950   case Intrinsic::x86_sse2_storeu_dq:
9951     // Turn X86 storeu -> store if the pointer is known aligned.
9952     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9953       const Type *OpPtrTy = 
9954         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9955       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9956       return new StoreInst(II->getOperand(2), Ptr);
9957     }
9958     break;
9959     
9960   case Intrinsic::x86_sse_cvttss2si: {
9961     // These intrinsics only demands the 0th element of its input vector.  If
9962     // we can simplify the input based on that, do so now.
9963     unsigned VWidth =
9964       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9965     APInt DemandedElts(VWidth, 1);
9966     APInt UndefElts(VWidth, 0);
9967     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9968                                               UndefElts)) {
9969       II->setOperand(1, V);
9970       return II;
9971     }
9972     break;
9973   }
9974     
9975   case Intrinsic::ppc_altivec_vperm:
9976     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9977     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9978       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9979       
9980       // Check that all of the elements are integer constants or undefs.
9981       bool AllEltsOk = true;
9982       for (unsigned i = 0; i != 16; ++i) {
9983         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9984             !isa<UndefValue>(Mask->getOperand(i))) {
9985           AllEltsOk = false;
9986           break;
9987         }
9988       }
9989       
9990       if (AllEltsOk) {
9991         // Cast the input vectors to byte vectors.
9992         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9993         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9994         Value *Result = Context->getUndef(Op0->getType());
9995         
9996         // Only extract each element once.
9997         Value *ExtractedElts[32];
9998         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9999         
10000         for (unsigned i = 0; i != 16; ++i) {
10001           if (isa<UndefValue>(Mask->getOperand(i)))
10002             continue;
10003           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10004           Idx &= 31;  // Match the hardware behavior.
10005           
10006           if (ExtractedElts[Idx] == 0) {
10007             Instruction *Elt = 
10008               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
10009             InsertNewInstBefore(Elt, CI);
10010             ExtractedElts[Idx] = Elt;
10011           }
10012         
10013           // Insert this value into the result vector.
10014           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10015                                              i, "tmp");
10016           InsertNewInstBefore(cast<Instruction>(Result), CI);
10017         }
10018         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10019       }
10020     }
10021     break;
10022
10023   case Intrinsic::stackrestore: {
10024     // If the save is right next to the restore, remove the restore.  This can
10025     // happen when variable allocas are DCE'd.
10026     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10027       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10028         BasicBlock::iterator BI = SS;
10029         if (&*++BI == II)
10030           return EraseInstFromFunction(CI);
10031       }
10032     }
10033     
10034     // Scan down this block to see if there is another stack restore in the
10035     // same block without an intervening call/alloca.
10036     BasicBlock::iterator BI = II;
10037     TerminatorInst *TI = II->getParent()->getTerminator();
10038     bool CannotRemove = false;
10039     for (++BI; &*BI != TI; ++BI) {
10040       if (isa<AllocaInst>(BI)) {
10041         CannotRemove = true;
10042         break;
10043       }
10044       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10045         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10046           // If there is a stackrestore below this one, remove this one.
10047           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10048             return EraseInstFromFunction(CI);
10049           // Otherwise, ignore the intrinsic.
10050         } else {
10051           // If we found a non-intrinsic call, we can't remove the stack
10052           // restore.
10053           CannotRemove = true;
10054           break;
10055         }
10056       }
10057     }
10058     
10059     // If the stack restore is in a return/unwind block and if there are no
10060     // allocas or calls between the restore and the return, nuke the restore.
10061     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10062       return EraseInstFromFunction(CI);
10063     break;
10064   }
10065   }
10066
10067   return visitCallSite(II);
10068 }
10069
10070 // InvokeInst simplification
10071 //
10072 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10073   return visitCallSite(&II);
10074 }
10075
10076 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10077 /// passed through the varargs area, we can eliminate the use of the cast.
10078 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10079                                          const CastInst * const CI,
10080                                          const TargetData * const TD,
10081                                          const int ix) {
10082   if (!CI->isLosslessCast())
10083     return false;
10084
10085   // The size of ByVal arguments is derived from the type, so we
10086   // can't change to a type with a different size.  If the size were
10087   // passed explicitly we could avoid this check.
10088   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10089     return true;
10090
10091   const Type* SrcTy = 
10092             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10093   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10094   if (!SrcTy->isSized() || !DstTy->isSized())
10095     return false;
10096   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10097     return false;
10098   return true;
10099 }
10100
10101 // visitCallSite - Improvements for call and invoke instructions.
10102 //
10103 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10104   bool Changed = false;
10105
10106   // If the callee is a constexpr cast of a function, attempt to move the cast
10107   // to the arguments of the call/invoke.
10108   if (transformConstExprCastCall(CS)) return 0;
10109
10110   Value *Callee = CS.getCalledValue();
10111
10112   if (Function *CalleeF = dyn_cast<Function>(Callee))
10113     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10114       Instruction *OldCall = CS.getInstruction();
10115       // If the call and callee calling conventions don't match, this call must
10116       // be unreachable, as the call is undefined.
10117       new StoreInst(Context->getConstantIntTrue(),
10118                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10119                                   OldCall);
10120       if (!OldCall->use_empty())
10121         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10122       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10123         return EraseInstFromFunction(*OldCall);
10124       return 0;
10125     }
10126
10127   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10128     // This instruction is not reachable, just remove it.  We insert a store to
10129     // undef so that we know that this code is not reachable, despite the fact
10130     // that we can't modify the CFG here.
10131     new StoreInst(Context->getConstantIntTrue(),
10132                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10133                   CS.getInstruction());
10134
10135     if (!CS.getInstruction()->use_empty())
10136       CS.getInstruction()->
10137         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10138
10139     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10140       // Don't break the CFG, insert a dummy cond branch.
10141       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10142                          Context->getConstantIntTrue(), II);
10143     }
10144     return EraseInstFromFunction(*CS.getInstruction());
10145   }
10146
10147   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10148     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10149       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10150         return transformCallThroughTrampoline(CS);
10151
10152   const PointerType *PTy = cast<PointerType>(Callee->getType());
10153   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10154   if (FTy->isVarArg()) {
10155     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10156     // See if we can optimize any arguments passed through the varargs area of
10157     // the call.
10158     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10159            E = CS.arg_end(); I != E; ++I, ++ix) {
10160       CastInst *CI = dyn_cast<CastInst>(*I);
10161       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10162         *I = CI->getOperand(0);
10163         Changed = true;
10164       }
10165     }
10166   }
10167
10168   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10169     // Inline asm calls cannot throw - mark them 'nounwind'.
10170     CS.setDoesNotThrow();
10171     Changed = true;
10172   }
10173
10174   return Changed ? CS.getInstruction() : 0;
10175 }
10176
10177 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10178 // attempt to move the cast to the arguments of the call/invoke.
10179 //
10180 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10181   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10182   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10183   if (CE->getOpcode() != Instruction::BitCast || 
10184       !isa<Function>(CE->getOperand(0)))
10185     return false;
10186   Function *Callee = cast<Function>(CE->getOperand(0));
10187   Instruction *Caller = CS.getInstruction();
10188   const AttrListPtr &CallerPAL = CS.getAttributes();
10189
10190   // Okay, this is a cast from a function to a different type.  Unless doing so
10191   // would cause a type conversion of one of our arguments, change this call to
10192   // be a direct call with arguments casted to the appropriate types.
10193   //
10194   const FunctionType *FT = Callee->getFunctionType();
10195   const Type *OldRetTy = Caller->getType();
10196   const Type *NewRetTy = FT->getReturnType();
10197
10198   if (isa<StructType>(NewRetTy))
10199     return false; // TODO: Handle multiple return values.
10200
10201   // Check to see if we are changing the return type...
10202   if (OldRetTy != NewRetTy) {
10203     if (Callee->isDeclaration() &&
10204         // Conversion is ok if changing from one pointer type to another or from
10205         // a pointer to an integer of the same size.
10206         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10207           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10208       return false;   // Cannot transform this return value.
10209
10210     if (!Caller->use_empty() &&
10211         // void -> non-void is handled specially
10212         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10213       return false;   // Cannot transform this return value.
10214
10215     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10216       Attributes RAttrs = CallerPAL.getRetAttributes();
10217       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10218         return false;   // Attribute not compatible with transformed value.
10219     }
10220
10221     // If the callsite is an invoke instruction, and the return value is used by
10222     // a PHI node in a successor, we cannot change the return type of the call
10223     // because there is no place to put the cast instruction (without breaking
10224     // the critical edge).  Bail out in this case.
10225     if (!Caller->use_empty())
10226       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10227         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10228              UI != E; ++UI)
10229           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10230             if (PN->getParent() == II->getNormalDest() ||
10231                 PN->getParent() == II->getUnwindDest())
10232               return false;
10233   }
10234
10235   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10236   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10237
10238   CallSite::arg_iterator AI = CS.arg_begin();
10239   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10240     const Type *ParamTy = FT->getParamType(i);
10241     const Type *ActTy = (*AI)->getType();
10242
10243     if (!CastInst::isCastable(ActTy, ParamTy))
10244       return false;   // Cannot transform this parameter value.
10245
10246     if (CallerPAL.getParamAttributes(i + 1) 
10247         & Attribute::typeIncompatible(ParamTy))
10248       return false;   // Attribute not compatible with transformed value.
10249
10250     // Converting from one pointer type to another or between a pointer and an
10251     // integer of the same size is safe even if we do not have a body.
10252     bool isConvertible = ActTy == ParamTy ||
10253       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10254        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10255     if (Callee->isDeclaration() && !isConvertible) return false;
10256   }
10257
10258   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10259       Callee->isDeclaration())
10260     return false;   // Do not delete arguments unless we have a function body.
10261
10262   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10263       !CallerPAL.isEmpty())
10264     // In this case we have more arguments than the new function type, but we
10265     // won't be dropping them.  Check that these extra arguments have attributes
10266     // that are compatible with being a vararg call argument.
10267     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10268       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10269         break;
10270       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10271       if (PAttrs & Attribute::VarArgsIncompatible)
10272         return false;
10273     }
10274
10275   // Okay, we decided that this is a safe thing to do: go ahead and start
10276   // inserting cast instructions as necessary...
10277   std::vector<Value*> Args;
10278   Args.reserve(NumActualArgs);
10279   SmallVector<AttributeWithIndex, 8> attrVec;
10280   attrVec.reserve(NumCommonArgs);
10281
10282   // Get any return attributes.
10283   Attributes RAttrs = CallerPAL.getRetAttributes();
10284
10285   // If the return value is not being used, the type may not be compatible
10286   // with the existing attributes.  Wipe out any problematic attributes.
10287   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10288
10289   // Add the new return attributes.
10290   if (RAttrs)
10291     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10292
10293   AI = CS.arg_begin();
10294   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10295     const Type *ParamTy = FT->getParamType(i);
10296     if ((*AI)->getType() == ParamTy) {
10297       Args.push_back(*AI);
10298     } else {
10299       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10300           false, ParamTy, false);
10301       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10302       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10303     }
10304
10305     // Add any parameter attributes.
10306     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10307       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10308   }
10309
10310   // If the function takes more arguments than the call was taking, add them
10311   // now...
10312   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10313     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10314
10315   // If we are removing arguments to the function, emit an obnoxious warning...
10316   if (FT->getNumParams() < NumActualArgs) {
10317     if (!FT->isVarArg()) {
10318       cerr << "WARNING: While resolving call to function '"
10319            << Callee->getName() << "' arguments were dropped!\n";
10320     } else {
10321       // Add all of the arguments in their promoted form to the arg list...
10322       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10323         const Type *PTy = getPromotedType((*AI)->getType());
10324         if (PTy != (*AI)->getType()) {
10325           // Must promote to pass through va_arg area!
10326           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10327                                                                 PTy, false);
10328           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10329           InsertNewInstBefore(Cast, *Caller);
10330           Args.push_back(Cast);
10331         } else {
10332           Args.push_back(*AI);
10333         }
10334
10335         // Add any parameter attributes.
10336         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10337           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10338       }
10339     }
10340   }
10341
10342   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10343     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10344
10345   if (NewRetTy == Type::VoidTy)
10346     Caller->setName("");   // Void type should not have a name.
10347
10348   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10349
10350   Instruction *NC;
10351   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10352     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10353                             Args.begin(), Args.end(),
10354                             Caller->getName(), Caller);
10355     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10356     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10357   } else {
10358     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10359                           Caller->getName(), Caller);
10360     CallInst *CI = cast<CallInst>(Caller);
10361     if (CI->isTailCall())
10362       cast<CallInst>(NC)->setTailCall();
10363     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10364     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10365   }
10366
10367   // Insert a cast of the return type as necessary.
10368   Value *NV = NC;
10369   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10370     if (NV->getType() != Type::VoidTy) {
10371       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10372                                                             OldRetTy, false);
10373       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10374
10375       // If this is an invoke instruction, we should insert it after the first
10376       // non-phi, instruction in the normal successor block.
10377       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10378         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10379         InsertNewInstBefore(NC, *I);
10380       } else {
10381         // Otherwise, it's a call, just insert cast right after the call instr
10382         InsertNewInstBefore(NC, *Caller);
10383       }
10384       AddUsersToWorkList(*Caller);
10385     } else {
10386       NV = Context->getUndef(Caller->getType());
10387     }
10388   }
10389
10390   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10391     Caller->replaceAllUsesWith(NV);
10392   Caller->eraseFromParent();
10393   RemoveFromWorkList(Caller);
10394   return true;
10395 }
10396
10397 // transformCallThroughTrampoline - Turn a call to a function created by the
10398 // init_trampoline intrinsic into a direct call to the underlying function.
10399 //
10400 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10401   Value *Callee = CS.getCalledValue();
10402   const PointerType *PTy = cast<PointerType>(Callee->getType());
10403   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10404   const AttrListPtr &Attrs = CS.getAttributes();
10405
10406   // If the call already has the 'nest' attribute somewhere then give up -
10407   // otherwise 'nest' would occur twice after splicing in the chain.
10408   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10409     return 0;
10410
10411   IntrinsicInst *Tramp =
10412     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10413
10414   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10415   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10416   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10417
10418   const AttrListPtr &NestAttrs = NestF->getAttributes();
10419   if (!NestAttrs.isEmpty()) {
10420     unsigned NestIdx = 1;
10421     const Type *NestTy = 0;
10422     Attributes NestAttr = Attribute::None;
10423
10424     // Look for a parameter marked with the 'nest' attribute.
10425     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10426          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10427       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10428         // Record the parameter type and any other attributes.
10429         NestTy = *I;
10430         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10431         break;
10432       }
10433
10434     if (NestTy) {
10435       Instruction *Caller = CS.getInstruction();
10436       std::vector<Value*> NewArgs;
10437       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10438
10439       SmallVector<AttributeWithIndex, 8> NewAttrs;
10440       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10441
10442       // Insert the nest argument into the call argument list, which may
10443       // mean appending it.  Likewise for attributes.
10444
10445       // Add any result attributes.
10446       if (Attributes Attr = Attrs.getRetAttributes())
10447         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10448
10449       {
10450         unsigned Idx = 1;
10451         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10452         do {
10453           if (Idx == NestIdx) {
10454             // Add the chain argument and attributes.
10455             Value *NestVal = Tramp->getOperand(3);
10456             if (NestVal->getType() != NestTy)
10457               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10458             NewArgs.push_back(NestVal);
10459             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10460           }
10461
10462           if (I == E)
10463             break;
10464
10465           // Add the original argument and attributes.
10466           NewArgs.push_back(*I);
10467           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10468             NewAttrs.push_back
10469               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10470
10471           ++Idx, ++I;
10472         } while (1);
10473       }
10474
10475       // Add any function attributes.
10476       if (Attributes Attr = Attrs.getFnAttributes())
10477         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10478
10479       // The trampoline may have been bitcast to a bogus type (FTy).
10480       // Handle this by synthesizing a new function type, equal to FTy
10481       // with the chain parameter inserted.
10482
10483       std::vector<const Type*> NewTypes;
10484       NewTypes.reserve(FTy->getNumParams()+1);
10485
10486       // Insert the chain's type into the list of parameter types, which may
10487       // mean appending it.
10488       {
10489         unsigned Idx = 1;
10490         FunctionType::param_iterator I = FTy->param_begin(),
10491           E = FTy->param_end();
10492
10493         do {
10494           if (Idx == NestIdx)
10495             // Add the chain's type.
10496             NewTypes.push_back(NestTy);
10497
10498           if (I == E)
10499             break;
10500
10501           // Add the original type.
10502           NewTypes.push_back(*I);
10503
10504           ++Idx, ++I;
10505         } while (1);
10506       }
10507
10508       // Replace the trampoline call with a direct call.  Let the generic
10509       // code sort out any function type mismatches.
10510       FunctionType *NewFTy =
10511                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10512                                                 FTy->isVarArg());
10513       Constant *NewCallee =
10514         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10515         NestF : Context->getConstantExprBitCast(NestF, 
10516                                          Context->getPointerTypeUnqual(NewFTy));
10517       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10518
10519       Instruction *NewCaller;
10520       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10521         NewCaller = InvokeInst::Create(NewCallee,
10522                                        II->getNormalDest(), II->getUnwindDest(),
10523                                        NewArgs.begin(), NewArgs.end(),
10524                                        Caller->getName(), Caller);
10525         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10526         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10527       } else {
10528         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10529                                      Caller->getName(), Caller);
10530         if (cast<CallInst>(Caller)->isTailCall())
10531           cast<CallInst>(NewCaller)->setTailCall();
10532         cast<CallInst>(NewCaller)->
10533           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10534         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10535       }
10536       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10537         Caller->replaceAllUsesWith(NewCaller);
10538       Caller->eraseFromParent();
10539       RemoveFromWorkList(Caller);
10540       return 0;
10541     }
10542   }
10543
10544   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10545   // parameter, there is no need to adjust the argument list.  Let the generic
10546   // code sort out any function type mismatches.
10547   Constant *NewCallee =
10548     NestF->getType() == PTy ? NestF : 
10549                               Context->getConstantExprBitCast(NestF, PTy);
10550   CS.setCalledFunction(NewCallee);
10551   return CS.getInstruction();
10552 }
10553
10554 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10555 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10556 /// and a single binop.
10557 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10558   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10559   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10560   unsigned Opc = FirstInst->getOpcode();
10561   Value *LHSVal = FirstInst->getOperand(0);
10562   Value *RHSVal = FirstInst->getOperand(1);
10563     
10564   const Type *LHSType = LHSVal->getType();
10565   const Type *RHSType = RHSVal->getType();
10566   
10567   // Scan to see if all operands are the same opcode, all have one use, and all
10568   // kill their operands (i.e. the operands have one use).
10569   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10570     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10571     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10572         // Verify type of the LHS matches so we don't fold cmp's of different
10573         // types or GEP's with different index types.
10574         I->getOperand(0)->getType() != LHSType ||
10575         I->getOperand(1)->getType() != RHSType)
10576       return 0;
10577
10578     // If they are CmpInst instructions, check their predicates
10579     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10580       if (cast<CmpInst>(I)->getPredicate() !=
10581           cast<CmpInst>(FirstInst)->getPredicate())
10582         return 0;
10583     
10584     // Keep track of which operand needs a phi node.
10585     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10586     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10587   }
10588   
10589   // Otherwise, this is safe to transform!
10590   
10591   Value *InLHS = FirstInst->getOperand(0);
10592   Value *InRHS = FirstInst->getOperand(1);
10593   PHINode *NewLHS = 0, *NewRHS = 0;
10594   if (LHSVal == 0) {
10595     NewLHS = PHINode::Create(LHSType,
10596                              FirstInst->getOperand(0)->getName() + ".pn");
10597     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10598     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10599     InsertNewInstBefore(NewLHS, PN);
10600     LHSVal = NewLHS;
10601   }
10602   
10603   if (RHSVal == 0) {
10604     NewRHS = PHINode::Create(RHSType,
10605                              FirstInst->getOperand(1)->getName() + ".pn");
10606     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10607     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10608     InsertNewInstBefore(NewRHS, PN);
10609     RHSVal = NewRHS;
10610   }
10611   
10612   // Add all operands to the new PHIs.
10613   if (NewLHS || NewRHS) {
10614     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10615       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10616       if (NewLHS) {
10617         Value *NewInLHS = InInst->getOperand(0);
10618         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10619       }
10620       if (NewRHS) {
10621         Value *NewInRHS = InInst->getOperand(1);
10622         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10623       }
10624     }
10625   }
10626     
10627   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10628     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10629   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10630   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10631                          LHSVal, RHSVal);
10632 }
10633
10634 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10635   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10636   
10637   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10638                                         FirstInst->op_end());
10639   // This is true if all GEP bases are allocas and if all indices into them are
10640   // constants.
10641   bool AllBasePointersAreAllocas = true;
10642   
10643   // Scan to see if all operands are the same opcode, all have one use, and all
10644   // kill their operands (i.e. the operands have one use).
10645   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10646     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10647     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10648       GEP->getNumOperands() != FirstInst->getNumOperands())
10649       return 0;
10650
10651     // Keep track of whether or not all GEPs are of alloca pointers.
10652     if (AllBasePointersAreAllocas &&
10653         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10654          !GEP->hasAllConstantIndices()))
10655       AllBasePointersAreAllocas = false;
10656     
10657     // Compare the operand lists.
10658     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10659       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10660         continue;
10661       
10662       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10663       // if one of the PHIs has a constant for the index.  The index may be
10664       // substantially cheaper to compute for the constants, so making it a
10665       // variable index could pessimize the path.  This also handles the case
10666       // for struct indices, which must always be constant.
10667       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10668           isa<ConstantInt>(GEP->getOperand(op)))
10669         return 0;
10670       
10671       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10672         return 0;
10673       FixedOperands[op] = 0;  // Needs a PHI.
10674     }
10675   }
10676   
10677   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10678   // bother doing this transformation.  At best, this will just save a bit of
10679   // offset calculation, but all the predecessors will have to materialize the
10680   // stack address into a register anyway.  We'd actually rather *clone* the
10681   // load up into the predecessors so that we have a load of a gep of an alloca,
10682   // which can usually all be folded into the load.
10683   if (AllBasePointersAreAllocas)
10684     return 0;
10685   
10686   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10687   // that is variable.
10688   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10689   
10690   bool HasAnyPHIs = false;
10691   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10692     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10693     Value *FirstOp = FirstInst->getOperand(i);
10694     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10695                                      FirstOp->getName()+".pn");
10696     InsertNewInstBefore(NewPN, PN);
10697     
10698     NewPN->reserveOperandSpace(e);
10699     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10700     OperandPhis[i] = NewPN;
10701     FixedOperands[i] = NewPN;
10702     HasAnyPHIs = true;
10703   }
10704
10705   
10706   // Add all operands to the new PHIs.
10707   if (HasAnyPHIs) {
10708     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10709       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10710       BasicBlock *InBB = PN.getIncomingBlock(i);
10711       
10712       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10713         if (PHINode *OpPhi = OperandPhis[op])
10714           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10715     }
10716   }
10717   
10718   Value *Base = FixedOperands[0];
10719   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10720                                    FixedOperands.end());
10721 }
10722
10723
10724 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10725 /// sink the load out of the block that defines it.  This means that it must be
10726 /// obvious the value of the load is not changed from the point of the load to
10727 /// the end of the block it is in.
10728 ///
10729 /// Finally, it is safe, but not profitable, to sink a load targetting a
10730 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10731 /// to a register.
10732 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10733   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10734   
10735   for (++BBI; BBI != E; ++BBI)
10736     if (BBI->mayWriteToMemory())
10737       return false;
10738   
10739   // Check for non-address taken alloca.  If not address-taken already, it isn't
10740   // profitable to do this xform.
10741   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10742     bool isAddressTaken = false;
10743     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10744          UI != E; ++UI) {
10745       if (isa<LoadInst>(UI)) continue;
10746       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10747         // If storing TO the alloca, then the address isn't taken.
10748         if (SI->getOperand(1) == AI) continue;
10749       }
10750       isAddressTaken = true;
10751       break;
10752     }
10753     
10754     if (!isAddressTaken && AI->isStaticAlloca())
10755       return false;
10756   }
10757   
10758   // If this load is a load from a GEP with a constant offset from an alloca,
10759   // then we don't want to sink it.  In its present form, it will be
10760   // load [constant stack offset].  Sinking it will cause us to have to
10761   // materialize the stack addresses in each predecessor in a register only to
10762   // do a shared load from register in the successor.
10763   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10764     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10765       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10766         return false;
10767   
10768   return true;
10769 }
10770
10771
10772 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10773 // operator and they all are only used by the PHI, PHI together their
10774 // inputs, and do the operation once, to the result of the PHI.
10775 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10776   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10777
10778   // Scan the instruction, looking for input operations that can be folded away.
10779   // If all input operands to the phi are the same instruction (e.g. a cast from
10780   // the same type or "+42") we can pull the operation through the PHI, reducing
10781   // code size and simplifying code.
10782   Constant *ConstantOp = 0;
10783   const Type *CastSrcTy = 0;
10784   bool isVolatile = false;
10785   if (isa<CastInst>(FirstInst)) {
10786     CastSrcTy = FirstInst->getOperand(0)->getType();
10787   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10788     // Can fold binop, compare or shift here if the RHS is a constant, 
10789     // otherwise call FoldPHIArgBinOpIntoPHI.
10790     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10791     if (ConstantOp == 0)
10792       return FoldPHIArgBinOpIntoPHI(PN);
10793   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10794     isVolatile = LI->isVolatile();
10795     // We can't sink the load if the loaded value could be modified between the
10796     // load and the PHI.
10797     if (LI->getParent() != PN.getIncomingBlock(0) ||
10798         !isSafeAndProfitableToSinkLoad(LI))
10799       return 0;
10800     
10801     // If the PHI is of volatile loads and the load block has multiple
10802     // successors, sinking it would remove a load of the volatile value from
10803     // the path through the other successor.
10804     if (isVolatile &&
10805         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10806       return 0;
10807     
10808   } else if (isa<GetElementPtrInst>(FirstInst)) {
10809     return FoldPHIArgGEPIntoPHI(PN);
10810   } else {
10811     return 0;  // Cannot fold this operation.
10812   }
10813
10814   // Check to see if all arguments are the same operation.
10815   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10816     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10817     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10818     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10819       return 0;
10820     if (CastSrcTy) {
10821       if (I->getOperand(0)->getType() != CastSrcTy)
10822         return 0;  // Cast operation must match.
10823     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10824       // We can't sink the load if the loaded value could be modified between 
10825       // the load and the PHI.
10826       if (LI->isVolatile() != isVolatile ||
10827           LI->getParent() != PN.getIncomingBlock(i) ||
10828           !isSafeAndProfitableToSinkLoad(LI))
10829         return 0;
10830       
10831       // If the PHI is of volatile loads and the load block has multiple
10832       // successors, sinking it would remove a load of the volatile value from
10833       // the path through the other successor.
10834       if (isVolatile &&
10835           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10836         return 0;
10837       
10838     } else if (I->getOperand(1) != ConstantOp) {
10839       return 0;
10840     }
10841   }
10842
10843   // Okay, they are all the same operation.  Create a new PHI node of the
10844   // correct type, and PHI together all of the LHS's of the instructions.
10845   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10846                                    PN.getName()+".in");
10847   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10848
10849   Value *InVal = FirstInst->getOperand(0);
10850   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10851
10852   // Add all operands to the new PHI.
10853   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10854     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10855     if (NewInVal != InVal)
10856       InVal = 0;
10857     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10858   }
10859
10860   Value *PhiVal;
10861   if (InVal) {
10862     // The new PHI unions all of the same values together.  This is really
10863     // common, so we handle it intelligently here for compile-time speed.
10864     PhiVal = InVal;
10865     delete NewPN;
10866   } else {
10867     InsertNewInstBefore(NewPN, PN);
10868     PhiVal = NewPN;
10869   }
10870
10871   // Insert and return the new operation.
10872   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10873     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10874   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10875     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10876   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10877     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10878                            PhiVal, ConstantOp);
10879   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10880   
10881   // If this was a volatile load that we are merging, make sure to loop through
10882   // and mark all the input loads as non-volatile.  If we don't do this, we will
10883   // insert a new volatile load and the old ones will not be deletable.
10884   if (isVolatile)
10885     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10886       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10887   
10888   return new LoadInst(PhiVal, "", isVolatile);
10889 }
10890
10891 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10892 /// that is dead.
10893 static bool DeadPHICycle(PHINode *PN,
10894                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10895   if (PN->use_empty()) return true;
10896   if (!PN->hasOneUse()) return false;
10897
10898   // Remember this node, and if we find the cycle, return.
10899   if (!PotentiallyDeadPHIs.insert(PN))
10900     return true;
10901   
10902   // Don't scan crazily complex things.
10903   if (PotentiallyDeadPHIs.size() == 16)
10904     return false;
10905
10906   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10907     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10908
10909   return false;
10910 }
10911
10912 /// PHIsEqualValue - Return true if this phi node is always equal to
10913 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10914 ///   z = some value; x = phi (y, z); y = phi (x, z)
10915 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10916                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10917   // See if we already saw this PHI node.
10918   if (!ValueEqualPHIs.insert(PN))
10919     return true;
10920   
10921   // Don't scan crazily complex things.
10922   if (ValueEqualPHIs.size() == 16)
10923     return false;
10924  
10925   // Scan the operands to see if they are either phi nodes or are equal to
10926   // the value.
10927   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10928     Value *Op = PN->getIncomingValue(i);
10929     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10930       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10931         return false;
10932     } else if (Op != NonPhiInVal)
10933       return false;
10934   }
10935   
10936   return true;
10937 }
10938
10939
10940 // PHINode simplification
10941 //
10942 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10943   // If LCSSA is around, don't mess with Phi nodes
10944   if (MustPreserveLCSSA) return 0;
10945   
10946   if (Value *V = PN.hasConstantValue())
10947     return ReplaceInstUsesWith(PN, V);
10948
10949   // If all PHI operands are the same operation, pull them through the PHI,
10950   // reducing code size.
10951   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10952       isa<Instruction>(PN.getIncomingValue(1)) &&
10953       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10954       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10955       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10956       // than themselves more than once.
10957       PN.getIncomingValue(0)->hasOneUse())
10958     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10959       return Result;
10960
10961   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10962   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10963   // PHI)... break the cycle.
10964   if (PN.hasOneUse()) {
10965     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10966     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10967       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10968       PotentiallyDeadPHIs.insert(&PN);
10969       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10970         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10971     }
10972    
10973     // If this phi has a single use, and if that use just computes a value for
10974     // the next iteration of a loop, delete the phi.  This occurs with unused
10975     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10976     // common case here is good because the only other things that catch this
10977     // are induction variable analysis (sometimes) and ADCE, which is only run
10978     // late.
10979     if (PHIUser->hasOneUse() &&
10980         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10981         PHIUser->use_back() == &PN) {
10982       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10983     }
10984   }
10985
10986   // We sometimes end up with phi cycles that non-obviously end up being the
10987   // same value, for example:
10988   //   z = some value; x = phi (y, z); y = phi (x, z)
10989   // where the phi nodes don't necessarily need to be in the same block.  Do a
10990   // quick check to see if the PHI node only contains a single non-phi value, if
10991   // so, scan to see if the phi cycle is actually equal to that value.
10992   {
10993     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10994     // Scan for the first non-phi operand.
10995     while (InValNo != NumOperandVals && 
10996            isa<PHINode>(PN.getIncomingValue(InValNo)))
10997       ++InValNo;
10998
10999     if (InValNo != NumOperandVals) {
11000       Value *NonPhiInVal = PN.getOperand(InValNo);
11001       
11002       // Scan the rest of the operands to see if there are any conflicts, if so
11003       // there is no need to recursively scan other phis.
11004       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11005         Value *OpVal = PN.getIncomingValue(InValNo);
11006         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11007           break;
11008       }
11009       
11010       // If we scanned over all operands, then we have one unique value plus
11011       // phi values.  Scan PHI nodes to see if they all merge in each other or
11012       // the value.
11013       if (InValNo == NumOperandVals) {
11014         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11015         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11016           return ReplaceInstUsesWith(PN, NonPhiInVal);
11017       }
11018     }
11019   }
11020   return 0;
11021 }
11022
11023 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11024                                    Instruction *InsertPoint,
11025                                    InstCombiner *IC) {
11026   unsigned PtrSize = DTy->getScalarSizeInBits();
11027   unsigned VTySize = V->getType()->getScalarSizeInBits();
11028   // We must cast correctly to the pointer type. Ensure that we
11029   // sign extend the integer value if it is smaller as this is
11030   // used for address computation.
11031   Instruction::CastOps opcode = 
11032      (VTySize < PtrSize ? Instruction::SExt :
11033       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11034   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11035 }
11036
11037
11038 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11039   Value *PtrOp = GEP.getOperand(0);
11040   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11041   // If so, eliminate the noop.
11042   if (GEP.getNumOperands() == 1)
11043     return ReplaceInstUsesWith(GEP, PtrOp);
11044
11045   if (isa<UndefValue>(GEP.getOperand(0)))
11046     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11047
11048   bool HasZeroPointerIndex = false;
11049   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11050     HasZeroPointerIndex = C->isNullValue();
11051
11052   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11053     return ReplaceInstUsesWith(GEP, PtrOp);
11054
11055   // Eliminate unneeded casts for indices.
11056   bool MadeChange = false;
11057   
11058   gep_type_iterator GTI = gep_type_begin(GEP);
11059   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11060        i != e; ++i, ++GTI) {
11061     if (isa<SequentialType>(*GTI)) {
11062       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11063         if (CI->getOpcode() == Instruction::ZExt ||
11064             CI->getOpcode() == Instruction::SExt) {
11065           const Type *SrcTy = CI->getOperand(0)->getType();
11066           // We can eliminate a cast from i32 to i64 iff the target 
11067           // is a 32-bit pointer target.
11068           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11069             MadeChange = true;
11070             *i = CI->getOperand(0);
11071           }
11072         }
11073       }
11074       // If we are using a wider index than needed for this platform, shrink it
11075       // to what we need.  If narrower, sign-extend it to what we need.
11076       // If the incoming value needs a cast instruction,
11077       // insert it.  This explicit cast can make subsequent optimizations more
11078       // obvious.
11079       Value *Op = *i;
11080       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11081         if (Constant *C = dyn_cast<Constant>(Op)) {
11082           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11083           MadeChange = true;
11084         } else {
11085           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11086                                 GEP);
11087           *i = Op;
11088           MadeChange = true;
11089         }
11090       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11091         if (Constant *C = dyn_cast<Constant>(Op)) {
11092           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11093           MadeChange = true;
11094         } else {
11095           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11096                                 GEP);
11097           *i = Op;
11098           MadeChange = true;
11099         }
11100       }
11101     }
11102   }
11103   if (MadeChange) return &GEP;
11104
11105   // Combine Indices - If the source pointer to this getelementptr instruction
11106   // is a getelementptr instruction, combine the indices of the two
11107   // getelementptr instructions into a single instruction.
11108   //
11109   SmallVector<Value*, 8> SrcGEPOperands;
11110   if (User *Src = dyn_castGetElementPtr(PtrOp))
11111     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11112
11113   if (!SrcGEPOperands.empty()) {
11114     // Note that if our source is a gep chain itself that we wait for that
11115     // chain to be resolved before we perform this transformation.  This
11116     // avoids us creating a TON of code in some cases.
11117     //
11118     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11119         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11120       return 0;   // Wait until our source is folded to completion.
11121
11122     SmallVector<Value*, 8> Indices;
11123
11124     // Find out whether the last index in the source GEP is a sequential idx.
11125     bool EndsWithSequential = false;
11126     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11127            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11128       EndsWithSequential = !isa<StructType>(*I);
11129
11130     // Can we combine the two pointer arithmetics offsets?
11131     if (EndsWithSequential) {
11132       // Replace: gep (gep %P, long B), long A, ...
11133       // With:    T = long A+B; gep %P, T, ...
11134       //
11135       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11136       if (SO1 == Context->getNullValue(SO1->getType())) {
11137         Sum = GO1;
11138       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11139         Sum = SO1;
11140       } else {
11141         // If they aren't the same type, convert both to an integer of the
11142         // target's pointer size.
11143         if (SO1->getType() != GO1->getType()) {
11144           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11145             SO1 =
11146                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11147           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11148             GO1 =
11149                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11150           } else {
11151             unsigned PS = TD->getPointerSizeInBits();
11152             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11153               // Convert GO1 to SO1's type.
11154               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11155
11156             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11157               // Convert SO1 to GO1's type.
11158               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11159             } else {
11160               const Type *PT = TD->getIntPtrType();
11161               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11162               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11163             }
11164           }
11165         }
11166         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11167           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11168                                             cast<Constant>(GO1));
11169         else {
11170           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11171           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11172         }
11173       }
11174
11175       // Recycle the GEP we already have if possible.
11176       if (SrcGEPOperands.size() == 2) {
11177         GEP.setOperand(0, SrcGEPOperands[0]);
11178         GEP.setOperand(1, Sum);
11179         return &GEP;
11180       } else {
11181         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11182                        SrcGEPOperands.end()-1);
11183         Indices.push_back(Sum);
11184         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11185       }
11186     } else if (isa<Constant>(*GEP.idx_begin()) &&
11187                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11188                SrcGEPOperands.size() != 1) {
11189       // Otherwise we can do the fold if the first index of the GEP is a zero
11190       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11191                      SrcGEPOperands.end());
11192       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11193     }
11194
11195     if (!Indices.empty())
11196       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11197                                        Indices.end(), GEP.getName());
11198
11199   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11200     // GEP of global variable.  If all of the indices for this GEP are
11201     // constants, we can promote this to a constexpr instead of an instruction.
11202
11203     // Scan for nonconstants...
11204     SmallVector<Constant*, 8> Indices;
11205     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11206     for (; I != E && isa<Constant>(*I); ++I)
11207       Indices.push_back(cast<Constant>(*I));
11208
11209     if (I == E) {  // If they are all constants...
11210       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11211                                                     &Indices[0],Indices.size());
11212
11213       // Replace all uses of the GEP with the new constexpr...
11214       return ReplaceInstUsesWith(GEP, CE);
11215     }
11216   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11217     if (!isa<PointerType>(X->getType())) {
11218       // Not interesting.  Source pointer must be a cast from pointer.
11219     } else if (HasZeroPointerIndex) {
11220       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11221       // into     : GEP [10 x i8]* X, i32 0, ...
11222       //
11223       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11224       //           into     : GEP i8* X, ...
11225       // 
11226       // This occurs when the program declares an array extern like "int X[];"
11227       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11228       const PointerType *XTy = cast<PointerType>(X->getType());
11229       if (const ArrayType *CATy =
11230           dyn_cast<ArrayType>(CPTy->getElementType())) {
11231         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11232         if (CATy->getElementType() == XTy->getElementType()) {
11233           // -> GEP i8* X, ...
11234           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11235           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11236                                            GEP.getName());
11237         } else if (const ArrayType *XATy =
11238                  dyn_cast<ArrayType>(XTy->getElementType())) {
11239           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11240           if (CATy->getElementType() == XATy->getElementType()) {
11241             // -> GEP [10 x i8]* X, i32 0, ...
11242             // At this point, we know that the cast source type is a pointer
11243             // to an array of the same type as the destination pointer
11244             // array.  Because the array type is never stepped over (there
11245             // is a leading zero) we can fold the cast into this GEP.
11246             GEP.setOperand(0, X);
11247             return &GEP;
11248           }
11249         }
11250       }
11251     } else if (GEP.getNumOperands() == 2) {
11252       // Transform things like:
11253       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11254       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11255       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11256       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11257       if (isa<ArrayType>(SrcElTy) &&
11258           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11259           TD->getTypeAllocSize(ResElTy)) {
11260         Value *Idx[2];
11261         Idx[0] = Context->getNullValue(Type::Int32Ty);
11262         Idx[1] = GEP.getOperand(1);
11263         Value *V = InsertNewInstBefore(
11264                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11265         // V and GEP are both pointer types --> BitCast
11266         return new BitCastInst(V, GEP.getType());
11267       }
11268       
11269       // Transform things like:
11270       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11271       //   (where tmp = 8*tmp2) into:
11272       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11273       
11274       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11275         uint64_t ArrayEltSize =
11276             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11277         
11278         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11279         // allow either a mul, shift, or constant here.
11280         Value *NewIdx = 0;
11281         ConstantInt *Scale = 0;
11282         if (ArrayEltSize == 1) {
11283           NewIdx = GEP.getOperand(1);
11284           Scale = 
11285                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11286         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11287           NewIdx = Context->getConstantInt(CI->getType(), 1);
11288           Scale = CI;
11289         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11290           if (Inst->getOpcode() == Instruction::Shl &&
11291               isa<ConstantInt>(Inst->getOperand(1))) {
11292             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11293             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11294             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11295                                      1ULL << ShAmtVal);
11296             NewIdx = Inst->getOperand(0);
11297           } else if (Inst->getOpcode() == Instruction::Mul &&
11298                      isa<ConstantInt>(Inst->getOperand(1))) {
11299             Scale = cast<ConstantInt>(Inst->getOperand(1));
11300             NewIdx = Inst->getOperand(0);
11301           }
11302         }
11303         
11304         // If the index will be to exactly the right offset with the scale taken
11305         // out, perform the transformation. Note, we don't know whether Scale is
11306         // signed or not. We'll use unsigned version of division/modulo
11307         // operation after making sure Scale doesn't have the sign bit set.
11308         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11309             Scale->getZExtValue() % ArrayEltSize == 0) {
11310           Scale = Context->getConstantInt(Scale->getType(),
11311                                    Scale->getZExtValue() / ArrayEltSize);
11312           if (Scale->getZExtValue() != 1) {
11313             Constant *C =
11314                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11315                                                        false /*ZExt*/);
11316             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11317             NewIdx = InsertNewInstBefore(Sc, GEP);
11318           }
11319
11320           // Insert the new GEP instruction.
11321           Value *Idx[2];
11322           Idx[0] = Context->getNullValue(Type::Int32Ty);
11323           Idx[1] = NewIdx;
11324           Instruction *NewGEP =
11325             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11326           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11327           // The NewGEP must be pointer typed, so must the old one -> BitCast
11328           return new BitCastInst(NewGEP, GEP.getType());
11329         }
11330       }
11331     }
11332   }
11333   
11334   /// See if we can simplify:
11335   ///   X = bitcast A to B*
11336   ///   Y = gep X, <...constant indices...>
11337   /// into a gep of the original struct.  This is important for SROA and alias
11338   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11339   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11340     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11341       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11342       // a constant back from EmitGEPOffset.
11343       ConstantInt *OffsetV =
11344                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11345       int64_t Offset = OffsetV->getSExtValue();
11346       
11347       // If this GEP instruction doesn't move the pointer, just replace the GEP
11348       // with a bitcast of the real input to the dest type.
11349       if (Offset == 0) {
11350         // If the bitcast is of an allocation, and the allocation will be
11351         // converted to match the type of the cast, don't touch this.
11352         if (isa<AllocationInst>(BCI->getOperand(0))) {
11353           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11354           if (Instruction *I = visitBitCast(*BCI)) {
11355             if (I != BCI) {
11356               I->takeName(BCI);
11357               BCI->getParent()->getInstList().insert(BCI, I);
11358               ReplaceInstUsesWith(*BCI, I);
11359             }
11360             return &GEP;
11361           }
11362         }
11363         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11364       }
11365       
11366       // Otherwise, if the offset is non-zero, we need to find out if there is a
11367       // field at Offset in 'A's type.  If so, we can pull the cast through the
11368       // GEP.
11369       SmallVector<Value*, 8> NewIndices;
11370       const Type *InTy =
11371         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11372       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11373         Instruction *NGEP =
11374            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11375                                      NewIndices.end());
11376         if (NGEP->getType() == GEP.getType()) return NGEP;
11377         InsertNewInstBefore(NGEP, GEP);
11378         NGEP->takeName(&GEP);
11379         return new BitCastInst(NGEP, GEP.getType());
11380       }
11381     }
11382   }    
11383     
11384   return 0;
11385 }
11386
11387 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11388   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11389   if (AI.isArrayAllocation()) {  // Check C != 1
11390     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11391       const Type *NewTy = 
11392         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11393       AllocationInst *New = 0;
11394
11395       // Create and insert the replacement instruction...
11396       if (isa<MallocInst>(AI))
11397         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11398       else {
11399         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11400         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11401       }
11402
11403       InsertNewInstBefore(New, AI);
11404
11405       // Scan to the end of the allocation instructions, to skip over a block of
11406       // allocas if possible...also skip interleaved debug info
11407       //
11408       BasicBlock::iterator It = New;
11409       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11410
11411       // Now that I is pointing to the first non-allocation-inst in the block,
11412       // insert our getelementptr instruction...
11413       //
11414       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11415       Value *Idx[2];
11416       Idx[0] = NullIdx;
11417       Idx[1] = NullIdx;
11418       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11419                                            New->getName()+".sub", It);
11420
11421       // Now make everything use the getelementptr instead of the original
11422       // allocation.
11423       return ReplaceInstUsesWith(AI, V);
11424     } else if (isa<UndefValue>(AI.getArraySize())) {
11425       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11426     }
11427   }
11428
11429   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11430     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11431     // Note that we only do this for alloca's, because malloc should allocate
11432     // and return a unique pointer, even for a zero byte allocation.
11433     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11434       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11435
11436     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11437     if (AI.getAlignment() == 0)
11438       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11439   }
11440
11441   return 0;
11442 }
11443
11444 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11445   Value *Op = FI.getOperand(0);
11446
11447   // free undef -> unreachable.
11448   if (isa<UndefValue>(Op)) {
11449     // Insert a new store to null because we cannot modify the CFG here.
11450     new StoreInst(Context->getConstantIntTrue(),
11451            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11452     return EraseInstFromFunction(FI);
11453   }
11454   
11455   // If we have 'free null' delete the instruction.  This can happen in stl code
11456   // when lots of inlining happens.
11457   if (isa<ConstantPointerNull>(Op))
11458     return EraseInstFromFunction(FI);
11459   
11460   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11461   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11462     FI.setOperand(0, CI->getOperand(0));
11463     return &FI;
11464   }
11465   
11466   // Change free (gep X, 0,0,0,0) into free(X)
11467   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11468     if (GEPI->hasAllZeroIndices()) {
11469       AddToWorkList(GEPI);
11470       FI.setOperand(0, GEPI->getOperand(0));
11471       return &FI;
11472     }
11473   }
11474   
11475   // Change free(malloc) into nothing, if the malloc has a single use.
11476   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11477     if (MI->hasOneUse()) {
11478       EraseInstFromFunction(FI);
11479       return EraseInstFromFunction(*MI);
11480     }
11481
11482   return 0;
11483 }
11484
11485
11486 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11487 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11488                                         const TargetData *TD) {
11489   User *CI = cast<User>(LI.getOperand(0));
11490   Value *CastOp = CI->getOperand(0);
11491   LLVMContext *Context = IC.getContext();
11492
11493   if (TD) {
11494     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11495       // Instead of loading constant c string, use corresponding integer value
11496       // directly if string length is small enough.
11497       std::string Str;
11498       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11499         unsigned len = Str.length();
11500         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11501         unsigned numBits = Ty->getPrimitiveSizeInBits();
11502         // Replace LI with immediate integer store.
11503         if ((numBits >> 3) == len + 1) {
11504           APInt StrVal(numBits, 0);
11505           APInt SingleChar(numBits, 0);
11506           if (TD->isLittleEndian()) {
11507             for (signed i = len-1; i >= 0; i--) {
11508               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11509               StrVal = (StrVal << 8) | SingleChar;
11510             }
11511           } else {
11512             for (unsigned i = 0; i < len; i++) {
11513               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11514               StrVal = (StrVal << 8) | SingleChar;
11515             }
11516             // Append NULL at the end.
11517             SingleChar = 0;
11518             StrVal = (StrVal << 8) | SingleChar;
11519           }
11520           Value *NL = Context->getConstantInt(StrVal);
11521           return IC.ReplaceInstUsesWith(LI, NL);
11522         }
11523       }
11524     }
11525   }
11526
11527   const PointerType *DestTy = cast<PointerType>(CI->getType());
11528   const Type *DestPTy = DestTy->getElementType();
11529   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11530
11531     // If the address spaces don't match, don't eliminate the cast.
11532     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11533       return 0;
11534
11535     const Type *SrcPTy = SrcTy->getElementType();
11536
11537     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11538          isa<VectorType>(DestPTy)) {
11539       // If the source is an array, the code below will not succeed.  Check to
11540       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11541       // constants.
11542       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11543         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11544           if (ASrcTy->getNumElements() != 0) {
11545             Value *Idxs[2];
11546             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11547             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11548             SrcTy = cast<PointerType>(CastOp->getType());
11549             SrcPTy = SrcTy->getElementType();
11550           }
11551
11552       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11553             isa<VectorType>(SrcPTy)) &&
11554           // Do not allow turning this into a load of an integer, which is then
11555           // casted to a pointer, this pessimizes pointer analysis a lot.
11556           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11557           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11558                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11559
11560         // Okay, we are casting from one integer or pointer type to another of
11561         // the same size.  Instead of casting the pointer before the load, cast
11562         // the result of the loaded value.
11563         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11564                                                              CI->getName(),
11565                                                          LI.isVolatile()),LI);
11566         // Now cast the result of the load.
11567         return new BitCastInst(NewLoad, LI.getType());
11568       }
11569     }
11570   }
11571   return 0;
11572 }
11573
11574 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11575   Value *Op = LI.getOperand(0);
11576
11577   // Attempt to improve the alignment.
11578   unsigned KnownAlign =
11579     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11580   if (KnownAlign >
11581       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11582                                 LI.getAlignment()))
11583     LI.setAlignment(KnownAlign);
11584
11585   // load (cast X) --> cast (load X) iff safe
11586   if (isa<CastInst>(Op))
11587     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11588       return Res;
11589
11590   // None of the following transforms are legal for volatile loads.
11591   if (LI.isVolatile()) return 0;
11592   
11593   // Do really simple store-to-load forwarding and load CSE, to catch cases
11594   // where there are several consequtive memory accesses to the same location,
11595   // separated by a few arithmetic operations.
11596   BasicBlock::iterator BBI = &LI;
11597   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11598     return ReplaceInstUsesWith(LI, AvailableVal);
11599
11600   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11601     const Value *GEPI0 = GEPI->getOperand(0);
11602     // TODO: Consider a target hook for valid address spaces for this xform.
11603     if (isa<ConstantPointerNull>(GEPI0) &&
11604         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
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
11615   if (Constant *C = dyn_cast<Constant>(Op)) {
11616     // load null/undef -> undef
11617     // TODO: Consider a target hook for valid address spaces for this xform.
11618     if (isa<UndefValue>(C) || (C->isNullValue() && 
11619         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11620       // Insert a new store to null instruction before the load to indicate that
11621       // this code is not reachable.  We do this instead of inserting an
11622       // unreachable instruction directly because we cannot modify the CFG.
11623       new StoreInst(Context->getUndef(LI.getType()),
11624                     Context->getNullValue(Op->getType()), &LI);
11625       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11626     }
11627
11628     // Instcombine load (constant global) into the value loaded.
11629     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11630       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11631         return ReplaceInstUsesWith(LI, GV->getInitializer());
11632
11633     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11634     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11635       if (CE->getOpcode() == Instruction::GetElementPtr) {
11636         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11637           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11638             if (Constant *V = 
11639                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11640                                                       Context))
11641               return ReplaceInstUsesWith(LI, V);
11642         if (CE->getOperand(0)->isNullValue()) {
11643           // Insert a new store to null instruction before the load to indicate
11644           // that this code is not reachable.  We do this instead of inserting
11645           // an unreachable instruction directly because we cannot modify the
11646           // CFG.
11647           new StoreInst(Context->getUndef(LI.getType()),
11648                         Context->getNullValue(Op->getType()), &LI);
11649           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11650         }
11651
11652       } else if (CE->isCast()) {
11653         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11654           return Res;
11655       }
11656     }
11657   }
11658     
11659   // If this load comes from anywhere in a constant global, and if the global
11660   // is all undef or zero, we know what it loads.
11661   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11662     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11663       if (GV->getInitializer()->isNullValue())
11664         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11665       else if (isa<UndefValue>(GV->getInitializer()))
11666         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11667     }
11668   }
11669
11670   if (Op->hasOneUse()) {
11671     // Change select and PHI nodes to select values instead of addresses: this
11672     // helps alias analysis out a lot, allows many others simplifications, and
11673     // exposes redundancy in the code.
11674     //
11675     // Note that we cannot do the transformation unless we know that the
11676     // introduced loads cannot trap!  Something like this is valid as long as
11677     // the condition is always false: load (select bool %C, int* null, int* %G),
11678     // but it would not be valid if we transformed it to load from null
11679     // unconditionally.
11680     //
11681     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11682       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11683       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11684           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11685         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11686                                      SI->getOperand(1)->getName()+".val"), LI);
11687         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11688                                      SI->getOperand(2)->getName()+".val"), LI);
11689         return SelectInst::Create(SI->getCondition(), V1, V2);
11690       }
11691
11692       // load (select (cond, null, P)) -> load P
11693       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11694         if (C->isNullValue()) {
11695           LI.setOperand(0, SI->getOperand(2));
11696           return &LI;
11697         }
11698
11699       // load (select (cond, P, null)) -> load P
11700       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11701         if (C->isNullValue()) {
11702           LI.setOperand(0, SI->getOperand(1));
11703           return &LI;
11704         }
11705     }
11706   }
11707   return 0;
11708 }
11709
11710 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11711 /// when possible.  This makes it generally easy to do alias analysis and/or
11712 /// SROA/mem2reg of the memory object.
11713 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11714   User *CI = cast<User>(SI.getOperand(1));
11715   Value *CastOp = CI->getOperand(0);
11716   LLVMContext *Context = IC.getContext();
11717
11718   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11719   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11720   if (SrcTy == 0) return 0;
11721   
11722   const Type *SrcPTy = SrcTy->getElementType();
11723
11724   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11725     return 0;
11726   
11727   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11728   /// to its first element.  This allows us to handle things like:
11729   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11730   /// on 32-bit hosts.
11731   SmallVector<Value*, 4> NewGEPIndices;
11732   
11733   // If the source is an array, the code below will not succeed.  Check to
11734   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11735   // constants.
11736   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11737     // Index through pointer.
11738     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11739     NewGEPIndices.push_back(Zero);
11740     
11741     while (1) {
11742       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11743         if (!STy->getNumElements()) /* Struct can be empty {} */
11744           break;
11745         NewGEPIndices.push_back(Zero);
11746         SrcPTy = STy->getElementType(0);
11747       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11748         NewGEPIndices.push_back(Zero);
11749         SrcPTy = ATy->getElementType();
11750       } else {
11751         break;
11752       }
11753     }
11754     
11755     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11756   }
11757
11758   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11759     return 0;
11760   
11761   // If the pointers point into different address spaces or if they point to
11762   // values with different sizes, we can't do the transformation.
11763   if (SrcTy->getAddressSpace() != 
11764         cast<PointerType>(CI->getType())->getAddressSpace() ||
11765       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11766       IC.getTargetData().getTypeSizeInBits(DestPTy))
11767     return 0;
11768
11769   // Okay, we are casting from one integer or pointer type to another of
11770   // the same size.  Instead of casting the pointer before 
11771   // the store, cast the value to be stored.
11772   Value *NewCast;
11773   Value *SIOp0 = SI.getOperand(0);
11774   Instruction::CastOps opcode = Instruction::BitCast;
11775   const Type* CastSrcTy = SIOp0->getType();
11776   const Type* CastDstTy = SrcPTy;
11777   if (isa<PointerType>(CastDstTy)) {
11778     if (CastSrcTy->isInteger())
11779       opcode = Instruction::IntToPtr;
11780   } else if (isa<IntegerType>(CastDstTy)) {
11781     if (isa<PointerType>(SIOp0->getType()))
11782       opcode = Instruction::PtrToInt;
11783   }
11784   
11785   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11786   // emit a GEP to index into its first field.
11787   if (!NewGEPIndices.empty()) {
11788     if (Constant *C = dyn_cast<Constant>(CastOp))
11789       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11790                                               NewGEPIndices.size());
11791     else
11792       CastOp = IC.InsertNewInstBefore(
11793               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11794                                         NewGEPIndices.end()), SI);
11795   }
11796   
11797   if (Constant *C = dyn_cast<Constant>(SIOp0))
11798     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11799   else
11800     NewCast = IC.InsertNewInstBefore(
11801       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11802       SI);
11803   return new StoreInst(NewCast, CastOp);
11804 }
11805
11806 /// equivalentAddressValues - Test if A and B will obviously have the same
11807 /// value. This includes recognizing that %t0 and %t1 will have the same
11808 /// value in code like this:
11809 ///   %t0 = getelementptr \@a, 0, 3
11810 ///   store i32 0, i32* %t0
11811 ///   %t1 = getelementptr \@a, 0, 3
11812 ///   %t2 = load i32* %t1
11813 ///
11814 static bool equivalentAddressValues(Value *A, Value *B) {
11815   // Test if the values are trivially equivalent.
11816   if (A == B) return true;
11817   
11818   // Test if the values come form identical arithmetic instructions.
11819   if (isa<BinaryOperator>(A) ||
11820       isa<CastInst>(A) ||
11821       isa<PHINode>(A) ||
11822       isa<GetElementPtrInst>(A))
11823     if (Instruction *BI = dyn_cast<Instruction>(B))
11824       if (cast<Instruction>(A)->isIdenticalTo(BI))
11825         return true;
11826   
11827   // Otherwise they may not be equivalent.
11828   return false;
11829 }
11830
11831 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11832 // return the llvm.dbg.declare.
11833 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11834   if (!V->hasNUses(2))
11835     return 0;
11836   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11837        UI != E; ++UI) {
11838     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11839       return DI;
11840     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11841       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11842         return DI;
11843       }
11844   }
11845   return 0;
11846 }
11847
11848 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11849   Value *Val = SI.getOperand(0);
11850   Value *Ptr = SI.getOperand(1);
11851
11852   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11853     EraseInstFromFunction(SI);
11854     ++NumCombined;
11855     return 0;
11856   }
11857   
11858   // If the RHS is an alloca with a single use, zapify the store, making the
11859   // alloca dead.
11860   // If the RHS is an alloca with a two uses, the other one being a 
11861   // llvm.dbg.declare, zapify the store and the declare, making the
11862   // alloca dead.  We must do this to prevent declare's from affecting
11863   // codegen.
11864   if (!SI.isVolatile()) {
11865     if (Ptr->hasOneUse()) {
11866       if (isa<AllocaInst>(Ptr)) {
11867         EraseInstFromFunction(SI);
11868         ++NumCombined;
11869         return 0;
11870       }
11871       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11872         if (isa<AllocaInst>(GEP->getOperand(0))) {
11873           if (GEP->getOperand(0)->hasOneUse()) {
11874             EraseInstFromFunction(SI);
11875             ++NumCombined;
11876             return 0;
11877           }
11878           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11879             EraseInstFromFunction(*DI);
11880             EraseInstFromFunction(SI);
11881             ++NumCombined;
11882             return 0;
11883           }
11884         }
11885       }
11886     }
11887     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11888       EraseInstFromFunction(*DI);
11889       EraseInstFromFunction(SI);
11890       ++NumCombined;
11891       return 0;
11892     }
11893   }
11894
11895   // Attempt to improve the alignment.
11896   unsigned KnownAlign =
11897     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11898   if (KnownAlign >
11899       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11900                                 SI.getAlignment()))
11901     SI.setAlignment(KnownAlign);
11902
11903   // Do really simple DSE, to catch cases where there are several consecutive
11904   // stores to the same location, separated by a few arithmetic operations. This
11905   // situation often occurs with bitfield accesses.
11906   BasicBlock::iterator BBI = &SI;
11907   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11908        --ScanInsts) {
11909     --BBI;
11910     // Don't count debug info directives, lest they affect codegen,
11911     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11912     // It is necessary for correctness to skip those that feed into a
11913     // llvm.dbg.declare, as these are not present when debugging is off.
11914     if (isa<DbgInfoIntrinsic>(BBI) ||
11915         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11916       ScanInsts++;
11917       continue;
11918     }    
11919     
11920     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11921       // Prev store isn't volatile, and stores to the same location?
11922       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11923                                                           SI.getOperand(1))) {
11924         ++NumDeadStore;
11925         ++BBI;
11926         EraseInstFromFunction(*PrevSI);
11927         continue;
11928       }
11929       break;
11930     }
11931     
11932     // If this is a load, we have to stop.  However, if the loaded value is from
11933     // the pointer we're loading and is producing the pointer we're storing,
11934     // then *this* store is dead (X = load P; store X -> P).
11935     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11936       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11937           !SI.isVolatile()) {
11938         EraseInstFromFunction(SI);
11939         ++NumCombined;
11940         return 0;
11941       }
11942       // Otherwise, this is a load from some other location.  Stores before it
11943       // may not be dead.
11944       break;
11945     }
11946     
11947     // Don't skip over loads or things that can modify memory.
11948     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11949       break;
11950   }
11951   
11952   
11953   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11954
11955   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11956   if (isa<ConstantPointerNull>(Ptr) &&
11957       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11958     if (!isa<UndefValue>(Val)) {
11959       SI.setOperand(0, Context->getUndef(Val->getType()));
11960       if (Instruction *U = dyn_cast<Instruction>(Val))
11961         AddToWorkList(U);  // Dropped a use.
11962       ++NumCombined;
11963     }
11964     return 0;  // Do not modify these!
11965   }
11966
11967   // store undef, Ptr -> noop
11968   if (isa<UndefValue>(Val)) {
11969     EraseInstFromFunction(SI);
11970     ++NumCombined;
11971     return 0;
11972   }
11973
11974   // If the pointer destination is a cast, see if we can fold the cast into the
11975   // source instead.
11976   if (isa<CastInst>(Ptr))
11977     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11978       return Res;
11979   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11980     if (CE->isCast())
11981       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11982         return Res;
11983
11984   
11985   // If this store is the last instruction in the basic block (possibly
11986   // excepting debug info instructions and the pointer bitcasts that feed
11987   // into them), and if the block ends with an unconditional branch, try
11988   // to move it to the successor block.
11989   BBI = &SI; 
11990   do {
11991     ++BBI;
11992   } while (isa<DbgInfoIntrinsic>(BBI) ||
11993            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11994   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11995     if (BI->isUnconditional())
11996       if (SimplifyStoreAtEndOfBlock(SI))
11997         return 0;  // xform done!
11998   
11999   return 0;
12000 }
12001
12002 /// SimplifyStoreAtEndOfBlock - Turn things like:
12003 ///   if () { *P = v1; } else { *P = v2 }
12004 /// into a phi node with a store in the successor.
12005 ///
12006 /// Simplify things like:
12007 ///   *P = v1; if () { *P = v2; }
12008 /// into a phi node with a store in the successor.
12009 ///
12010 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12011   BasicBlock *StoreBB = SI.getParent();
12012   
12013   // Check to see if the successor block has exactly two incoming edges.  If
12014   // so, see if the other predecessor contains a store to the same location.
12015   // if so, insert a PHI node (if needed) and move the stores down.
12016   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12017   
12018   // Determine whether Dest has exactly two predecessors and, if so, compute
12019   // the other predecessor.
12020   pred_iterator PI = pred_begin(DestBB);
12021   BasicBlock *OtherBB = 0;
12022   if (*PI != StoreBB)
12023     OtherBB = *PI;
12024   ++PI;
12025   if (PI == pred_end(DestBB))
12026     return false;
12027   
12028   if (*PI != StoreBB) {
12029     if (OtherBB)
12030       return false;
12031     OtherBB = *PI;
12032   }
12033   if (++PI != pred_end(DestBB))
12034     return false;
12035
12036   // Bail out if all the relevant blocks aren't distinct (this can happen,
12037   // for example, if SI is in an infinite loop)
12038   if (StoreBB == DestBB || OtherBB == DestBB)
12039     return false;
12040
12041   // Verify that the other block ends in a branch and is not otherwise empty.
12042   BasicBlock::iterator BBI = OtherBB->getTerminator();
12043   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12044   if (!OtherBr || BBI == OtherBB->begin())
12045     return false;
12046   
12047   // If the other block ends in an unconditional branch, check for the 'if then
12048   // else' case.  there is an instruction before the branch.
12049   StoreInst *OtherStore = 0;
12050   if (OtherBr->isUnconditional()) {
12051     --BBI;
12052     // Skip over debugging info.
12053     while (isa<DbgInfoIntrinsic>(BBI) ||
12054            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12055       if (BBI==OtherBB->begin())
12056         return false;
12057       --BBI;
12058     }
12059     // If this isn't a store, or isn't a store to the same location, bail out.
12060     OtherStore = dyn_cast<StoreInst>(BBI);
12061     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12062       return false;
12063   } else {
12064     // Otherwise, the other block ended with a conditional branch. If one of the
12065     // destinations is StoreBB, then we have the if/then case.
12066     if (OtherBr->getSuccessor(0) != StoreBB && 
12067         OtherBr->getSuccessor(1) != StoreBB)
12068       return false;
12069     
12070     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12071     // if/then triangle.  See if there is a store to the same ptr as SI that
12072     // lives in OtherBB.
12073     for (;; --BBI) {
12074       // Check to see if we find the matching store.
12075       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12076         if (OtherStore->getOperand(1) != SI.getOperand(1))
12077           return false;
12078         break;
12079       }
12080       // If we find something that may be using or overwriting the stored
12081       // value, or if we run out of instructions, we can't do the xform.
12082       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12083           BBI == OtherBB->begin())
12084         return false;
12085     }
12086     
12087     // In order to eliminate the store in OtherBr, we have to
12088     // make sure nothing reads or overwrites the stored value in
12089     // StoreBB.
12090     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12091       // FIXME: This should really be AA driven.
12092       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12093         return false;
12094     }
12095   }
12096   
12097   // Insert a PHI node now if we need it.
12098   Value *MergedVal = OtherStore->getOperand(0);
12099   if (MergedVal != SI.getOperand(0)) {
12100     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12101     PN->reserveOperandSpace(2);
12102     PN->addIncoming(SI.getOperand(0), SI.getParent());
12103     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12104     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12105   }
12106   
12107   // Advance to a place where it is safe to insert the new store and
12108   // insert it.
12109   BBI = DestBB->getFirstNonPHI();
12110   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12111                                     OtherStore->isVolatile()), *BBI);
12112   
12113   // Nuke the old stores.
12114   EraseInstFromFunction(SI);
12115   EraseInstFromFunction(*OtherStore);
12116   ++NumCombined;
12117   return true;
12118 }
12119
12120
12121 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12122   // Change br (not X), label True, label False to: br X, label False, True
12123   Value *X = 0;
12124   BasicBlock *TrueDest;
12125   BasicBlock *FalseDest;
12126   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12127       !isa<Constant>(X)) {
12128     // Swap Destinations and condition...
12129     BI.setCondition(X);
12130     BI.setSuccessor(0, FalseDest);
12131     BI.setSuccessor(1, TrueDest);
12132     return &BI;
12133   }
12134
12135   // Cannonicalize fcmp_one -> fcmp_oeq
12136   FCmpInst::Predicate FPred; Value *Y;
12137   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12138                              TrueDest, FalseDest), *Context))
12139     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12140          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12141       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12142       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12143       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12144       NewSCC->takeName(I);
12145       // Swap Destinations and condition...
12146       BI.setCondition(NewSCC);
12147       BI.setSuccessor(0, FalseDest);
12148       BI.setSuccessor(1, TrueDest);
12149       RemoveFromWorkList(I);
12150       I->eraseFromParent();
12151       AddToWorkList(NewSCC);
12152       return &BI;
12153     }
12154
12155   // Cannonicalize icmp_ne -> icmp_eq
12156   ICmpInst::Predicate IPred;
12157   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12158                       TrueDest, FalseDest), *Context))
12159     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12160          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12161          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12162       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12163       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12164       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12165       NewSCC->takeName(I);
12166       // Swap Destinations and condition...
12167       BI.setCondition(NewSCC);
12168       BI.setSuccessor(0, FalseDest);
12169       BI.setSuccessor(1, TrueDest);
12170       RemoveFromWorkList(I);
12171       I->eraseFromParent();;
12172       AddToWorkList(NewSCC);
12173       return &BI;
12174     }
12175
12176   return 0;
12177 }
12178
12179 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12180   Value *Cond = SI.getCondition();
12181   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12182     if (I->getOpcode() == Instruction::Add)
12183       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12184         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12185         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12186           SI.setOperand(i,
12187                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12188                                                 AddRHS));
12189         SI.setOperand(0, I->getOperand(0));
12190         AddToWorkList(I);
12191         return &SI;
12192       }
12193   }
12194   return 0;
12195 }
12196
12197 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12198   Value *Agg = EV.getAggregateOperand();
12199
12200   if (!EV.hasIndices())
12201     return ReplaceInstUsesWith(EV, Agg);
12202
12203   if (Constant *C = dyn_cast<Constant>(Agg)) {
12204     if (isa<UndefValue>(C))
12205       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12206       
12207     if (isa<ConstantAggregateZero>(C))
12208       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12209
12210     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12211       // Extract the element indexed by the first index out of the constant
12212       Value *V = C->getOperand(*EV.idx_begin());
12213       if (EV.getNumIndices() > 1)
12214         // Extract the remaining indices out of the constant indexed by the
12215         // first index
12216         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12217       else
12218         return ReplaceInstUsesWith(EV, V);
12219     }
12220     return 0; // Can't handle other constants
12221   } 
12222   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12223     // We're extracting from an insertvalue instruction, compare the indices
12224     const unsigned *exti, *exte, *insi, *inse;
12225     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12226          exte = EV.idx_end(), inse = IV->idx_end();
12227          exti != exte && insi != inse;
12228          ++exti, ++insi) {
12229       if (*insi != *exti)
12230         // The insert and extract both reference distinctly different elements.
12231         // This means the extract is not influenced by the insert, and we can
12232         // replace the aggregate operand of the extract with the aggregate
12233         // operand of the insert. i.e., replace
12234         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12235         // %E = extractvalue { i32, { i32 } } %I, 0
12236         // with
12237         // %E = extractvalue { i32, { i32 } } %A, 0
12238         return ExtractValueInst::Create(IV->getAggregateOperand(),
12239                                         EV.idx_begin(), EV.idx_end());
12240     }
12241     if (exti == exte && insi == inse)
12242       // Both iterators are at the end: Index lists are identical. Replace
12243       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12244       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12245       // with "i32 42"
12246       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12247     if (exti == exte) {
12248       // The extract list is a prefix of the insert list. i.e. replace
12249       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12250       // %E = extractvalue { i32, { i32 } } %I, 1
12251       // with
12252       // %X = extractvalue { i32, { i32 } } %A, 1
12253       // %E = insertvalue { i32 } %X, i32 42, 0
12254       // by switching the order of the insert and extract (though the
12255       // insertvalue should be left in, since it may have other uses).
12256       Value *NewEV = InsertNewInstBefore(
12257         ExtractValueInst::Create(IV->getAggregateOperand(),
12258                                  EV.idx_begin(), EV.idx_end()),
12259         EV);
12260       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12261                                      insi, inse);
12262     }
12263     if (insi == inse)
12264       // The insert list is a prefix of the extract list
12265       // We can simply remove the common indices from the extract and make it
12266       // operate on the inserted value instead of the insertvalue result.
12267       // i.e., replace
12268       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12269       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12270       // with
12271       // %E extractvalue { i32 } { i32 42 }, 0
12272       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12273                                       exti, exte);
12274   }
12275   // Can't simplify extracts from other values. Note that nested extracts are
12276   // already simplified implicitely by the above (extract ( extract (insert) )
12277   // will be translated into extract ( insert ( extract ) ) first and then just
12278   // the value inserted, if appropriate).
12279   return 0;
12280 }
12281
12282 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12283 /// is to leave as a vector operation.
12284 static bool CheapToScalarize(Value *V, bool isConstant) {
12285   if (isa<ConstantAggregateZero>(V)) 
12286     return true;
12287   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12288     if (isConstant) return true;
12289     // If all elts are the same, we can extract.
12290     Constant *Op0 = C->getOperand(0);
12291     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12292       if (C->getOperand(i) != Op0)
12293         return false;
12294     return true;
12295   }
12296   Instruction *I = dyn_cast<Instruction>(V);
12297   if (!I) return false;
12298   
12299   // Insert element gets simplified to the inserted element or is deleted if
12300   // this is constant idx extract element and its a constant idx insertelt.
12301   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12302       isa<ConstantInt>(I->getOperand(2)))
12303     return true;
12304   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12305     return true;
12306   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12307     if (BO->hasOneUse() &&
12308         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12309          CheapToScalarize(BO->getOperand(1), isConstant)))
12310       return true;
12311   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12312     if (CI->hasOneUse() &&
12313         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12314          CheapToScalarize(CI->getOperand(1), isConstant)))
12315       return true;
12316   
12317   return false;
12318 }
12319
12320 /// Read and decode a shufflevector mask.
12321 ///
12322 /// It turns undef elements into values that are larger than the number of
12323 /// elements in the input.
12324 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12325   unsigned NElts = SVI->getType()->getNumElements();
12326   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12327     return std::vector<unsigned>(NElts, 0);
12328   if (isa<UndefValue>(SVI->getOperand(2)))
12329     return std::vector<unsigned>(NElts, 2*NElts);
12330
12331   std::vector<unsigned> Result;
12332   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12333   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12334     if (isa<UndefValue>(*i))
12335       Result.push_back(NElts*2);  // undef -> 8
12336     else
12337       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12338   return Result;
12339 }
12340
12341 /// FindScalarElement - Given a vector and an element number, see if the scalar
12342 /// value is already around as a register, for example if it were inserted then
12343 /// extracted from the vector.
12344 static Value *FindScalarElement(Value *V, unsigned EltNo,
12345                                 LLVMContext *Context) {
12346   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12347   const VectorType *PTy = cast<VectorType>(V->getType());
12348   unsigned Width = PTy->getNumElements();
12349   if (EltNo >= Width)  // Out of range access.
12350     return Context->getUndef(PTy->getElementType());
12351   
12352   if (isa<UndefValue>(V))
12353     return Context->getUndef(PTy->getElementType());
12354   else if (isa<ConstantAggregateZero>(V))
12355     return Context->getNullValue(PTy->getElementType());
12356   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12357     return CP->getOperand(EltNo);
12358   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12359     // If this is an insert to a variable element, we don't know what it is.
12360     if (!isa<ConstantInt>(III->getOperand(2))) 
12361       return 0;
12362     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12363     
12364     // If this is an insert to the element we are looking for, return the
12365     // inserted value.
12366     if (EltNo == IIElt) 
12367       return III->getOperand(1);
12368     
12369     // Otherwise, the insertelement doesn't modify the value, recurse on its
12370     // vector input.
12371     return FindScalarElement(III->getOperand(0), EltNo, Context);
12372   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12373     unsigned LHSWidth =
12374       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12375     unsigned InEl = getShuffleMask(SVI)[EltNo];
12376     if (InEl < LHSWidth)
12377       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12378     else if (InEl < LHSWidth*2)
12379       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12380     else
12381       return Context->getUndef(PTy->getElementType());
12382   }
12383   
12384   // Otherwise, we don't know.
12385   return 0;
12386 }
12387
12388 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12389   // If vector val is undef, replace extract with scalar undef.
12390   if (isa<UndefValue>(EI.getOperand(0)))
12391     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12392
12393   // If vector val is constant 0, replace extract with scalar 0.
12394   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12395     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12396   
12397   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12398     // If vector val is constant with all elements the same, replace EI with
12399     // that element. When the elements are not identical, we cannot replace yet
12400     // (we do that below, but only when the index is constant).
12401     Constant *op0 = C->getOperand(0);
12402     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12403       if (C->getOperand(i) != op0) {
12404         op0 = 0; 
12405         break;
12406       }
12407     if (op0)
12408       return ReplaceInstUsesWith(EI, op0);
12409   }
12410   
12411   // If extracting a specified index from the vector, see if we can recursively
12412   // find a previously computed scalar that was inserted into the vector.
12413   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12414     unsigned IndexVal = IdxC->getZExtValue();
12415     unsigned VectorWidth = 
12416       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12417       
12418     // If this is extracting an invalid index, turn this into undef, to avoid
12419     // crashing the code below.
12420     if (IndexVal >= VectorWidth)
12421       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12422     
12423     // This instruction only demands the single element from the input vector.
12424     // If the input vector has a single use, simplify it based on this use
12425     // property.
12426     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12427       APInt UndefElts(VectorWidth, 0);
12428       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12429       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12430                                                 DemandedMask, UndefElts)) {
12431         EI.setOperand(0, V);
12432         return &EI;
12433       }
12434     }
12435     
12436     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12437       return ReplaceInstUsesWith(EI, Elt);
12438     
12439     // If the this extractelement is directly using a bitcast from a vector of
12440     // the same number of elements, see if we can find the source element from
12441     // it.  In this case, we will end up needing to bitcast the scalars.
12442     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12443       if (const VectorType *VT = 
12444               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12445         if (VT->getNumElements() == VectorWidth)
12446           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12447                                              IndexVal, Context))
12448             return new BitCastInst(Elt, EI.getType());
12449     }
12450   }
12451   
12452   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12453     if (I->hasOneUse()) {
12454       // Push extractelement into predecessor operation if legal and
12455       // profitable to do so
12456       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12457         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12458         if (CheapToScalarize(BO, isConstantElt)) {
12459           ExtractElementInst *newEI0 = 
12460             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12461                                    EI.getName()+".lhs");
12462           ExtractElementInst *newEI1 =
12463             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12464                                    EI.getName()+".rhs");
12465           InsertNewInstBefore(newEI0, EI);
12466           InsertNewInstBefore(newEI1, EI);
12467           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12468         }
12469       } else if (isa<LoadInst>(I)) {
12470         unsigned AS = 
12471           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12472         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12473                                   Context->getPointerType(EI.getType(), AS),EI);
12474         GetElementPtrInst *GEP =
12475           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12476         InsertNewInstBefore(GEP, EI);
12477         return new LoadInst(GEP);
12478       }
12479     }
12480     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12481       // Extracting the inserted element?
12482       if (IE->getOperand(2) == EI.getOperand(1))
12483         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12484       // If the inserted and extracted elements are constants, they must not
12485       // be the same value, extract from the pre-inserted value instead.
12486       if (isa<Constant>(IE->getOperand(2)) &&
12487           isa<Constant>(EI.getOperand(1))) {
12488         AddUsesToWorkList(EI);
12489         EI.setOperand(0, IE->getOperand(0));
12490         return &EI;
12491       }
12492     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12493       // If this is extracting an element from a shufflevector, figure out where
12494       // it came from and extract from the appropriate input element instead.
12495       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12496         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12497         Value *Src;
12498         unsigned LHSWidth =
12499           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12500
12501         if (SrcIdx < LHSWidth)
12502           Src = SVI->getOperand(0);
12503         else if (SrcIdx < LHSWidth*2) {
12504           SrcIdx -= LHSWidth;
12505           Src = SVI->getOperand(1);
12506         } else {
12507           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12508         }
12509         return new ExtractElementInst(Src, SrcIdx);
12510       }
12511     }
12512   }
12513   return 0;
12514 }
12515
12516 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12517 /// elements from either LHS or RHS, return the shuffle mask and true. 
12518 /// Otherwise, return false.
12519 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12520                                          std::vector<Constant*> &Mask,
12521                                          LLVMContext *Context) {
12522   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12523          "Invalid CollectSingleShuffleElements");
12524   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12525
12526   if (isa<UndefValue>(V)) {
12527     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12528     return true;
12529   } else if (V == LHS) {
12530     for (unsigned i = 0; i != NumElts; ++i)
12531       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12532     return true;
12533   } else if (V == RHS) {
12534     for (unsigned i = 0; i != NumElts; ++i)
12535       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12536     return true;
12537   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12538     // If this is an insert of an extract from some other vector, include it.
12539     Value *VecOp    = IEI->getOperand(0);
12540     Value *ScalarOp = IEI->getOperand(1);
12541     Value *IdxOp    = IEI->getOperand(2);
12542     
12543     if (!isa<ConstantInt>(IdxOp))
12544       return false;
12545     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12546     
12547     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12548       // Okay, we can handle this if the vector we are insertinting into is
12549       // transitively ok.
12550       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12551         // If so, update the mask to reflect the inserted undef.
12552         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12553         return true;
12554       }      
12555     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12556       if (isa<ConstantInt>(EI->getOperand(1)) &&
12557           EI->getOperand(0)->getType() == V->getType()) {
12558         unsigned ExtractedIdx =
12559           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12560         
12561         // This must be extracting from either LHS or RHS.
12562         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12563           // Okay, we can handle this if the vector we are insertinting into is
12564           // transitively ok.
12565           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12566             // If so, update the mask to reflect the inserted value.
12567             if (EI->getOperand(0) == LHS) {
12568               Mask[InsertedIdx % NumElts] = 
12569                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12570             } else {
12571               assert(EI->getOperand(0) == RHS);
12572               Mask[InsertedIdx % NumElts] = 
12573                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12574               
12575             }
12576             return true;
12577           }
12578         }
12579       }
12580     }
12581   }
12582   // TODO: Handle shufflevector here!
12583   
12584   return false;
12585 }
12586
12587 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12588 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12589 /// that computes V and the LHS value of the shuffle.
12590 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12591                                      Value *&RHS, LLVMContext *Context) {
12592   assert(isa<VectorType>(V->getType()) && 
12593          (RHS == 0 || V->getType() == RHS->getType()) &&
12594          "Invalid shuffle!");
12595   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12596
12597   if (isa<UndefValue>(V)) {
12598     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12599     return V;
12600   } else if (isa<ConstantAggregateZero>(V)) {
12601     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12602     return V;
12603   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12604     // If this is an insert of an extract from some other vector, include it.
12605     Value *VecOp    = IEI->getOperand(0);
12606     Value *ScalarOp = IEI->getOperand(1);
12607     Value *IdxOp    = IEI->getOperand(2);
12608     
12609     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12610       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12611           EI->getOperand(0)->getType() == V->getType()) {
12612         unsigned ExtractedIdx =
12613           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12614         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12615         
12616         // Either the extracted from or inserted into vector must be RHSVec,
12617         // otherwise we'd end up with a shuffle of three inputs.
12618         if (EI->getOperand(0) == RHS || RHS == 0) {
12619           RHS = EI->getOperand(0);
12620           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12621           Mask[InsertedIdx % NumElts] = 
12622             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12623           return V;
12624         }
12625         
12626         if (VecOp == RHS) {
12627           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12628                                             RHS, Context);
12629           // Everything but the extracted element is replaced with the RHS.
12630           for (unsigned i = 0; i != NumElts; ++i) {
12631             if (i != InsertedIdx)
12632               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12633           }
12634           return V;
12635         }
12636         
12637         // If this insertelement is a chain that comes from exactly these two
12638         // vectors, return the vector and the effective shuffle.
12639         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12640                                          Context))
12641           return EI->getOperand(0);
12642         
12643       }
12644     }
12645   }
12646   // TODO: Handle shufflevector here!
12647   
12648   // Otherwise, can't do anything fancy.  Return an identity vector.
12649   for (unsigned i = 0; i != NumElts; ++i)
12650     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12651   return V;
12652 }
12653
12654 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12655   Value *VecOp    = IE.getOperand(0);
12656   Value *ScalarOp = IE.getOperand(1);
12657   Value *IdxOp    = IE.getOperand(2);
12658   
12659   // Inserting an undef or into an undefined place, remove this.
12660   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12661     ReplaceInstUsesWith(IE, VecOp);
12662   
12663   // If the inserted element was extracted from some other vector, and if the 
12664   // indexes are constant, try to turn this into a shufflevector operation.
12665   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12666     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12667         EI->getOperand(0)->getType() == IE.getType()) {
12668       unsigned NumVectorElts = IE.getType()->getNumElements();
12669       unsigned ExtractedIdx =
12670         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12671       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12672       
12673       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12674         return ReplaceInstUsesWith(IE, VecOp);
12675       
12676       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12677         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12678       
12679       // If we are extracting a value from a vector, then inserting it right
12680       // back into the same place, just use the input vector.
12681       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12682         return ReplaceInstUsesWith(IE, VecOp);      
12683       
12684       // We could theoretically do this for ANY input.  However, doing so could
12685       // turn chains of insertelement instructions into a chain of shufflevector
12686       // instructions, and right now we do not merge shufflevectors.  As such,
12687       // only do this in a situation where it is clear that there is benefit.
12688       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12689         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12690         // the values of VecOp, except then one read from EIOp0.
12691         // Build a new shuffle mask.
12692         std::vector<Constant*> Mask;
12693         if (isa<UndefValue>(VecOp))
12694           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12695         else {
12696           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12697           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12698                                                        NumVectorElts));
12699         } 
12700         Mask[InsertedIdx] = 
12701                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12702         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12703                                      Context->getConstantVector(Mask));
12704       }
12705       
12706       // If this insertelement isn't used by some other insertelement, turn it
12707       // (and any insertelements it points to), into one big shuffle.
12708       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12709         std::vector<Constant*> Mask;
12710         Value *RHS = 0;
12711         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12712         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12713         // We now have a shuffle of LHS, RHS, Mask.
12714         return new ShuffleVectorInst(LHS, RHS,
12715                                      Context->getConstantVector(Mask));
12716       }
12717     }
12718   }
12719
12720   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12721   APInt UndefElts(VWidth, 0);
12722   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12723   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12724     return &IE;
12725
12726   return 0;
12727 }
12728
12729
12730 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12731   Value *LHS = SVI.getOperand(0);
12732   Value *RHS = SVI.getOperand(1);
12733   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12734
12735   bool MadeChange = false;
12736
12737   // Undefined shuffle mask -> undefined value.
12738   if (isa<UndefValue>(SVI.getOperand(2)))
12739     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12740
12741   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12742
12743   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12744     return 0;
12745
12746   APInt UndefElts(VWidth, 0);
12747   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12748   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12749     LHS = SVI.getOperand(0);
12750     RHS = SVI.getOperand(1);
12751     MadeChange = true;
12752   }
12753   
12754   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12755   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12756   if (LHS == RHS || isa<UndefValue>(LHS)) {
12757     if (isa<UndefValue>(LHS) && LHS == RHS) {
12758       // shuffle(undef,undef,mask) -> undef.
12759       return ReplaceInstUsesWith(SVI, LHS);
12760     }
12761     
12762     // Remap any references to RHS to use LHS.
12763     std::vector<Constant*> Elts;
12764     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12765       if (Mask[i] >= 2*e)
12766         Elts.push_back(Context->getUndef(Type::Int32Ty));
12767       else {
12768         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12769             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12770           Mask[i] = 2*e;     // Turn into undef.
12771           Elts.push_back(Context->getUndef(Type::Int32Ty));
12772         } else {
12773           Mask[i] = Mask[i] % e;  // Force to LHS.
12774           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12775         }
12776       }
12777     }
12778     SVI.setOperand(0, SVI.getOperand(1));
12779     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12780     SVI.setOperand(2, Context->getConstantVector(Elts));
12781     LHS = SVI.getOperand(0);
12782     RHS = SVI.getOperand(1);
12783     MadeChange = true;
12784   }
12785   
12786   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12787   bool isLHSID = true, isRHSID = true;
12788     
12789   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12790     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12791     // Is this an identity shuffle of the LHS value?
12792     isLHSID &= (Mask[i] == i);
12793       
12794     // Is this an identity shuffle of the RHS value?
12795     isRHSID &= (Mask[i]-e == i);
12796   }
12797
12798   // Eliminate identity shuffles.
12799   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12800   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12801   
12802   // If the LHS is a shufflevector itself, see if we can combine it with this
12803   // one without producing an unusual shuffle.  Here we are really conservative:
12804   // we are absolutely afraid of producing a shuffle mask not in the input
12805   // program, because the code gen may not be smart enough to turn a merged
12806   // shuffle into two specific shuffles: it may produce worse code.  As such,
12807   // we only merge two shuffles if the result is one of the two input shuffle
12808   // masks.  In this case, merging the shuffles just removes one instruction,
12809   // which we know is safe.  This is good for things like turning:
12810   // (splat(splat)) -> splat.
12811   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12812     if (isa<UndefValue>(RHS)) {
12813       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12814
12815       std::vector<unsigned> NewMask;
12816       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12817         if (Mask[i] >= 2*e)
12818           NewMask.push_back(2*e);
12819         else
12820           NewMask.push_back(LHSMask[Mask[i]]);
12821       
12822       // If the result mask is equal to the src shuffle or this shuffle mask, do
12823       // the replacement.
12824       if (NewMask == LHSMask || NewMask == Mask) {
12825         unsigned LHSInNElts =
12826           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12827         std::vector<Constant*> Elts;
12828         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12829           if (NewMask[i] >= LHSInNElts*2) {
12830             Elts.push_back(Context->getUndef(Type::Int32Ty));
12831           } else {
12832             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12833           }
12834         }
12835         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12836                                      LHSSVI->getOperand(1),
12837                                      Context->getConstantVector(Elts));
12838       }
12839     }
12840   }
12841
12842   return MadeChange ? &SVI : 0;
12843 }
12844
12845
12846
12847
12848 /// TryToSinkInstruction - Try to move the specified instruction from its
12849 /// current block into the beginning of DestBlock, which can only happen if it's
12850 /// safe to move the instruction past all of the instructions between it and the
12851 /// end of its block.
12852 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12853   assert(I->hasOneUse() && "Invariants didn't hold!");
12854
12855   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12856   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12857     return false;
12858
12859   // Do not sink alloca instructions out of the entry block.
12860   if (isa<AllocaInst>(I) && I->getParent() ==
12861         &DestBlock->getParent()->getEntryBlock())
12862     return false;
12863
12864   // We can only sink load instructions if there is nothing between the load and
12865   // the end of block that could change the value.
12866   if (I->mayReadFromMemory()) {
12867     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12868          Scan != E; ++Scan)
12869       if (Scan->mayWriteToMemory())
12870         return false;
12871   }
12872
12873   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12874
12875   CopyPrecedingStopPoint(I, InsertPos);
12876   I->moveBefore(InsertPos);
12877   ++NumSunkInst;
12878   return true;
12879 }
12880
12881
12882 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12883 /// all reachable code to the worklist.
12884 ///
12885 /// This has a couple of tricks to make the code faster and more powerful.  In
12886 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12887 /// them to the worklist (this significantly speeds up instcombine on code where
12888 /// many instructions are dead or constant).  Additionally, if we find a branch
12889 /// whose condition is a known constant, we only visit the reachable successors.
12890 ///
12891 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12892                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12893                                        InstCombiner &IC,
12894                                        const TargetData *TD) {
12895   SmallVector<BasicBlock*, 256> Worklist;
12896   Worklist.push_back(BB);
12897
12898   while (!Worklist.empty()) {
12899     BB = Worklist.back();
12900     Worklist.pop_back();
12901     
12902     // We have now visited this block!  If we've already been here, ignore it.
12903     if (!Visited.insert(BB)) continue;
12904
12905     DbgInfoIntrinsic *DBI_Prev = NULL;
12906     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12907       Instruction *Inst = BBI++;
12908       
12909       // DCE instruction if trivially dead.
12910       if (isInstructionTriviallyDead(Inst)) {
12911         ++NumDeadInst;
12912         DOUT << "IC: DCE: " << *Inst;
12913         Inst->eraseFromParent();
12914         continue;
12915       }
12916       
12917       // ConstantProp instruction if trivially constant.
12918       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12919         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12920         Inst->replaceAllUsesWith(C);
12921         ++NumConstProp;
12922         Inst->eraseFromParent();
12923         continue;
12924       }
12925      
12926       // If there are two consecutive llvm.dbg.stoppoint calls then
12927       // it is likely that the optimizer deleted code in between these
12928       // two intrinsics. 
12929       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12930       if (DBI_Next) {
12931         if (DBI_Prev
12932             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12933             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12934           IC.RemoveFromWorkList(DBI_Prev);
12935           DBI_Prev->eraseFromParent();
12936         }
12937         DBI_Prev = DBI_Next;
12938       } else {
12939         DBI_Prev = 0;
12940       }
12941
12942       IC.AddToWorkList(Inst);
12943     }
12944
12945     // Recursively visit successors.  If this is a branch or switch on a
12946     // constant, only visit the reachable successor.
12947     TerminatorInst *TI = BB->getTerminator();
12948     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12949       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12950         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12951         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12952         Worklist.push_back(ReachableBB);
12953         continue;
12954       }
12955     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12956       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12957         // See if this is an explicit destination.
12958         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12959           if (SI->getCaseValue(i) == Cond) {
12960             BasicBlock *ReachableBB = SI->getSuccessor(i);
12961             Worklist.push_back(ReachableBB);
12962             continue;
12963           }
12964         
12965         // Otherwise it is the default destination.
12966         Worklist.push_back(SI->getSuccessor(0));
12967         continue;
12968       }
12969     }
12970     
12971     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12972       Worklist.push_back(TI->getSuccessor(i));
12973   }
12974 }
12975
12976 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12977   bool Changed = false;
12978   TD = &getAnalysis<TargetData>();
12979   
12980   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12981              << F.getNameStr() << "\n");
12982
12983   {
12984     // Do a depth-first traversal of the function, populate the worklist with
12985     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12986     // track of which blocks we visit.
12987     SmallPtrSet<BasicBlock*, 64> Visited;
12988     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12989
12990     // Do a quick scan over the function.  If we find any blocks that are
12991     // unreachable, remove any instructions inside of them.  This prevents
12992     // the instcombine code from having to deal with some bad special cases.
12993     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12994       if (!Visited.count(BB)) {
12995         Instruction *Term = BB->getTerminator();
12996         while (Term != BB->begin()) {   // Remove instrs bottom-up
12997           BasicBlock::iterator I = Term; --I;
12998
12999           DOUT << "IC: DCE: " << *I;
13000           // A debug intrinsic shouldn't force another iteration if we weren't
13001           // going to do one without it.
13002           if (!isa<DbgInfoIntrinsic>(I)) {
13003             ++NumDeadInst;
13004             Changed = true;
13005           }
13006           if (!I->use_empty())
13007             I->replaceAllUsesWith(Context->getUndef(I->getType()));
13008           I->eraseFromParent();
13009         }
13010       }
13011   }
13012
13013   while (!Worklist.empty()) {
13014     Instruction *I = RemoveOneFromWorkList();
13015     if (I == 0) continue;  // skip null values.
13016
13017     // Check to see if we can DCE the instruction.
13018     if (isInstructionTriviallyDead(I)) {
13019       // Add operands to the worklist.
13020       if (I->getNumOperands() < 4)
13021         AddUsesToWorkList(*I);
13022       ++NumDeadInst;
13023
13024       DOUT << "IC: DCE: " << *I;
13025
13026       I->eraseFromParent();
13027       RemoveFromWorkList(I);
13028       Changed = true;
13029       continue;
13030     }
13031
13032     // Instruction isn't dead, see if we can constant propagate it.
13033     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13034       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13035
13036       // Add operands to the worklist.
13037       AddUsesToWorkList(*I);
13038       ReplaceInstUsesWith(*I, C);
13039
13040       ++NumConstProp;
13041       I->eraseFromParent();
13042       RemoveFromWorkList(I);
13043       Changed = true;
13044       continue;
13045     }
13046
13047     if (TD &&
13048         (I->getType()->getTypeID() == Type::VoidTyID ||
13049          I->isTrapping())) {
13050       // See if we can constant fold its operands.
13051       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13052         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13053           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13054                                   F.getContext(), TD))
13055             if (NewC != CE) {
13056               i->set(NewC);
13057               Changed = true;
13058             }
13059     }
13060
13061     // See if we can trivially sink this instruction to a successor basic block.
13062     if (I->hasOneUse()) {
13063       BasicBlock *BB = I->getParent();
13064       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13065       if (UserParent != BB) {
13066         bool UserIsSuccessor = false;
13067         // See if the user is one of our successors.
13068         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13069           if (*SI == UserParent) {
13070             UserIsSuccessor = true;
13071             break;
13072           }
13073
13074         // If the user is one of our immediate successors, and if that successor
13075         // only has us as a predecessors (we'd have to split the critical edge
13076         // otherwise), we can keep going.
13077         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13078             next(pred_begin(UserParent)) == pred_end(UserParent))
13079           // Okay, the CFG is simple enough, try to sink this instruction.
13080           Changed |= TryToSinkInstruction(I, UserParent);
13081       }
13082     }
13083
13084     // Now that we have an instruction, try combining it to simplify it...
13085 #ifndef NDEBUG
13086     std::string OrigI;
13087 #endif
13088     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13089     if (Instruction *Result = visit(*I)) {
13090       ++NumCombined;
13091       // Should we replace the old instruction with a new one?
13092       if (Result != I) {
13093         DOUT << "IC: Old = " << *I
13094              << "    New = " << *Result;
13095
13096         // Everything uses the new instruction now.
13097         I->replaceAllUsesWith(Result);
13098
13099         // Push the new instruction and any users onto the worklist.
13100         AddToWorkList(Result);
13101         AddUsersToWorkList(*Result);
13102
13103         // Move the name to the new instruction first.
13104         Result->takeName(I);
13105
13106         // Insert the new instruction into the basic block...
13107         BasicBlock *InstParent = I->getParent();
13108         BasicBlock::iterator InsertPos = I;
13109
13110         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13111           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13112             ++InsertPos;
13113
13114         InstParent->getInstList().insert(InsertPos, Result);
13115
13116         // Make sure that we reprocess all operands now that we reduced their
13117         // use counts.
13118         AddUsesToWorkList(*I);
13119
13120         // Instructions can end up on the worklist more than once.  Make sure
13121         // we do not process an instruction that has been deleted.
13122         RemoveFromWorkList(I);
13123
13124         // Erase the old instruction.
13125         InstParent->getInstList().erase(I);
13126       } else {
13127 #ifndef NDEBUG
13128         DOUT << "IC: Mod = " << OrigI
13129              << "    New = " << *I;
13130 #endif
13131
13132         // If the instruction was modified, it's possible that it is now dead.
13133         // if so, remove it.
13134         if (isInstructionTriviallyDead(I)) {
13135           // Make sure we process all operands now that we are reducing their
13136           // use counts.
13137           AddUsesToWorkList(*I);
13138
13139           // Instructions may end up in the worklist more than once.  Erase all
13140           // occurrences of this instruction.
13141           RemoveFromWorkList(I);
13142           I->eraseFromParent();
13143         } else {
13144           AddToWorkList(I);
13145           AddUsersToWorkList(*I);
13146         }
13147       }
13148       Changed = true;
13149     }
13150   }
13151
13152   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13153     
13154   // Do an explicit clear, this shrinks the map if needed.
13155   WorklistMap.clear();
13156   return Changed;
13157 }
13158
13159
13160 bool InstCombiner::runOnFunction(Function &F) {
13161   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13162   
13163   bool EverMadeChange = false;
13164
13165   // Iterate while there is work to do.
13166   unsigned Iteration = 0;
13167   while (DoOneIteration(F, Iteration++))
13168     EverMadeChange = true;
13169   return EverMadeChange;
13170 }
13171
13172 FunctionPass *llvm::createInstructionCombiningPass() {
13173   return new InstCombiner();
13174 }