Do not check use_empty() before replaceAllUsesWith(). This gives ValueHandles a chanc...
[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/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/MallocHelper.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/ConstantRange.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/GetElementPtrTypeIterator.h"
55 #include "llvm/Support/InstVisitor.h"
56 #include "llvm/Support/IRBuilder.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/PatternMatch.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include <algorithm>
66 #include <climits>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   /// InstCombineWorklist - This is the worklist management logic for
78   /// InstCombine.
79   class InstCombineWorklist {
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     
83     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
84     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85   public:
86     InstCombineWorklist() {}
87     
88     bool isEmpty() const { return Worklist.empty(); }
89     
90     /// Add - Add the specified instruction to the worklist if it isn't already
91     /// in it.
92     void Add(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
94         DEBUG(errs() << "IC: ADD: " << *I << '\n');
95         Worklist.push_back(I);
96       }
97     }
98     
99     void AddValue(Value *V) {
100       if (Instruction *I = dyn_cast<Instruction>(V))
101         Add(I);
102     }
103     
104     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
105     /// which should only be done when the worklist is empty and when the group
106     /// has no duplicates.
107     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
108       assert(Worklist.empty() && "Worklist must be empty to add initial group");
109       Worklist.reserve(NumEntries+16);
110       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
111       for (; NumEntries; --NumEntries) {
112         Instruction *I = List[NumEntries-1];
113         WorklistMap.insert(std::make_pair(I, Worklist.size()));
114         Worklist.push_back(I);
115       }
116     }
117     
118     // Remove - remove I from the worklist if it exists.
119     void Remove(Instruction *I) {
120       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
121       if (It == WorklistMap.end()) return; // Not in worklist.
122       
123       // Don't bother moving everything down, just null out the slot.
124       Worklist[It->second] = 0;
125       
126       WorklistMap.erase(It);
127     }
128     
129     Instruction *RemoveOne() {
130       Instruction *I = Worklist.back();
131       Worklist.pop_back();
132       WorklistMap.erase(I);
133       return I;
134     }
135
136     /// AddUsersToWorkList - When an instruction is simplified, add all users of
137     /// the instruction to the work lists because they might get more simplified
138     /// now.
139     ///
140     void AddUsersToWorkList(Instruction &I) {
141       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
142            UI != UE; ++UI)
143         Add(cast<Instruction>(*UI));
144     }
145     
146     
147     /// Zap - check that the worklist is empty and nuke the backing store for
148     /// the map if it is large.
149     void Zap() {
150       assert(WorklistMap.empty() && "Worklist empty, but map not?");
151       
152       // Do an explicit clear, this shrinks the map if needed.
153       WorklistMap.clear();
154     }
155   };
156 } // end anonymous namespace.
157
158
159 namespace {
160   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
161   /// just like the normal insertion helper, but also adds any new instructions
162   /// to the instcombine worklist.
163   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
164     InstCombineWorklist &Worklist;
165   public:
166     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
167     
168     void InsertHelper(Instruction *I, const Twine &Name,
169                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
170       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
171       Worklist.Add(I);
172     }
173   };
174 } // end anonymous namespace
175
176
177 namespace {
178   class InstCombiner : public FunctionPass,
179                        public InstVisitor<InstCombiner, Instruction*> {
180     TargetData *TD;
181     bool MustPreserveLCSSA;
182     bool MadeIRChange;
183   public:
184     /// Worklist - All of the instructions that need to be simplified.
185     InstCombineWorklist Worklist;
186
187     /// Builder - This is an IRBuilder that automatically inserts new
188     /// instructions into the worklist when they are created.
189     typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
190     BuilderTy *Builder;
191         
192     static char ID; // Pass identification, replacement for typeid
193     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
194
195     LLVMContext *Context;
196     LLVMContext *getContext() const { return Context; }
197
198   public:
199     virtual bool runOnFunction(Function &F);
200     
201     bool DoOneIteration(Function &F, unsigned ItNum);
202
203     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
204       AU.addPreservedID(LCSSAID);
205       AU.setPreservesCFG();
206     }
207
208     TargetData *getTargetData() const { return TD; }
209
210     // Visitation implementation - Implement instruction combining for different
211     // instruction types.  The semantics are as follows:
212     // Return Value:
213     //    null        - No change was made
214     //     I          - Change was made, I is still valid, I may be dead though
215     //   otherwise    - Change was made, replace I with returned instruction
216     //
217     Instruction *visitAdd(BinaryOperator &I);
218     Instruction *visitFAdd(BinaryOperator &I);
219     Instruction *visitSub(BinaryOperator &I);
220     Instruction *visitFSub(BinaryOperator &I);
221     Instruction *visitMul(BinaryOperator &I);
222     Instruction *visitFMul(BinaryOperator &I);
223     Instruction *visitURem(BinaryOperator &I);
224     Instruction *visitSRem(BinaryOperator &I);
225     Instruction *visitFRem(BinaryOperator &I);
226     bool SimplifyDivRemOfSelect(BinaryOperator &I);
227     Instruction *commonRemTransforms(BinaryOperator &I);
228     Instruction *commonIRemTransforms(BinaryOperator &I);
229     Instruction *commonDivTransforms(BinaryOperator &I);
230     Instruction *commonIDivTransforms(BinaryOperator &I);
231     Instruction *visitUDiv(BinaryOperator &I);
232     Instruction *visitSDiv(BinaryOperator &I);
233     Instruction *visitFDiv(BinaryOperator &I);
234     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
235     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
236     Instruction *visitAnd(BinaryOperator &I);
237     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
238     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
239     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
240                                      Value *A, Value *B, Value *C);
241     Instruction *visitOr (BinaryOperator &I);
242     Instruction *visitXor(BinaryOperator &I);
243     Instruction *visitShl(BinaryOperator &I);
244     Instruction *visitAShr(BinaryOperator &I);
245     Instruction *visitLShr(BinaryOperator &I);
246     Instruction *commonShiftTransforms(BinaryOperator &I);
247     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
248                                       Constant *RHSC);
249     Instruction *visitFCmpInst(FCmpInst &I);
250     Instruction *visitICmpInst(ICmpInst &I);
251     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
252     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
253                                                 Instruction *LHS,
254                                                 ConstantInt *RHS);
255     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
256                                 ConstantInt *DivRHS);
257
258     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
259                              ICmpInst::Predicate Cond, Instruction &I);
260     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
261                                      BinaryOperator &I);
262     Instruction *commonCastTransforms(CastInst &CI);
263     Instruction *commonIntCastTransforms(CastInst &CI);
264     Instruction *commonPointerCastTransforms(CastInst &CI);
265     Instruction *visitTrunc(TruncInst &CI);
266     Instruction *visitZExt(ZExtInst &CI);
267     Instruction *visitSExt(SExtInst &CI);
268     Instruction *visitFPTrunc(FPTruncInst &CI);
269     Instruction *visitFPExt(CastInst &CI);
270     Instruction *visitFPToUI(FPToUIInst &FI);
271     Instruction *visitFPToSI(FPToSIInst &FI);
272     Instruction *visitUIToFP(CastInst &CI);
273     Instruction *visitSIToFP(CastInst &CI);
274     Instruction *visitPtrToInt(PtrToIntInst &CI);
275     Instruction *visitIntToPtr(IntToPtrInst &CI);
276     Instruction *visitBitCast(BitCastInst &CI);
277     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
278                                 Instruction *FI);
279     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
280     Instruction *visitSelectInst(SelectInst &SI);
281     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
282     Instruction *visitCallInst(CallInst &CI);
283     Instruction *visitInvokeInst(InvokeInst &II);
284     Instruction *visitPHINode(PHINode &PN);
285     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
286     Instruction *visitAllocationInst(AllocationInst &AI);
287     Instruction *visitFreeInst(FreeInst &FI);
288     Instruction *visitLoadInst(LoadInst &LI);
289     Instruction *visitStoreInst(StoreInst &SI);
290     Instruction *visitBranchInst(BranchInst &BI);
291     Instruction *visitSwitchInst(SwitchInst &SI);
292     Instruction *visitInsertElementInst(InsertElementInst &IE);
293     Instruction *visitExtractElementInst(ExtractElementInst &EI);
294     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
295     Instruction *visitExtractValueInst(ExtractValueInst &EV);
296
297     // visitInstruction - Specify what to return for unhandled instructions...
298     Instruction *visitInstruction(Instruction &I) { return 0; }
299
300   private:
301     Instruction *visitCallSite(CallSite CS);
302     bool transformConstExprCastCall(CallSite CS);
303     Instruction *transformCallThroughTrampoline(CallSite CS);
304     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
305                                    bool DoXform = true);
306     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
307     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
308
309
310   public:
311     // InsertNewInstBefore - insert an instruction New before instruction Old
312     // in the program.  Add the new instruction to the worklist.
313     //
314     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
315       assert(New && New->getParent() == 0 &&
316              "New instruction already inserted into a basic block!");
317       BasicBlock *BB = Old.getParent();
318       BB->getInstList().insert(&Old, New);  // Insert inst
319       Worklist.Add(New);
320       return New;
321     }
322         
323     // ReplaceInstUsesWith - This method is to be used when an instruction is
324     // found to be dead, replacable with another preexisting expression.  Here
325     // we add all uses of I to the worklist, replace all uses of I with the new
326     // value, then return I, so that the inst combiner will know that I was
327     // modified.
328     //
329     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
330       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
331       
332       // If we are replacing the instruction with itself, this must be in a
333       // segment of unreachable code, so just clobber the instruction.
334       if (&I == V) 
335         V = UndefValue::get(I.getType());
336         
337       I.replaceAllUsesWith(V);
338       return &I;
339     }
340
341     // EraseInstFromFunction - When dealing with an instruction that has side
342     // effects or produces a void value, we can't rely on DCE to delete the
343     // instruction.  Instead, visit methods should return the value returned by
344     // this function.
345     Instruction *EraseInstFromFunction(Instruction &I) {
346       DEBUG(errs() << "IC: ERASE " << I << '\n');
347
348       assert(I.use_empty() && "Cannot erase instruction that is used!");
349       // Make sure that we reprocess all operands now that we reduced their
350       // use counts.
351       if (I.getNumOperands() < 8) {
352         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
353           if (Instruction *Op = dyn_cast<Instruction>(*i))
354             Worklist.Add(Op);
355       }
356       Worklist.Remove(&I);
357       I.eraseFromParent();
358       MadeIRChange = true;
359       return 0;  // Don't do anything with FI
360     }
361         
362     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
363                            APInt &KnownOne, unsigned Depth = 0) const {
364       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
365     }
366     
367     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
368                            unsigned Depth = 0) const {
369       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
370     }
371     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
372       return llvm::ComputeNumSignBits(Op, TD, Depth);
373     }
374
375   private:
376
377     /// SimplifyCommutative - This performs a few simplifications for 
378     /// commutative operators.
379     bool SimplifyCommutative(BinaryOperator &I);
380
381     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
382     /// most-complex to least-complex order.
383     bool SimplifyCompare(CmpInst &I);
384
385     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
386     /// based on the demanded bits.
387     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
388                                    APInt& KnownZero, APInt& KnownOne,
389                                    unsigned Depth);
390     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
391                               APInt& KnownZero, APInt& KnownOne,
392                               unsigned Depth=0);
393         
394     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
395     /// SimplifyDemandedBits knows about.  See if the instruction has any
396     /// properties that allow us to simplify its operands.
397     bool SimplifyDemandedInstructionBits(Instruction &Inst);
398         
399     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
400                                       APInt& UndefElts, unsigned Depth = 0);
401       
402     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
403     // which has a PHI node as operand #0, see if we can fold the instruction
404     // into the PHI (which is only possible if all operands to the PHI are
405     // constants).
406     //
407     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
408     // that would normally be unprofitable because they strongly encourage jump
409     // threading.
410     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
411
412     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
413     // operator and they all are only used by the PHI, PHI together their
414     // inputs, and do the operation once, to the result of the PHI.
415     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
416     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
417     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
418
419     
420     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
421                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
422     
423     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
424                               bool isSub, Instruction &I);
425     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
426                                  bool isSigned, bool Inside, Instruction &IB);
427     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
428     Instruction *MatchBSwap(BinaryOperator &I);
429     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
430     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
431     Instruction *SimplifyMemSet(MemSetInst *MI);
432
433
434     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
435
436     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
437                                     unsigned CastOpc, int &NumCastsRemoved);
438     unsigned GetOrEnforceKnownAlignment(Value *V,
439                                         unsigned PrefAlign = 0);
440
441   };
442 } // end anonymous namespace
443
444 char InstCombiner::ID = 0;
445 static RegisterPass<InstCombiner>
446 X("instcombine", "Combine redundant instructions");
447
448 // getComplexity:  Assign a complexity or rank value to LLVM Values...
449 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
450 static unsigned getComplexity(Value *V) {
451   if (isa<Instruction>(V)) {
452     if (BinaryOperator::isNeg(V) ||
453         BinaryOperator::isFNeg(V) ||
454         BinaryOperator::isNot(V))
455       return 3;
456     return 4;
457   }
458   if (isa<Argument>(V)) return 3;
459   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
460 }
461
462 // isOnlyUse - Return true if this instruction will be deleted if we stop using
463 // it.
464 static bool isOnlyUse(Value *V) {
465   return V->hasOneUse() || isa<Constant>(V);
466 }
467
468 // getPromotedType - Return the specified type promoted as it would be to pass
469 // though a va_arg area...
470 static const Type *getPromotedType(const Type *Ty) {
471   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
472     if (ITy->getBitWidth() < 32)
473       return Type::getInt32Ty(Ty->getContext());
474   }
475   return Ty;
476 }
477
478 /// getBitCastOperand - If the specified operand is a CastInst, a constant
479 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
480 /// operand value, otherwise return null.
481 static Value *getBitCastOperand(Value *V) {
482   if (Operator *O = dyn_cast<Operator>(V)) {
483     if (O->getOpcode() == Instruction::BitCast)
484       return O->getOperand(0);
485     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
486       if (GEP->hasAllZeroIndices())
487         return GEP->getPointerOperand();
488   }
489   return 0;
490 }
491
492 /// This function is a wrapper around CastInst::isEliminableCastPair. It
493 /// simply extracts arguments and returns what that function returns.
494 static Instruction::CastOps 
495 isEliminableCastPair(
496   const CastInst *CI, ///< The first cast instruction
497   unsigned opcode,       ///< The opcode of the second cast instruction
498   const Type *DstTy,     ///< The target type for the second cast instruction
499   TargetData *TD         ///< The target data for pointer size
500 ) {
501
502   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
503   const Type *MidTy = CI->getType();                  // B from above
504
505   // Get the opcodes of the two Cast instructions
506   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
507   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
508
509   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
510                                                 DstTy,
511                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
512   
513   // We don't want to form an inttoptr or ptrtoint that converts to an integer
514   // type that differs from the pointer size.
515   if ((Res == Instruction::IntToPtr &&
516           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
517       (Res == Instruction::PtrToInt &&
518           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
519     Res = 0;
520   
521   return Instruction::CastOps(Res);
522 }
523
524 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
525 /// in any code being generated.  It does not require codegen if V is simple
526 /// enough or if the cast can be folded into other casts.
527 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
528                               const Type *Ty, TargetData *TD) {
529   if (V->getType() == Ty || isa<Constant>(V)) return false;
530   
531   // If this is another cast that can be eliminated, it isn't codegen either.
532   if (const CastInst *CI = dyn_cast<CastInst>(V))
533     if (isEliminableCastPair(CI, opcode, Ty, TD))
534       return false;
535   return true;
536 }
537
538 // SimplifyCommutative - This performs a few simplifications for commutative
539 // operators:
540 //
541 //  1. Order operands such that they are listed from right (least complex) to
542 //     left (most complex).  This puts constants before unary operators before
543 //     binary operators.
544 //
545 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
546 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547 //
548 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
549   bool Changed = false;
550   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
551     Changed = !I.swapOperands();
552
553   if (!I.isAssociative()) return Changed;
554   Instruction::BinaryOps Opcode = I.getOpcode();
555   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
556     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
557       if (isa<Constant>(I.getOperand(1))) {
558         Constant *Folded = ConstantExpr::get(I.getOpcode(),
559                                              cast<Constant>(I.getOperand(1)),
560                                              cast<Constant>(Op->getOperand(1)));
561         I.setOperand(0, Op->getOperand(0));
562         I.setOperand(1, Folded);
563         return true;
564       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
565         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
566             isOnlyUse(Op) && isOnlyUse(Op1)) {
567           Constant *C1 = cast<Constant>(Op->getOperand(1));
568           Constant *C2 = cast<Constant>(Op1->getOperand(1));
569
570           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
571           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
572           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
573                                                     Op1->getOperand(0),
574                                                     Op1->getName(), &I);
575           Worklist.Add(New);
576           I.setOperand(0, New);
577           I.setOperand(1, Folded);
578           return true;
579         }
580     }
581   return Changed;
582 }
583
584 /// SimplifyCompare - For a CmpInst this function just orders the operands
585 /// so that theyare listed from right (least complex) to left (most complex).
586 /// This puts constants before unary operators before binary operators.
587 bool InstCombiner::SimplifyCompare(CmpInst &I) {
588   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
589     return false;
590   I.swapOperands();
591   // Compare instructions are not associative so there's nothing else we can do.
592   return true;
593 }
594
595 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
596 // if the LHS is a constant zero (which is the 'negate' form).
597 //
598 static inline Value *dyn_castNegVal(Value *V) {
599   if (BinaryOperator::isNeg(V))
600     return BinaryOperator::getNegArgument(V);
601
602   // Constants can be considered to be negated values if they can be folded.
603   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
604     return ConstantExpr::getNeg(C);
605
606   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
607     if (C->getType()->getElementType()->isInteger())
608       return ConstantExpr::getNeg(C);
609
610   return 0;
611 }
612
613 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
614 // instruction if the LHS is a constant negative zero (which is the 'negate'
615 // form).
616 //
617 static inline Value *dyn_castFNegVal(Value *V) {
618   if (BinaryOperator::isFNeg(V))
619     return BinaryOperator::getFNegArgument(V);
620
621   // Constants can be considered to be negated values if they can be folded.
622   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
623     return ConstantExpr::getFNeg(C);
624
625   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626     if (C->getType()->getElementType()->isFloatingPoint())
627       return ConstantExpr::getFNeg(C);
628
629   return 0;
630 }
631
632 static inline Value *dyn_castNotVal(Value *V) {
633   if (BinaryOperator::isNot(V))
634     return BinaryOperator::getNotArgument(V);
635
636   // Constants can be considered to be not'ed values...
637   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
638     return ConstantInt::get(C->getType(), ~C->getValue());
639   return 0;
640 }
641
642 // dyn_castFoldableMul - If this value is a multiply that can be folded into
643 // other computations (because it has a constant operand), return the
644 // non-constant operand of the multiply, and set CST to point to the multiplier.
645 // Otherwise, return null.
646 //
647 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
648   if (V->hasOneUse() && V->getType()->isInteger())
649     if (Instruction *I = dyn_cast<Instruction>(V)) {
650       if (I->getOpcode() == Instruction::Mul)
651         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
652           return I->getOperand(0);
653       if (I->getOpcode() == Instruction::Shl)
654         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
655           // The multiplier is really 1 << CST.
656           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
657           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
658           CST = ConstantInt::get(V->getType()->getContext(),
659                                  APInt(BitWidth, 1).shl(CSTVal));
660           return I->getOperand(0);
661         }
662     }
663   return 0;
664 }
665
666 /// AddOne - Add one to a ConstantInt
667 static Constant *AddOne(Constant *C) {
668   return ConstantExpr::getAdd(C, 
669     ConstantInt::get(C->getType(), 1));
670 }
671 /// SubOne - Subtract one from a ConstantInt
672 static Constant *SubOne(ConstantInt *C) {
673   return ConstantExpr::getSub(C, 
674     ConstantInt::get(C->getType(), 1));
675 }
676 /// MultiplyOverflows - True if the multiply can not be expressed in an int
677 /// this size.
678 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
679   uint32_t W = C1->getBitWidth();
680   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
681   if (sign) {
682     LHSExt.sext(W * 2);
683     RHSExt.sext(W * 2);
684   } else {
685     LHSExt.zext(W * 2);
686     RHSExt.zext(W * 2);
687   }
688
689   APInt MulExt = LHSExt * RHSExt;
690
691   if (sign) {
692     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
693     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
694     return MulExt.slt(Min) || MulExt.sgt(Max);
695   } else 
696     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
697 }
698
699
700 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
701 /// specified instruction is a constant integer.  If so, check to see if there
702 /// are any bits set in the constant that are not demanded.  If so, shrink the
703 /// constant and return true.
704 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
705                                    APInt Demanded) {
706   assert(I && "No instruction?");
707   assert(OpNo < I->getNumOperands() && "Operand index too large");
708
709   // If the operand is not a constant integer, nothing to do.
710   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
711   if (!OpC) return false;
712
713   // If there are no bits set that aren't demanded, nothing to do.
714   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
715   if ((~Demanded & OpC->getValue()) == 0)
716     return false;
717
718   // This instruction is producing bits that are not demanded. Shrink the RHS.
719   Demanded &= OpC->getValue();
720   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
721   return true;
722 }
723
724 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
725 // set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
727 // min/max.
728 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
729                                                    const APInt& KnownOne,
730                                                    APInt& Min, APInt& Max) {
731   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732          KnownZero.getBitWidth() == Min.getBitWidth() &&
733          KnownZero.getBitWidth() == Max.getBitWidth() &&
734          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735   APInt UnknownBits = ~(KnownZero|KnownOne);
736
737   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
738   // bit if it is unknown.
739   Min = KnownOne;
740   Max = KnownOne|UnknownBits;
741   
742   if (UnknownBits.isNegative()) { // Sign bit is unknown
743     Min.set(Min.getBitWidth()-1);
744     Max.clear(Max.getBitWidth()-1);
745   }
746 }
747
748 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
749 // a set of known zero and one bits, compute the maximum and minimum values that
750 // could have the specified known zero and known one bits, returning them in
751 // min/max.
752 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
753                                                      const APInt &KnownOne,
754                                                      APInt &Min, APInt &Max) {
755   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
756          KnownZero.getBitWidth() == Min.getBitWidth() &&
757          KnownZero.getBitWidth() == Max.getBitWidth() &&
758          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
759   APInt UnknownBits = ~(KnownZero|KnownOne);
760   
761   // The minimum value is when the unknown bits are all zeros.
762   Min = KnownOne;
763   // The maximum value is when the unknown bits are all ones.
764   Max = KnownOne|UnknownBits;
765 }
766
767 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
768 /// SimplifyDemandedBits knows about.  See if the instruction has any
769 /// properties that allow us to simplify its operands.
770 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
771   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
772   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
773   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
774   
775   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
776                                      KnownZero, KnownOne, 0);
777   if (V == 0) return false;
778   if (V == &Inst) return true;
779   ReplaceInstUsesWith(Inst, V);
780   return true;
781 }
782
783 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
784 /// specified instruction operand if possible, updating it in place.  It returns
785 /// true if it made any change and false otherwise.
786 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
787                                         APInt &KnownZero, APInt &KnownOne,
788                                         unsigned Depth) {
789   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
790                                           KnownZero, KnownOne, Depth);
791   if (NewVal == 0) return false;
792   U = NewVal;
793   return true;
794 }
795
796
797 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
798 /// value based on the demanded bits.  When this function is called, it is known
799 /// that only the bits set in DemandedMask of the result of V are ever used
800 /// downstream. Consequently, depending on the mask and V, it may be possible
801 /// to replace V with a constant or one of its operands. In such cases, this
802 /// function does the replacement and returns true. In all other cases, it
803 /// returns false after analyzing the expression and setting KnownOne and known
804 /// to be one in the expression.  KnownZero contains all the bits that are known
805 /// to be zero in the expression. These are provided to potentially allow the
806 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
807 /// the expression. KnownOne and KnownZero always follow the invariant that 
808 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
809 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
810 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
811 /// and KnownOne must all be the same.
812 ///
813 /// This returns null if it did not change anything and it permits no
814 /// simplification.  This returns V itself if it did some simplification of V's
815 /// operands based on the information about what bits are demanded. This returns
816 /// some other non-null value if it found out that V is equal to another value
817 /// in the context where the specified bits are demanded, but not for all users.
818 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
819                                              APInt &KnownZero, APInt &KnownOne,
820                                              unsigned Depth) {
821   assert(V != 0 && "Null pointer of Value???");
822   assert(Depth <= 6 && "Limit Search Depth");
823   uint32_t BitWidth = DemandedMask.getBitWidth();
824   const Type *VTy = V->getType();
825   assert((TD || !isa<PointerType>(VTy)) &&
826          "SimplifyDemandedBits needs to know bit widths!");
827   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
828          (!VTy->isIntOrIntVector() ||
829           VTy->getScalarSizeInBits() == BitWidth) &&
830          KnownZero.getBitWidth() == BitWidth &&
831          KnownOne.getBitWidth() == BitWidth &&
832          "Value *V, DemandedMask, KnownZero and KnownOne "
833          "must have same BitWidth");
834   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
835     // We know all of the bits for a constant!
836     KnownOne = CI->getValue() & DemandedMask;
837     KnownZero = ~KnownOne & DemandedMask;
838     return 0;
839   }
840   if (isa<ConstantPointerNull>(V)) {
841     // We know all of the bits for a constant!
842     KnownOne.clear();
843     KnownZero = DemandedMask;
844     return 0;
845   }
846
847   KnownZero.clear();
848   KnownOne.clear();
849   if (DemandedMask == 0) {   // Not demanding any bits from V.
850     if (isa<UndefValue>(V))
851       return 0;
852     return UndefValue::get(VTy);
853   }
854   
855   if (Depth == 6)        // Limit search depth.
856     return 0;
857   
858   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
859   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
860
861   Instruction *I = dyn_cast<Instruction>(V);
862   if (!I) {
863     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
864     return 0;        // Only analyze instructions.
865   }
866
867   // If there are multiple uses of this value and we aren't at the root, then
868   // we can't do any simplifications of the operands, because DemandedMask
869   // only reflects the bits demanded by *one* of the users.
870   if (Depth != 0 && !I->hasOneUse()) {
871     // Despite the fact that we can't simplify this instruction in all User's
872     // context, we can at least compute the knownzero/knownone bits, and we can
873     // do simplifications that apply to *just* the one user if we know that
874     // this instruction has a simpler value in that context.
875     if (I->getOpcode() == Instruction::And) {
876       // If either the LHS or the RHS are Zero, the result is zero.
877       ComputeMaskedBits(I->getOperand(1), DemandedMask,
878                         RHSKnownZero, RHSKnownOne, Depth+1);
879       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
880                         LHSKnownZero, LHSKnownOne, Depth+1);
881       
882       // If all of the demanded bits are known 1 on one side, return the other.
883       // These bits cannot contribute to the result of the 'and' in this
884       // context.
885       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
886           (DemandedMask & ~LHSKnownZero))
887         return I->getOperand(0);
888       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
889           (DemandedMask & ~RHSKnownZero))
890         return I->getOperand(1);
891       
892       // If all of the demanded bits in the inputs are known zeros, return zero.
893       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
894         return Constant::getNullValue(VTy);
895       
896     } else if (I->getOpcode() == Instruction::Or) {
897       // We can simplify (X|Y) -> X or Y in the user's context if we know that
898       // only bits from X or Y are demanded.
899       
900       // If either the LHS or the RHS are One, the result is One.
901       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
902                         RHSKnownZero, RHSKnownOne, Depth+1);
903       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
904                         LHSKnownZero, LHSKnownOne, Depth+1);
905       
906       // If all of the demanded bits are known zero on one side, return the
907       // other.  These bits cannot contribute to the result of the 'or' in this
908       // context.
909       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
910           (DemandedMask & ~LHSKnownOne))
911         return I->getOperand(0);
912       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
913           (DemandedMask & ~RHSKnownOne))
914         return I->getOperand(1);
915       
916       // If all of the potentially set bits on one side are known to be set on
917       // the other side, just use the 'other' side.
918       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
919           (DemandedMask & (~RHSKnownZero)))
920         return I->getOperand(0);
921       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
922           (DemandedMask & (~LHSKnownZero)))
923         return I->getOperand(1);
924     }
925     
926     // Compute the KnownZero/KnownOne bits to simplify things downstream.
927     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
928     return 0;
929   }
930   
931   // If this is the root being simplified, allow it to have multiple uses,
932   // just set the DemandedMask to all bits so that we can try to simplify the
933   // operands.  This allows visitTruncInst (for example) to simplify the
934   // operand of a trunc without duplicating all the logic below.
935   if (Depth == 0 && !V->hasOneUse())
936     DemandedMask = APInt::getAllOnesValue(BitWidth);
937   
938   switch (I->getOpcode()) {
939   default:
940     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
941     break;
942   case Instruction::And:
943     // If either the LHS or the RHS are Zero, the result is zero.
944     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
945                              RHSKnownZero, RHSKnownOne, Depth+1) ||
946         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
947                              LHSKnownZero, LHSKnownOne, Depth+1))
948       return I;
949     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
950     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
951
952     // If all of the demanded bits are known 1 on one side, return the other.
953     // These bits cannot contribute to the result of the 'and'.
954     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
955         (DemandedMask & ~LHSKnownZero))
956       return I->getOperand(0);
957     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
958         (DemandedMask & ~RHSKnownZero))
959       return I->getOperand(1);
960     
961     // If all of the demanded bits in the inputs are known zeros, return zero.
962     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
963       return Constant::getNullValue(VTy);
964       
965     // If the RHS is a constant, see if we can simplify it.
966     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
967       return I;
968       
969     // Output known-1 bits are only known if set in both the LHS & RHS.
970     RHSKnownOne &= LHSKnownOne;
971     // Output known-0 are known to be clear if zero in either the LHS | RHS.
972     RHSKnownZero |= LHSKnownZero;
973     break;
974   case Instruction::Or:
975     // If either the LHS or the RHS are One, the result is One.
976     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
977                              RHSKnownZero, RHSKnownOne, Depth+1) ||
978         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
979                              LHSKnownZero, LHSKnownOne, Depth+1))
980       return I;
981     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
982     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
983     
984     // If all of the demanded bits are known zero on one side, return the other.
985     // These bits cannot contribute to the result of the 'or'.
986     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
987         (DemandedMask & ~LHSKnownOne))
988       return I->getOperand(0);
989     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
990         (DemandedMask & ~RHSKnownOne))
991       return I->getOperand(1);
992
993     // If all of the potentially set bits on one side are known to be set on
994     // the other side, just use the 'other' side.
995     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
996         (DemandedMask & (~RHSKnownZero)))
997       return I->getOperand(0);
998     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
999         (DemandedMask & (~LHSKnownZero)))
1000       return I->getOperand(1);
1001         
1002     // If the RHS is a constant, see if we can simplify it.
1003     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1004       return I;
1005           
1006     // Output known-0 bits are only known if clear in both the LHS & RHS.
1007     RHSKnownZero &= LHSKnownZero;
1008     // Output known-1 are known to be set if set in either the LHS | RHS.
1009     RHSKnownOne |= LHSKnownOne;
1010     break;
1011   case Instruction::Xor: {
1012     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1013                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1014         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1015                              LHSKnownZero, LHSKnownOne, Depth+1))
1016       return I;
1017     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1018     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1019     
1020     // If all of the demanded bits are known zero on one side, return the other.
1021     // These bits cannot contribute to the result of the 'xor'.
1022     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1023       return I->getOperand(0);
1024     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1025       return I->getOperand(1);
1026     
1027     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1028     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1029                          (RHSKnownOne & LHSKnownOne);
1030     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1031     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1032                         (RHSKnownOne & LHSKnownZero);
1033     
1034     // If all of the demanded bits are known to be zero on one side or the
1035     // other, turn this into an *inclusive* or.
1036     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1037     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1038       Instruction *Or = 
1039         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1040                                  I->getName());
1041       return InsertNewInstBefore(Or, *I);
1042     }
1043     
1044     // If all of the demanded bits on one side are known, and all of the set
1045     // bits on that side are also known to be set on the other side, turn this
1046     // into an AND, as we know the bits will be cleared.
1047     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1048     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1049       // all known
1050       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1051         Constant *AndC = Constant::getIntegerValue(VTy,
1052                                                    ~RHSKnownOne & DemandedMask);
1053         Instruction *And = 
1054           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1055         return InsertNewInstBefore(And, *I);
1056       }
1057     }
1058     
1059     // If the RHS is a constant, see if we can simplify it.
1060     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1061     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1062       return I;
1063     
1064     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1065     // are flipping are known to be set, then the xor is just resetting those
1066     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1067     // simplifying both of them.
1068     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1069       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1070           isa<ConstantInt>(I->getOperand(1)) &&
1071           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1072           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1073         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1074         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1075         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1076         
1077         Constant *AndC =
1078           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1079         Instruction *NewAnd = 
1080           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1081         InsertNewInstBefore(NewAnd, *I);
1082         
1083         Constant *XorC =
1084           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1085         Instruction *NewXor =
1086           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1087         return InsertNewInstBefore(NewXor, *I);
1088       }
1089           
1090           
1091     RHSKnownZero = KnownZeroOut;
1092     RHSKnownOne  = KnownOneOut;
1093     break;
1094   }
1095   case Instruction::Select:
1096     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1097                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1098         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1099                              LHSKnownZero, LHSKnownOne, Depth+1))
1100       return I;
1101     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1102     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1103     
1104     // If the operands are constants, see if we can simplify them.
1105     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1106         ShrinkDemandedConstant(I, 2, DemandedMask))
1107       return I;
1108     
1109     // Only known if known in both the LHS and RHS.
1110     RHSKnownOne &= LHSKnownOne;
1111     RHSKnownZero &= LHSKnownZero;
1112     break;
1113   case Instruction::Trunc: {
1114     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1115     DemandedMask.zext(truncBf);
1116     RHSKnownZero.zext(truncBf);
1117     RHSKnownOne.zext(truncBf);
1118     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1119                              RHSKnownZero, RHSKnownOne, Depth+1))
1120       return I;
1121     DemandedMask.trunc(BitWidth);
1122     RHSKnownZero.trunc(BitWidth);
1123     RHSKnownOne.trunc(BitWidth);
1124     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1125     break;
1126   }
1127   case Instruction::BitCast:
1128     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1129       return false;  // vector->int or fp->int?
1130
1131     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1132       if (const VectorType *SrcVTy =
1133             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1134         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1135           // Don't touch a bitcast between vectors of different element counts.
1136           return false;
1137       } else
1138         // Don't touch a scalar-to-vector bitcast.
1139         return false;
1140     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1141       // Don't touch a vector-to-scalar bitcast.
1142       return false;
1143
1144     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1145                              RHSKnownZero, RHSKnownOne, Depth+1))
1146       return I;
1147     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1148     break;
1149   case Instruction::ZExt: {
1150     // Compute the bits in the result that are not present in the input.
1151     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1152     
1153     DemandedMask.trunc(SrcBitWidth);
1154     RHSKnownZero.trunc(SrcBitWidth);
1155     RHSKnownOne.trunc(SrcBitWidth);
1156     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1157                              RHSKnownZero, RHSKnownOne, Depth+1))
1158       return I;
1159     DemandedMask.zext(BitWidth);
1160     RHSKnownZero.zext(BitWidth);
1161     RHSKnownOne.zext(BitWidth);
1162     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1163     // The top bits are known to be zero.
1164     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1165     break;
1166   }
1167   case Instruction::SExt: {
1168     // Compute the bits in the result that are not present in the input.
1169     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1170     
1171     APInt InputDemandedBits = DemandedMask & 
1172                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1173
1174     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1175     // If any of the sign extended bits are demanded, we know that the sign
1176     // bit is demanded.
1177     if ((NewBits & DemandedMask) != 0)
1178       InputDemandedBits.set(SrcBitWidth-1);
1179       
1180     InputDemandedBits.trunc(SrcBitWidth);
1181     RHSKnownZero.trunc(SrcBitWidth);
1182     RHSKnownOne.trunc(SrcBitWidth);
1183     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1184                              RHSKnownZero, RHSKnownOne, Depth+1))
1185       return I;
1186     InputDemandedBits.zext(BitWidth);
1187     RHSKnownZero.zext(BitWidth);
1188     RHSKnownOne.zext(BitWidth);
1189     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1190       
1191     // If the sign bit of the input is known set or clear, then we know the
1192     // top bits of the result.
1193
1194     // If the input sign bit is known zero, or if the NewBits are not demanded
1195     // convert this into a zero extension.
1196     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1197       // Convert to ZExt cast
1198       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1199       return InsertNewInstBefore(NewCast, *I);
1200     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1201       RHSKnownOne |= NewBits;
1202     }
1203     break;
1204   }
1205   case Instruction::Add: {
1206     // Figure out what the input bits are.  If the top bits of the and result
1207     // are not demanded, then the add doesn't demand them from its input
1208     // either.
1209     unsigned NLZ = DemandedMask.countLeadingZeros();
1210       
1211     // If there is a constant on the RHS, there are a variety of xformations
1212     // we can do.
1213     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1214       // If null, this should be simplified elsewhere.  Some of the xforms here
1215       // won't work if the RHS is zero.
1216       if (RHS->isZero())
1217         break;
1218       
1219       // If the top bit of the output is demanded, demand everything from the
1220       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1221       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1222
1223       // Find information about known zero/one bits in the input.
1224       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1225                                LHSKnownZero, LHSKnownOne, Depth+1))
1226         return I;
1227
1228       // If the RHS of the add has bits set that can't affect the input, reduce
1229       // the constant.
1230       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1231         return I;
1232       
1233       // Avoid excess work.
1234       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1235         break;
1236       
1237       // Turn it into OR if input bits are zero.
1238       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1239         Instruction *Or =
1240           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1241                                    I->getName());
1242         return InsertNewInstBefore(Or, *I);
1243       }
1244       
1245       // We can say something about the output known-zero and known-one bits,
1246       // depending on potential carries from the input constant and the
1247       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1248       // bits set and the RHS constant is 0x01001, then we know we have a known
1249       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1250       
1251       // To compute this, we first compute the potential carry bits.  These are
1252       // the bits which may be modified.  I'm not aware of a better way to do
1253       // this scan.
1254       const APInt &RHSVal = RHS->getValue();
1255       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1256       
1257       // Now that we know which bits have carries, compute the known-1/0 sets.
1258       
1259       // Bits are known one if they are known zero in one operand and one in the
1260       // other, and there is no input carry.
1261       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1262                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1263       
1264       // Bits are known zero if they are known zero in both operands and there
1265       // is no input carry.
1266       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1267     } else {
1268       // If the high-bits of this ADD are not demanded, then it does not demand
1269       // the high bits of its LHS or RHS.
1270       if (DemandedMask[BitWidth-1] == 0) {
1271         // Right fill the mask of bits for this ADD to demand the most
1272         // significant bit and all those below it.
1273         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1274         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1275                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1276             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1277                                  LHSKnownZero, LHSKnownOne, Depth+1))
1278           return I;
1279       }
1280     }
1281     break;
1282   }
1283   case Instruction::Sub:
1284     // If the high-bits of this SUB are not demanded, then it does not demand
1285     // the high bits of its LHS or RHS.
1286     if (DemandedMask[BitWidth-1] == 0) {
1287       // Right fill the mask of bits for this SUB to demand the most
1288       // significant bit and all those below it.
1289       uint32_t NLZ = DemandedMask.countLeadingZeros();
1290       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1291       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1292                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1293           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1294                                LHSKnownZero, LHSKnownOne, Depth+1))
1295         return I;
1296     }
1297     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1298     // the known zeros and ones.
1299     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1300     break;
1301   case Instruction::Shl:
1302     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1303       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1304       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1305       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1306                                RHSKnownZero, RHSKnownOne, Depth+1))
1307         return I;
1308       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1309       RHSKnownZero <<= ShiftAmt;
1310       RHSKnownOne  <<= ShiftAmt;
1311       // low bits known zero.
1312       if (ShiftAmt)
1313         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1314     }
1315     break;
1316   case Instruction::LShr:
1317     // For a logical shift right
1318     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1319       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1320       
1321       // Unsigned shift right.
1322       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1323       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1324                                RHSKnownZero, RHSKnownOne, Depth+1))
1325         return I;
1326       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1327       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1328       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1329       if (ShiftAmt) {
1330         // Compute the new bits that are at the top now.
1331         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1332         RHSKnownZero |= HighBits;  // high bits known zero.
1333       }
1334     }
1335     break;
1336   case Instruction::AShr:
1337     // If this is an arithmetic shift right and only the low-bit is set, we can
1338     // always convert this into a logical shr, even if the shift amount is
1339     // variable.  The low bit of the shift cannot be an input sign bit unless
1340     // the shift amount is >= the size of the datatype, which is undefined.
1341     if (DemandedMask == 1) {
1342       // Perform the logical shift right.
1343       Instruction *NewVal = BinaryOperator::CreateLShr(
1344                         I->getOperand(0), I->getOperand(1), I->getName());
1345       return InsertNewInstBefore(NewVal, *I);
1346     }    
1347
1348     // If the sign bit is the only bit demanded by this ashr, then there is no
1349     // need to do it, the shift doesn't change the high bit.
1350     if (DemandedMask.isSignBit())
1351       return I->getOperand(0);
1352     
1353     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1354       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1355       
1356       // Signed shift right.
1357       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1358       // If any of the "high bits" are demanded, we should set the sign bit as
1359       // demanded.
1360       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1361         DemandedMaskIn.set(BitWidth-1);
1362       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1363                                RHSKnownZero, RHSKnownOne, Depth+1))
1364         return I;
1365       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1366       // Compute the new bits that are at the top now.
1367       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1368       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1369       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1370         
1371       // Handle the sign bits.
1372       APInt SignBit(APInt::getSignBit(BitWidth));
1373       // Adjust to where it is now in the mask.
1374       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1375         
1376       // If the input sign bit is known to be zero, or if none of the top bits
1377       // are demanded, turn this into an unsigned shift right.
1378       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1379           (HighBits & ~DemandedMask) == HighBits) {
1380         // Perform the logical shift right.
1381         Instruction *NewVal = BinaryOperator::CreateLShr(
1382                           I->getOperand(0), SA, I->getName());
1383         return InsertNewInstBefore(NewVal, *I);
1384       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1385         RHSKnownOne |= HighBits;
1386       }
1387     }
1388     break;
1389   case Instruction::SRem:
1390     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1391       APInt RA = Rem->getValue().abs();
1392       if (RA.isPowerOf2()) {
1393         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1394           return I->getOperand(0);
1395
1396         APInt LowBits = RA - 1;
1397         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1398         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1399                                  LHSKnownZero, LHSKnownOne, Depth+1))
1400           return I;
1401
1402         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1403           LHSKnownZero |= ~LowBits;
1404
1405         KnownZero |= LHSKnownZero & DemandedMask;
1406
1407         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1408       }
1409     }
1410     break;
1411   case Instruction::URem: {
1412     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1413     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1414     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1415                              KnownZero2, KnownOne2, Depth+1) ||
1416         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1417                              KnownZero2, KnownOne2, Depth+1))
1418       return I;
1419
1420     unsigned Leaders = KnownZero2.countLeadingOnes();
1421     Leaders = std::max(Leaders,
1422                        KnownZero2.countLeadingOnes());
1423     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1424     break;
1425   }
1426   case Instruction::Call:
1427     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1428       switch (II->getIntrinsicID()) {
1429       default: break;
1430       case Intrinsic::bswap: {
1431         // If the only bits demanded come from one byte of the bswap result,
1432         // just shift the input byte into position to eliminate the bswap.
1433         unsigned NLZ = DemandedMask.countLeadingZeros();
1434         unsigned NTZ = DemandedMask.countTrailingZeros();
1435           
1436         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1437         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1438         // have 14 leading zeros, round to 8.
1439         NLZ &= ~7;
1440         NTZ &= ~7;
1441         // If we need exactly one byte, we can do this transformation.
1442         if (BitWidth-NLZ-NTZ == 8) {
1443           unsigned ResultBit = NTZ;
1444           unsigned InputBit = BitWidth-NTZ-8;
1445           
1446           // Replace this with either a left or right shift to get the byte into
1447           // the right place.
1448           Instruction *NewVal;
1449           if (InputBit > ResultBit)
1450             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1451                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1452           else
1453             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1454                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1455           NewVal->takeName(I);
1456           return InsertNewInstBefore(NewVal, *I);
1457         }
1458           
1459         // TODO: Could compute known zero/one bits based on the input.
1460         break;
1461       }
1462       }
1463     }
1464     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1465     break;
1466   }
1467   
1468   // If the client is only demanding bits that we know, return the known
1469   // constant.
1470   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1471     return Constant::getIntegerValue(VTy, RHSKnownOne);
1472   return false;
1473 }
1474
1475
1476 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1477 /// any number of elements. DemandedElts contains the set of elements that are
1478 /// actually used by the caller.  This method analyzes which elements of the
1479 /// operand are undef and returns that information in UndefElts.
1480 ///
1481 /// If the information about demanded elements can be used to simplify the
1482 /// operation, the operation is simplified, then the resultant value is
1483 /// returned.  This returns null if no change was made.
1484 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1485                                                 APInt& UndefElts,
1486                                                 unsigned Depth) {
1487   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1488   APInt EltMask(APInt::getAllOnesValue(VWidth));
1489   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1490
1491   if (isa<UndefValue>(V)) {
1492     // If the entire vector is undefined, just return this info.
1493     UndefElts = EltMask;
1494     return 0;
1495   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1496     UndefElts = EltMask;
1497     return UndefValue::get(V->getType());
1498   }
1499
1500   UndefElts = 0;
1501   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1502     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1503     Constant *Undef = UndefValue::get(EltTy);
1504
1505     std::vector<Constant*> Elts;
1506     for (unsigned i = 0; i != VWidth; ++i)
1507       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1508         Elts.push_back(Undef);
1509         UndefElts.set(i);
1510       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1511         Elts.push_back(Undef);
1512         UndefElts.set(i);
1513       } else {                               // Otherwise, defined.
1514         Elts.push_back(CP->getOperand(i));
1515       }
1516
1517     // If we changed the constant, return it.
1518     Constant *NewCP = ConstantVector::get(Elts);
1519     return NewCP != CP ? NewCP : 0;
1520   } else if (isa<ConstantAggregateZero>(V)) {
1521     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1522     // set to undef.
1523     
1524     // Check if this is identity. If so, return 0 since we are not simplifying
1525     // anything.
1526     if (DemandedElts == ((1ULL << VWidth) -1))
1527       return 0;
1528     
1529     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1530     Constant *Zero = Constant::getNullValue(EltTy);
1531     Constant *Undef = UndefValue::get(EltTy);
1532     std::vector<Constant*> Elts;
1533     for (unsigned i = 0; i != VWidth; ++i) {
1534       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1535       Elts.push_back(Elt);
1536     }
1537     UndefElts = DemandedElts ^ EltMask;
1538     return ConstantVector::get(Elts);
1539   }
1540   
1541   // Limit search depth.
1542   if (Depth == 10)
1543     return 0;
1544
1545   // If multiple users are using the root value, procede with
1546   // simplification conservatively assuming that all elements
1547   // are needed.
1548   if (!V->hasOneUse()) {
1549     // Quit if we find multiple users of a non-root value though.
1550     // They'll be handled when it's their turn to be visited by
1551     // the main instcombine process.
1552     if (Depth != 0)
1553       // TODO: Just compute the UndefElts information recursively.
1554       return 0;
1555
1556     // Conservatively assume that all elements are needed.
1557     DemandedElts = EltMask;
1558   }
1559   
1560   Instruction *I = dyn_cast<Instruction>(V);
1561   if (!I) return 0;        // Only analyze instructions.
1562   
1563   bool MadeChange = false;
1564   APInt UndefElts2(VWidth, 0);
1565   Value *TmpV;
1566   switch (I->getOpcode()) {
1567   default: break;
1568     
1569   case Instruction::InsertElement: {
1570     // If this is a variable index, we don't know which element it overwrites.
1571     // demand exactly the same input as we produce.
1572     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1573     if (Idx == 0) {
1574       // Note that we can't propagate undef elt info, because we don't know
1575       // which elt is getting updated.
1576       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1577                                         UndefElts2, Depth+1);
1578       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1579       break;
1580     }
1581     
1582     // If this is inserting an element that isn't demanded, remove this
1583     // insertelement.
1584     unsigned IdxNo = Idx->getZExtValue();
1585     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1586       Worklist.Add(I);
1587       return I->getOperand(0);
1588     }
1589     
1590     // Otherwise, the element inserted overwrites whatever was there, so the
1591     // input demanded set is simpler than the output set.
1592     APInt DemandedElts2 = DemandedElts;
1593     DemandedElts2.clear(IdxNo);
1594     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1595                                       UndefElts, Depth+1);
1596     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1597
1598     // The inserted element is defined.
1599     UndefElts.clear(IdxNo);
1600     break;
1601   }
1602   case Instruction::ShuffleVector: {
1603     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1604     uint64_t LHSVWidth =
1605       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1606     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1607     for (unsigned i = 0; i < VWidth; i++) {
1608       if (DemandedElts[i]) {
1609         unsigned MaskVal = Shuffle->getMaskValue(i);
1610         if (MaskVal != -1u) {
1611           assert(MaskVal < LHSVWidth * 2 &&
1612                  "shufflevector mask index out of range!");
1613           if (MaskVal < LHSVWidth)
1614             LeftDemanded.set(MaskVal);
1615           else
1616             RightDemanded.set(MaskVal - LHSVWidth);
1617         }
1618       }
1619     }
1620
1621     APInt UndefElts4(LHSVWidth, 0);
1622     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1623                                       UndefElts4, Depth+1);
1624     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1625
1626     APInt UndefElts3(LHSVWidth, 0);
1627     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1628                                       UndefElts3, Depth+1);
1629     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1630
1631     bool NewUndefElts = false;
1632     for (unsigned i = 0; i < VWidth; i++) {
1633       unsigned MaskVal = Shuffle->getMaskValue(i);
1634       if (MaskVal == -1u) {
1635         UndefElts.set(i);
1636       } else if (MaskVal < LHSVWidth) {
1637         if (UndefElts4[MaskVal]) {
1638           NewUndefElts = true;
1639           UndefElts.set(i);
1640         }
1641       } else {
1642         if (UndefElts3[MaskVal - LHSVWidth]) {
1643           NewUndefElts = true;
1644           UndefElts.set(i);
1645         }
1646       }
1647     }
1648
1649     if (NewUndefElts) {
1650       // Add additional discovered undefs.
1651       std::vector<Constant*> Elts;
1652       for (unsigned i = 0; i < VWidth; ++i) {
1653         if (UndefElts[i])
1654           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1655         else
1656           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1657                                           Shuffle->getMaskValue(i)));
1658       }
1659       I->setOperand(2, ConstantVector::get(Elts));
1660       MadeChange = true;
1661     }
1662     break;
1663   }
1664   case Instruction::BitCast: {
1665     // Vector->vector casts only.
1666     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1667     if (!VTy) break;
1668     unsigned InVWidth = VTy->getNumElements();
1669     APInt InputDemandedElts(InVWidth, 0);
1670     unsigned Ratio;
1671
1672     if (VWidth == InVWidth) {
1673       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1674       // elements as are demanded of us.
1675       Ratio = 1;
1676       InputDemandedElts = DemandedElts;
1677     } else if (VWidth > InVWidth) {
1678       // Untested so far.
1679       break;
1680       
1681       // If there are more elements in the result than there are in the source,
1682       // then an input element is live if any of the corresponding output
1683       // elements are live.
1684       Ratio = VWidth/InVWidth;
1685       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1686         if (DemandedElts[OutIdx])
1687           InputDemandedElts.set(OutIdx/Ratio);
1688       }
1689     } else {
1690       // Untested so far.
1691       break;
1692       
1693       // If there are more elements in the source than there are in the result,
1694       // then an input element is live if the corresponding output element is
1695       // live.
1696       Ratio = InVWidth/VWidth;
1697       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1698         if (DemandedElts[InIdx/Ratio])
1699           InputDemandedElts.set(InIdx);
1700     }
1701     
1702     // div/rem demand all inputs, because they don't want divide by zero.
1703     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1704                                       UndefElts2, Depth+1);
1705     if (TmpV) {
1706       I->setOperand(0, TmpV);
1707       MadeChange = true;
1708     }
1709     
1710     UndefElts = UndefElts2;
1711     if (VWidth > InVWidth) {
1712       llvm_unreachable("Unimp");
1713       // If there are more elements in the result than there are in the source,
1714       // then an output element is undef if the corresponding input element is
1715       // undef.
1716       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1717         if (UndefElts2[OutIdx/Ratio])
1718           UndefElts.set(OutIdx);
1719     } else if (VWidth < InVWidth) {
1720       llvm_unreachable("Unimp");
1721       // If there are more elements in the source than there are in the result,
1722       // then a result element is undef if all of the corresponding input
1723       // elements are undef.
1724       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1725       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1726         if (!UndefElts2[InIdx])            // Not undef?
1727           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1728     }
1729     break;
1730   }
1731   case Instruction::And:
1732   case Instruction::Or:
1733   case Instruction::Xor:
1734   case Instruction::Add:
1735   case Instruction::Sub:
1736   case Instruction::Mul:
1737     // div/rem demand all inputs, because they don't want divide by zero.
1738     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1739                                       UndefElts, Depth+1);
1740     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1741     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1742                                       UndefElts2, Depth+1);
1743     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1744       
1745     // Output elements are undefined if both are undefined.  Consider things
1746     // like undef&0.  The result is known zero, not undef.
1747     UndefElts &= UndefElts2;
1748     break;
1749     
1750   case Instruction::Call: {
1751     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1752     if (!II) break;
1753     switch (II->getIntrinsicID()) {
1754     default: break;
1755       
1756     // Binary vector operations that work column-wise.  A dest element is a
1757     // function of the corresponding input elements from the two inputs.
1758     case Intrinsic::x86_sse_sub_ss:
1759     case Intrinsic::x86_sse_mul_ss:
1760     case Intrinsic::x86_sse_min_ss:
1761     case Intrinsic::x86_sse_max_ss:
1762     case Intrinsic::x86_sse2_sub_sd:
1763     case Intrinsic::x86_sse2_mul_sd:
1764     case Intrinsic::x86_sse2_min_sd:
1765     case Intrinsic::x86_sse2_max_sd:
1766       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1767                                         UndefElts, Depth+1);
1768       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1769       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1770                                         UndefElts2, Depth+1);
1771       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1772
1773       // If only the low elt is demanded and this is a scalarizable intrinsic,
1774       // scalarize it now.
1775       if (DemandedElts == 1) {
1776         switch (II->getIntrinsicID()) {
1777         default: break;
1778         case Intrinsic::x86_sse_sub_ss:
1779         case Intrinsic::x86_sse_mul_ss:
1780         case Intrinsic::x86_sse2_sub_sd:
1781         case Intrinsic::x86_sse2_mul_sd:
1782           // TODO: Lower MIN/MAX/ABS/etc
1783           Value *LHS = II->getOperand(1);
1784           Value *RHS = II->getOperand(2);
1785           // Extract the element as scalars.
1786           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1787             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1788           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1789             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1790           
1791           switch (II->getIntrinsicID()) {
1792           default: llvm_unreachable("Case stmts out of sync!");
1793           case Intrinsic::x86_sse_sub_ss:
1794           case Intrinsic::x86_sse2_sub_sd:
1795             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1796                                                         II->getName()), *II);
1797             break;
1798           case Intrinsic::x86_sse_mul_ss:
1799           case Intrinsic::x86_sse2_mul_sd:
1800             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1801                                                          II->getName()), *II);
1802             break;
1803           }
1804           
1805           Instruction *New =
1806             InsertElementInst::Create(
1807               UndefValue::get(II->getType()), TmpV,
1808               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1809           InsertNewInstBefore(New, *II);
1810           return New;
1811         }            
1812       }
1813         
1814       // Output elements are undefined if both are undefined.  Consider things
1815       // like undef&0.  The result is known zero, not undef.
1816       UndefElts &= UndefElts2;
1817       break;
1818     }
1819     break;
1820   }
1821   }
1822   return MadeChange ? I : 0;
1823 }
1824
1825
1826 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1827 /// function is designed to check a chain of associative operators for a
1828 /// potential to apply a certain optimization.  Since the optimization may be
1829 /// applicable if the expression was reassociated, this checks the chain, then
1830 /// reassociates the expression as necessary to expose the optimization
1831 /// opportunity.  This makes use of a special Functor, which must define
1832 /// 'shouldApply' and 'apply' methods.
1833 ///
1834 template<typename Functor>
1835 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1836   unsigned Opcode = Root.getOpcode();
1837   Value *LHS = Root.getOperand(0);
1838
1839   // Quick check, see if the immediate LHS matches...
1840   if (F.shouldApply(LHS))
1841     return F.apply(Root);
1842
1843   // Otherwise, if the LHS is not of the same opcode as the root, return.
1844   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1845   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1846     // Should we apply this transform to the RHS?
1847     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1848
1849     // If not to the RHS, check to see if we should apply to the LHS...
1850     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1851       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1852       ShouldApply = true;
1853     }
1854
1855     // If the functor wants to apply the optimization to the RHS of LHSI,
1856     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1857     if (ShouldApply) {
1858       // Now all of the instructions are in the current basic block, go ahead
1859       // and perform the reassociation.
1860       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1861
1862       // First move the selected RHS to the LHS of the root...
1863       Root.setOperand(0, LHSI->getOperand(1));
1864
1865       // Make what used to be the LHS of the root be the user of the root...
1866       Value *ExtraOperand = TmpLHSI->getOperand(1);
1867       if (&Root == TmpLHSI) {
1868         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1869         return 0;
1870       }
1871       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1872       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1873       BasicBlock::iterator ARI = &Root; ++ARI;
1874       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1875       ARI = Root;
1876
1877       // Now propagate the ExtraOperand down the chain of instructions until we
1878       // get to LHSI.
1879       while (TmpLHSI != LHSI) {
1880         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1881         // Move the instruction to immediately before the chain we are
1882         // constructing to avoid breaking dominance properties.
1883         NextLHSI->moveBefore(ARI);
1884         ARI = NextLHSI;
1885
1886         Value *NextOp = NextLHSI->getOperand(1);
1887         NextLHSI->setOperand(1, ExtraOperand);
1888         TmpLHSI = NextLHSI;
1889         ExtraOperand = NextOp;
1890       }
1891
1892       // Now that the instructions are reassociated, have the functor perform
1893       // the transformation...
1894       return F.apply(Root);
1895     }
1896
1897     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1898   }
1899   return 0;
1900 }
1901
1902 namespace {
1903
1904 // AddRHS - Implements: X + X --> X << 1
1905 struct AddRHS {
1906   Value *RHS;
1907   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1908   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1909   Instruction *apply(BinaryOperator &Add) const {
1910     return BinaryOperator::CreateShl(Add.getOperand(0),
1911                                      ConstantInt::get(Add.getType(), 1));
1912   }
1913 };
1914
1915 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1916 //                 iff C1&C2 == 0
1917 struct AddMaskingAnd {
1918   Constant *C2;
1919   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1920   bool shouldApply(Value *LHS) const {
1921     ConstantInt *C1;
1922     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1923            ConstantExpr::getAnd(C1, C2)->isNullValue();
1924   }
1925   Instruction *apply(BinaryOperator &Add) const {
1926     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1927   }
1928 };
1929
1930 }
1931
1932 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1933                                              InstCombiner *IC) {
1934   if (CastInst *CI = dyn_cast<CastInst>(&I))
1935     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1936
1937   // Figure out if the constant is the left or the right argument.
1938   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1939   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1940
1941   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1942     if (ConstIsRHS)
1943       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1944     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1945   }
1946
1947   Value *Op0 = SO, *Op1 = ConstOperand;
1948   if (!ConstIsRHS)
1949     std::swap(Op0, Op1);
1950   
1951   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1952     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1953                                     SO->getName()+".op");
1954   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1955     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1956                                    SO->getName()+".cmp");
1957   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1958     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1959                                    SO->getName()+".cmp");
1960   llvm_unreachable("Unknown binary instruction type!");
1961 }
1962
1963 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1964 // constant as the other operand, try to fold the binary operator into the
1965 // select arguments.  This also works for Cast instructions, which obviously do
1966 // not have a second operand.
1967 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1968                                      InstCombiner *IC) {
1969   // Don't modify shared select instructions
1970   if (!SI->hasOneUse()) return 0;
1971   Value *TV = SI->getOperand(1);
1972   Value *FV = SI->getOperand(2);
1973
1974   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1975     // Bool selects with constant operands can be folded to logical ops.
1976     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1977
1978     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1979     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1980
1981     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1982                               SelectFalseVal);
1983   }
1984   return 0;
1985 }
1986
1987
1988 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1989 /// has a PHI node as operand #0, see if we can fold the instruction into the
1990 /// PHI (which is only possible if all operands to the PHI are constants).
1991 ///
1992 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1993 /// that would normally be unprofitable because they strongly encourage jump
1994 /// threading.
1995 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1996                                          bool AllowAggressive) {
1997   AllowAggressive = false;
1998   PHINode *PN = cast<PHINode>(I.getOperand(0));
1999   unsigned NumPHIValues = PN->getNumIncomingValues();
2000   if (NumPHIValues == 0 ||
2001       // We normally only transform phis with a single use, unless we're trying
2002       // hard to make jump threading happen.
2003       (!PN->hasOneUse() && !AllowAggressive))
2004     return 0;
2005   
2006   
2007   // Check to see if all of the operands of the PHI are simple constants
2008   // (constantint/constantfp/undef).  If there is one non-constant value,
2009   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2010   // bail out.  We don't do arbitrary constant expressions here because moving
2011   // their computation can be expensive without a cost model.
2012   BasicBlock *NonConstBB = 0;
2013   for (unsigned i = 0; i != NumPHIValues; ++i)
2014     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2015         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2016       if (NonConstBB) return 0;  // More than one non-const value.
2017       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2018       NonConstBB = PN->getIncomingBlock(i);
2019       
2020       // If the incoming non-constant value is in I's block, we have an infinite
2021       // loop.
2022       if (NonConstBB == I.getParent())
2023         return 0;
2024     }
2025   
2026   // If there is exactly one non-constant value, we can insert a copy of the
2027   // operation in that block.  However, if this is a critical edge, we would be
2028   // inserting the computation one some other paths (e.g. inside a loop).  Only
2029   // do this if the pred block is unconditionally branching into the phi block.
2030   if (NonConstBB != 0 && !AllowAggressive) {
2031     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2032     if (!BI || !BI->isUnconditional()) return 0;
2033   }
2034
2035   // Okay, we can do the transformation: create the new PHI node.
2036   PHINode *NewPN = PHINode::Create(I.getType(), "");
2037   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2038   InsertNewInstBefore(NewPN, *PN);
2039   NewPN->takeName(PN);
2040
2041   // Next, add all of the operands to the PHI.
2042   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2043     // We only currently try to fold the condition of a select when it is a phi,
2044     // not the true/false values.
2045     Value *TrueV = SI->getTrueValue();
2046     Value *FalseV = SI->getFalseValue();
2047     BasicBlock *PhiTransBB = PN->getParent();
2048     for (unsigned i = 0; i != NumPHIValues; ++i) {
2049       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2050       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2051       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2052       Value *InV = 0;
2053       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2054         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2055       } else {
2056         assert(PN->getIncomingBlock(i) == NonConstBB);
2057         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2058                                  FalseVInPred,
2059                                  "phitmp", NonConstBB->getTerminator());
2060         Worklist.Add(cast<Instruction>(InV));
2061       }
2062       NewPN->addIncoming(InV, ThisBB);
2063     }
2064   } else if (I.getNumOperands() == 2) {
2065     Constant *C = cast<Constant>(I.getOperand(1));
2066     for (unsigned i = 0; i != NumPHIValues; ++i) {
2067       Value *InV = 0;
2068       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2069         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2070           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2071         else
2072           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2073       } else {
2074         assert(PN->getIncomingBlock(i) == NonConstBB);
2075         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2076           InV = BinaryOperator::Create(BO->getOpcode(),
2077                                        PN->getIncomingValue(i), C, "phitmp",
2078                                        NonConstBB->getTerminator());
2079         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2080           InV = CmpInst::Create(CI->getOpcode(),
2081                                 CI->getPredicate(),
2082                                 PN->getIncomingValue(i), C, "phitmp",
2083                                 NonConstBB->getTerminator());
2084         else
2085           llvm_unreachable("Unknown binop!");
2086         
2087         Worklist.Add(cast<Instruction>(InV));
2088       }
2089       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2090     }
2091   } else { 
2092     CastInst *CI = cast<CastInst>(&I);
2093     const Type *RetTy = CI->getType();
2094     for (unsigned i = 0; i != NumPHIValues; ++i) {
2095       Value *InV;
2096       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2097         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2098       } else {
2099         assert(PN->getIncomingBlock(i) == NonConstBB);
2100         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2101                                I.getType(), "phitmp", 
2102                                NonConstBB->getTerminator());
2103         Worklist.Add(cast<Instruction>(InV));
2104       }
2105       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2106     }
2107   }
2108   return ReplaceInstUsesWith(I, NewPN);
2109 }
2110
2111
2112 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2113 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2114 /// This basically requires proving that the add in the original type would not
2115 /// overflow to change the sign bit or have a carry out.
2116 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2117   // There are different heuristics we can use for this.  Here are some simple
2118   // ones.
2119   
2120   // Add has the property that adding any two 2's complement numbers can only 
2121   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2122   // have at least two sign bits, we know that the addition of the two values will
2123   // sign extend fine.
2124   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2125     return true;
2126   
2127   
2128   // If one of the operands only has one non-zero bit, and if the other operand
2129   // has a known-zero bit in a more significant place than it (not including the
2130   // sign bit) the ripple may go up to and fill the zero, but won't change the
2131   // sign.  For example, (X & ~4) + 1.
2132   
2133   // TODO: Implement.
2134   
2135   return false;
2136 }
2137
2138
2139 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2140   bool Changed = SimplifyCommutative(I);
2141   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2142
2143   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2144     // X + undef -> undef
2145     if (isa<UndefValue>(RHS))
2146       return ReplaceInstUsesWith(I, RHS);
2147
2148     // X + 0 --> X
2149     if (RHSC->isNullValue())
2150       return ReplaceInstUsesWith(I, LHS);
2151
2152     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2153       // X + (signbit) --> X ^ signbit
2154       const APInt& Val = CI->getValue();
2155       uint32_t BitWidth = Val.getBitWidth();
2156       if (Val == APInt::getSignBit(BitWidth))
2157         return BinaryOperator::CreateXor(LHS, RHS);
2158       
2159       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2160       // (X & 254)+1 -> (X&254)|1
2161       if (SimplifyDemandedInstructionBits(I))
2162         return &I;
2163
2164       // zext(bool) + C -> bool ? C + 1 : C
2165       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2166         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2167           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2168     }
2169
2170     if (isa<PHINode>(LHS))
2171       if (Instruction *NV = FoldOpIntoPhi(I))
2172         return NV;
2173     
2174     ConstantInt *XorRHS = 0;
2175     Value *XorLHS = 0;
2176     if (isa<ConstantInt>(RHSC) &&
2177         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2178       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2179       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2180       
2181       uint32_t Size = TySizeBits / 2;
2182       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2183       APInt CFF80Val(-C0080Val);
2184       do {
2185         if (TySizeBits > Size) {
2186           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2187           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2188           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2189               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2190             // This is a sign extend if the top bits are known zero.
2191             if (!MaskedValueIsZero(XorLHS, 
2192                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2193               Size = 0;  // Not a sign ext, but can't be any others either.
2194             break;
2195           }
2196         }
2197         Size >>= 1;
2198         C0080Val = APIntOps::lshr(C0080Val, Size);
2199         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2200       } while (Size >= 1);
2201       
2202       // FIXME: This shouldn't be necessary. When the backends can handle types
2203       // with funny bit widths then this switch statement should be removed. It
2204       // is just here to get the size of the "middle" type back up to something
2205       // that the back ends can handle.
2206       const Type *MiddleType = 0;
2207       switch (Size) {
2208         default: break;
2209         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2210         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2211         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2212       }
2213       if (MiddleType) {
2214         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2215         return new SExtInst(NewTrunc, I.getType(), I.getName());
2216       }
2217     }
2218   }
2219
2220   if (I.getType() == Type::getInt1Ty(*Context))
2221     return BinaryOperator::CreateXor(LHS, RHS);
2222
2223   // X + X --> X << 1
2224   if (I.getType()->isInteger()) {
2225     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2226       return Result;
2227
2228     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2229       if (RHSI->getOpcode() == Instruction::Sub)
2230         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2231           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2232     }
2233     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2234       if (LHSI->getOpcode() == Instruction::Sub)
2235         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2236           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2237     }
2238   }
2239
2240   // -A + B  -->  B - A
2241   // -A + -B  -->  -(A + B)
2242   if (Value *LHSV = dyn_castNegVal(LHS)) {
2243     if (LHS->getType()->isIntOrIntVector()) {
2244       if (Value *RHSV = dyn_castNegVal(RHS)) {
2245         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2246         return BinaryOperator::CreateNeg(NewAdd);
2247       }
2248     }
2249     
2250     return BinaryOperator::CreateSub(RHS, LHSV);
2251   }
2252
2253   // A + -B  -->  A - B
2254   if (!isa<Constant>(RHS))
2255     if (Value *V = dyn_castNegVal(RHS))
2256       return BinaryOperator::CreateSub(LHS, V);
2257
2258
2259   ConstantInt *C2;
2260   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2261     if (X == RHS)   // X*C + X --> X * (C+1)
2262       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2263
2264     // X*C1 + X*C2 --> X * (C1+C2)
2265     ConstantInt *C1;
2266     if (X == dyn_castFoldableMul(RHS, C1))
2267       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2268   }
2269
2270   // X + X*C --> X * (C+1)
2271   if (dyn_castFoldableMul(RHS, C2) == LHS)
2272     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2273
2274   // X + ~X --> -1   since   ~X = -X-1
2275   if (dyn_castNotVal(LHS) == RHS ||
2276       dyn_castNotVal(RHS) == LHS)
2277     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2278   
2279
2280   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2281   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2282     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2283       return R;
2284   
2285   // A+B --> A|B iff A and B have no bits set in common.
2286   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2287     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2288     APInt LHSKnownOne(IT->getBitWidth(), 0);
2289     APInt LHSKnownZero(IT->getBitWidth(), 0);
2290     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2291     if (LHSKnownZero != 0) {
2292       APInt RHSKnownOne(IT->getBitWidth(), 0);
2293       APInt RHSKnownZero(IT->getBitWidth(), 0);
2294       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2295       
2296       // No bits in common -> bitwise or.
2297       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2298         return BinaryOperator::CreateOr(LHS, RHS);
2299     }
2300   }
2301
2302   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2303   if (I.getType()->isIntOrIntVector()) {
2304     Value *W, *X, *Y, *Z;
2305     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2306         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2307       if (W != Y) {
2308         if (W == Z) {
2309           std::swap(Y, Z);
2310         } else if (Y == X) {
2311           std::swap(W, X);
2312         } else if (X == Z) {
2313           std::swap(Y, Z);
2314           std::swap(W, X);
2315         }
2316       }
2317
2318       if (W == Y) {
2319         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2320         return BinaryOperator::CreateMul(W, NewAdd);
2321       }
2322     }
2323   }
2324
2325   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2326     Value *X = 0;
2327     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2328       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2329
2330     // (X & FF00) + xx00  -> (X+xx00) & FF00
2331     if (LHS->hasOneUse() &&
2332         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2333       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2334       if (Anded == CRHS) {
2335         // See if all bits from the first bit set in the Add RHS up are included
2336         // in the mask.  First, get the rightmost bit.
2337         const APInt& AddRHSV = CRHS->getValue();
2338
2339         // Form a mask of all bits from the lowest bit added through the top.
2340         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2341
2342         // See if the and mask includes all of these bits.
2343         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2344
2345         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2346           // Okay, the xform is safe.  Insert the new add pronto.
2347           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2348           return BinaryOperator::CreateAnd(NewAdd, C2);
2349         }
2350       }
2351     }
2352
2353     // Try to fold constant add into select arguments.
2354     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2355       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2356         return R;
2357   }
2358
2359   // add (select X 0 (sub n A)) A  -->  select X A n
2360   {
2361     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2362     Value *A = RHS;
2363     if (!SI) {
2364       SI = dyn_cast<SelectInst>(RHS);
2365       A = LHS;
2366     }
2367     if (SI && SI->hasOneUse()) {
2368       Value *TV = SI->getTrueValue();
2369       Value *FV = SI->getFalseValue();
2370       Value *N;
2371
2372       // Can we fold the add into the argument of the select?
2373       // We check both true and false select arguments for a matching subtract.
2374       if (match(FV, m_Zero()) &&
2375           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2376         // Fold the add into the true select value.
2377         return SelectInst::Create(SI->getCondition(), N, A);
2378       if (match(TV, m_Zero()) &&
2379           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2380         // Fold the add into the false select value.
2381         return SelectInst::Create(SI->getCondition(), A, N);
2382     }
2383   }
2384
2385   // Check for (add (sext x), y), see if we can merge this into an
2386   // integer add followed by a sext.
2387   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2388     // (add (sext x), cst) --> (sext (add x, cst'))
2389     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2390       Constant *CI = 
2391         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2392       if (LHSConv->hasOneUse() &&
2393           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2394           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2395         // Insert the new, smaller add.
2396         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2397                                            CI, "addconv");
2398         return new SExtInst(NewAdd, I.getType());
2399       }
2400     }
2401     
2402     // (add (sext x), (sext y)) --> (sext (add int x, y))
2403     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2404       // Only do this if x/y have the same type, if at last one of them has a
2405       // single use (so we don't increase the number of sexts), and if the
2406       // integer add will not overflow.
2407       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2408           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2409           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2410                                    RHSConv->getOperand(0))) {
2411         // Insert the new integer add.
2412         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2413                                            RHSConv->getOperand(0), "addconv");
2414         return new SExtInst(NewAdd, I.getType());
2415       }
2416     }
2417   }
2418
2419   return Changed ? &I : 0;
2420 }
2421
2422 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2423   bool Changed = SimplifyCommutative(I);
2424   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2425
2426   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2427     // X + 0 --> X
2428     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2429       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2430                               (I.getType())->getValueAPF()))
2431         return ReplaceInstUsesWith(I, LHS);
2432     }
2433
2434     if (isa<PHINode>(LHS))
2435       if (Instruction *NV = FoldOpIntoPhi(I))
2436         return NV;
2437   }
2438
2439   // -A + B  -->  B - A
2440   // -A + -B  -->  -(A + B)
2441   if (Value *LHSV = dyn_castFNegVal(LHS))
2442     return BinaryOperator::CreateFSub(RHS, LHSV);
2443
2444   // A + -B  -->  A - B
2445   if (!isa<Constant>(RHS))
2446     if (Value *V = dyn_castFNegVal(RHS))
2447       return BinaryOperator::CreateFSub(LHS, V);
2448
2449   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2450   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2451     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2452       return ReplaceInstUsesWith(I, LHS);
2453
2454   // Check for (add double (sitofp x), y), see if we can merge this into an
2455   // integer add followed by a promotion.
2456   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2457     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2458     // ... if the constant fits in the integer value.  This is useful for things
2459     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2460     // requires a constant pool load, and generally allows the add to be better
2461     // instcombined.
2462     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2463       Constant *CI = 
2464       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2465       if (LHSConv->hasOneUse() &&
2466           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2467           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2468         // Insert the new integer add.
2469         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2470                                            CI, "addconv");
2471         return new SIToFPInst(NewAdd, I.getType());
2472       }
2473     }
2474     
2475     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2476     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2477       // Only do this if x/y have the same type, if at last one of them has a
2478       // single use (so we don't increase the number of int->fp conversions),
2479       // and if the integer add will not overflow.
2480       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2481           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2482           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2483                                    RHSConv->getOperand(0))) {
2484         // Insert the new integer add.
2485         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2486                                            RHSConv->getOperand(0), "addconv");
2487         return new SIToFPInst(NewAdd, I.getType());
2488       }
2489     }
2490   }
2491   
2492   return Changed ? &I : 0;
2493 }
2494
2495 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2496   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2497
2498   if (Op0 == Op1)                        // sub X, X  -> 0
2499     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2500
2501   // If this is a 'B = x-(-A)', change to B = x+A...
2502   if (Value *V = dyn_castNegVal(Op1))
2503     return BinaryOperator::CreateAdd(Op0, V);
2504
2505   if (isa<UndefValue>(Op0))
2506     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2507   if (isa<UndefValue>(Op1))
2508     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2509
2510   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2511     // Replace (-1 - A) with (~A)...
2512     if (C->isAllOnesValue())
2513       return BinaryOperator::CreateNot(Op1);
2514
2515     // C - ~X == X + (1+C)
2516     Value *X = 0;
2517     if (match(Op1, m_Not(m_Value(X))))
2518       return BinaryOperator::CreateAdd(X, AddOne(C));
2519
2520     // -(X >>u 31) -> (X >>s 31)
2521     // -(X >>s 31) -> (X >>u 31)
2522     if (C->isZero()) {
2523       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2524         if (SI->getOpcode() == Instruction::LShr) {
2525           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2526             // Check to see if we are shifting out everything but the sign bit.
2527             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2528                 SI->getType()->getPrimitiveSizeInBits()-1) {
2529               // Ok, the transformation is safe.  Insert AShr.
2530               return BinaryOperator::Create(Instruction::AShr, 
2531                                           SI->getOperand(0), CU, SI->getName());
2532             }
2533           }
2534         }
2535         else if (SI->getOpcode() == Instruction::AShr) {
2536           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2537             // Check to see if we are shifting out everything but the sign bit.
2538             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2539                 SI->getType()->getPrimitiveSizeInBits()-1) {
2540               // Ok, the transformation is safe.  Insert LShr. 
2541               return BinaryOperator::CreateLShr(
2542                                           SI->getOperand(0), CU, SI->getName());
2543             }
2544           }
2545         }
2546       }
2547     }
2548
2549     // Try to fold constant sub into select arguments.
2550     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2551       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2552         return R;
2553
2554     // C - zext(bool) -> bool ? C - 1 : C
2555     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2556       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2557         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2558   }
2559
2560   if (I.getType() == Type::getInt1Ty(*Context))
2561     return BinaryOperator::CreateXor(Op0, Op1);
2562
2563   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2564     if (Op1I->getOpcode() == Instruction::Add) {
2565       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2566         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2567                                          I.getName());
2568       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2569         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2570                                          I.getName());
2571       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2572         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2573           // C1-(X+C2) --> (C1-C2)-X
2574           return BinaryOperator::CreateSub(
2575             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2576       }
2577     }
2578
2579     if (Op1I->hasOneUse()) {
2580       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2581       // is not used by anyone else...
2582       //
2583       if (Op1I->getOpcode() == Instruction::Sub) {
2584         // Swap the two operands of the subexpr...
2585         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2586         Op1I->setOperand(0, IIOp1);
2587         Op1I->setOperand(1, IIOp0);
2588
2589         // Create the new top level add instruction...
2590         return BinaryOperator::CreateAdd(Op0, Op1);
2591       }
2592
2593       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2594       //
2595       if (Op1I->getOpcode() == Instruction::And &&
2596           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2597         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2598
2599         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2600         return BinaryOperator::CreateAnd(Op0, NewNot);
2601       }
2602
2603       // 0 - (X sdiv C)  -> (X sdiv -C)
2604       if (Op1I->getOpcode() == Instruction::SDiv)
2605         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2606           if (CSI->isZero())
2607             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2608               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2609                                           ConstantExpr::getNeg(DivRHS));
2610
2611       // X - X*C --> X * (1-C)
2612       ConstantInt *C2 = 0;
2613       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2614         Constant *CP1 = 
2615           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2616                                              C2);
2617         return BinaryOperator::CreateMul(Op0, CP1);
2618       }
2619     }
2620   }
2621
2622   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2623     if (Op0I->getOpcode() == Instruction::Add) {
2624       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2625         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2626       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2627         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2628     } else if (Op0I->getOpcode() == Instruction::Sub) {
2629       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2630         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2631                                          I.getName());
2632     }
2633   }
2634
2635   ConstantInt *C1;
2636   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2637     if (X == Op1)  // X*C - X --> X * (C-1)
2638       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2639
2640     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2641     if (X == dyn_castFoldableMul(Op1, C2))
2642       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2643   }
2644   return 0;
2645 }
2646
2647 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2648   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650   // If this is a 'B = x-(-A)', change to B = x+A...
2651   if (Value *V = dyn_castFNegVal(Op1))
2652     return BinaryOperator::CreateFAdd(Op0, V);
2653
2654   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2655     if (Op1I->getOpcode() == Instruction::FAdd) {
2656       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2657         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2658                                           I.getName());
2659       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2660         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2661                                           I.getName());
2662     }
2663   }
2664
2665   return 0;
2666 }
2667
2668 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2669 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2670 /// TrueIfSigned if the result of the comparison is true when the input value is
2671 /// signed.
2672 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2673                            bool &TrueIfSigned) {
2674   switch (pred) {
2675   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2676     TrueIfSigned = true;
2677     return RHS->isZero();
2678   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2679     TrueIfSigned = true;
2680     return RHS->isAllOnesValue();
2681   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2682     TrueIfSigned = false;
2683     return RHS->isAllOnesValue();
2684   case ICmpInst::ICMP_UGT:
2685     // True if LHS u> RHS and RHS == high-bit-mask - 1
2686     TrueIfSigned = true;
2687     return RHS->getValue() ==
2688       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2689   case ICmpInst::ICMP_UGE: 
2690     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2691     TrueIfSigned = true;
2692     return RHS->getValue().isSignBit();
2693   default:
2694     return false;
2695   }
2696 }
2697
2698 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2699   bool Changed = SimplifyCommutative(I);
2700   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2701
2702   if (isa<UndefValue>(Op1))              // undef * X -> 0
2703     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2704
2705   // Simplify mul instructions with a constant RHS.
2706   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2707     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2708
2709       // ((X << C1)*C2) == (X * (C2 << C1))
2710       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2711         if (SI->getOpcode() == Instruction::Shl)
2712           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2713             return BinaryOperator::CreateMul(SI->getOperand(0),
2714                                         ConstantExpr::getShl(CI, ShOp));
2715
2716       if (CI->isZero())
2717         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2718       if (CI->equalsInt(1))                  // X * 1  == X
2719         return ReplaceInstUsesWith(I, Op0);
2720       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2721         return BinaryOperator::CreateNeg(Op0, I.getName());
2722
2723       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2724       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2725         return BinaryOperator::CreateShl(Op0,
2726                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2727       }
2728     } else if (isa<VectorType>(Op1C->getType())) {
2729       if (Op1C->isNullValue())
2730         return ReplaceInstUsesWith(I, Op1C);
2731
2732       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2733         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2734           return BinaryOperator::CreateNeg(Op0, I.getName());
2735
2736         // As above, vector X*splat(1.0) -> X in all defined cases.
2737         if (Constant *Splat = Op1V->getSplatValue()) {
2738           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2739             if (CI->equalsInt(1))
2740               return ReplaceInstUsesWith(I, Op0);
2741         }
2742       }
2743     }
2744     
2745     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2746       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2747           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2748         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2749         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2750         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2751         return BinaryOperator::CreateAdd(Add, C1C2);
2752         
2753       }
2754
2755     // Try to fold constant mul into select arguments.
2756     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2757       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2758         return R;
2759
2760     if (isa<PHINode>(Op0))
2761       if (Instruction *NV = FoldOpIntoPhi(I))
2762         return NV;
2763   }
2764
2765   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2766     if (Value *Op1v = dyn_castNegVal(Op1))
2767       return BinaryOperator::CreateMul(Op0v, Op1v);
2768
2769   // (X / Y) *  Y = X - (X % Y)
2770   // (X / Y) * -Y = (X % Y) - X
2771   {
2772     Value *Op1C = Op1;
2773     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2774     if (!BO ||
2775         (BO->getOpcode() != Instruction::UDiv && 
2776          BO->getOpcode() != Instruction::SDiv)) {
2777       Op1C = Op0;
2778       BO = dyn_cast<BinaryOperator>(Op1);
2779     }
2780     Value *Neg = dyn_castNegVal(Op1C);
2781     if (BO && BO->hasOneUse() &&
2782         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
2783         (BO->getOpcode() == Instruction::UDiv ||
2784          BO->getOpcode() == Instruction::SDiv)) {
2785       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2786
2787       // If the division is exact, X % Y is zero.
2788       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2789         if (SDiv->isExact()) {
2790           if (Op1BO == Op1C)
2791             return ReplaceInstUsesWith(I, Op0BO);
2792           return BinaryOperator::CreateNeg(Op0BO);
2793         }
2794
2795       Value *Rem;
2796       if (BO->getOpcode() == Instruction::UDiv)
2797         Rem = Builder->CreateURem(Op0BO, Op1BO);
2798       else
2799         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2800       Rem->takeName(BO);
2801
2802       if (Op1BO == Op1C)
2803         return BinaryOperator::CreateSub(Op0BO, Rem);
2804       return BinaryOperator::CreateSub(Rem, Op0BO);
2805     }
2806   }
2807
2808   /// i1 mul -> i1 and.
2809   if (I.getType() == Type::getInt1Ty(*Context))
2810     return BinaryOperator::CreateAnd(Op0, Op1);
2811
2812   // X*(1 << Y) --> X << Y
2813   // (1 << Y)*X --> X << Y
2814   {
2815     Value *Y;
2816     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
2817       return BinaryOperator::CreateShl(Op1, Y);
2818     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
2819       return BinaryOperator::CreateShl(Op0, Y);
2820   }
2821   
2822   // If one of the operands of the multiply is a cast from a boolean value, then
2823   // we know the bool is either zero or one, so this is a 'masking' multiply.
2824   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
2825   if (!isa<VectorType>(I.getType())) {
2826     // -2 is "-1 << 1" so it is all bits set except the low one.
2827     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
2828     
2829     Value *BoolCast = 0, *OtherOp = 0;
2830     if (MaskedValueIsZero(Op0, Negative2))
2831       BoolCast = Op0, OtherOp = Op1;
2832     else if (MaskedValueIsZero(Op1, Negative2))
2833       BoolCast = Op1, OtherOp = Op0;
2834
2835     if (BoolCast) {
2836       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2837                                     BoolCast, "tmp");
2838       return BinaryOperator::CreateAnd(V, OtherOp);
2839     }
2840   }
2841
2842   return Changed ? &I : 0;
2843 }
2844
2845 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2846   bool Changed = SimplifyCommutative(I);
2847   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2848
2849   // Simplify mul instructions with a constant RHS...
2850   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2851     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
2852       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2853       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2854       if (Op1F->isExactlyValue(1.0))
2855         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2856     } else if (isa<VectorType>(Op1C->getType())) {
2857       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2858         // As above, vector X*splat(1.0) -> X in all defined cases.
2859         if (Constant *Splat = Op1V->getSplatValue()) {
2860           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2861             if (F->isExactlyValue(1.0))
2862               return ReplaceInstUsesWith(I, Op0);
2863         }
2864       }
2865     }
2866
2867     // Try to fold constant mul into select arguments.
2868     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2869       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2870         return R;
2871
2872     if (isa<PHINode>(Op0))
2873       if (Instruction *NV = FoldOpIntoPhi(I))
2874         return NV;
2875   }
2876
2877   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2878     if (Value *Op1v = dyn_castFNegVal(Op1))
2879       return BinaryOperator::CreateFMul(Op0v, Op1v);
2880
2881   return Changed ? &I : 0;
2882 }
2883
2884 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2885 /// instruction.
2886 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2887   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2888   
2889   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2890   int NonNullOperand = -1;
2891   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2892     if (ST->isNullValue())
2893       NonNullOperand = 2;
2894   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2895   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2896     if (ST->isNullValue())
2897       NonNullOperand = 1;
2898   
2899   if (NonNullOperand == -1)
2900     return false;
2901   
2902   Value *SelectCond = SI->getOperand(0);
2903   
2904   // Change the div/rem to use 'Y' instead of the select.
2905   I.setOperand(1, SI->getOperand(NonNullOperand));
2906   
2907   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2908   // problem.  However, the select, or the condition of the select may have
2909   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2910   // propagate the known value for the select into other uses of it, and
2911   // propagate a known value of the condition into its other users.
2912   
2913   // If the select and condition only have a single use, don't bother with this,
2914   // early exit.
2915   if (SI->use_empty() && SelectCond->hasOneUse())
2916     return true;
2917   
2918   // Scan the current block backward, looking for other uses of SI.
2919   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2920   
2921   while (BBI != BBFront) {
2922     --BBI;
2923     // If we found a call to a function, we can't assume it will return, so
2924     // information from below it cannot be propagated above it.
2925     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2926       break;
2927     
2928     // Replace uses of the select or its condition with the known values.
2929     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2930          I != E; ++I) {
2931       if (*I == SI) {
2932         *I = SI->getOperand(NonNullOperand);
2933         Worklist.Add(BBI);
2934       } else if (*I == SelectCond) {
2935         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2936                                    ConstantInt::getFalse(*Context);
2937         Worklist.Add(BBI);
2938       }
2939     }
2940     
2941     // If we past the instruction, quit looking for it.
2942     if (&*BBI == SI)
2943       SI = 0;
2944     if (&*BBI == SelectCond)
2945       SelectCond = 0;
2946     
2947     // If we ran out of things to eliminate, break out of the loop.
2948     if (SelectCond == 0 && SI == 0)
2949       break;
2950     
2951   }
2952   return true;
2953 }
2954
2955
2956 /// This function implements the transforms on div instructions that work
2957 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2958 /// used by the visitors to those instructions.
2959 /// @brief Transforms common to all three div instructions
2960 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2961   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2962
2963   // undef / X -> 0        for integer.
2964   // undef / X -> undef    for FP (the undef could be a snan).
2965   if (isa<UndefValue>(Op0)) {
2966     if (Op0->getType()->isFPOrFPVector())
2967       return ReplaceInstUsesWith(I, Op0);
2968     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2969   }
2970
2971   // X / undef -> undef
2972   if (isa<UndefValue>(Op1))
2973     return ReplaceInstUsesWith(I, Op1);
2974
2975   return 0;
2976 }
2977
2978 /// This function implements the transforms common to both integer division
2979 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2980 /// division instructions.
2981 /// @brief Common integer divide transforms
2982 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2983   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2984
2985   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2986   if (Op0 == Op1) {
2987     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2988       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2989       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2990       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2991     }
2992
2993     Constant *CI = ConstantInt::get(I.getType(), 1);
2994     return ReplaceInstUsesWith(I, CI);
2995   }
2996   
2997   if (Instruction *Common = commonDivTransforms(I))
2998     return Common;
2999   
3000   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3001   // This does not apply for fdiv.
3002   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3003     return &I;
3004
3005   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3006     // div X, 1 == X
3007     if (RHS->equalsInt(1))
3008       return ReplaceInstUsesWith(I, Op0);
3009
3010     // (X / C1) / C2  -> X / (C1*C2)
3011     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3012       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3013         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3014           if (MultiplyOverflows(RHS, LHSRHS,
3015                                 I.getOpcode()==Instruction::SDiv))
3016             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3017           else 
3018             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3019                                       ConstantExpr::getMul(RHS, LHSRHS));
3020         }
3021
3022     if (!RHS->isZero()) { // avoid X udiv 0
3023       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3024         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3025           return R;
3026       if (isa<PHINode>(Op0))
3027         if (Instruction *NV = FoldOpIntoPhi(I))
3028           return NV;
3029     }
3030   }
3031
3032   // 0 / X == 0, we don't need to preserve faults!
3033   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3034     if (LHS->equalsInt(0))
3035       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3036
3037   // It can't be division by zero, hence it must be division by one.
3038   if (I.getType() == Type::getInt1Ty(*Context))
3039     return ReplaceInstUsesWith(I, Op0);
3040
3041   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3042     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3043       // div X, 1 == X
3044       if (X->isOne())
3045         return ReplaceInstUsesWith(I, Op0);
3046   }
3047
3048   return 0;
3049 }
3050
3051 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3052   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053
3054   // Handle the integer div common cases
3055   if (Instruction *Common = commonIDivTransforms(I))
3056     return Common;
3057
3058   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3059     // X udiv C^2 -> X >> C
3060     // Check to see if this is an unsigned division with an exact power of 2,
3061     // if so, convert to a right shift.
3062     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3063       return BinaryOperator::CreateLShr(Op0, 
3064             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3065
3066     // X udiv C, where C >= signbit
3067     if (C->getValue().isNegative()) {
3068       Value *IC = Builder->CreateICmpULT( Op0, C);
3069       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3070                                 ConstantInt::get(I.getType(), 1));
3071     }
3072   }
3073
3074   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3075   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3076     if (RHSI->getOpcode() == Instruction::Shl &&
3077         isa<ConstantInt>(RHSI->getOperand(0))) {
3078       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3079       if (C1.isPowerOf2()) {
3080         Value *N = RHSI->getOperand(1);
3081         const Type *NTy = N->getType();
3082         if (uint32_t C2 = C1.logBase2())
3083           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3084         return BinaryOperator::CreateLShr(Op0, N);
3085       }
3086     }
3087   }
3088   
3089   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3090   // where C1&C2 are powers of two.
3091   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3092     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3093       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3094         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3095         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3096           // Compute the shift amounts
3097           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3098           // Construct the "on true" case of the select
3099           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3100           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3101   
3102           // Construct the "on false" case of the select
3103           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3104           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3105
3106           // construct the select instruction and return it.
3107           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3108         }
3109       }
3110   return 0;
3111 }
3112
3113 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3114   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3115
3116   // Handle the integer div common cases
3117   if (Instruction *Common = commonIDivTransforms(I))
3118     return Common;
3119
3120   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3121     // sdiv X, -1 == -X
3122     if (RHS->isAllOnesValue())
3123       return BinaryOperator::CreateNeg(Op0);
3124
3125     // sdiv X, C  -->  ashr X, log2(C)
3126     if (cast<SDivOperator>(&I)->isExact() &&
3127         RHS->getValue().isNonNegative() &&
3128         RHS->getValue().isPowerOf2()) {
3129       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3130                                             RHS->getValue().exactLogBase2());
3131       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3132     }
3133
3134     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3135     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3136       if (isa<Constant>(Sub->getOperand(0)) &&
3137           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3138           Sub->hasNoSignedWrap())
3139         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3140                                           ConstantExpr::getNeg(RHS));
3141   }
3142
3143   // If the sign bits of both operands are zero (i.e. we can prove they are
3144   // unsigned inputs), turn this into a udiv.
3145   if (I.getType()->isInteger()) {
3146     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3147     if (MaskedValueIsZero(Op0, Mask)) {
3148       if (MaskedValueIsZero(Op1, Mask)) {
3149         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3150         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3151       }
3152       ConstantInt *ShiftedInt;
3153       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3154           ShiftedInt->getValue().isPowerOf2()) {
3155         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3156         // Safe because the only negative value (1 << Y) can take on is
3157         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3158         // the sign bit set.
3159         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3160       }
3161     }
3162   }
3163   
3164   return 0;
3165 }
3166
3167 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3168   return commonDivTransforms(I);
3169 }
3170
3171 /// This function implements the transforms on rem instructions that work
3172 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3173 /// is used by the visitors to those instructions.
3174 /// @brief Transforms common to all three rem instructions
3175 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3176   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3177
3178   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3179     if (I.getType()->isFPOrFPVector())
3180       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3181     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3182   }
3183   if (isa<UndefValue>(Op1))
3184     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3185
3186   // Handle cases involving: rem X, (select Cond, Y, Z)
3187   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3188     return &I;
3189
3190   return 0;
3191 }
3192
3193 /// This function implements the transforms common to both integer remainder
3194 /// instructions (urem and srem). It is called by the visitors to those integer
3195 /// remainder instructions.
3196 /// @brief Common integer remainder transforms
3197 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3198   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3199
3200   if (Instruction *common = commonRemTransforms(I))
3201     return common;
3202
3203   // 0 % X == 0 for integer, we don't need to preserve faults!
3204   if (Constant *LHS = dyn_cast<Constant>(Op0))
3205     if (LHS->isNullValue())
3206       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3207
3208   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209     // X % 0 == undef, we don't need to preserve faults!
3210     if (RHS->equalsInt(0))
3211       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3212     
3213     if (RHS->equalsInt(1))  // X % 1 == 0
3214       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3215
3216     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3217       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3218         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3219           return R;
3220       } else if (isa<PHINode>(Op0I)) {
3221         if (Instruction *NV = FoldOpIntoPhi(I))
3222           return NV;
3223       }
3224
3225       // See if we can fold away this rem instruction.
3226       if (SimplifyDemandedInstructionBits(I))
3227         return &I;
3228     }
3229   }
3230
3231   return 0;
3232 }
3233
3234 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3235   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3236
3237   if (Instruction *common = commonIRemTransforms(I))
3238     return common;
3239   
3240   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3241     // X urem C^2 -> X and C
3242     // Check to see if this is an unsigned remainder with an exact power of 2,
3243     // if so, convert to a bitwise and.
3244     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3245       if (C->getValue().isPowerOf2())
3246         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3247   }
3248
3249   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3250     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3251     if (RHSI->getOpcode() == Instruction::Shl &&
3252         isa<ConstantInt>(RHSI->getOperand(0))) {
3253       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3254         Constant *N1 = Constant::getAllOnesValue(I.getType());
3255         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3256         return BinaryOperator::CreateAnd(Op0, Add);
3257       }
3258     }
3259   }
3260
3261   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3262   // where C1&C2 are powers of two.
3263   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3264     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3265       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3266         // STO == 0 and SFO == 0 handled above.
3267         if ((STO->getValue().isPowerOf2()) && 
3268             (SFO->getValue().isPowerOf2())) {
3269           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3270                                               SI->getName()+".t");
3271           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3272                                                SI->getName()+".f");
3273           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3274         }
3275       }
3276   }
3277   
3278   return 0;
3279 }
3280
3281 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3282   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3283
3284   // Handle the integer rem common cases
3285   if (Instruction *Common = commonIRemTransforms(I))
3286     return Common;
3287   
3288   if (Value *RHSNeg = dyn_castNegVal(Op1))
3289     if (!isa<Constant>(RHSNeg) ||
3290         (isa<ConstantInt>(RHSNeg) &&
3291          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3292       // X % -Y -> X % Y
3293       Worklist.AddValue(I.getOperand(1));
3294       I.setOperand(1, RHSNeg);
3295       return &I;
3296     }
3297
3298   // If the sign bits of both operands are zero (i.e. we can prove they are
3299   // unsigned inputs), turn this into a urem.
3300   if (I.getType()->isInteger()) {
3301     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3302     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3303       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3304       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3305     }
3306   }
3307
3308   // If it's a constant vector, flip any negative values positive.
3309   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3310     unsigned VWidth = RHSV->getNumOperands();
3311
3312     bool hasNegative = false;
3313     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3314       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3315         if (RHS->getValue().isNegative())
3316           hasNegative = true;
3317
3318     if (hasNegative) {
3319       std::vector<Constant *> Elts(VWidth);
3320       for (unsigned i = 0; i != VWidth; ++i) {
3321         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3322           if (RHS->getValue().isNegative())
3323             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3324           else
3325             Elts[i] = RHS;
3326         }
3327       }
3328
3329       Constant *NewRHSV = ConstantVector::get(Elts);
3330       if (NewRHSV != RHSV) {
3331         Worklist.AddValue(I.getOperand(1));
3332         I.setOperand(1, NewRHSV);
3333         return &I;
3334       }
3335     }
3336   }
3337
3338   return 0;
3339 }
3340
3341 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3342   return commonRemTransforms(I);
3343 }
3344
3345 // isOneBitSet - Return true if there is exactly one bit set in the specified
3346 // constant.
3347 static bool isOneBitSet(const ConstantInt *CI) {
3348   return CI->getValue().isPowerOf2();
3349 }
3350
3351 // isHighOnes - Return true if the constant is of the form 1+0+.
3352 // This is the same as lowones(~X).
3353 static bool isHighOnes(const ConstantInt *CI) {
3354   return (~CI->getValue() + 1).isPowerOf2();
3355 }
3356
3357 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3358 /// are carefully arranged to allow folding of expressions such as:
3359 ///
3360 ///      (A < B) | (A > B) --> (A != B)
3361 ///
3362 /// Note that this is only valid if the first and second predicates have the
3363 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3364 ///
3365 /// Three bits are used to represent the condition, as follows:
3366 ///   0  A > B
3367 ///   1  A == B
3368 ///   2  A < B
3369 ///
3370 /// <=>  Value  Definition
3371 /// 000     0   Always false
3372 /// 001     1   A >  B
3373 /// 010     2   A == B
3374 /// 011     3   A >= B
3375 /// 100     4   A <  B
3376 /// 101     5   A != B
3377 /// 110     6   A <= B
3378 /// 111     7   Always true
3379 ///  
3380 static unsigned getICmpCode(const ICmpInst *ICI) {
3381   switch (ICI->getPredicate()) {
3382     // False -> 0
3383   case ICmpInst::ICMP_UGT: return 1;  // 001
3384   case ICmpInst::ICMP_SGT: return 1;  // 001
3385   case ICmpInst::ICMP_EQ:  return 2;  // 010
3386   case ICmpInst::ICMP_UGE: return 3;  // 011
3387   case ICmpInst::ICMP_SGE: return 3;  // 011
3388   case ICmpInst::ICMP_ULT: return 4;  // 100
3389   case ICmpInst::ICMP_SLT: return 4;  // 100
3390   case ICmpInst::ICMP_NE:  return 5;  // 101
3391   case ICmpInst::ICMP_ULE: return 6;  // 110
3392   case ICmpInst::ICMP_SLE: return 6;  // 110
3393     // True -> 7
3394   default:
3395     llvm_unreachable("Invalid ICmp predicate!");
3396     return 0;
3397   }
3398 }
3399
3400 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3401 /// predicate into a three bit mask. It also returns whether it is an ordered
3402 /// predicate by reference.
3403 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3404   isOrdered = false;
3405   switch (CC) {
3406   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3407   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3408   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3409   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3410   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3411   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3412   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3413   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3414   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3415   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3416   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3417   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3418   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3419   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3420     // True -> 7
3421   default:
3422     // Not expecting FCMP_FALSE and FCMP_TRUE;
3423     llvm_unreachable("Unexpected FCmp predicate!");
3424     return 0;
3425   }
3426 }
3427
3428 /// getICmpValue - This is the complement of getICmpCode, which turns an
3429 /// opcode and two operands into either a constant true or false, or a brand 
3430 /// new ICmp instruction. The sign is passed in to determine which kind
3431 /// of predicate to use in the new icmp instruction.
3432 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3433                            LLVMContext *Context) {
3434   switch (code) {
3435   default: llvm_unreachable("Illegal ICmp code!");
3436   case  0: return ConstantInt::getFalse(*Context);
3437   case  1: 
3438     if (sign)
3439       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3440     else
3441       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3442   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3443   case  3: 
3444     if (sign)
3445       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3446     else
3447       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3448   case  4: 
3449     if (sign)
3450       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3451     else
3452       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3453   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3454   case  6: 
3455     if (sign)
3456       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3457     else
3458       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3459   case  7: return ConstantInt::getTrue(*Context);
3460   }
3461 }
3462
3463 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3464 /// opcode and two operands into either a FCmp instruction. isordered is passed
3465 /// in to determine which kind of predicate to use in the new fcmp instruction.
3466 static Value *getFCmpValue(bool isordered, unsigned code,
3467                            Value *LHS, Value *RHS, LLVMContext *Context) {
3468   switch (code) {
3469   default: llvm_unreachable("Illegal FCmp code!");
3470   case  0:
3471     if (isordered)
3472       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3473     else
3474       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3475   case  1: 
3476     if (isordered)
3477       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3478     else
3479       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3480   case  2: 
3481     if (isordered)
3482       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3483     else
3484       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3485   case  3: 
3486     if (isordered)
3487       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3488     else
3489       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3490   case  4: 
3491     if (isordered)
3492       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3493     else
3494       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3495   case  5: 
3496     if (isordered)
3497       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3498     else
3499       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3500   case  6: 
3501     if (isordered)
3502       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3503     else
3504       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3505   case  7: return ConstantInt::getTrue(*Context);
3506   }
3507 }
3508
3509 /// PredicatesFoldable - Return true if both predicates match sign or if at
3510 /// least one of them is an equality comparison (which is signless).
3511 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3512   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3513          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3514          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3515 }
3516
3517 namespace { 
3518 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3519 struct FoldICmpLogical {
3520   InstCombiner &IC;
3521   Value *LHS, *RHS;
3522   ICmpInst::Predicate pred;
3523   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3524     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3525       pred(ICI->getPredicate()) {}
3526   bool shouldApply(Value *V) const {
3527     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3528       if (PredicatesFoldable(pred, ICI->getPredicate()))
3529         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3530                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3531     return false;
3532   }
3533   Instruction *apply(Instruction &Log) const {
3534     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3535     if (ICI->getOperand(0) != LHS) {
3536       assert(ICI->getOperand(1) == LHS);
3537       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3538     }
3539
3540     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3541     unsigned LHSCode = getICmpCode(ICI);
3542     unsigned RHSCode = getICmpCode(RHSICI);
3543     unsigned Code;
3544     switch (Log.getOpcode()) {
3545     case Instruction::And: Code = LHSCode & RHSCode; break;
3546     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3547     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3548     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3549     }
3550
3551     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3552                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3553       
3554     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3555     if (Instruction *I = dyn_cast<Instruction>(RV))
3556       return I;
3557     // Otherwise, it's a constant boolean value...
3558     return IC.ReplaceInstUsesWith(Log, RV);
3559   }
3560 };
3561 } // end anonymous namespace
3562
3563 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3564 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3565 // guaranteed to be a binary operator.
3566 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3567                                     ConstantInt *OpRHS,
3568                                     ConstantInt *AndRHS,
3569                                     BinaryOperator &TheAnd) {
3570   Value *X = Op->getOperand(0);
3571   Constant *Together = 0;
3572   if (!Op->isShift())
3573     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3574
3575   switch (Op->getOpcode()) {
3576   case Instruction::Xor:
3577     if (Op->hasOneUse()) {
3578       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3579       Value *And = Builder->CreateAnd(X, AndRHS);
3580       And->takeName(Op);
3581       return BinaryOperator::CreateXor(And, Together);
3582     }
3583     break;
3584   case Instruction::Or:
3585     if (Together == AndRHS) // (X | C) & C --> C
3586       return ReplaceInstUsesWith(TheAnd, AndRHS);
3587
3588     if (Op->hasOneUse() && Together != OpRHS) {
3589       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3590       Value *Or = Builder->CreateOr(X, Together);
3591       Or->takeName(Op);
3592       return BinaryOperator::CreateAnd(Or, AndRHS);
3593     }
3594     break;
3595   case Instruction::Add:
3596     if (Op->hasOneUse()) {
3597       // Adding a one to a single bit bit-field should be turned into an XOR
3598       // of the bit.  First thing to check is to see if this AND is with a
3599       // single bit constant.
3600       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3601
3602       // If there is only one bit set...
3603       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3604         // Ok, at this point, we know that we are masking the result of the
3605         // ADD down to exactly one bit.  If the constant we are adding has
3606         // no bits set below this bit, then we can eliminate the ADD.
3607         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3608
3609         // Check to see if any bits below the one bit set in AndRHSV are set.
3610         if ((AddRHS & (AndRHSV-1)) == 0) {
3611           // If not, the only thing that can effect the output of the AND is
3612           // the bit specified by AndRHSV.  If that bit is set, the effect of
3613           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3614           // no effect.
3615           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3616             TheAnd.setOperand(0, X);
3617             return &TheAnd;
3618           } else {
3619             // Pull the XOR out of the AND.
3620             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3621             NewAnd->takeName(Op);
3622             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3623           }
3624         }
3625       }
3626     }
3627     break;
3628
3629   case Instruction::Shl: {
3630     // We know that the AND will not produce any of the bits shifted in, so if
3631     // the anded constant includes them, clear them now!
3632     //
3633     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3634     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3635     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3636     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3637
3638     if (CI->getValue() == ShlMask) { 
3639     // Masking out bits that the shift already masks
3640       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3641     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3642       TheAnd.setOperand(1, CI);
3643       return &TheAnd;
3644     }
3645     break;
3646   }
3647   case Instruction::LShr:
3648   {
3649     // We know that the AND will not produce any of the bits shifted in, so if
3650     // the anded constant includes them, clear them now!  This only applies to
3651     // unsigned shifts, because a signed shr may bring in set bits!
3652     //
3653     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3654     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3655     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3656     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3657
3658     if (CI->getValue() == ShrMask) {   
3659     // Masking out bits that the shift already masks.
3660       return ReplaceInstUsesWith(TheAnd, Op);
3661     } else if (CI != AndRHS) {
3662       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3663       return &TheAnd;
3664     }
3665     break;
3666   }
3667   case Instruction::AShr:
3668     // Signed shr.
3669     // See if this is shifting in some sign extension, then masking it out
3670     // with an and.
3671     if (Op->hasOneUse()) {
3672       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3673       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3674       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3675       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3676       if (C == AndRHS) {          // Masking out bits shifted in.
3677         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3678         // Make the argument unsigned.
3679         Value *ShVal = Op->getOperand(0);
3680         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3681         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3682       }
3683     }
3684     break;
3685   }
3686   return 0;
3687 }
3688
3689
3690 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3691 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3692 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3693 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3694 /// insert new instructions.
3695 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3696                                            bool isSigned, bool Inside, 
3697                                            Instruction &IB) {
3698   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3699             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3700          "Lo is not <= Hi in range emission code!");
3701     
3702   if (Inside) {
3703     if (Lo == Hi)  // Trivially false.
3704       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3705
3706     // V >= Min && V < Hi --> V < Hi
3707     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3708       ICmpInst::Predicate pred = (isSigned ? 
3709         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3710       return new ICmpInst(pred, V, Hi);
3711     }
3712
3713     // Emit V-Lo <u Hi-Lo
3714     Constant *NegLo = ConstantExpr::getNeg(Lo);
3715     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3716     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3717     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3718   }
3719
3720   if (Lo == Hi)  // Trivially true.
3721     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3722
3723   // V < Min || V >= Hi -> V > Hi-1
3724   Hi = SubOne(cast<ConstantInt>(Hi));
3725   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3726     ICmpInst::Predicate pred = (isSigned ? 
3727         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3728     return new ICmpInst(pred, V, Hi);
3729   }
3730
3731   // Emit V-Lo >u Hi-1-Lo
3732   // Note that Hi has already had one subtracted from it, above.
3733   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3734   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3735   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3736   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3737 }
3738
3739 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3740 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3741 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3742 // not, since all 1s are not contiguous.
3743 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3744   const APInt& V = Val->getValue();
3745   uint32_t BitWidth = Val->getType()->getBitWidth();
3746   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3747
3748   // look for the first zero bit after the run of ones
3749   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3750   // look for the first non-zero bit
3751   ME = V.getActiveBits(); 
3752   return true;
3753 }
3754
3755 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3756 /// where isSub determines whether the operator is a sub.  If we can fold one of
3757 /// the following xforms:
3758 /// 
3759 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3760 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3761 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3762 ///
3763 /// return (A +/- B).
3764 ///
3765 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3766                                         ConstantInt *Mask, bool isSub,
3767                                         Instruction &I) {
3768   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3769   if (!LHSI || LHSI->getNumOperands() != 2 ||
3770       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3771
3772   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3773
3774   switch (LHSI->getOpcode()) {
3775   default: return 0;
3776   case Instruction::And:
3777     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3778       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3779       if ((Mask->getValue().countLeadingZeros() + 
3780            Mask->getValue().countPopulation()) == 
3781           Mask->getValue().getBitWidth())
3782         break;
3783
3784       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3785       // part, we don't need any explicit masks to take them out of A.  If that
3786       // is all N is, ignore it.
3787       uint32_t MB = 0, ME = 0;
3788       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3789         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3790         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3791         if (MaskedValueIsZero(RHS, Mask))
3792           break;
3793       }
3794     }
3795     return 0;
3796   case Instruction::Or:
3797   case Instruction::Xor:
3798     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3799     if ((Mask->getValue().countLeadingZeros() + 
3800          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3801         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3802       break;
3803     return 0;
3804   }
3805   
3806   if (isSub)
3807     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3808   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3809 }
3810
3811 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3812 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3813                                           ICmpInst *LHS, ICmpInst *RHS) {
3814   Value *Val, *Val2;
3815   ConstantInt *LHSCst, *RHSCst;
3816   ICmpInst::Predicate LHSCC, RHSCC;
3817   
3818   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3819   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3820                          m_ConstantInt(LHSCst))) ||
3821       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3822                          m_ConstantInt(RHSCst))))
3823     return 0;
3824   
3825   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3826   // where C is a power of 2
3827   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3828       LHSCst->getValue().isPowerOf2()) {
3829     Value *NewOr = Builder->CreateOr(Val, Val2);
3830     return new ICmpInst(LHSCC, NewOr, LHSCst);
3831   }
3832   
3833   // From here on, we only handle:
3834   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3835   if (Val != Val2) return 0;
3836   
3837   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3838   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3839       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3840       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3841       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3842     return 0;
3843   
3844   // We can't fold (ugt x, C) & (sgt x, C2).
3845   if (!PredicatesFoldable(LHSCC, RHSCC))
3846     return 0;
3847     
3848   // Ensure that the larger constant is on the RHS.
3849   bool ShouldSwap;
3850   if (ICmpInst::isSignedPredicate(LHSCC) ||
3851       (ICmpInst::isEquality(LHSCC) && 
3852        ICmpInst::isSignedPredicate(RHSCC)))
3853     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3854   else
3855     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3856     
3857   if (ShouldSwap) {
3858     std::swap(LHS, RHS);
3859     std::swap(LHSCst, RHSCst);
3860     std::swap(LHSCC, RHSCC);
3861   }
3862
3863   // At this point, we know we have have two icmp instructions
3864   // comparing a value against two constants and and'ing the result
3865   // together.  Because of the above check, we know that we only have
3866   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3867   // (from the FoldICmpLogical check above), that the two constants 
3868   // are not equal and that the larger constant is on the RHS
3869   assert(LHSCst != RHSCst && "Compares not folded above?");
3870
3871   switch (LHSCC) {
3872   default: llvm_unreachable("Unknown integer condition code!");
3873   case ICmpInst::ICMP_EQ:
3874     switch (RHSCC) {
3875     default: llvm_unreachable("Unknown integer condition code!");
3876     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3877     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3878     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3879       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3880     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3881     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3882     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3883       return ReplaceInstUsesWith(I, LHS);
3884     }
3885   case ICmpInst::ICMP_NE:
3886     switch (RHSCC) {
3887     default: llvm_unreachable("Unknown integer condition code!");
3888     case ICmpInst::ICMP_ULT:
3889       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3890         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3891       break;                        // (X != 13 & X u< 15) -> no change
3892     case ICmpInst::ICMP_SLT:
3893       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3894         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3895       break;                        // (X != 13 & X s< 15) -> no change
3896     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3897     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3898     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3899       return ReplaceInstUsesWith(I, RHS);
3900     case ICmpInst::ICMP_NE:
3901       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3902         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3903         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3904         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3905                             ConstantInt::get(Add->getType(), 1));
3906       }
3907       break;                        // (X != 13 & X != 15) -> no change
3908     }
3909     break;
3910   case ICmpInst::ICMP_ULT:
3911     switch (RHSCC) {
3912     default: llvm_unreachable("Unknown integer condition code!");
3913     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3914     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3915       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3916     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3917       break;
3918     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3919     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3920       return ReplaceInstUsesWith(I, LHS);
3921     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3922       break;
3923     }
3924     break;
3925   case ICmpInst::ICMP_SLT:
3926     switch (RHSCC) {
3927     default: llvm_unreachable("Unknown integer condition code!");
3928     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3929     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3930       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3931     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3932       break;
3933     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3934     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3935       return ReplaceInstUsesWith(I, LHS);
3936     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3937       break;
3938     }
3939     break;
3940   case ICmpInst::ICMP_UGT:
3941     switch (RHSCC) {
3942     default: llvm_unreachable("Unknown integer condition code!");
3943     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3944     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3945       return ReplaceInstUsesWith(I, RHS);
3946     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3947       break;
3948     case ICmpInst::ICMP_NE:
3949       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3950         return new ICmpInst(LHSCC, Val, RHSCst);
3951       break;                        // (X u> 13 & X != 15) -> no change
3952     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3953       return InsertRangeTest(Val, AddOne(LHSCst),
3954                              RHSCst, false, true, I);
3955     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3956       break;
3957     }
3958     break;
3959   case ICmpInst::ICMP_SGT:
3960     switch (RHSCC) {
3961     default: llvm_unreachable("Unknown integer condition code!");
3962     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3963     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3964       return ReplaceInstUsesWith(I, RHS);
3965     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3966       break;
3967     case ICmpInst::ICMP_NE:
3968       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3969         return new ICmpInst(LHSCC, Val, RHSCst);
3970       break;                        // (X s> 13 & X != 15) -> no change
3971     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3972       return InsertRangeTest(Val, AddOne(LHSCst),
3973                              RHSCst, true, true, I);
3974     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3975       break;
3976     }
3977     break;
3978   }
3979  
3980   return 0;
3981 }
3982
3983 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3984                                           FCmpInst *RHS) {
3985   
3986   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3987       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3988     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3989     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3990       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3991         // If either of the constants are nans, then the whole thing returns
3992         // false.
3993         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3994           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3995         return new FCmpInst(FCmpInst::FCMP_ORD,
3996                             LHS->getOperand(0), RHS->getOperand(0));
3997       }
3998     
3999     // Handle vector zeros.  This occurs because the canonical form of
4000     // "fcmp ord x,x" is "fcmp ord x, 0".
4001     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4002         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4003       return new FCmpInst(FCmpInst::FCMP_ORD,
4004                           LHS->getOperand(0), RHS->getOperand(0));
4005     return 0;
4006   }
4007   
4008   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4009   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4010   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4011   
4012   
4013   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4014     // Swap RHS operands to match LHS.
4015     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4016     std::swap(Op1LHS, Op1RHS);
4017   }
4018   
4019   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4020     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4021     if (Op0CC == Op1CC)
4022       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4023     
4024     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4025       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4026     if (Op0CC == FCmpInst::FCMP_TRUE)
4027       return ReplaceInstUsesWith(I, RHS);
4028     if (Op1CC == FCmpInst::FCMP_TRUE)
4029       return ReplaceInstUsesWith(I, LHS);
4030     
4031     bool Op0Ordered;
4032     bool Op1Ordered;
4033     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4034     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4035     if (Op1Pred == 0) {
4036       std::swap(LHS, RHS);
4037       std::swap(Op0Pred, Op1Pred);
4038       std::swap(Op0Ordered, Op1Ordered);
4039     }
4040     if (Op0Pred == 0) {
4041       // uno && ueq -> uno && (uno || eq) -> ueq
4042       // ord && olt -> ord && (ord && lt) -> olt
4043       if (Op0Ordered == Op1Ordered)
4044         return ReplaceInstUsesWith(I, RHS);
4045       
4046       // uno && oeq -> uno && (ord && eq) -> false
4047       // uno && ord -> false
4048       if (!Op0Ordered)
4049         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4050       // ord && ueq -> ord && (uno || eq) -> oeq
4051       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4052                                             Op0LHS, Op0RHS, Context));
4053     }
4054   }
4055
4056   return 0;
4057 }
4058
4059
4060 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4061   bool Changed = SimplifyCommutative(I);
4062   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4063
4064   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4065     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4066
4067   // and X, X = X
4068   if (Op0 == Op1)
4069     return ReplaceInstUsesWith(I, Op1);
4070
4071   // See if we can simplify any instructions used by the instruction whose sole 
4072   // purpose is to compute bits we don't care about.
4073   if (SimplifyDemandedInstructionBits(I))
4074     return &I;
4075   if (isa<VectorType>(I.getType())) {
4076     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4077       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4078         return ReplaceInstUsesWith(I, I.getOperand(0));
4079     } else if (isa<ConstantAggregateZero>(Op1)) {
4080       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4081     }
4082   }
4083
4084   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4085     const APInt &AndRHSMask = AndRHS->getValue();
4086     APInt NotAndRHS(~AndRHSMask);
4087
4088     // Optimize a variety of ((val OP C1) & C2) combinations...
4089     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4090       Value *Op0LHS = Op0I->getOperand(0);
4091       Value *Op0RHS = Op0I->getOperand(1);
4092       switch (Op0I->getOpcode()) {
4093       default: break;
4094       case Instruction::Xor:
4095       case Instruction::Or:
4096         // If the mask is only needed on one incoming arm, push it up.
4097         if (!Op0I->hasOneUse()) break;
4098           
4099         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4100           // Not masking anything out for the LHS, move to RHS.
4101           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4102                                              Op0RHS->getName()+".masked");
4103           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4104         }
4105         if (!isa<Constant>(Op0RHS) &&
4106             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4107           // Not masking anything out for the RHS, move to LHS.
4108           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4109                                              Op0LHS->getName()+".masked");
4110           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4111         }
4112
4113         break;
4114       case Instruction::Add:
4115         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4116         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4117         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4119           return BinaryOperator::CreateAnd(V, AndRHS);
4120         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4121           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4122         break;
4123
4124       case Instruction::Sub:
4125         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4126         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4127         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4129           return BinaryOperator::CreateAnd(V, AndRHS);
4130
4131         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4132         // has 1's for all bits that the subtraction with A might affect.
4133         if (Op0I->hasOneUse()) {
4134           uint32_t BitWidth = AndRHSMask.getBitWidth();
4135           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4136           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4137
4138           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4139           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4140               MaskedValueIsZero(Op0LHS, Mask)) {
4141             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4142             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4143           }
4144         }
4145         break;
4146
4147       case Instruction::Shl:
4148       case Instruction::LShr:
4149         // (1 << x) & 1 --> zext(x == 0)
4150         // (1 >> x) & 1 --> zext(x == 0)
4151         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4152           Value *NewICmp =
4153             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4154           return new ZExtInst(NewICmp, I.getType());
4155         }
4156         break;
4157       }
4158
4159       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4160         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4161           return Res;
4162     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4163       // If this is an integer truncation or change from signed-to-unsigned, and
4164       // if the source is an and/or with immediate, transform it.  This
4165       // frequently occurs for bitfield accesses.
4166       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4167         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4168             CastOp->getNumOperands() == 2)
4169           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4170             if (CastOp->getOpcode() == Instruction::And) {
4171               // Change: and (cast (and X, C1) to T), C2
4172               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4173               // This will fold the two constants together, which may allow 
4174               // other simplifications.
4175               Value *NewCast = Builder->CreateTruncOrBitCast(
4176                 CastOp->getOperand(0), I.getType(), 
4177                 CastOp->getName()+".shrunk");
4178               // trunc_or_bitcast(C1)&C2
4179               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4180               C3 = ConstantExpr::getAnd(C3, AndRHS);
4181               return BinaryOperator::CreateAnd(NewCast, C3);
4182             } else if (CastOp->getOpcode() == Instruction::Or) {
4183               // Change: and (cast (or X, C1) to T), C2
4184               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4185               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4186               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4187                 // trunc(C1)&C2
4188                 return ReplaceInstUsesWith(I, AndRHS);
4189             }
4190           }
4191       }
4192     }
4193
4194     // Try to fold constant and into select arguments.
4195     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4196       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4197         return R;
4198     if (isa<PHINode>(Op0))
4199       if (Instruction *NV = FoldOpIntoPhi(I))
4200         return NV;
4201   }
4202
4203   Value *Op0NotVal = dyn_castNotVal(Op0);
4204   Value *Op1NotVal = dyn_castNotVal(Op1);
4205
4206   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4207     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4208
4209   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4210   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4211     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4212                                   I.getName()+".demorgan");
4213     return BinaryOperator::CreateNot(Or);
4214   }
4215   
4216   {
4217     Value *A = 0, *B = 0, *C = 0, *D = 0;
4218     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4219       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4220         return ReplaceInstUsesWith(I, Op1);
4221     
4222       // (A|B) & ~(A&B) -> A^B
4223       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4224         if ((A == C && B == D) || (A == D && B == C))
4225           return BinaryOperator::CreateXor(A, B);
4226       }
4227     }
4228     
4229     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4230       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4231         return ReplaceInstUsesWith(I, Op0);
4232
4233       // ~(A&B) & (A|B) -> A^B
4234       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4235         if ((A == C && B == D) || (A == D && B == C))
4236           return BinaryOperator::CreateXor(A, B);
4237       }
4238     }
4239     
4240     if (Op0->hasOneUse() &&
4241         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4242       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4243         I.swapOperands();     // Simplify below
4244         std::swap(Op0, Op1);
4245       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4246         cast<BinaryOperator>(Op0)->swapOperands();
4247         I.swapOperands();     // Simplify below
4248         std::swap(Op0, Op1);
4249       }
4250     }
4251
4252     if (Op1->hasOneUse() &&
4253         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4254       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4255         cast<BinaryOperator>(Op1)->swapOperands();
4256         std::swap(A, B);
4257       }
4258       if (A == Op0)                                // A&(A^B) -> A & ~B
4259         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4260     }
4261
4262     // (A&((~A)|B)) -> A&B
4263     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4264         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4265       return BinaryOperator::CreateAnd(A, Op1);
4266     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4267         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4268       return BinaryOperator::CreateAnd(A, Op0);
4269   }
4270   
4271   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4272     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4273     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4274       return R;
4275
4276     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4277       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4278         return Res;
4279   }
4280
4281   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4282   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4283     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4284       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4285         const Type *SrcTy = Op0C->getOperand(0)->getType();
4286         if (SrcTy == Op1C->getOperand(0)->getType() &&
4287             SrcTy->isIntOrIntVector() &&
4288             // Only do this if the casts both really cause code to be generated.
4289             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4290                               I.getType(), TD) &&
4291             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4292                               I.getType(), TD)) {
4293           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4294                                             Op1C->getOperand(0), I.getName());
4295           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4296         }
4297       }
4298     
4299   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4300   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4301     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4302       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4303           SI0->getOperand(1) == SI1->getOperand(1) &&
4304           (SI0->hasOneUse() || SI1->hasOneUse())) {
4305         Value *NewOp =
4306           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4307                              SI0->getName());
4308         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4309                                       SI1->getOperand(1));
4310       }
4311   }
4312
4313   // If and'ing two fcmp, try combine them into one.
4314   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4315     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4316       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4317         return Res;
4318   }
4319
4320   return Changed ? &I : 0;
4321 }
4322
4323 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4324 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4325 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4326 /// the expression came from the corresponding "byte swapped" byte in some other
4327 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4328 /// we know that the expression deposits the low byte of %X into the high byte
4329 /// of the bswap result and that all other bytes are zero.  This expression is
4330 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4331 /// match.
4332 ///
4333 /// This function returns true if the match was unsuccessful and false if so.
4334 /// On entry to the function the "OverallLeftShift" is a signed integer value
4335 /// indicating the number of bytes that the subexpression is later shifted.  For
4336 /// example, if the expression is later right shifted by 16 bits, the
4337 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4338 /// byte of ByteValues is actually being set.
4339 ///
4340 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4341 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4342 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4343 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4344 /// always in the local (OverallLeftShift) coordinate space.
4345 ///
4346 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4347                               SmallVector<Value*, 8> &ByteValues) {
4348   if (Instruction *I = dyn_cast<Instruction>(V)) {
4349     // If this is an or instruction, it may be an inner node of the bswap.
4350     if (I->getOpcode() == Instruction::Or) {
4351       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4352                                ByteValues) ||
4353              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4354                                ByteValues);
4355     }
4356   
4357     // If this is a logical shift by a constant multiple of 8, recurse with
4358     // OverallLeftShift and ByteMask adjusted.
4359     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4360       unsigned ShAmt = 
4361         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4362       // Ensure the shift amount is defined and of a byte value.
4363       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4364         return true;
4365
4366       unsigned ByteShift = ShAmt >> 3;
4367       if (I->getOpcode() == Instruction::Shl) {
4368         // X << 2 -> collect(X, +2)
4369         OverallLeftShift += ByteShift;
4370         ByteMask >>= ByteShift;
4371       } else {
4372         // X >>u 2 -> collect(X, -2)
4373         OverallLeftShift -= ByteShift;
4374         ByteMask <<= ByteShift;
4375         ByteMask &= (~0U >> (32-ByteValues.size()));
4376       }
4377
4378       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4379       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4380
4381       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4382                                ByteValues);
4383     }
4384
4385     // If this is a logical 'and' with a mask that clears bytes, clear the
4386     // corresponding bytes in ByteMask.
4387     if (I->getOpcode() == Instruction::And &&
4388         isa<ConstantInt>(I->getOperand(1))) {
4389       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4390       unsigned NumBytes = ByteValues.size();
4391       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4392       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4393       
4394       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4395         // If this byte is masked out by a later operation, we don't care what
4396         // the and mask is.
4397         if ((ByteMask & (1 << i)) == 0)
4398           continue;
4399         
4400         // If the AndMask is all zeros for this byte, clear the bit.
4401         APInt MaskB = AndMask & Byte;
4402         if (MaskB == 0) {
4403           ByteMask &= ~(1U << i);
4404           continue;
4405         }
4406         
4407         // If the AndMask is not all ones for this byte, it's not a bytezap.
4408         if (MaskB != Byte)
4409           return true;
4410
4411         // Otherwise, this byte is kept.
4412       }
4413
4414       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4415                                ByteValues);
4416     }
4417   }
4418   
4419   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4420   // the input value to the bswap.  Some observations: 1) if more than one byte
4421   // is demanded from this input, then it could not be successfully assembled
4422   // into a byteswap.  At least one of the two bytes would not be aligned with
4423   // their ultimate destination.
4424   if (!isPowerOf2_32(ByteMask)) return true;
4425   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4426   
4427   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4428   // is demanded, it needs to go into byte 0 of the result.  This means that the
4429   // byte needs to be shifted until it lands in the right byte bucket.  The
4430   // shift amount depends on the position: if the byte is coming from the high
4431   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4432   // low part, it must be shifted left.
4433   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4434   if (InputByteNo < ByteValues.size()/2) {
4435     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4436       return true;
4437   } else {
4438     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4439       return true;
4440   }
4441   
4442   // If the destination byte value is already defined, the values are or'd
4443   // together, which isn't a bswap (unless it's an or of the same bits).
4444   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4445     return true;
4446   ByteValues[DestByteNo] = V;
4447   return false;
4448 }
4449
4450 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4451 /// If so, insert the new bswap intrinsic and return it.
4452 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4453   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4454   if (!ITy || ITy->getBitWidth() % 16 || 
4455       // ByteMask only allows up to 32-byte values.
4456       ITy->getBitWidth() > 32*8) 
4457     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4458   
4459   /// ByteValues - For each byte of the result, we keep track of which value
4460   /// defines each byte.
4461   SmallVector<Value*, 8> ByteValues;
4462   ByteValues.resize(ITy->getBitWidth()/8);
4463     
4464   // Try to find all the pieces corresponding to the bswap.
4465   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4466   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4467     return 0;
4468   
4469   // Check to see if all of the bytes come from the same value.
4470   Value *V = ByteValues[0];
4471   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4472   
4473   // Check to make sure that all of the bytes come from the same value.
4474   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4475     if (ByteValues[i] != V)
4476       return 0;
4477   const Type *Tys[] = { ITy };
4478   Module *M = I.getParent()->getParent()->getParent();
4479   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4480   return CallInst::Create(F, V);
4481 }
4482
4483 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4484 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4485 /// we can simplify this expression to "cond ? C : D or B".
4486 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4487                                          Value *C, Value *D,
4488                                          LLVMContext *Context) {
4489   // If A is not a select of -1/0, this cannot match.
4490   Value *Cond = 0;
4491   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4492     return 0;
4493
4494   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4495   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4496     return SelectInst::Create(Cond, C, B);
4497   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4498     return SelectInst::Create(Cond, C, B);
4499   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4500   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4501     return SelectInst::Create(Cond, C, D);
4502   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4503     return SelectInst::Create(Cond, C, D);
4504   return 0;
4505 }
4506
4507 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4508 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4509                                          ICmpInst *LHS, ICmpInst *RHS) {
4510   Value *Val, *Val2;
4511   ConstantInt *LHSCst, *RHSCst;
4512   ICmpInst::Predicate LHSCC, RHSCC;
4513   
4514   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4515   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4516              m_ConstantInt(LHSCst))) ||
4517       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4518              m_ConstantInt(RHSCst))))
4519     return 0;
4520   
4521   // From here on, we only handle:
4522   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4523   if (Val != Val2) return 0;
4524   
4525   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4526   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4527       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4528       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4529       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4530     return 0;
4531   
4532   // We can't fold (ugt x, C) | (sgt x, C2).
4533   if (!PredicatesFoldable(LHSCC, RHSCC))
4534     return 0;
4535   
4536   // Ensure that the larger constant is on the RHS.
4537   bool ShouldSwap;
4538   if (ICmpInst::isSignedPredicate(LHSCC) ||
4539       (ICmpInst::isEquality(LHSCC) && 
4540        ICmpInst::isSignedPredicate(RHSCC)))
4541     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4542   else
4543     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4544   
4545   if (ShouldSwap) {
4546     std::swap(LHS, RHS);
4547     std::swap(LHSCst, RHSCst);
4548     std::swap(LHSCC, RHSCC);
4549   }
4550   
4551   // At this point, we know we have have two icmp instructions
4552   // comparing a value against two constants and or'ing the result
4553   // together.  Because of the above check, we know that we only have
4554   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4555   // FoldICmpLogical check above), that the two constants are not
4556   // equal.
4557   assert(LHSCst != RHSCst && "Compares not folded above?");
4558
4559   switch (LHSCC) {
4560   default: llvm_unreachable("Unknown integer condition code!");
4561   case ICmpInst::ICMP_EQ:
4562     switch (RHSCC) {
4563     default: llvm_unreachable("Unknown integer condition code!");
4564     case ICmpInst::ICMP_EQ:
4565       if (LHSCst == SubOne(RHSCst)) {
4566         // (X == 13 | X == 14) -> X-13 <u 2
4567         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4568         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4569         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4570         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4571       }
4572       break;                         // (X == 13 | X == 15) -> no change
4573     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4574     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4575       break;
4576     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4577     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4578     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4579       return ReplaceInstUsesWith(I, RHS);
4580     }
4581     break;
4582   case ICmpInst::ICMP_NE:
4583     switch (RHSCC) {
4584     default: llvm_unreachable("Unknown integer condition code!");
4585     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4586     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4587     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4588       return ReplaceInstUsesWith(I, LHS);
4589     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4590     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4591     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4592       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4593     }
4594     break;
4595   case ICmpInst::ICMP_ULT:
4596     switch (RHSCC) {
4597     default: llvm_unreachable("Unknown integer condition code!");
4598     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4599       break;
4600     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4601       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4602       // this can cause overflow.
4603       if (RHSCst->isMaxValue(false))
4604         return ReplaceInstUsesWith(I, LHS);
4605       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4606                              false, false, I);
4607     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4608       break;
4609     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4610     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4611       return ReplaceInstUsesWith(I, RHS);
4612     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4613       break;
4614     }
4615     break;
4616   case ICmpInst::ICMP_SLT:
4617     switch (RHSCC) {
4618     default: llvm_unreachable("Unknown integer condition code!");
4619     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4620       break;
4621     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4622       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4623       // this can cause overflow.
4624       if (RHSCst->isMaxValue(true))
4625         return ReplaceInstUsesWith(I, LHS);
4626       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4627                              true, false, I);
4628     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4629       break;
4630     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4631     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4632       return ReplaceInstUsesWith(I, RHS);
4633     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4634       break;
4635     }
4636     break;
4637   case ICmpInst::ICMP_UGT:
4638     switch (RHSCC) {
4639     default: llvm_unreachable("Unknown integer condition code!");
4640     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4641     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4642       return ReplaceInstUsesWith(I, LHS);
4643     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4644       break;
4645     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4646     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4647       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4648     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4649       break;
4650     }
4651     break;
4652   case ICmpInst::ICMP_SGT:
4653     switch (RHSCC) {
4654     default: llvm_unreachable("Unknown integer condition code!");
4655     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4656     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4657       return ReplaceInstUsesWith(I, LHS);
4658     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4659       break;
4660     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4661     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4662       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4663     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4664       break;
4665     }
4666     break;
4667   }
4668   return 0;
4669 }
4670
4671 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4672                                          FCmpInst *RHS) {
4673   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4674       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4675       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4676     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4677       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4678         // If either of the constants are nans, then the whole thing returns
4679         // true.
4680         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4681           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4682         
4683         // Otherwise, no need to compare the two constants, compare the
4684         // rest.
4685         return new FCmpInst(FCmpInst::FCMP_UNO,
4686                             LHS->getOperand(0), RHS->getOperand(0));
4687       }
4688     
4689     // Handle vector zeros.  This occurs because the canonical form of
4690     // "fcmp uno x,x" is "fcmp uno x, 0".
4691     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4692         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4693       return new FCmpInst(FCmpInst::FCMP_UNO,
4694                           LHS->getOperand(0), RHS->getOperand(0));
4695     
4696     return 0;
4697   }
4698   
4699   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4700   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4701   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4702   
4703   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4704     // Swap RHS operands to match LHS.
4705     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4706     std::swap(Op1LHS, Op1RHS);
4707   }
4708   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4709     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4710     if (Op0CC == Op1CC)
4711       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4712                           Op0LHS, Op0RHS);
4713     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4714       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4715     if (Op0CC == FCmpInst::FCMP_FALSE)
4716       return ReplaceInstUsesWith(I, RHS);
4717     if (Op1CC == FCmpInst::FCMP_FALSE)
4718       return ReplaceInstUsesWith(I, LHS);
4719     bool Op0Ordered;
4720     bool Op1Ordered;
4721     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4722     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4723     if (Op0Ordered == Op1Ordered) {
4724       // If both are ordered or unordered, return a new fcmp with
4725       // or'ed predicates.
4726       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4727                                Op0LHS, Op0RHS, Context);
4728       if (Instruction *I = dyn_cast<Instruction>(RV))
4729         return I;
4730       // Otherwise, it's a constant boolean value...
4731       return ReplaceInstUsesWith(I, RV);
4732     }
4733   }
4734   return 0;
4735 }
4736
4737 /// FoldOrWithConstants - This helper function folds:
4738 ///
4739 ///     ((A | B) & C1) | (B & C2)
4740 ///
4741 /// into:
4742 /// 
4743 ///     (A & C1) | B
4744 ///
4745 /// when the XOR of the two constants is "all ones" (-1).
4746 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4747                                                Value *A, Value *B, Value *C) {
4748   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4749   if (!CI1) return 0;
4750
4751   Value *V1 = 0;
4752   ConstantInt *CI2 = 0;
4753   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4754
4755   APInt Xor = CI1->getValue() ^ CI2->getValue();
4756   if (!Xor.isAllOnesValue()) return 0;
4757
4758   if (V1 == A || V1 == B) {
4759     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4760     return BinaryOperator::CreateOr(NewOp, V1);
4761   }
4762
4763   return 0;
4764 }
4765
4766 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4767   bool Changed = SimplifyCommutative(I);
4768   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4769
4770   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4771     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4772
4773   // or X, X = X
4774   if (Op0 == Op1)
4775     return ReplaceInstUsesWith(I, Op0);
4776
4777   // See if we can simplify any instructions used by the instruction whose sole 
4778   // purpose is to compute bits we don't care about.
4779   if (SimplifyDemandedInstructionBits(I))
4780     return &I;
4781   if (isa<VectorType>(I.getType())) {
4782     if (isa<ConstantAggregateZero>(Op1)) {
4783       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4784     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4785       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4786         return ReplaceInstUsesWith(I, I.getOperand(1));
4787     }
4788   }
4789
4790   // or X, -1 == -1
4791   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4792     ConstantInt *C1 = 0; Value *X = 0;
4793     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4794     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4795         isOnlyUse(Op0)) {
4796       Value *Or = Builder->CreateOr(X, RHS);
4797       Or->takeName(Op0);
4798       return BinaryOperator::CreateAnd(Or, 
4799                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4800     }
4801
4802     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4803     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4804         isOnlyUse(Op0)) {
4805       Value *Or = Builder->CreateOr(X, RHS);
4806       Or->takeName(Op0);
4807       return BinaryOperator::CreateXor(Or,
4808                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4809     }
4810
4811     // Try to fold constant and into select arguments.
4812     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4813       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4814         return R;
4815     if (isa<PHINode>(Op0))
4816       if (Instruction *NV = FoldOpIntoPhi(I))
4817         return NV;
4818   }
4819
4820   Value *A = 0, *B = 0;
4821   ConstantInt *C1 = 0, *C2 = 0;
4822
4823   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4824     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4825       return ReplaceInstUsesWith(I, Op1);
4826   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4827     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4828       return ReplaceInstUsesWith(I, Op0);
4829
4830   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4831   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4832   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4833       match(Op1, m_Or(m_Value(), m_Value())) ||
4834       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4835        match(Op1, m_Shift(m_Value(), m_Value())))) {
4836     if (Instruction *BSwap = MatchBSwap(I))
4837       return BSwap;
4838   }
4839   
4840   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4841   if (Op0->hasOneUse() &&
4842       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4843       MaskedValueIsZero(Op1, C1->getValue())) {
4844     Value *NOr = Builder->CreateOr(A, Op1);
4845     NOr->takeName(Op0);
4846     return BinaryOperator::CreateXor(NOr, C1);
4847   }
4848
4849   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4850   if (Op1->hasOneUse() &&
4851       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4852       MaskedValueIsZero(Op0, C1->getValue())) {
4853     Value *NOr = Builder->CreateOr(A, Op0);
4854     NOr->takeName(Op0);
4855     return BinaryOperator::CreateXor(NOr, C1);
4856   }
4857
4858   // (A & C)|(B & D)
4859   Value *C = 0, *D = 0;
4860   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4861       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4862     Value *V1 = 0, *V2 = 0, *V3 = 0;
4863     C1 = dyn_cast<ConstantInt>(C);
4864     C2 = dyn_cast<ConstantInt>(D);
4865     if (C1 && C2) {  // (A & C1)|(B & C2)
4866       // If we have: ((V + N) & C1) | (V & C2)
4867       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4868       // replace with V+N.
4869       if (C1->getValue() == ~C2->getValue()) {
4870         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4871             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4872           // Add commutes, try both ways.
4873           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4874             return ReplaceInstUsesWith(I, A);
4875           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4876             return ReplaceInstUsesWith(I, A);
4877         }
4878         // Or commutes, try both ways.
4879         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4880             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4881           // Add commutes, try both ways.
4882           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4883             return ReplaceInstUsesWith(I, B);
4884           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4885             return ReplaceInstUsesWith(I, B);
4886         }
4887       }
4888       V1 = 0; V2 = 0; V3 = 0;
4889     }
4890     
4891     // Check to see if we have any common things being and'ed.  If so, find the
4892     // terms for V1 & (V2|V3).
4893     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4894       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4895         V1 = A, V2 = C, V3 = D;
4896       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4897         V1 = A, V2 = B, V3 = C;
4898       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4899         V1 = C, V2 = A, V3 = D;
4900       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4901         V1 = C, V2 = A, V3 = B;
4902       
4903       if (V1) {
4904         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4905         return BinaryOperator::CreateAnd(V1, Or);
4906       }
4907     }
4908
4909     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4910     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4911       return Match;
4912     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4913       return Match;
4914     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4915       return Match;
4916     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4917       return Match;
4918
4919     // ((A&~B)|(~A&B)) -> A^B
4920     if ((match(C, m_Not(m_Specific(D))) &&
4921          match(B, m_Not(m_Specific(A)))))
4922       return BinaryOperator::CreateXor(A, D);
4923     // ((~B&A)|(~A&B)) -> A^B
4924     if ((match(A, m_Not(m_Specific(D))) &&
4925          match(B, m_Not(m_Specific(C)))))
4926       return BinaryOperator::CreateXor(C, D);
4927     // ((A&~B)|(B&~A)) -> A^B
4928     if ((match(C, m_Not(m_Specific(B))) &&
4929          match(D, m_Not(m_Specific(A)))))
4930       return BinaryOperator::CreateXor(A, B);
4931     // ((~B&A)|(B&~A)) -> A^B
4932     if ((match(A, m_Not(m_Specific(B))) &&
4933          match(D, m_Not(m_Specific(C)))))
4934       return BinaryOperator::CreateXor(C, B);
4935   }
4936   
4937   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4938   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4939     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4940       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4941           SI0->getOperand(1) == SI1->getOperand(1) &&
4942           (SI0->hasOneUse() || SI1->hasOneUse())) {
4943         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4944                                          SI0->getName());
4945         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4946                                       SI1->getOperand(1));
4947       }
4948   }
4949
4950   // ((A|B)&1)|(B&-2) -> (A&1) | B
4951   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4952       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4953     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4954     if (Ret) return Ret;
4955   }
4956   // (B&-2)|((A|B)&1) -> (A&1) | B
4957   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4958       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4959     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4960     if (Ret) return Ret;
4961   }
4962
4963   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4964     if (A == Op1)   // ~A | A == -1
4965       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4966   } else {
4967     A = 0;
4968   }
4969   // Note, A is still live here!
4970   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4971     if (Op0 == B)
4972       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4973
4974     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4975     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4976       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4977       return BinaryOperator::CreateNot(And);
4978     }
4979   }
4980
4981   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4982   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4983     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4984       return R;
4985
4986     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4987       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4988         return Res;
4989   }
4990     
4991   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4992   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4993     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4994       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4995         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4996             !isa<ICmpInst>(Op1C->getOperand(0))) {
4997           const Type *SrcTy = Op0C->getOperand(0)->getType();
4998           if (SrcTy == Op1C->getOperand(0)->getType() &&
4999               SrcTy->isIntOrIntVector() &&
5000               // Only do this if the casts both really cause code to be
5001               // generated.
5002               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5003                                 I.getType(), TD) &&
5004               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5005                                 I.getType(), TD)) {
5006             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5007                                              Op1C->getOperand(0), I.getName());
5008             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5009           }
5010         }
5011       }
5012   }
5013   
5014     
5015   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5016   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5017     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5018       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5019         return Res;
5020   }
5021
5022   return Changed ? &I : 0;
5023 }
5024
5025 namespace {
5026
5027 // XorSelf - Implements: X ^ X --> 0
5028 struct XorSelf {
5029   Value *RHS;
5030   XorSelf(Value *rhs) : RHS(rhs) {}
5031   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5032   Instruction *apply(BinaryOperator &Xor) const {
5033     return &Xor;
5034   }
5035 };
5036
5037 }
5038
5039 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5040   bool Changed = SimplifyCommutative(I);
5041   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5042
5043   if (isa<UndefValue>(Op1)) {
5044     if (isa<UndefValue>(Op0))
5045       // Handle undef ^ undef -> 0 special case. This is a common
5046       // idiom (misuse).
5047       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5048     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5049   }
5050
5051   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5052   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5053     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5054     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5055   }
5056   
5057   // See if we can simplify any instructions used by the instruction whose sole 
5058   // purpose is to compute bits we don't care about.
5059   if (SimplifyDemandedInstructionBits(I))
5060     return &I;
5061   if (isa<VectorType>(I.getType()))
5062     if (isa<ConstantAggregateZero>(Op1))
5063       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5064
5065   // Is this a ~ operation?
5066   if (Value *NotOp = dyn_castNotVal(&I)) {
5067     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5068     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5069     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5070       if (Op0I->getOpcode() == Instruction::And || 
5071           Op0I->getOpcode() == Instruction::Or) {
5072         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5073         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5074           Value *NotY =
5075             Builder->CreateNot(Op0I->getOperand(1),
5076                                Op0I->getOperand(1)->getName()+".not");
5077           if (Op0I->getOpcode() == Instruction::And)
5078             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5079           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5080         }
5081       }
5082     }
5083   }
5084   
5085   
5086   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5087     if (RHS->isOne() && Op0->hasOneUse()) {
5088       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5089       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5090         return new ICmpInst(ICI->getInversePredicate(),
5091                             ICI->getOperand(0), ICI->getOperand(1));
5092
5093       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5094         return new FCmpInst(FCI->getInversePredicate(),
5095                             FCI->getOperand(0), FCI->getOperand(1));
5096     }
5097
5098     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5099     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5100       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5101         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5102           Instruction::CastOps Opcode = Op0C->getOpcode();
5103           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5104               (RHS == ConstantExpr::getCast(Opcode, 
5105                                             ConstantInt::getTrue(*Context),
5106                                             Op0C->getDestTy()))) {
5107             CI->setPredicate(CI->getInversePredicate());
5108             return CastInst::Create(Opcode, CI, Op0C->getType());
5109           }
5110         }
5111       }
5112     }
5113
5114     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5115       // ~(c-X) == X-c-1 == X+(-c-1)
5116       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5117         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5118           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5119           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5120                                       ConstantInt::get(I.getType(), 1));
5121           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5122         }
5123           
5124       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5125         if (Op0I->getOpcode() == Instruction::Add) {
5126           // ~(X-c) --> (-c-1)-X
5127           if (RHS->isAllOnesValue()) {
5128             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5129             return BinaryOperator::CreateSub(
5130                            ConstantExpr::getSub(NegOp0CI,
5131                                       ConstantInt::get(I.getType(), 1)),
5132                                       Op0I->getOperand(0));
5133           } else if (RHS->getValue().isSignBit()) {
5134             // (X + C) ^ signbit -> (X + C + signbit)
5135             Constant *C = ConstantInt::get(*Context,
5136                                            RHS->getValue() + Op0CI->getValue());
5137             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5138
5139           }
5140         } else if (Op0I->getOpcode() == Instruction::Or) {
5141           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5142           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5143             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5144             // Anything in both C1 and C2 is known to be zero, remove it from
5145             // NewRHS.
5146             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5147             NewRHS = ConstantExpr::getAnd(NewRHS, 
5148                                        ConstantExpr::getNot(CommonBits));
5149             Worklist.Add(Op0I);
5150             I.setOperand(0, Op0I->getOperand(0));
5151             I.setOperand(1, NewRHS);
5152             return &I;
5153           }
5154         }
5155       }
5156     }
5157
5158     // Try to fold constant and into select arguments.
5159     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5160       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5161         return R;
5162     if (isa<PHINode>(Op0))
5163       if (Instruction *NV = FoldOpIntoPhi(I))
5164         return NV;
5165   }
5166
5167   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5168     if (X == Op1)
5169       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5170
5171   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5172     if (X == Op0)
5173       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5174
5175   
5176   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5177   if (Op1I) {
5178     Value *A, *B;
5179     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5180       if (A == Op0) {              // B^(B|A) == (A|B)^B
5181         Op1I->swapOperands();
5182         I.swapOperands();
5183         std::swap(Op0, Op1);
5184       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5185         I.swapOperands();     // Simplified below.
5186         std::swap(Op0, Op1);
5187       }
5188     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5189       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5190     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5191       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5192     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5193                Op1I->hasOneUse()){
5194       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5195         Op1I->swapOperands();
5196         std::swap(A, B);
5197       }
5198       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5199         I.swapOperands();     // Simplified below.
5200         std::swap(Op0, Op1);
5201       }
5202     }
5203   }
5204   
5205   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5206   if (Op0I) {
5207     Value *A, *B;
5208     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5209         Op0I->hasOneUse()) {
5210       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5211         std::swap(A, B);
5212       if (B == Op1)                                  // (A|B)^B == A & ~B
5213         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5214     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5215       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5216     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5217       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5218     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5219                Op0I->hasOneUse()){
5220       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5221         std::swap(A, B);
5222       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5223           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5224         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5225       }
5226     }
5227   }
5228   
5229   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5230   if (Op0I && Op1I && Op0I->isShift() && 
5231       Op0I->getOpcode() == Op1I->getOpcode() && 
5232       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5234     Value *NewOp =
5235       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5236                          Op0I->getName());
5237     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5238                                   Op1I->getOperand(1));
5239   }
5240     
5241   if (Op0I && Op1I) {
5242     Value *A, *B, *C, *D;
5243     // (A & B)^(A | B) -> A ^ B
5244     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5245         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5246       if ((A == C && B == D) || (A == D && B == C)) 
5247         return BinaryOperator::CreateXor(A, B);
5248     }
5249     // (A | B)^(A & B) -> A ^ B
5250     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5251         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5252       if ((A == C && B == D) || (A == D && B == C)) 
5253         return BinaryOperator::CreateXor(A, B);
5254     }
5255     
5256     // (A & B)^(C & D)
5257     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5258         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5259         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5260       // (X & Y)^(X & Y) -> (Y^Z) & X
5261       Value *X = 0, *Y = 0, *Z = 0;
5262       if (A == C)
5263         X = A, Y = B, Z = D;
5264       else if (A == D)
5265         X = A, Y = B, Z = C;
5266       else if (B == C)
5267         X = B, Y = A, Z = D;
5268       else if (B == D)
5269         X = B, Y = A, Z = C;
5270       
5271       if (X) {
5272         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5273         return BinaryOperator::CreateAnd(NewOp, X);
5274       }
5275     }
5276   }
5277     
5278   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5280     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5281       return R;
5282
5283   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5284   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5285     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5286       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287         const Type *SrcTy = Op0C->getOperand(0)->getType();
5288         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5289             // Only do this if the casts both really cause code to be generated.
5290             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5291                               I.getType(), TD) &&
5292             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5293                               I.getType(), TD)) {
5294           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5295                                             Op1C->getOperand(0), I.getName());
5296           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5297         }
5298       }
5299   }
5300
5301   return Changed ? &I : 0;
5302 }
5303
5304 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5305                                    LLVMContext *Context) {
5306   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5307 }
5308
5309 static bool HasAddOverflow(ConstantInt *Result,
5310                            ConstantInt *In1, ConstantInt *In2,
5311                            bool IsSigned) {
5312   if (IsSigned)
5313     if (In2->getValue().isNegative())
5314       return Result->getValue().sgt(In1->getValue());
5315     else
5316       return Result->getValue().slt(In1->getValue());
5317   else
5318     return Result->getValue().ult(In1->getValue());
5319 }
5320
5321 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5322 /// overflowed for this type.
5323 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5324                             Constant *In2, LLVMContext *Context,
5325                             bool IsSigned = false) {
5326   Result = ConstantExpr::getAdd(In1, In2);
5327
5328   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5329     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5330       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5331       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5332                          ExtractElement(In1, Idx, Context),
5333                          ExtractElement(In2, Idx, Context),
5334                          IsSigned))
5335         return true;
5336     }
5337     return false;
5338   }
5339
5340   return HasAddOverflow(cast<ConstantInt>(Result),
5341                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5342                         IsSigned);
5343 }
5344
5345 static bool HasSubOverflow(ConstantInt *Result,
5346                            ConstantInt *In1, ConstantInt *In2,
5347                            bool IsSigned) {
5348   if (IsSigned)
5349     if (In2->getValue().isNegative())
5350       return Result->getValue().slt(In1->getValue());
5351     else
5352       return Result->getValue().sgt(In1->getValue());
5353   else
5354     return Result->getValue().ugt(In1->getValue());
5355 }
5356
5357 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5358 /// overflowed for this type.
5359 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5360                             Constant *In2, LLVMContext *Context,
5361                             bool IsSigned = false) {
5362   Result = ConstantExpr::getSub(In1, In2);
5363
5364   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5365     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5366       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5367       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5368                          ExtractElement(In1, Idx, Context),
5369                          ExtractElement(In2, Idx, Context),
5370                          IsSigned))
5371         return true;
5372     }
5373     return false;
5374   }
5375
5376   return HasSubOverflow(cast<ConstantInt>(Result),
5377                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5378                         IsSigned);
5379 }
5380
5381 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5382 /// code necessary to compute the offset from the base pointer (without adding
5383 /// in the base pointer).  Return the result as a signed integer of intptr size.
5384 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5385   TargetData &TD = *IC.getTargetData();
5386   gep_type_iterator GTI = gep_type_begin(GEP);
5387   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5388   Value *Result = Constant::getNullValue(IntPtrTy);
5389
5390   // Build a mask for high order bits.
5391   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5392   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5393
5394   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5395        ++i, ++GTI) {
5396     Value *Op = *i;
5397     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5398     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5399       if (OpC->isZero()) continue;
5400       
5401       // Handle a struct index, which adds its field offset to the pointer.
5402       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5403         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5404         
5405         Result = IC.Builder->CreateAdd(Result,
5406                                        ConstantInt::get(IntPtrTy, Size),
5407                                        GEP->getName()+".offs");
5408         continue;
5409       }
5410       
5411       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5412       Constant *OC =
5413               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5414       Scale = ConstantExpr::getMul(OC, Scale);
5415       // Emit an add instruction.
5416       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5417       continue;
5418     }
5419     // Convert to correct type.
5420     if (Op->getType() != IntPtrTy)
5421       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5422     if (Size != 1) {
5423       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5424       // We'll let instcombine(mul) convert this to a shl if possible.
5425       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5426     }
5427
5428     // Emit an add instruction.
5429     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5430   }
5431   return Result;
5432 }
5433
5434
5435 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5436 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5437 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5438 /// be complex, and scales are involved.  The above expression would also be
5439 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5440 /// This later form is less amenable to optimization though, and we are allowed
5441 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5442 ///
5443 /// If we can't emit an optimized form for this expression, this returns null.
5444 /// 
5445 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5446                                           InstCombiner &IC) {
5447   TargetData &TD = *IC.getTargetData();
5448   gep_type_iterator GTI = gep_type_begin(GEP);
5449
5450   // Check to see if this gep only has a single variable index.  If so, and if
5451   // any constant indices are a multiple of its scale, then we can compute this
5452   // in terms of the scale of the variable index.  For example, if the GEP
5453   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5454   // because the expression will cross zero at the same point.
5455   unsigned i, e = GEP->getNumOperands();
5456   int64_t Offset = 0;
5457   for (i = 1; i != e; ++i, ++GTI) {
5458     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5459       // Compute the aggregate offset of constant indices.
5460       if (CI->isZero()) continue;
5461
5462       // Handle a struct index, which adds its field offset to the pointer.
5463       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5464         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5465       } else {
5466         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5467         Offset += Size*CI->getSExtValue();
5468       }
5469     } else {
5470       // Found our variable index.
5471       break;
5472     }
5473   }
5474   
5475   // If there are no variable indices, we must have a constant offset, just
5476   // evaluate it the general way.
5477   if (i == e) return 0;
5478   
5479   Value *VariableIdx = GEP->getOperand(i);
5480   // Determine the scale factor of the variable element.  For example, this is
5481   // 4 if the variable index is into an array of i32.
5482   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5483   
5484   // Verify that there are no other variable indices.  If so, emit the hard way.
5485   for (++i, ++GTI; i != e; ++i, ++GTI) {
5486     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5487     if (!CI) return 0;
5488    
5489     // Compute the aggregate offset of constant indices.
5490     if (CI->isZero()) continue;
5491     
5492     // Handle a struct index, which adds its field offset to the pointer.
5493     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5494       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5495     } else {
5496       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5497       Offset += Size*CI->getSExtValue();
5498     }
5499   }
5500   
5501   // Okay, we know we have a single variable index, which must be a
5502   // pointer/array/vector index.  If there is no offset, life is simple, return
5503   // the index.
5504   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5505   if (Offset == 0) {
5506     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5507     // we don't need to bother extending: the extension won't affect where the
5508     // computation crosses zero.
5509     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5510       VariableIdx = new TruncInst(VariableIdx, 
5511                                   TD.getIntPtrType(VariableIdx->getContext()),
5512                                   VariableIdx->getName(), &I);
5513     return VariableIdx;
5514   }
5515   
5516   // Otherwise, there is an index.  The computation we will do will be modulo
5517   // the pointer size, so get it.
5518   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5519   
5520   Offset &= PtrSizeMask;
5521   VariableScale &= PtrSizeMask;
5522
5523   // To do this transformation, any constant index must be a multiple of the
5524   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5525   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5526   // multiple of the variable scale.
5527   int64_t NewOffs = Offset / (int64_t)VariableScale;
5528   if (Offset != NewOffs*(int64_t)VariableScale)
5529     return 0;
5530
5531   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5532   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5533   if (VariableIdx->getType() != IntPtrTy)
5534     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5535                                               true /*SExt*/, 
5536                                               VariableIdx->getName(), &I);
5537   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5538   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5539 }
5540
5541
5542 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5543 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5544 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5545                                        ICmpInst::Predicate Cond,
5546                                        Instruction &I) {
5547   // Look through bitcasts.
5548   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5549     RHS = BCI->getOperand(0);
5550
5551   Value *PtrBase = GEPLHS->getOperand(0);
5552   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5553     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5554     // This transformation (ignoring the base and scales) is valid because we
5555     // know pointers can't overflow since the gep is inbounds.  See if we can
5556     // output an optimized form.
5557     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5558     
5559     // If not, synthesize the offset the hard way.
5560     if (Offset == 0)
5561       Offset = EmitGEPOffset(GEPLHS, I, *this);
5562     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5563                         Constant::getNullValue(Offset->getType()));
5564   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5565     // If the base pointers are different, but the indices are the same, just
5566     // compare the base pointer.
5567     if (PtrBase != GEPRHS->getOperand(0)) {
5568       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5569       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5570                         GEPRHS->getOperand(0)->getType();
5571       if (IndicesTheSame)
5572         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5573           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5574             IndicesTheSame = false;
5575             break;
5576           }
5577
5578       // If all indices are the same, just compare the base pointers.
5579       if (IndicesTheSame)
5580         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5581                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5582
5583       // Otherwise, the base pointers are different and the indices are
5584       // different, bail out.
5585       return 0;
5586     }
5587
5588     // If one of the GEPs has all zero indices, recurse.
5589     bool AllZeros = true;
5590     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5592           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5593         AllZeros = false;
5594         break;
5595       }
5596     if (AllZeros)
5597       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5598                           ICmpInst::getSwappedPredicate(Cond), I);
5599
5600     // If the other GEP has all zero indices, recurse.
5601     AllZeros = true;
5602     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5603       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5604           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5605         AllZeros = false;
5606         break;
5607       }
5608     if (AllZeros)
5609       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5610
5611     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5612       // If the GEPs only differ by one index, compare it.
5613       unsigned NumDifferences = 0;  // Keep track of # differences.
5614       unsigned DiffOperand = 0;     // The operand that differs.
5615       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5616         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5617           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5618                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5619             // Irreconcilable differences.
5620             NumDifferences = 2;
5621             break;
5622           } else {
5623             if (NumDifferences++) break;
5624             DiffOperand = i;
5625           }
5626         }
5627
5628       if (NumDifferences == 0)   // SAME GEP?
5629         return ReplaceInstUsesWith(I, // No comparison is needed here.
5630                                    ConstantInt::get(Type::getInt1Ty(*Context),
5631                                              ICmpInst::isTrueWhenEqual(Cond)));
5632
5633       else if (NumDifferences == 1) {
5634         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5635         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5636         // Make sure we do a signed comparison here.
5637         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5638       }
5639     }
5640
5641     // Only lower this if the icmp is the only user of the GEP or if we expect
5642     // the result to fold to a constant!
5643     if (TD &&
5644         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5645         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5646       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5647       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5648       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5649       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5650     }
5651   }
5652   return 0;
5653 }
5654
5655 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5656 ///
5657 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5658                                                 Instruction *LHSI,
5659                                                 Constant *RHSC) {
5660   if (!isa<ConstantFP>(RHSC)) return 0;
5661   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5662   
5663   // Get the width of the mantissa.  We don't want to hack on conversions that
5664   // might lose information from the integer, e.g. "i64 -> float"
5665   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5666   if (MantissaWidth == -1) return 0;  // Unknown.
5667   
5668   // Check to see that the input is converted from an integer type that is small
5669   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5670   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5671   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5672   
5673   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5674   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5675   if (LHSUnsigned)
5676     ++InputSize;
5677   
5678   // If the conversion would lose info, don't hack on this.
5679   if ((int)InputSize > MantissaWidth)
5680     return 0;
5681   
5682   // Otherwise, we can potentially simplify the comparison.  We know that it
5683   // will always come through as an integer value and we know the constant is
5684   // not a NAN (it would have been previously simplified).
5685   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5686   
5687   ICmpInst::Predicate Pred;
5688   switch (I.getPredicate()) {
5689   default: llvm_unreachable("Unexpected predicate!");
5690   case FCmpInst::FCMP_UEQ:
5691   case FCmpInst::FCMP_OEQ:
5692     Pred = ICmpInst::ICMP_EQ;
5693     break;
5694   case FCmpInst::FCMP_UGT:
5695   case FCmpInst::FCMP_OGT:
5696     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5697     break;
5698   case FCmpInst::FCMP_UGE:
5699   case FCmpInst::FCMP_OGE:
5700     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5701     break;
5702   case FCmpInst::FCMP_ULT:
5703   case FCmpInst::FCMP_OLT:
5704     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5705     break;
5706   case FCmpInst::FCMP_ULE:
5707   case FCmpInst::FCMP_OLE:
5708     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5709     break;
5710   case FCmpInst::FCMP_UNE:
5711   case FCmpInst::FCMP_ONE:
5712     Pred = ICmpInst::ICMP_NE;
5713     break;
5714   case FCmpInst::FCMP_ORD:
5715     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5716   case FCmpInst::FCMP_UNO:
5717     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5718   }
5719   
5720   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5721   
5722   // Now we know that the APFloat is a normal number, zero or inf.
5723   
5724   // See if the FP constant is too large for the integer.  For example,
5725   // comparing an i8 to 300.0.
5726   unsigned IntWidth = IntTy->getScalarSizeInBits();
5727   
5728   if (!LHSUnsigned) {
5729     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5730     // and large values.
5731     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5732     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5733                           APFloat::rmNearestTiesToEven);
5734     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5735       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5736           Pred == ICmpInst::ICMP_SLE)
5737         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5738       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5739     }
5740   } else {
5741     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5742     // +INF and large values.
5743     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5744     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5745                           APFloat::rmNearestTiesToEven);
5746     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5747       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5748           Pred == ICmpInst::ICMP_ULE)
5749         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5750       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5751     }
5752   }
5753   
5754   if (!LHSUnsigned) {
5755     // See if the RHS value is < SignedMin.
5756     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5757     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5758                           APFloat::rmNearestTiesToEven);
5759     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5760       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5761           Pred == ICmpInst::ICMP_SGE)
5762         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5763       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5764     }
5765   }
5766
5767   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5768   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5769   // casting the FP value to the integer value and back, checking for equality.
5770   // Don't do this for zero, because -0.0 is not fractional.
5771   Constant *RHSInt = LHSUnsigned
5772     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5773     : ConstantExpr::getFPToSI(RHSC, IntTy);
5774   if (!RHS.isZero()) {
5775     bool Equal = LHSUnsigned
5776       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5777       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5778     if (!Equal) {
5779       // If we had a comparison against a fractional value, we have to adjust
5780       // the compare predicate and sometimes the value.  RHSC is rounded towards
5781       // zero at this point.
5782       switch (Pred) {
5783       default: llvm_unreachable("Unexpected integer comparison!");
5784       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5785         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5786       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5787         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5788       case ICmpInst::ICMP_ULE:
5789         // (float)int <= 4.4   --> int <= 4
5790         // (float)int <= -4.4  --> false
5791         if (RHS.isNegative())
5792           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5793         break;
5794       case ICmpInst::ICMP_SLE:
5795         // (float)int <= 4.4   --> int <= 4
5796         // (float)int <= -4.4  --> int < -4
5797         if (RHS.isNegative())
5798           Pred = ICmpInst::ICMP_SLT;
5799         break;
5800       case ICmpInst::ICMP_ULT:
5801         // (float)int < -4.4   --> false
5802         // (float)int < 4.4    --> int <= 4
5803         if (RHS.isNegative())
5804           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5805         Pred = ICmpInst::ICMP_ULE;
5806         break;
5807       case ICmpInst::ICMP_SLT:
5808         // (float)int < -4.4   --> int < -4
5809         // (float)int < 4.4    --> int <= 4
5810         if (!RHS.isNegative())
5811           Pred = ICmpInst::ICMP_SLE;
5812         break;
5813       case ICmpInst::ICMP_UGT:
5814         // (float)int > 4.4    --> int > 4
5815         // (float)int > -4.4   --> true
5816         if (RHS.isNegative())
5817           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5818         break;
5819       case ICmpInst::ICMP_SGT:
5820         // (float)int > 4.4    --> int > 4
5821         // (float)int > -4.4   --> int >= -4
5822         if (RHS.isNegative())
5823           Pred = ICmpInst::ICMP_SGE;
5824         break;
5825       case ICmpInst::ICMP_UGE:
5826         // (float)int >= -4.4   --> true
5827         // (float)int >= 4.4    --> int > 4
5828         if (!RHS.isNegative())
5829           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5830         Pred = ICmpInst::ICMP_UGT;
5831         break;
5832       case ICmpInst::ICMP_SGE:
5833         // (float)int >= -4.4   --> int >= -4
5834         // (float)int >= 4.4    --> int > 4
5835         if (!RHS.isNegative())
5836           Pred = ICmpInst::ICMP_SGT;
5837         break;
5838       }
5839     }
5840   }
5841
5842   // Lower this FP comparison into an appropriate integer version of the
5843   // comparison.
5844   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5845 }
5846
5847 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5848   bool Changed = SimplifyCompare(I);
5849   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5850
5851   // Fold trivial predicates.
5852   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5853     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5854   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5855     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5856   
5857   // Simplify 'fcmp pred X, X'
5858   if (Op0 == Op1) {
5859     switch (I.getPredicate()) {
5860     default: llvm_unreachable("Unknown predicate!");
5861     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5862     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5863     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5864       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5865     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5866     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5867     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5868       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5869       
5870     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5871     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5872     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5873     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5874       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5875       I.setPredicate(FCmpInst::FCMP_UNO);
5876       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5877       return &I;
5878       
5879     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5880     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5881     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5882     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5883       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5884       I.setPredicate(FCmpInst::FCMP_ORD);
5885       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5886       return &I;
5887     }
5888   }
5889     
5890   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5891     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5892
5893   // Handle fcmp with constant RHS
5894   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5895     // If the constant is a nan, see if we can fold the comparison based on it.
5896     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5897       if (CFP->getValueAPF().isNaN()) {
5898         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5899           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5900         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5901                "Comparison must be either ordered or unordered!");
5902         // True if unordered.
5903         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5904       }
5905     }
5906     
5907     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5908       switch (LHSI->getOpcode()) {
5909       case Instruction::PHI:
5910         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5911         // block.  If in the same block, we're encouraging jump threading.  If
5912         // not, we are just pessimizing the code by making an i1 phi.
5913         if (LHSI->getParent() == I.getParent())
5914           if (Instruction *NV = FoldOpIntoPhi(I, true))
5915             return NV;
5916         break;
5917       case Instruction::SIToFP:
5918       case Instruction::UIToFP:
5919         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5920           return NV;
5921         break;
5922       case Instruction::Select:
5923         // If either operand of the select is a constant, we can fold the
5924         // comparison into the select arms, which will cause one to be
5925         // constant folded and the select turned into a bitwise or.
5926         Value *Op1 = 0, *Op2 = 0;
5927         if (LHSI->hasOneUse()) {
5928           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5929             // Fold the known value into the constant operand.
5930             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5931             // Insert a new FCmp of the other select operand.
5932             Op2 = Builder->CreateFCmp(I.getPredicate(),
5933                                       LHSI->getOperand(2), RHSC, I.getName());
5934           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5935             // Fold the known value into the constant operand.
5936             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5937             // Insert a new FCmp of the other select operand.
5938             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5939                                       RHSC, I.getName());
5940           }
5941         }
5942
5943         if (Op1)
5944           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5945         break;
5946       }
5947   }
5948
5949   return Changed ? &I : 0;
5950 }
5951
5952 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5953   bool Changed = SimplifyCompare(I);
5954   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5955   const Type *Ty = Op0->getType();
5956
5957   // icmp X, X
5958   if (Op0 == Op1)
5959     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5960                                                    I.isTrueWhenEqual()));
5961
5962   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5963     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5964   
5965   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5966   // addresses never equal each other!  We already know that Op0 != Op1.
5967   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
5968        isa<ConstantPointerNull>(Op0)) &&
5969       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
5970        isa<ConstantPointerNull>(Op1)))
5971     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5972                                                    !I.isTrueWhenEqual()));
5973
5974   // icmp's with boolean values can always be turned into bitwise operations
5975   if (Ty == Type::getInt1Ty(*Context)) {
5976     switch (I.getPredicate()) {
5977     default: llvm_unreachable("Invalid icmp instruction!");
5978     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5979       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5980       return BinaryOperator::CreateNot(Xor);
5981     }
5982     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5983       return BinaryOperator::CreateXor(Op0, Op1);
5984
5985     case ICmpInst::ICMP_UGT:
5986       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5987       // FALL THROUGH
5988     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5989       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5990       return BinaryOperator::CreateAnd(Not, Op1);
5991     }
5992     case ICmpInst::ICMP_SGT:
5993       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5994       // FALL THROUGH
5995     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5996       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5997       return BinaryOperator::CreateAnd(Not, Op0);
5998     }
5999     case ICmpInst::ICMP_UGE:
6000       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6001       // FALL THROUGH
6002     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6003       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6004       return BinaryOperator::CreateOr(Not, Op1);
6005     }
6006     case ICmpInst::ICMP_SGE:
6007       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6008       // FALL THROUGH
6009     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6010       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6011       return BinaryOperator::CreateOr(Not, Op0);
6012     }
6013     }
6014   }
6015
6016   unsigned BitWidth = 0;
6017   if (TD)
6018     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6019   else if (Ty->isIntOrIntVector())
6020     BitWidth = Ty->getScalarSizeInBits();
6021
6022   bool isSignBit = false;
6023
6024   // See if we are doing a comparison with a constant.
6025   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6026     Value *A = 0, *B = 0;
6027     
6028     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6029     if (I.isEquality() && CI->isNullValue() &&
6030         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6031       // (icmp cond A B) if cond is equality
6032       return new ICmpInst(I.getPredicate(), A, B);
6033     }
6034     
6035     // If we have an icmp le or icmp ge instruction, turn it into the
6036     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6037     // them being folded in the code below.
6038     switch (I.getPredicate()) {
6039     default: break;
6040     case ICmpInst::ICMP_ULE:
6041       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6042         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6043       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6044                           AddOne(CI));
6045     case ICmpInst::ICMP_SLE:
6046       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6047         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6048       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6049                           AddOne(CI));
6050     case ICmpInst::ICMP_UGE:
6051       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6052         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6053       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6054                           SubOne(CI));
6055     case ICmpInst::ICMP_SGE:
6056       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6057         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6058       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6059                           SubOne(CI));
6060     }
6061     
6062     // If this comparison is a normal comparison, it demands all
6063     // bits, if it is a sign bit comparison, it only demands the sign bit.
6064     bool UnusedBit;
6065     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6066   }
6067
6068   // See if we can fold the comparison based on range information we can get
6069   // by checking whether bits are known to be zero or one in the input.
6070   if (BitWidth != 0) {
6071     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6072     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6073
6074     if (SimplifyDemandedBits(I.getOperandUse(0),
6075                              isSignBit ? APInt::getSignBit(BitWidth)
6076                                        : APInt::getAllOnesValue(BitWidth),
6077                              Op0KnownZero, Op0KnownOne, 0))
6078       return &I;
6079     if (SimplifyDemandedBits(I.getOperandUse(1),
6080                              APInt::getAllOnesValue(BitWidth),
6081                              Op1KnownZero, Op1KnownOne, 0))
6082       return &I;
6083
6084     // Given the known and unknown bits, compute a range that the LHS could be
6085     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6086     // EQ and NE we use unsigned values.
6087     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6088     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6089     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6090       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6091                                              Op0Min, Op0Max);
6092       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6093                                              Op1Min, Op1Max);
6094     } else {
6095       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6096                                                Op0Min, Op0Max);
6097       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6098                                                Op1Min, Op1Max);
6099     }
6100
6101     // If Min and Max are known to be the same, then SimplifyDemandedBits
6102     // figured out that the LHS is a constant.  Just constant fold this now so
6103     // that code below can assume that Min != Max.
6104     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6105       return new ICmpInst(I.getPredicate(),
6106                           ConstantInt::get(*Context, Op0Min), Op1);
6107     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6108       return new ICmpInst(I.getPredicate(), Op0,
6109                           ConstantInt::get(*Context, Op1Min));
6110
6111     // Based on the range information we know about the LHS, see if we can
6112     // simplify this comparison.  For example, (x&4) < 8  is always true.
6113     switch (I.getPredicate()) {
6114     default: llvm_unreachable("Unknown icmp opcode!");
6115     case ICmpInst::ICMP_EQ:
6116       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6117         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6118       break;
6119     case ICmpInst::ICMP_NE:
6120       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6121         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6122       break;
6123     case ICmpInst::ICMP_ULT:
6124       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6125         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6126       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6127         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6128       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6129         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6130       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6131         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6132           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6133                               SubOne(CI));
6134
6135         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6136         if (CI->isMinValue(true))
6137           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6138                            Constant::getAllOnesValue(Op0->getType()));
6139       }
6140       break;
6141     case ICmpInst::ICMP_UGT:
6142       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6143         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6144       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6145         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6146
6147       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6148         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6149       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6150         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6151           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6152                               AddOne(CI));
6153
6154         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6155         if (CI->isMaxValue(true))
6156           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6157                               Constant::getNullValue(Op0->getType()));
6158       }
6159       break;
6160     case ICmpInst::ICMP_SLT:
6161       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6162         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6163       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6164         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6165       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6166         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6167       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6168         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6169           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6170                               SubOne(CI));
6171       }
6172       break;
6173     case ICmpInst::ICMP_SGT:
6174       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6175         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6176       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6177         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6178
6179       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6180         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6181       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6182         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6183           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6184                               AddOne(CI));
6185       }
6186       break;
6187     case ICmpInst::ICMP_SGE:
6188       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6189       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6190         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6191       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6192         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6193       break;
6194     case ICmpInst::ICMP_SLE:
6195       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6196       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6197         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6198       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6199         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6200       break;
6201     case ICmpInst::ICMP_UGE:
6202       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6203       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6204         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6205       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6206         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6207       break;
6208     case ICmpInst::ICMP_ULE:
6209       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6210       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6211         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6212       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6213         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6214       break;
6215     }
6216
6217     // Turn a signed comparison into an unsigned one if both operands
6218     // are known to have the same sign.
6219     if (I.isSignedPredicate() &&
6220         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6221          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6222       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6223   }
6224
6225   // Test if the ICmpInst instruction is used exclusively by a select as
6226   // part of a minimum or maximum operation. If so, refrain from doing
6227   // any other folding. This helps out other analyses which understand
6228   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6229   // and CodeGen. And in this case, at least one of the comparison
6230   // operands has at least one user besides the compare (the select),
6231   // which would often largely negate the benefit of folding anyway.
6232   if (I.hasOneUse())
6233     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6234       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6235           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6236         return 0;
6237
6238   // See if we are doing a comparison between a constant and an instruction that
6239   // can be folded into the comparison.
6240   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6241     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6242     // instruction, see if that instruction also has constants so that the 
6243     // instruction can be folded into the icmp 
6244     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6245       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6246         return Res;
6247   }
6248
6249   // Handle icmp with constant (but not simple integer constant) RHS
6250   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6251     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252       switch (LHSI->getOpcode()) {
6253       case Instruction::GetElementPtr:
6254         if (RHSC->isNullValue()) {
6255           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6256           bool isAllZeros = true;
6257           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6258             if (!isa<Constant>(LHSI->getOperand(i)) ||
6259                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6260               isAllZeros = false;
6261               break;
6262             }
6263           if (isAllZeros)
6264             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6265                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6266         }
6267         break;
6268
6269       case Instruction::PHI:
6270         // Only fold icmp into the PHI if the phi and icmp are in the same
6271         // block.  If in the same block, we're encouraging jump threading.  If
6272         // not, we are just pessimizing the code by making an i1 phi.
6273         if (LHSI->getParent() == I.getParent())
6274           if (Instruction *NV = FoldOpIntoPhi(I, true))
6275             return NV;
6276         break;
6277       case Instruction::Select: {
6278         // If either operand of the select is a constant, we can fold the
6279         // comparison into the select arms, which will cause one to be
6280         // constant folded and the select turned into a bitwise or.
6281         Value *Op1 = 0, *Op2 = 0;
6282         if (LHSI->hasOneUse()) {
6283           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6284             // Fold the known value into the constant operand.
6285             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6286             // Insert a new ICmp of the other select operand.
6287             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6288                                       RHSC, I.getName());
6289           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6290             // Fold the known value into the constant operand.
6291             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6292             // Insert a new ICmp of the other select operand.
6293             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6294                                       RHSC, I.getName());
6295           }
6296         }
6297
6298         if (Op1)
6299           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6300         break;
6301       }
6302       case Instruction::Malloc:
6303         // If we have (malloc != null), and if the malloc has a single use, we
6304         // can assume it is successful and remove the malloc.
6305         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6306           Worklist.Add(LHSI);
6307           return ReplaceInstUsesWith(I,
6308                                      ConstantInt::get(Type::getInt1Ty(*Context),
6309                                                       !I.isTrueWhenEqual()));
6310         }
6311         break;
6312       case Instruction::Call:
6313         // If we have (malloc != null), and if the malloc has a single use, we
6314         // can assume it is successful and remove the malloc.
6315         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6316             isa<ConstantPointerNull>(RHSC)) {
6317           Worklist.Add(LHSI);
6318           return ReplaceInstUsesWith(I,
6319                                      ConstantInt::get(Type::getInt1Ty(*Context),
6320                                                       !I.isTrueWhenEqual()));
6321         }
6322         break;
6323       }
6324   }
6325
6326   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6327   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6328     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6329       return NI;
6330   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6331     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6332                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6333       return NI;
6334
6335   // Test to see if the operands of the icmp are casted versions of other
6336   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6337   // now.
6338   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6339     if (isa<PointerType>(Op0->getType()) && 
6340         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6341       // We keep moving the cast from the left operand over to the right
6342       // operand, where it can often be eliminated completely.
6343       Op0 = CI->getOperand(0);
6344
6345       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6346       // so eliminate it as well.
6347       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6348         Op1 = CI2->getOperand(0);
6349
6350       // If Op1 is a constant, we can fold the cast into the constant.
6351       if (Op0->getType() != Op1->getType()) {
6352         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6353           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6354         } else {
6355           // Otherwise, cast the RHS right before the icmp
6356           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6357         }
6358       }
6359       return new ICmpInst(I.getPredicate(), Op0, Op1);
6360     }
6361   }
6362   
6363   if (isa<CastInst>(Op0)) {
6364     // Handle the special case of: icmp (cast bool to X), <cst>
6365     // This comes up when you have code like
6366     //   int X = A < B;
6367     //   if (X) ...
6368     // For generality, we handle any zero-extension of any operand comparison
6369     // with a constant or another cast from the same type.
6370     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6371       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6372         return R;
6373   }
6374   
6375   // See if it's the same type of instruction on the left and right.
6376   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6377     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6378       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6379           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6380         switch (Op0I->getOpcode()) {
6381         default: break;
6382         case Instruction::Add:
6383         case Instruction::Sub:
6384         case Instruction::Xor:
6385           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6386             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6387                                 Op1I->getOperand(0));
6388           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6389           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6390             if (CI->getValue().isSignBit()) {
6391               ICmpInst::Predicate Pred = I.isSignedPredicate()
6392                                              ? I.getUnsignedPredicate()
6393                                              : I.getSignedPredicate();
6394               return new ICmpInst(Pred, Op0I->getOperand(0),
6395                                   Op1I->getOperand(0));
6396             }
6397             
6398             if (CI->getValue().isMaxSignedValue()) {
6399               ICmpInst::Predicate Pred = I.isSignedPredicate()
6400                                              ? I.getUnsignedPredicate()
6401                                              : I.getSignedPredicate();
6402               Pred = I.getSwappedPredicate(Pred);
6403               return new ICmpInst(Pred, Op0I->getOperand(0),
6404                                   Op1I->getOperand(0));
6405             }
6406           }
6407           break;
6408         case Instruction::Mul:
6409           if (!I.isEquality())
6410             break;
6411
6412           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6413             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6414             // Mask = -1 >> count-trailing-zeros(Cst).
6415             if (!CI->isZero() && !CI->isOne()) {
6416               const APInt &AP = CI->getValue();
6417               ConstantInt *Mask = ConstantInt::get(*Context, 
6418                                       APInt::getLowBitsSet(AP.getBitWidth(),
6419                                                            AP.getBitWidth() -
6420                                                       AP.countTrailingZeros()));
6421               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6422               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6423               return new ICmpInst(I.getPredicate(), And1, And2);
6424             }
6425           }
6426           break;
6427         }
6428       }
6429     }
6430   }
6431   
6432   // ~x < ~y --> y < x
6433   { Value *A, *B;
6434     if (match(Op0, m_Not(m_Value(A))) &&
6435         match(Op1, m_Not(m_Value(B))))
6436       return new ICmpInst(I.getPredicate(), B, A);
6437   }
6438   
6439   if (I.isEquality()) {
6440     Value *A, *B, *C, *D;
6441     
6442     // -x == -y --> x == y
6443     if (match(Op0, m_Neg(m_Value(A))) &&
6444         match(Op1, m_Neg(m_Value(B))))
6445       return new ICmpInst(I.getPredicate(), A, B);
6446     
6447     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6448       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6449         Value *OtherVal = A == Op1 ? B : A;
6450         return new ICmpInst(I.getPredicate(), OtherVal,
6451                             Constant::getNullValue(A->getType()));
6452       }
6453
6454       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6455         // A^c1 == C^c2 --> A == C^(c1^c2)
6456         ConstantInt *C1, *C2;
6457         if (match(B, m_ConstantInt(C1)) &&
6458             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6459           Constant *NC = 
6460                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6461           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6462           return new ICmpInst(I.getPredicate(), A, Xor);
6463         }
6464         
6465         // A^B == A^D -> B == D
6466         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6467         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6468         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6469         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6470       }
6471     }
6472     
6473     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6474         (A == Op0 || B == Op0)) {
6475       // A == (A^B)  ->  B == 0
6476       Value *OtherVal = A == Op0 ? B : A;
6477       return new ICmpInst(I.getPredicate(), OtherVal,
6478                           Constant::getNullValue(A->getType()));
6479     }
6480
6481     // (A-B) == A  ->  B == 0
6482     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6483       return new ICmpInst(I.getPredicate(), B, 
6484                           Constant::getNullValue(B->getType()));
6485
6486     // A == (A-B)  ->  B == 0
6487     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6488       return new ICmpInst(I.getPredicate(), B,
6489                           Constant::getNullValue(B->getType()));
6490     
6491     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6492     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6493         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6494         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6495       Value *X = 0, *Y = 0, *Z = 0;
6496       
6497       if (A == C) {
6498         X = B; Y = D; Z = A;
6499       } else if (A == D) {
6500         X = B; Y = C; Z = A;
6501       } else if (B == C) {
6502         X = A; Y = D; Z = B;
6503       } else if (B == D) {
6504         X = A; Y = C; Z = B;
6505       }
6506       
6507       if (X) {   // Build (X^Y) & Z
6508         Op1 = Builder->CreateXor(X, Y, "tmp");
6509         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6510         I.setOperand(0, Op1);
6511         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6512         return &I;
6513       }
6514     }
6515   }
6516   return Changed ? &I : 0;
6517 }
6518
6519
6520 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6521 /// and CmpRHS are both known to be integer constants.
6522 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6523                                           ConstantInt *DivRHS) {
6524   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6525   const APInt &CmpRHSV = CmpRHS->getValue();
6526   
6527   // FIXME: If the operand types don't match the type of the divide 
6528   // then don't attempt this transform. The code below doesn't have the
6529   // logic to deal with a signed divide and an unsigned compare (and
6530   // vice versa). This is because (x /s C1) <s C2  produces different 
6531   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6532   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6533   // work. :(  The if statement below tests that condition and bails 
6534   // if it finds it. 
6535   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6536   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6537     return 0;
6538   if (DivRHS->isZero())
6539     return 0; // The ProdOV computation fails on divide by zero.
6540   if (DivIsSigned && DivRHS->isAllOnesValue())
6541     return 0; // The overflow computation also screws up here
6542   if (DivRHS->isOne())
6543     return 0; // Not worth bothering, and eliminates some funny cases
6544               // with INT_MIN.
6545
6546   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6547   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6548   // C2 (CI). By solving for X we can turn this into a range check 
6549   // instead of computing a divide. 
6550   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6551
6552   // Determine if the product overflows by seeing if the product is
6553   // not equal to the divide. Make sure we do the same kind of divide
6554   // as in the LHS instruction that we're folding. 
6555   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6556                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6557
6558   // Get the ICmp opcode
6559   ICmpInst::Predicate Pred = ICI.getPredicate();
6560
6561   // Figure out the interval that is being checked.  For example, a comparison
6562   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6563   // Compute this interval based on the constants involved and the signedness of
6564   // the compare/divide.  This computes a half-open interval, keeping track of
6565   // whether either value in the interval overflows.  After analysis each
6566   // overflow variable is set to 0 if it's corresponding bound variable is valid
6567   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6568   int LoOverflow = 0, HiOverflow = 0;
6569   Constant *LoBound = 0, *HiBound = 0;
6570   
6571   if (!DivIsSigned) {  // udiv
6572     // e.g. X/5 op 3  --> [15, 20)
6573     LoBound = Prod;
6574     HiOverflow = LoOverflow = ProdOV;
6575     if (!HiOverflow)
6576       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6577   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6578     if (CmpRHSV == 0) {       // (X / pos) op 0
6579       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6580       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6581       HiBound = DivRHS;
6582     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6583       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6584       HiOverflow = LoOverflow = ProdOV;
6585       if (!HiOverflow)
6586         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6587     } else {                       // (X / pos) op neg
6588       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6589       HiBound = AddOne(Prod);
6590       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6591       if (!LoOverflow) {
6592         ConstantInt* DivNeg =
6593                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6594         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6595                                      true) ? -1 : 0;
6596        }
6597     }
6598   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6599     if (CmpRHSV == 0) {       // (X / neg) op 0
6600       // e.g. X/-5 op 0  --> [-4, 5)
6601       LoBound = AddOne(DivRHS);
6602       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6603       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6604         HiOverflow = 1;            // [INTMIN+1, overflow)
6605         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6606       }
6607     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6608       // e.g. X/-5 op 3  --> [-19, -14)
6609       HiBound = AddOne(Prod);
6610       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6611       if (!LoOverflow)
6612         LoOverflow = AddWithOverflow(LoBound, HiBound,
6613                                      DivRHS, Context, true) ? -1 : 0;
6614     } else {                       // (X / neg) op neg
6615       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6616       LoOverflow = HiOverflow = ProdOV;
6617       if (!HiOverflow)
6618         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6619     }
6620     
6621     // Dividing by a negative swaps the condition.  LT <-> GT
6622     Pred = ICmpInst::getSwappedPredicate(Pred);
6623   }
6624
6625   Value *X = DivI->getOperand(0);
6626   switch (Pred) {
6627   default: llvm_unreachable("Unhandled icmp opcode!");
6628   case ICmpInst::ICMP_EQ:
6629     if (LoOverflow && HiOverflow)
6630       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6631     else if (HiOverflow)
6632       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6633                           ICmpInst::ICMP_UGE, X, LoBound);
6634     else if (LoOverflow)
6635       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6636                           ICmpInst::ICMP_ULT, X, HiBound);
6637     else
6638       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6639   case ICmpInst::ICMP_NE:
6640     if (LoOverflow && HiOverflow)
6641       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6642     else if (HiOverflow)
6643       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6644                           ICmpInst::ICMP_ULT, X, LoBound);
6645     else if (LoOverflow)
6646       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6647                           ICmpInst::ICMP_UGE, X, HiBound);
6648     else
6649       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6650   case ICmpInst::ICMP_ULT:
6651   case ICmpInst::ICMP_SLT:
6652     if (LoOverflow == +1)   // Low bound is greater than input range.
6653       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6654     if (LoOverflow == -1)   // Low bound is less than input range.
6655       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6656     return new ICmpInst(Pred, X, LoBound);
6657   case ICmpInst::ICMP_UGT:
6658   case ICmpInst::ICMP_SGT:
6659     if (HiOverflow == +1)       // High bound greater than input range.
6660       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6661     else if (HiOverflow == -1)  // High bound less than input range.
6662       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6663     if (Pred == ICmpInst::ICMP_UGT)
6664       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6665     else
6666       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6667   }
6668 }
6669
6670
6671 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6672 ///
6673 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6674                                                           Instruction *LHSI,
6675                                                           ConstantInt *RHS) {
6676   const APInt &RHSV = RHS->getValue();
6677   
6678   switch (LHSI->getOpcode()) {
6679   case Instruction::Trunc:
6680     if (ICI.isEquality() && LHSI->hasOneUse()) {
6681       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6682       // of the high bits truncated out of x are known.
6683       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6684              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6685       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6686       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6687       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6688       
6689       // If all the high bits are known, we can do this xform.
6690       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6691         // Pull in the high bits from known-ones set.
6692         APInt NewRHS(RHS->getValue());
6693         NewRHS.zext(SrcBits);
6694         NewRHS |= KnownOne;
6695         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6696                             ConstantInt::get(*Context, NewRHS));
6697       }
6698     }
6699     break;
6700       
6701   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6702     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6703       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6704       // fold the xor.
6705       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6706           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6707         Value *CompareVal = LHSI->getOperand(0);
6708         
6709         // If the sign bit of the XorCST is not set, there is no change to
6710         // the operation, just stop using the Xor.
6711         if (!XorCST->getValue().isNegative()) {
6712           ICI.setOperand(0, CompareVal);
6713           Worklist.Add(LHSI);
6714           return &ICI;
6715         }
6716         
6717         // Was the old condition true if the operand is positive?
6718         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6719         
6720         // If so, the new one isn't.
6721         isTrueIfPositive ^= true;
6722         
6723         if (isTrueIfPositive)
6724           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6725                               SubOne(RHS));
6726         else
6727           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6728                               AddOne(RHS));
6729       }
6730
6731       if (LHSI->hasOneUse()) {
6732         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6733         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6734           const APInt &SignBit = XorCST->getValue();
6735           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6736                                          ? ICI.getUnsignedPredicate()
6737                                          : ICI.getSignedPredicate();
6738           return new ICmpInst(Pred, LHSI->getOperand(0),
6739                               ConstantInt::get(*Context, RHSV ^ SignBit));
6740         }
6741
6742         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6743         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6744           const APInt &NotSignBit = XorCST->getValue();
6745           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6746                                          ? ICI.getUnsignedPredicate()
6747                                          : ICI.getSignedPredicate();
6748           Pred = ICI.getSwappedPredicate(Pred);
6749           return new ICmpInst(Pred, LHSI->getOperand(0),
6750                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6751         }
6752       }
6753     }
6754     break;
6755   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6756     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6757         LHSI->getOperand(0)->hasOneUse()) {
6758       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6759       
6760       // If the LHS is an AND of a truncating cast, we can widen the
6761       // and/compare to be the input width without changing the value
6762       // produced, eliminating a cast.
6763       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6764         // We can do this transformation if either the AND constant does not
6765         // have its sign bit set or if it is an equality comparison. 
6766         // Extending a relational comparison when we're checking the sign
6767         // bit would not work.
6768         if (Cast->hasOneUse() &&
6769             (ICI.isEquality() ||
6770              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6771           uint32_t BitWidth = 
6772             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6773           APInt NewCST = AndCST->getValue();
6774           NewCST.zext(BitWidth);
6775           APInt NewCI = RHSV;
6776           NewCI.zext(BitWidth);
6777           Value *NewAnd = 
6778             Builder->CreateAnd(Cast->getOperand(0),
6779                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6780           return new ICmpInst(ICI.getPredicate(), NewAnd,
6781                               ConstantInt::get(*Context, NewCI));
6782         }
6783       }
6784       
6785       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6786       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6787       // happens a LOT in code produced by the C front-end, for bitfield
6788       // access.
6789       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6790       if (Shift && !Shift->isShift())
6791         Shift = 0;
6792       
6793       ConstantInt *ShAmt;
6794       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6795       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6796       const Type *AndTy = AndCST->getType();          // Type of the and.
6797       
6798       // We can fold this as long as we can't shift unknown bits
6799       // into the mask.  This can only happen with signed shift
6800       // rights, as they sign-extend.
6801       if (ShAmt) {
6802         bool CanFold = Shift->isLogicalShift();
6803         if (!CanFold) {
6804           // To test for the bad case of the signed shr, see if any
6805           // of the bits shifted in could be tested after the mask.
6806           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6807           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6808           
6809           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6810           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6811                AndCST->getValue()) == 0)
6812             CanFold = true;
6813         }
6814         
6815         if (CanFold) {
6816           Constant *NewCst;
6817           if (Shift->getOpcode() == Instruction::Shl)
6818             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6819           else
6820             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6821           
6822           // Check to see if we are shifting out any of the bits being
6823           // compared.
6824           if (ConstantExpr::get(Shift->getOpcode(),
6825                                        NewCst, ShAmt) != RHS) {
6826             // If we shifted bits out, the fold is not going to work out.
6827             // As a special case, check to see if this means that the
6828             // result is always true or false now.
6829             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6830               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6831             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6832               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6833           } else {
6834             ICI.setOperand(1, NewCst);
6835             Constant *NewAndCST;
6836             if (Shift->getOpcode() == Instruction::Shl)
6837               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6838             else
6839               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6840             LHSI->setOperand(1, NewAndCST);
6841             LHSI->setOperand(0, Shift->getOperand(0));
6842             Worklist.Add(Shift); // Shift is dead.
6843             return &ICI;
6844           }
6845         }
6846       }
6847       
6848       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6849       // preferable because it allows the C<<Y expression to be hoisted out
6850       // of a loop if Y is invariant and X is not.
6851       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6852           ICI.isEquality() && !Shift->isArithmeticShift() &&
6853           !isa<Constant>(Shift->getOperand(0))) {
6854         // Compute C << Y.
6855         Value *NS;
6856         if (Shift->getOpcode() == Instruction::LShr) {
6857           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6858         } else {
6859           // Insert a logical shift.
6860           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6861         }
6862         
6863         // Compute X & (C << Y).
6864         Value *NewAnd = 
6865           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6866         
6867         ICI.setOperand(0, NewAnd);
6868         return &ICI;
6869       }
6870     }
6871     break;
6872     
6873   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6874     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6875     if (!ShAmt) break;
6876     
6877     uint32_t TypeBits = RHSV.getBitWidth();
6878     
6879     // Check that the shift amount is in range.  If not, don't perform
6880     // undefined shifts.  When the shift is visited it will be
6881     // simplified.
6882     if (ShAmt->uge(TypeBits))
6883       break;
6884     
6885     if (ICI.isEquality()) {
6886       // If we are comparing against bits always shifted out, the
6887       // comparison cannot succeed.
6888       Constant *Comp =
6889         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6890                                                                  ShAmt);
6891       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6892         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6893         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6894         return ReplaceInstUsesWith(ICI, Cst);
6895       }
6896       
6897       if (LHSI->hasOneUse()) {
6898         // Otherwise strength reduce the shift into an and.
6899         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6900         Constant *Mask =
6901           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6902                                                        TypeBits-ShAmtVal));
6903         
6904         Value *And =
6905           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6906         return new ICmpInst(ICI.getPredicate(), And,
6907                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6908       }
6909     }
6910     
6911     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6912     bool TrueIfSigned = false;
6913     if (LHSI->hasOneUse() &&
6914         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6915       // (X << 31) <s 0  --> (X&1) != 0
6916       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6917                                            (TypeBits-ShAmt->getZExtValue()-1));
6918       Value *And =
6919         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6920       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6921                           And, Constant::getNullValue(And->getType()));
6922     }
6923     break;
6924   }
6925     
6926   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6927   case Instruction::AShr: {
6928     // Only handle equality comparisons of shift-by-constant.
6929     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6930     if (!ShAmt || !ICI.isEquality()) break;
6931
6932     // Check that the shift amount is in range.  If not, don't perform
6933     // undefined shifts.  When the shift is visited it will be
6934     // simplified.
6935     uint32_t TypeBits = RHSV.getBitWidth();
6936     if (ShAmt->uge(TypeBits))
6937       break;
6938     
6939     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6940       
6941     // If we are comparing against bits always shifted out, the
6942     // comparison cannot succeed.
6943     APInt Comp = RHSV << ShAmtVal;
6944     if (LHSI->getOpcode() == Instruction::LShr)
6945       Comp = Comp.lshr(ShAmtVal);
6946     else
6947       Comp = Comp.ashr(ShAmtVal);
6948     
6949     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6950       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6951       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6952       return ReplaceInstUsesWith(ICI, Cst);
6953     }
6954     
6955     // Otherwise, check to see if the bits shifted out are known to be zero.
6956     // If so, we can compare against the unshifted value:
6957     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6958     if (LHSI->hasOneUse() &&
6959         MaskedValueIsZero(LHSI->getOperand(0), 
6960                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6961       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6962                           ConstantExpr::getShl(RHS, ShAmt));
6963     }
6964       
6965     if (LHSI->hasOneUse()) {
6966       // Otherwise strength reduce the shift into an and.
6967       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6968       Constant *Mask = ConstantInt::get(*Context, Val);
6969       
6970       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6971                                       Mask, LHSI->getName()+".mask");
6972       return new ICmpInst(ICI.getPredicate(), And,
6973                           ConstantExpr::getShl(RHS, ShAmt));
6974     }
6975     break;
6976   }
6977     
6978   case Instruction::SDiv:
6979   case Instruction::UDiv:
6980     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6981     // Fold this div into the comparison, producing a range check. 
6982     // Determine, based on the divide type, what the range is being 
6983     // checked.  If there is an overflow on the low or high side, remember 
6984     // it, otherwise compute the range [low, hi) bounding the new value.
6985     // See: InsertRangeTest above for the kinds of replacements possible.
6986     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6987       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6988                                           DivRHS))
6989         return R;
6990     break;
6991
6992   case Instruction::Add:
6993     // Fold: icmp pred (add, X, C1), C2
6994
6995     if (!ICI.isEquality()) {
6996       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6997       if (!LHSC) break;
6998       const APInt &LHSV = LHSC->getValue();
6999
7000       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7001                             .subtract(LHSV);
7002
7003       if (ICI.isSignedPredicate()) {
7004         if (CR.getLower().isSignBit()) {
7005           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7006                               ConstantInt::get(*Context, CR.getUpper()));
7007         } else if (CR.getUpper().isSignBit()) {
7008           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7009                               ConstantInt::get(*Context, CR.getLower()));
7010         }
7011       } else {
7012         if (CR.getLower().isMinValue()) {
7013           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7014                               ConstantInt::get(*Context, CR.getUpper()));
7015         } else if (CR.getUpper().isMinValue()) {
7016           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7017                               ConstantInt::get(*Context, CR.getLower()));
7018         }
7019       }
7020     }
7021     break;
7022   }
7023   
7024   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7025   if (ICI.isEquality()) {
7026     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7027     
7028     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7029     // the second operand is a constant, simplify a bit.
7030     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7031       switch (BO->getOpcode()) {
7032       case Instruction::SRem:
7033         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7034         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7035           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7036           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7037             Value *NewRem =
7038               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7039                                   BO->getName());
7040             return new ICmpInst(ICI.getPredicate(), NewRem,
7041                                 Constant::getNullValue(BO->getType()));
7042           }
7043         }
7044         break;
7045       case Instruction::Add:
7046         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7047         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7048           if (BO->hasOneUse())
7049             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7050                                 ConstantExpr::getSub(RHS, BOp1C));
7051         } else if (RHSV == 0) {
7052           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7053           // efficiently invertible, or if the add has just this one use.
7054           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7055           
7056           if (Value *NegVal = dyn_castNegVal(BOp1))
7057             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7058           else if (Value *NegVal = dyn_castNegVal(BOp0))
7059             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7060           else if (BO->hasOneUse()) {
7061             Value *Neg = Builder->CreateNeg(BOp1);
7062             Neg->takeName(BO);
7063             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7064           }
7065         }
7066         break;
7067       case Instruction::Xor:
7068         // For the xor case, we can xor two constants together, eliminating
7069         // the explicit xor.
7070         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7071           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7072                               ConstantExpr::getXor(RHS, BOC));
7073         
7074         // FALLTHROUGH
7075       case Instruction::Sub:
7076         // Replace (([sub|xor] A, B) != 0) with (A != B)
7077         if (RHSV == 0)
7078           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7079                               BO->getOperand(1));
7080         break;
7081         
7082       case Instruction::Or:
7083         // If bits are being or'd in that are not present in the constant we
7084         // are comparing against, then the comparison could never succeed!
7085         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7086           Constant *NotCI = ConstantExpr::getNot(RHS);
7087           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7088             return ReplaceInstUsesWith(ICI,
7089                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7090                                        isICMP_NE));
7091         }
7092         break;
7093         
7094       case Instruction::And:
7095         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7096           // If bits are being compared against that are and'd out, then the
7097           // comparison can never succeed!
7098           if ((RHSV & ~BOC->getValue()) != 0)
7099             return ReplaceInstUsesWith(ICI,
7100                                        ConstantInt::get(Type::getInt1Ty(*Context),
7101                                        isICMP_NE));
7102           
7103           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7104           if (RHS == BOC && RHSV.isPowerOf2())
7105             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7106                                 ICmpInst::ICMP_NE, LHSI,
7107                                 Constant::getNullValue(RHS->getType()));
7108           
7109           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7110           if (BOC->getValue().isSignBit()) {
7111             Value *X = BO->getOperand(0);
7112             Constant *Zero = Constant::getNullValue(X->getType());
7113             ICmpInst::Predicate pred = isICMP_NE ? 
7114               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7115             return new ICmpInst(pred, X, Zero);
7116           }
7117           
7118           // ((X & ~7) == 0) --> X < 8
7119           if (RHSV == 0 && isHighOnes(BOC)) {
7120             Value *X = BO->getOperand(0);
7121             Constant *NegX = ConstantExpr::getNeg(BOC);
7122             ICmpInst::Predicate pred = isICMP_NE ? 
7123               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7124             return new ICmpInst(pred, X, NegX);
7125           }
7126         }
7127       default: break;
7128       }
7129     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7130       // Handle icmp {eq|ne} <intrinsic>, intcst.
7131       if (II->getIntrinsicID() == Intrinsic::bswap) {
7132         Worklist.Add(II);
7133         ICI.setOperand(0, II->getOperand(1));
7134         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7135         return &ICI;
7136       }
7137     }
7138   }
7139   return 0;
7140 }
7141
7142 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7143 /// We only handle extending casts so far.
7144 ///
7145 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7146   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7147   Value *LHSCIOp        = LHSCI->getOperand(0);
7148   const Type *SrcTy     = LHSCIOp->getType();
7149   const Type *DestTy    = LHSCI->getType();
7150   Value *RHSCIOp;
7151
7152   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7153   // integer type is the same size as the pointer type.
7154   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7155       TD->getPointerSizeInBits() ==
7156          cast<IntegerType>(DestTy)->getBitWidth()) {
7157     Value *RHSOp = 0;
7158     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7159       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7160     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7161       RHSOp = RHSC->getOperand(0);
7162       // If the pointer types don't match, insert a bitcast.
7163       if (LHSCIOp->getType() != RHSOp->getType())
7164         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7165     }
7166
7167     if (RHSOp)
7168       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7169   }
7170   
7171   // The code below only handles extension cast instructions, so far.
7172   // Enforce this.
7173   if (LHSCI->getOpcode() != Instruction::ZExt &&
7174       LHSCI->getOpcode() != Instruction::SExt)
7175     return 0;
7176
7177   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7178   bool isSignedCmp = ICI.isSignedPredicate();
7179
7180   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7181     // Not an extension from the same type?
7182     RHSCIOp = CI->getOperand(0);
7183     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7184       return 0;
7185     
7186     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7187     // and the other is a zext), then we can't handle this.
7188     if (CI->getOpcode() != LHSCI->getOpcode())
7189       return 0;
7190
7191     // Deal with equality cases early.
7192     if (ICI.isEquality())
7193       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7194
7195     // A signed comparison of sign extended values simplifies into a
7196     // signed comparison.
7197     if (isSignedCmp && isSignedExt)
7198       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7199
7200     // The other three cases all fold into an unsigned comparison.
7201     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7202   }
7203
7204   // If we aren't dealing with a constant on the RHS, exit early
7205   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7206   if (!CI)
7207     return 0;
7208
7209   // Compute the constant that would happen if we truncated to SrcTy then
7210   // reextended to DestTy.
7211   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7212   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7213                                                 Res1, DestTy);
7214
7215   // If the re-extended constant didn't change...
7216   if (Res2 == CI) {
7217     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7218     // For example, we might have:
7219     //    %A = sext i16 %X to i32
7220     //    %B = icmp ugt i32 %A, 1330
7221     // It is incorrect to transform this into 
7222     //    %B = icmp ugt i16 %X, 1330
7223     // because %A may have negative value. 
7224     //
7225     // However, we allow this when the compare is EQ/NE, because they are
7226     // signless.
7227     if (isSignedExt == isSignedCmp || ICI.isEquality())
7228       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7229     return 0;
7230   }
7231
7232   // The re-extended constant changed so the constant cannot be represented 
7233   // in the shorter type. Consequently, we cannot emit a simple comparison.
7234
7235   // First, handle some easy cases. We know the result cannot be equal at this
7236   // point so handle the ICI.isEquality() cases
7237   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7238     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7239   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7240     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7241
7242   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7243   // should have been folded away previously and not enter in here.
7244   Value *Result;
7245   if (isSignedCmp) {
7246     // We're performing a signed comparison.
7247     if (cast<ConstantInt>(CI)->getValue().isNegative())
7248       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7249     else
7250       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7251   } else {
7252     // We're performing an unsigned comparison.
7253     if (isSignedExt) {
7254       // We're performing an unsigned comp with a sign extended value.
7255       // This is true if the input is >= 0. [aka >s -1]
7256       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7257       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7258     } else {
7259       // Unsigned extend & unsigned compare -> always true.
7260       Result = ConstantInt::getTrue(*Context);
7261     }
7262   }
7263
7264   // Finally, return the value computed.
7265   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7266       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7267     return ReplaceInstUsesWith(ICI, Result);
7268
7269   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7270           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7271          "ICmp should be folded!");
7272   if (Constant *CI = dyn_cast<Constant>(Result))
7273     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7274   return BinaryOperator::CreateNot(Result);
7275 }
7276
7277 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7278   return commonShiftTransforms(I);
7279 }
7280
7281 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7282   return commonShiftTransforms(I);
7283 }
7284
7285 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7286   if (Instruction *R = commonShiftTransforms(I))
7287     return R;
7288   
7289   Value *Op0 = I.getOperand(0);
7290   
7291   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7292   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7293     if (CSI->isAllOnesValue())
7294       return ReplaceInstUsesWith(I, CSI);
7295
7296   // See if we can turn a signed shr into an unsigned shr.
7297   if (MaskedValueIsZero(Op0,
7298                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7299     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7300
7301   // Arithmetic shifting an all-sign-bit value is a no-op.
7302   unsigned NumSignBits = ComputeNumSignBits(Op0);
7303   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7304     return ReplaceInstUsesWith(I, Op0);
7305
7306   return 0;
7307 }
7308
7309 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7310   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7311   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7312
7313   // shl X, 0 == X and shr X, 0 == X
7314   // shl 0, X == 0 and shr 0, X == 0
7315   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7316       Op0 == Constant::getNullValue(Op0->getType()))
7317     return ReplaceInstUsesWith(I, Op0);
7318   
7319   if (isa<UndefValue>(Op0)) {            
7320     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7321       return ReplaceInstUsesWith(I, Op0);
7322     else                                    // undef << X -> 0, undef >>u X -> 0
7323       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7324   }
7325   if (isa<UndefValue>(Op1)) {
7326     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7327       return ReplaceInstUsesWith(I, Op0);          
7328     else                                     // X << undef, X >>u undef -> 0
7329       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7330   }
7331
7332   // See if we can fold away this shift.
7333   if (SimplifyDemandedInstructionBits(I))
7334     return &I;
7335
7336   // Try to fold constant and into select arguments.
7337   if (isa<Constant>(Op0))
7338     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7339       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7340         return R;
7341
7342   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7343     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7344       return Res;
7345   return 0;
7346 }
7347
7348 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7349                                                BinaryOperator &I) {
7350   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7351
7352   // See if we can simplify any instructions used by the instruction whose sole 
7353   // purpose is to compute bits we don't care about.
7354   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7355   
7356   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7357   // a signed shift.
7358   //
7359   if (Op1->uge(TypeBits)) {
7360     if (I.getOpcode() != Instruction::AShr)
7361       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7362     else {
7363       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7364       return &I;
7365     }
7366   }
7367   
7368   // ((X*C1) << C2) == (X * (C1 << C2))
7369   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7370     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7371       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7372         return BinaryOperator::CreateMul(BO->getOperand(0),
7373                                         ConstantExpr::getShl(BOOp, Op1));
7374   
7375   // Try to fold constant and into select arguments.
7376   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7377     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7378       return R;
7379   if (isa<PHINode>(Op0))
7380     if (Instruction *NV = FoldOpIntoPhi(I))
7381       return NV;
7382   
7383   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7384   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7385     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7386     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7387     // place.  Don't try to do this transformation in this case.  Also, we
7388     // require that the input operand is a shift-by-constant so that we have
7389     // confidence that the shifts will get folded together.  We could do this
7390     // xform in more cases, but it is unlikely to be profitable.
7391     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7392         isa<ConstantInt>(TrOp->getOperand(1))) {
7393       // Okay, we'll do this xform.  Make the shift of shift.
7394       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7395       // (shift2 (shift1 & 0x00FF), c2)
7396       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7397
7398       // For logical shifts, the truncation has the effect of making the high
7399       // part of the register be zeros.  Emulate this by inserting an AND to
7400       // clear the top bits as needed.  This 'and' will usually be zapped by
7401       // other xforms later if dead.
7402       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7403       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7404       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7405       
7406       // The mask we constructed says what the trunc would do if occurring
7407       // between the shifts.  We want to know the effect *after* the second
7408       // shift.  We know that it is a logical shift by a constant, so adjust the
7409       // mask as appropriate.
7410       if (I.getOpcode() == Instruction::Shl)
7411         MaskV <<= Op1->getZExtValue();
7412       else {
7413         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7414         MaskV = MaskV.lshr(Op1->getZExtValue());
7415       }
7416
7417       // shift1 & 0x00FF
7418       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7419                                       TI->getName());
7420
7421       // Return the value truncated to the interesting size.
7422       return new TruncInst(And, I.getType());
7423     }
7424   }
7425   
7426   if (Op0->hasOneUse()) {
7427     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7428       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7429       Value *V1, *V2;
7430       ConstantInt *CC;
7431       switch (Op0BO->getOpcode()) {
7432         default: break;
7433         case Instruction::Add:
7434         case Instruction::And:
7435         case Instruction::Or:
7436         case Instruction::Xor: {
7437           // These operators commute.
7438           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7439           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7440               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7441                     m_Specific(Op1)))) {
7442             Value *YS =         // (Y << C)
7443               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7444             // (X + (Y << C))
7445             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7446                                             Op0BO->getOperand(1)->getName());
7447             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7448             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7449                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7450           }
7451           
7452           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7453           Value *Op0BOOp1 = Op0BO->getOperand(1);
7454           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7455               match(Op0BOOp1, 
7456                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7457                           m_ConstantInt(CC))) &&
7458               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7459             Value *YS =   // (Y << C)
7460               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7461                                            Op0BO->getName());
7462             // X & (CC << C)
7463             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7464                                            V1->getName()+".mask");
7465             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7466           }
7467         }
7468           
7469         // FALL THROUGH.
7470         case Instruction::Sub: {
7471           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7472           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7473               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7474                     m_Specific(Op1)))) {
7475             Value *YS =  // (Y << C)
7476               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7477             // (X + (Y << C))
7478             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7479                                             Op0BO->getOperand(0)->getName());
7480             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7481             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7482                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7483           }
7484           
7485           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7486           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7487               match(Op0BO->getOperand(0),
7488                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7489                           m_ConstantInt(CC))) && V2 == Op1 &&
7490               cast<BinaryOperator>(Op0BO->getOperand(0))
7491                   ->getOperand(0)->hasOneUse()) {
7492             Value *YS = // (Y << C)
7493               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7494             // X & (CC << C)
7495             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7496                                            V1->getName()+".mask");
7497             
7498             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7499           }
7500           
7501           break;
7502         }
7503       }
7504       
7505       
7506       // If the operand is an bitwise operator with a constant RHS, and the
7507       // shift is the only use, we can pull it out of the shift.
7508       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7509         bool isValid = true;     // Valid only for And, Or, Xor
7510         bool highBitSet = false; // Transform if high bit of constant set?
7511         
7512         switch (Op0BO->getOpcode()) {
7513           default: isValid = false; break;   // Do not perform transform!
7514           case Instruction::Add:
7515             isValid = isLeftShift;
7516             break;
7517           case Instruction::Or:
7518           case Instruction::Xor:
7519             highBitSet = false;
7520             break;
7521           case Instruction::And:
7522             highBitSet = true;
7523             break;
7524         }
7525         
7526         // If this is a signed shift right, and the high bit is modified
7527         // by the logical operation, do not perform the transformation.
7528         // The highBitSet boolean indicates the value of the high bit of
7529         // the constant which would cause it to be modified for this
7530         // operation.
7531         //
7532         if (isValid && I.getOpcode() == Instruction::AShr)
7533           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7534         
7535         if (isValid) {
7536           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7537           
7538           Value *NewShift =
7539             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7540           NewShift->takeName(Op0BO);
7541           
7542           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7543                                         NewRHS);
7544         }
7545       }
7546     }
7547   }
7548   
7549   // Find out if this is a shift of a shift by a constant.
7550   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7551   if (ShiftOp && !ShiftOp->isShift())
7552     ShiftOp = 0;
7553   
7554   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7555     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7556     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7557     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7558     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7559     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7560     Value *X = ShiftOp->getOperand(0);
7561     
7562     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7563     
7564     const IntegerType *Ty = cast<IntegerType>(I.getType());
7565     
7566     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7567     if (I.getOpcode() == ShiftOp->getOpcode()) {
7568       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7569       // saturates.
7570       if (AmtSum >= TypeBits) {
7571         if (I.getOpcode() != Instruction::AShr)
7572           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7573         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7574       }
7575       
7576       return BinaryOperator::Create(I.getOpcode(), X,
7577                                     ConstantInt::get(Ty, AmtSum));
7578     }
7579     
7580     if (ShiftOp->getOpcode() == Instruction::LShr &&
7581         I.getOpcode() == Instruction::AShr) {
7582       if (AmtSum >= TypeBits)
7583         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7584       
7585       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7586       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7587     }
7588     
7589     if (ShiftOp->getOpcode() == Instruction::AShr &&
7590         I.getOpcode() == Instruction::LShr) {
7591       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7592       if (AmtSum >= TypeBits)
7593         AmtSum = TypeBits-1;
7594       
7595       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7596
7597       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7598       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7599     }
7600     
7601     // Okay, if we get here, one shift must be left, and the other shift must be
7602     // right.  See if the amounts are equal.
7603     if (ShiftAmt1 == ShiftAmt2) {
7604       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7605       if (I.getOpcode() == Instruction::Shl) {
7606         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7607         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7608       }
7609       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7610       if (I.getOpcode() == Instruction::LShr) {
7611         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7612         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7613       }
7614       // We can simplify ((X << C) >>s C) into a trunc + sext.
7615       // NOTE: we could do this for any C, but that would make 'unusual' integer
7616       // types.  For now, just stick to ones well-supported by the code
7617       // generators.
7618       const Type *SExtType = 0;
7619       switch (Ty->getBitWidth() - ShiftAmt1) {
7620       case 1  :
7621       case 8  :
7622       case 16 :
7623       case 32 :
7624       case 64 :
7625       case 128:
7626         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7627         break;
7628       default: break;
7629       }
7630       if (SExtType)
7631         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7632       // Otherwise, we can't handle it yet.
7633     } else if (ShiftAmt1 < ShiftAmt2) {
7634       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7635       
7636       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7637       if (I.getOpcode() == Instruction::Shl) {
7638         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7639                ShiftOp->getOpcode() == Instruction::AShr);
7640         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7641         
7642         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7643         return BinaryOperator::CreateAnd(Shift,
7644                                          ConstantInt::get(*Context, Mask));
7645       }
7646       
7647       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7648       if (I.getOpcode() == Instruction::LShr) {
7649         assert(ShiftOp->getOpcode() == Instruction::Shl);
7650         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7651         
7652         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7653         return BinaryOperator::CreateAnd(Shift,
7654                                          ConstantInt::get(*Context, Mask));
7655       }
7656       
7657       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7658     } else {
7659       assert(ShiftAmt2 < ShiftAmt1);
7660       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7661
7662       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7663       if (I.getOpcode() == Instruction::Shl) {
7664         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7665                ShiftOp->getOpcode() == Instruction::AShr);
7666         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7667                                             ConstantInt::get(Ty, ShiftDiff));
7668         
7669         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7670         return BinaryOperator::CreateAnd(Shift,
7671                                          ConstantInt::get(*Context, Mask));
7672       }
7673       
7674       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7675       if (I.getOpcode() == Instruction::LShr) {
7676         assert(ShiftOp->getOpcode() == Instruction::Shl);
7677         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7678         
7679         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7680         return BinaryOperator::CreateAnd(Shift,
7681                                          ConstantInt::get(*Context, Mask));
7682       }
7683       
7684       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7685     }
7686   }
7687   return 0;
7688 }
7689
7690
7691 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7692 /// expression.  If so, decompose it, returning some value X, such that Val is
7693 /// X*Scale+Offset.
7694 ///
7695 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7696                                         int &Offset, LLVMContext *Context) {
7697   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7698          "Unexpected allocation size type!");
7699   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7700     Offset = CI->getZExtValue();
7701     Scale  = 0;
7702     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7703   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7704     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7705       if (I->getOpcode() == Instruction::Shl) {
7706         // This is a value scaled by '1 << the shift amt'.
7707         Scale = 1U << RHS->getZExtValue();
7708         Offset = 0;
7709         return I->getOperand(0);
7710       } else if (I->getOpcode() == Instruction::Mul) {
7711         // This value is scaled by 'RHS'.
7712         Scale = RHS->getZExtValue();
7713         Offset = 0;
7714         return I->getOperand(0);
7715       } else if (I->getOpcode() == Instruction::Add) {
7716         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7717         // where C1 is divisible by C2.
7718         unsigned SubScale;
7719         Value *SubVal = 
7720           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7721                                     Offset, Context);
7722         Offset += RHS->getZExtValue();
7723         Scale = SubScale;
7724         return SubVal;
7725       }
7726     }
7727   }
7728
7729   // Otherwise, we can't look past this.
7730   Scale = 1;
7731   Offset = 0;
7732   return Val;
7733 }
7734
7735
7736 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7737 /// try to eliminate the cast by moving the type information into the alloc.
7738 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7739                                                    AllocationInst &AI) {
7740   const PointerType *PTy = cast<PointerType>(CI.getType());
7741   
7742   BuilderTy AllocaBuilder(*Builder);
7743   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7744   
7745   // Remove any uses of AI that are dead.
7746   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7747   
7748   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7749     Instruction *User = cast<Instruction>(*UI++);
7750     if (isInstructionTriviallyDead(User)) {
7751       while (UI != E && *UI == User)
7752         ++UI; // If this instruction uses AI more than once, don't break UI.
7753       
7754       ++NumDeadInst;
7755       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7756       EraseInstFromFunction(*User);
7757     }
7758   }
7759
7760   // This requires TargetData to get the alloca alignment and size information.
7761   if (!TD) return 0;
7762
7763   // Get the type really allocated and the type casted to.
7764   const Type *AllocElTy = AI.getAllocatedType();
7765   const Type *CastElTy = PTy->getElementType();
7766   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7767
7768   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7769   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7770   if (CastElTyAlign < AllocElTyAlign) return 0;
7771
7772   // If the allocation has multiple uses, only promote it if we are strictly
7773   // increasing the alignment of the resultant allocation.  If we keep it the
7774   // same, we open the door to infinite loops of various kinds.  (A reference
7775   // from a dbg.declare doesn't count as a use for this purpose.)
7776   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7777       CastElTyAlign == AllocElTyAlign) return 0;
7778
7779   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7780   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7781   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7782
7783   // See if we can satisfy the modulus by pulling a scale out of the array
7784   // size argument.
7785   unsigned ArraySizeScale;
7786   int ArrayOffset;
7787   Value *NumElements = // See if the array size is a decomposable linear expr.
7788     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7789                               ArrayOffset, Context);
7790  
7791   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7792   // do the xform.
7793   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7794       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7795
7796   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7797   Value *Amt = 0;
7798   if (Scale == 1) {
7799     Amt = NumElements;
7800   } else {
7801     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7802     // Insert before the alloca, not before the cast.
7803     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7804   }
7805   
7806   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7807     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7808     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7809   }
7810   
7811   AllocationInst *New;
7812   if (isa<MallocInst>(AI))
7813     New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7814   else
7815     New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7816   New->setAlignment(AI.getAlignment());
7817   New->takeName(&AI);
7818   
7819   // If the allocation has one real use plus a dbg.declare, just remove the
7820   // declare.
7821   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7822     EraseInstFromFunction(*DI);
7823   }
7824   // If the allocation has multiple real uses, insert a cast and change all
7825   // things that used it to use the new cast.  This will also hack on CI, but it
7826   // will die soon.
7827   else if (!AI.hasOneUse()) {
7828     // New is the allocation instruction, pointer typed. AI is the original
7829     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7830     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7831     AI.replaceAllUsesWith(NewCast);
7832   }
7833   return ReplaceInstUsesWith(CI, New);
7834 }
7835
7836 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7837 /// and return it as type Ty without inserting any new casts and without
7838 /// changing the computed value.  This is used by code that tries to decide
7839 /// whether promoting or shrinking integer operations to wider or smaller types
7840 /// will allow us to eliminate a truncate or extend.
7841 ///
7842 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7843 /// extension operation if Ty is larger.
7844 ///
7845 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7846 /// should return true if trunc(V) can be computed by computing V in the smaller
7847 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7848 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7849 /// efficiently truncated.
7850 ///
7851 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7852 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7853 /// the final result.
7854 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7855                                               unsigned CastOpc,
7856                                               int &NumCastsRemoved){
7857   // We can always evaluate constants in another type.
7858   if (isa<Constant>(V))
7859     return true;
7860   
7861   Instruction *I = dyn_cast<Instruction>(V);
7862   if (!I) return false;
7863   
7864   const Type *OrigTy = V->getType();
7865   
7866   // If this is an extension or truncate, we can often eliminate it.
7867   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7868     // If this is a cast from the destination type, we can trivially eliminate
7869     // it, and this will remove a cast overall.
7870     if (I->getOperand(0)->getType() == Ty) {
7871       // If the first operand is itself a cast, and is eliminable, do not count
7872       // this as an eliminable cast.  We would prefer to eliminate those two
7873       // casts first.
7874       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7875         ++NumCastsRemoved;
7876       return true;
7877     }
7878   }
7879
7880   // We can't extend or shrink something that has multiple uses: doing so would
7881   // require duplicating the instruction in general, which isn't profitable.
7882   if (!I->hasOneUse()) return false;
7883
7884   unsigned Opc = I->getOpcode();
7885   switch (Opc) {
7886   case Instruction::Add:
7887   case Instruction::Sub:
7888   case Instruction::Mul:
7889   case Instruction::And:
7890   case Instruction::Or:
7891   case Instruction::Xor:
7892     // These operators can all arbitrarily be extended or truncated.
7893     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7894                                       NumCastsRemoved) &&
7895            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7896                                       NumCastsRemoved);
7897
7898   case Instruction::UDiv:
7899   case Instruction::URem: {
7900     // UDiv and URem can be truncated if all the truncated bits are zero.
7901     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7902     uint32_t BitWidth = Ty->getScalarSizeInBits();
7903     if (BitWidth < OrigBitWidth) {
7904       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7905       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7906           MaskedValueIsZero(I->getOperand(1), Mask)) {
7907         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7908                                           NumCastsRemoved) &&
7909                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7910                                           NumCastsRemoved);
7911       }
7912     }
7913     break;
7914   }
7915   case Instruction::Shl:
7916     // If we are truncating the result of this SHL, and if it's a shift of a
7917     // constant amount, we can always perform a SHL in a smaller type.
7918     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7919       uint32_t BitWidth = Ty->getScalarSizeInBits();
7920       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7921           CI->getLimitedValue(BitWidth) < BitWidth)
7922         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7923                                           NumCastsRemoved);
7924     }
7925     break;
7926   case Instruction::LShr:
7927     // If this is a truncate of a logical shr, we can truncate it to a smaller
7928     // lshr iff we know that the bits we would otherwise be shifting in are
7929     // already zeros.
7930     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7931       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7932       uint32_t BitWidth = Ty->getScalarSizeInBits();
7933       if (BitWidth < OrigBitWidth &&
7934           MaskedValueIsZero(I->getOperand(0),
7935             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7936           CI->getLimitedValue(BitWidth) < BitWidth) {
7937         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7938                                           NumCastsRemoved);
7939       }
7940     }
7941     break;
7942   case Instruction::ZExt:
7943   case Instruction::SExt:
7944   case Instruction::Trunc:
7945     // If this is the same kind of case as our original (e.g. zext+zext), we
7946     // can safely replace it.  Note that replacing it does not reduce the number
7947     // of casts in the input.
7948     if (Opc == CastOpc)
7949       return true;
7950
7951     // sext (zext ty1), ty2 -> zext ty2
7952     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7953       return true;
7954     break;
7955   case Instruction::Select: {
7956     SelectInst *SI = cast<SelectInst>(I);
7957     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7958                                       NumCastsRemoved) &&
7959            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7960                                       NumCastsRemoved);
7961   }
7962   case Instruction::PHI: {
7963     // We can change a phi if we can change all operands.
7964     PHINode *PN = cast<PHINode>(I);
7965     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7966       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7967                                       NumCastsRemoved))
7968         return false;
7969     return true;
7970   }
7971   default:
7972     // TODO: Can handle more cases here.
7973     break;
7974   }
7975   
7976   return false;
7977 }
7978
7979 /// EvaluateInDifferentType - Given an expression that 
7980 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7981 /// evaluate the expression.
7982 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7983                                              bool isSigned) {
7984   if (Constant *C = dyn_cast<Constant>(V))
7985     return ConstantExpr::getIntegerCast(C, Ty,
7986                                                isSigned /*Sext or ZExt*/);
7987
7988   // Otherwise, it must be an instruction.
7989   Instruction *I = cast<Instruction>(V);
7990   Instruction *Res = 0;
7991   unsigned Opc = I->getOpcode();
7992   switch (Opc) {
7993   case Instruction::Add:
7994   case Instruction::Sub:
7995   case Instruction::Mul:
7996   case Instruction::And:
7997   case Instruction::Or:
7998   case Instruction::Xor:
7999   case Instruction::AShr:
8000   case Instruction::LShr:
8001   case Instruction::Shl:
8002   case Instruction::UDiv:
8003   case Instruction::URem: {
8004     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8005     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8006     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8007     break;
8008   }    
8009   case Instruction::Trunc:
8010   case Instruction::ZExt:
8011   case Instruction::SExt:
8012     // If the source type of the cast is the type we're trying for then we can
8013     // just return the source.  There's no need to insert it because it is not
8014     // new.
8015     if (I->getOperand(0)->getType() == Ty)
8016       return I->getOperand(0);
8017     
8018     // Otherwise, must be the same type of cast, so just reinsert a new one.
8019     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8020                            Ty);
8021     break;
8022   case Instruction::Select: {
8023     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8024     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8025     Res = SelectInst::Create(I->getOperand(0), True, False);
8026     break;
8027   }
8028   case Instruction::PHI: {
8029     PHINode *OPN = cast<PHINode>(I);
8030     PHINode *NPN = PHINode::Create(Ty);
8031     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8032       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8033       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8034     }
8035     Res = NPN;
8036     break;
8037   }
8038   default: 
8039     // TODO: Can handle more cases here.
8040     llvm_unreachable("Unreachable!");
8041     break;
8042   }
8043   
8044   Res->takeName(I);
8045   return InsertNewInstBefore(Res, *I);
8046 }
8047
8048 /// @brief Implement the transforms common to all CastInst visitors.
8049 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8050   Value *Src = CI.getOperand(0);
8051
8052   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8053   // eliminate it now.
8054   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8055     if (Instruction::CastOps opc = 
8056         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8057       // The first cast (CSrc) is eliminable so we need to fix up or replace
8058       // the second cast (CI). CSrc will then have a good chance of being dead.
8059       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8060     }
8061   }
8062
8063   // If we are casting a select then fold the cast into the select
8064   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8065     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8066       return NV;
8067
8068   // If we are casting a PHI then fold the cast into the PHI
8069   if (isa<PHINode>(Src))
8070     if (Instruction *NV = FoldOpIntoPhi(CI))
8071       return NV;
8072   
8073   return 0;
8074 }
8075
8076 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8077 /// or not there is a sequence of GEP indices into the type that will land us at
8078 /// the specified offset.  If so, fill them into NewIndices and return the
8079 /// resultant element type, otherwise return null.
8080 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8081                                        SmallVectorImpl<Value*> &NewIndices,
8082                                        const TargetData *TD,
8083                                        LLVMContext *Context) {
8084   if (!TD) return 0;
8085   if (!Ty->isSized()) return 0;
8086   
8087   // Start with the index over the outer type.  Note that the type size
8088   // might be zero (even if the offset isn't zero) if the indexed type
8089   // is something like [0 x {int, int}]
8090   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8091   int64_t FirstIdx = 0;
8092   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8093     FirstIdx = Offset/TySize;
8094     Offset -= FirstIdx*TySize;
8095     
8096     // Handle hosts where % returns negative instead of values [0..TySize).
8097     if (Offset < 0) {
8098       --FirstIdx;
8099       Offset += TySize;
8100       assert(Offset >= 0);
8101     }
8102     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8103   }
8104   
8105   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8106     
8107   // Index into the types.  If we fail, set OrigBase to null.
8108   while (Offset) {
8109     // Indexing into tail padding between struct/array elements.
8110     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8111       return 0;
8112     
8113     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8114       const StructLayout *SL = TD->getStructLayout(STy);
8115       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8116              "Offset must stay within the indexed type");
8117       
8118       unsigned Elt = SL->getElementContainingOffset(Offset);
8119       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8120       
8121       Offset -= SL->getElementOffset(Elt);
8122       Ty = STy->getElementType(Elt);
8123     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8124       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8125       assert(EltSize && "Cannot index into a zero-sized array");
8126       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8127       Offset %= EltSize;
8128       Ty = AT->getElementType();
8129     } else {
8130       // Otherwise, we can't index into the middle of this atomic type, bail.
8131       return 0;
8132     }
8133   }
8134   
8135   return Ty;
8136 }
8137
8138 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8139 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8140   Value *Src = CI.getOperand(0);
8141   
8142   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8143     // If casting the result of a getelementptr instruction with no offset, turn
8144     // this into a cast of the original pointer!
8145     if (GEP->hasAllZeroIndices()) {
8146       // Changing the cast operand is usually not a good idea but it is safe
8147       // here because the pointer operand is being replaced with another 
8148       // pointer operand so the opcode doesn't need to change.
8149       Worklist.Add(GEP);
8150       CI.setOperand(0, GEP->getOperand(0));
8151       return &CI;
8152     }
8153     
8154     // If the GEP has a single use, and the base pointer is a bitcast, and the
8155     // GEP computes a constant offset, see if we can convert these three
8156     // instructions into fewer.  This typically happens with unions and other
8157     // non-type-safe code.
8158     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8159       if (GEP->hasAllConstantIndices()) {
8160         // We are guaranteed to get a constant from EmitGEPOffset.
8161         ConstantInt *OffsetV =
8162                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8163         int64_t Offset = OffsetV->getSExtValue();
8164         
8165         // Get the base pointer input of the bitcast, and the type it points to.
8166         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8167         const Type *GEPIdxTy =
8168           cast<PointerType>(OrigBase->getType())->getElementType();
8169         SmallVector<Value*, 8> NewIndices;
8170         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8171           // If we were able to index down into an element, create the GEP
8172           // and bitcast the result.  This eliminates one bitcast, potentially
8173           // two.
8174           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8175             Builder->CreateInBoundsGEP(OrigBase,
8176                                        NewIndices.begin(), NewIndices.end()) :
8177             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8178           NGEP->takeName(GEP);
8179           
8180           if (isa<BitCastInst>(CI))
8181             return new BitCastInst(NGEP, CI.getType());
8182           assert(isa<PtrToIntInst>(CI));
8183           return new PtrToIntInst(NGEP, CI.getType());
8184         }
8185       }      
8186     }
8187   }
8188     
8189   return commonCastTransforms(CI);
8190 }
8191
8192 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8193 /// type like i42.  We don't want to introduce operations on random non-legal
8194 /// integer types where they don't already exist in the code.  In the future,
8195 /// we should consider making this based off target-data, so that 32-bit targets
8196 /// won't get i64 operations etc.
8197 static bool isSafeIntegerType(const Type *Ty) {
8198   switch (Ty->getPrimitiveSizeInBits()) {
8199   case 8:
8200   case 16:
8201   case 32:
8202   case 64:
8203     return true;
8204   default: 
8205     return false;
8206   }
8207 }
8208
8209 /// commonIntCastTransforms - This function implements the common transforms
8210 /// for trunc, zext, and sext.
8211 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8212   if (Instruction *Result = commonCastTransforms(CI))
8213     return Result;
8214
8215   Value *Src = CI.getOperand(0);
8216   const Type *SrcTy = Src->getType();
8217   const Type *DestTy = CI.getType();
8218   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8219   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8220
8221   // See if we can simplify any instructions used by the LHS whose sole 
8222   // purpose is to compute bits we don't care about.
8223   if (SimplifyDemandedInstructionBits(CI))
8224     return &CI;
8225
8226   // If the source isn't an instruction or has more than one use then we
8227   // can't do anything more. 
8228   Instruction *SrcI = dyn_cast<Instruction>(Src);
8229   if (!SrcI || !Src->hasOneUse())
8230     return 0;
8231
8232   // Attempt to propagate the cast into the instruction for int->int casts.
8233   int NumCastsRemoved = 0;
8234   // Only do this if the dest type is a simple type, don't convert the
8235   // expression tree to something weird like i93 unless the source is also
8236   // strange.
8237   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8238        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8239       CanEvaluateInDifferentType(SrcI, DestTy,
8240                                  CI.getOpcode(), NumCastsRemoved)) {
8241     // If this cast is a truncate, evaluting in a different type always
8242     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8243     // we need to do an AND to maintain the clear top-part of the computation,
8244     // so we require that the input have eliminated at least one cast.  If this
8245     // is a sign extension, we insert two new casts (to do the extension) so we
8246     // require that two casts have been eliminated.
8247     bool DoXForm = false;
8248     bool JustReplace = false;
8249     switch (CI.getOpcode()) {
8250     default:
8251       // All the others use floating point so we shouldn't actually 
8252       // get here because of the check above.
8253       llvm_unreachable("Unknown cast type");
8254     case Instruction::Trunc:
8255       DoXForm = true;
8256       break;
8257     case Instruction::ZExt: {
8258       DoXForm = NumCastsRemoved >= 1;
8259       if (!DoXForm && 0) {
8260         // If it's unnecessary to issue an AND to clear the high bits, it's
8261         // always profitable to do this xform.
8262         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8263         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8264         if (MaskedValueIsZero(TryRes, Mask))
8265           return ReplaceInstUsesWith(CI, TryRes);
8266         
8267         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8268           if (TryI->use_empty())
8269             EraseInstFromFunction(*TryI);
8270       }
8271       break;
8272     }
8273     case Instruction::SExt: {
8274       DoXForm = NumCastsRemoved >= 2;
8275       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8276         // If we do not have to emit the truncate + sext pair, then it's always
8277         // profitable to do this xform.
8278         //
8279         // It's not safe to eliminate the trunc + sext pair if one of the
8280         // eliminated cast is a truncate. e.g.
8281         // t2 = trunc i32 t1 to i16
8282         // t3 = sext i16 t2 to i32
8283         // !=
8284         // i32 t1
8285         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8286         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8287         if (NumSignBits > (DestBitSize - SrcBitSize))
8288           return ReplaceInstUsesWith(CI, TryRes);
8289         
8290         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8291           if (TryI->use_empty())
8292             EraseInstFromFunction(*TryI);
8293       }
8294       break;
8295     }
8296     }
8297     
8298     if (DoXForm) {
8299       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8300             " to avoid cast: " << CI);
8301       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8302                                            CI.getOpcode() == Instruction::SExt);
8303       if (JustReplace)
8304         // Just replace this cast with the result.
8305         return ReplaceInstUsesWith(CI, Res);
8306
8307       assert(Res->getType() == DestTy);
8308       switch (CI.getOpcode()) {
8309       default: llvm_unreachable("Unknown cast type!");
8310       case Instruction::Trunc:
8311         // Just replace this cast with the result.
8312         return ReplaceInstUsesWith(CI, Res);
8313       case Instruction::ZExt: {
8314         assert(SrcBitSize < DestBitSize && "Not a zext?");
8315
8316         // If the high bits are already zero, just replace this cast with the
8317         // result.
8318         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8319         if (MaskedValueIsZero(Res, Mask))
8320           return ReplaceInstUsesWith(CI, Res);
8321
8322         // We need to emit an AND to clear the high bits.
8323         Constant *C = ConstantInt::get(*Context, 
8324                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8325         return BinaryOperator::CreateAnd(Res, C);
8326       }
8327       case Instruction::SExt: {
8328         // If the high bits are already filled with sign bit, just replace this
8329         // cast with the result.
8330         unsigned NumSignBits = ComputeNumSignBits(Res);
8331         if (NumSignBits > (DestBitSize - SrcBitSize))
8332           return ReplaceInstUsesWith(CI, Res);
8333
8334         // We need to emit a cast to truncate, then a cast to sext.
8335         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8336       }
8337       }
8338     }
8339   }
8340   
8341   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8342   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8343
8344   switch (SrcI->getOpcode()) {
8345   case Instruction::Add:
8346   case Instruction::Mul:
8347   case Instruction::And:
8348   case Instruction::Or:
8349   case Instruction::Xor:
8350     // If we are discarding information, rewrite.
8351     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8352       // Don't insert two casts unless at least one can be eliminated.
8353       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8354           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8355         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8356         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8357         return BinaryOperator::Create(
8358             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8359       }
8360     }
8361
8362     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8363     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8364         SrcI->getOpcode() == Instruction::Xor &&
8365         Op1 == ConstantInt::getTrue(*Context) &&
8366         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8367       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8368       return BinaryOperator::CreateXor(New,
8369                                       ConstantInt::get(CI.getType(), 1));
8370     }
8371     break;
8372
8373   case Instruction::Shl: {
8374     // Canonicalize trunc inside shl, if we can.
8375     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8376     if (CI && DestBitSize < SrcBitSize &&
8377         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8378       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8379       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8380       return BinaryOperator::CreateShl(Op0c, Op1c);
8381     }
8382     break;
8383   }
8384   }
8385   return 0;
8386 }
8387
8388 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8389   if (Instruction *Result = commonIntCastTransforms(CI))
8390     return Result;
8391   
8392   Value *Src = CI.getOperand(0);
8393   const Type *Ty = CI.getType();
8394   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8395   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8396
8397   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8398   if (DestBitWidth == 1) {
8399     Constant *One = ConstantInt::get(Src->getType(), 1);
8400     Src = Builder->CreateAnd(Src, One, "tmp");
8401     Value *Zero = Constant::getNullValue(Src->getType());
8402     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8403   }
8404
8405   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8406   ConstantInt *ShAmtV = 0;
8407   Value *ShiftOp = 0;
8408   if (Src->hasOneUse() &&
8409       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8410     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8411     
8412     // Get a mask for the bits shifting in.
8413     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8414     if (MaskedValueIsZero(ShiftOp, Mask)) {
8415       if (ShAmt >= DestBitWidth)        // All zeros.
8416         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8417       
8418       // Okay, we can shrink this.  Truncate the input, then return a new
8419       // shift.
8420       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8421       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8422       return BinaryOperator::CreateLShr(V1, V2);
8423     }
8424   }
8425   
8426   return 0;
8427 }
8428
8429 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8430 /// in order to eliminate the icmp.
8431 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8432                                              bool DoXform) {
8433   // If we are just checking for a icmp eq of a single bit and zext'ing it
8434   // to an integer, then shift the bit to the appropriate place and then
8435   // cast to integer to avoid the comparison.
8436   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8437     const APInt &Op1CV = Op1C->getValue();
8438       
8439     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8440     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8441     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8442         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8443       if (!DoXform) return ICI;
8444
8445       Value *In = ICI->getOperand(0);
8446       Value *Sh = ConstantInt::get(In->getType(),
8447                                    In->getType()->getScalarSizeInBits()-1);
8448       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8449       if (In->getType() != CI.getType())
8450         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8451
8452       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8453         Constant *One = ConstantInt::get(In->getType(), 1);
8454         In = Builder->CreateXor(In, One, In->getName()+".not");
8455       }
8456
8457       return ReplaceInstUsesWith(CI, In);
8458     }
8459       
8460       
8461       
8462     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8463     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8464     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8465     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8466     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8467     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8468     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8469     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8470     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8471         // This only works for EQ and NE
8472         ICI->isEquality()) {
8473       // If Op1C some other power of two, convert:
8474       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8475       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8476       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8477       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8478         
8479       APInt KnownZeroMask(~KnownZero);
8480       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8481         if (!DoXform) return ICI;
8482
8483         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8484         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8485           // (X&4) == 2 --> false
8486           // (X&4) != 2 --> true
8487           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8488           Res = ConstantExpr::getZExt(Res, CI.getType());
8489           return ReplaceInstUsesWith(CI, Res);
8490         }
8491           
8492         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8493         Value *In = ICI->getOperand(0);
8494         if (ShiftAmt) {
8495           // Perform a logical shr by shiftamt.
8496           // Insert the shift to put the result in the low bit.
8497           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8498                                    In->getName()+".lobit");
8499         }
8500           
8501         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8502           Constant *One = ConstantInt::get(In->getType(), 1);
8503           In = Builder->CreateXor(In, One, "tmp");
8504         }
8505           
8506         if (CI.getType() == In->getType())
8507           return ReplaceInstUsesWith(CI, In);
8508         else
8509           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8510       }
8511     }
8512   }
8513
8514   return 0;
8515 }
8516
8517 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8518   // If one of the common conversion will work ..
8519   if (Instruction *Result = commonIntCastTransforms(CI))
8520     return Result;
8521
8522   Value *Src = CI.getOperand(0);
8523
8524   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8525   // types and if the sizes are just right we can convert this into a logical
8526   // 'and' which will be much cheaper than the pair of casts.
8527   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8528     // Get the sizes of the types involved.  We know that the intermediate type
8529     // will be smaller than A or C, but don't know the relation between A and C.
8530     Value *A = CSrc->getOperand(0);
8531     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8532     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8533     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8534     // If we're actually extending zero bits, then if
8535     // SrcSize <  DstSize: zext(a & mask)
8536     // SrcSize == DstSize: a & mask
8537     // SrcSize  > DstSize: trunc(a) & mask
8538     if (SrcSize < DstSize) {
8539       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8540       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8541       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8542       return new ZExtInst(And, CI.getType());
8543     }
8544     
8545     if (SrcSize == DstSize) {
8546       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8547       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8548                                                            AndValue));
8549     }
8550     if (SrcSize > DstSize) {
8551       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8552       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8553       return BinaryOperator::CreateAnd(Trunc, 
8554                                        ConstantInt::get(Trunc->getType(),
8555                                                                AndValue));
8556     }
8557   }
8558
8559   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8560     return transformZExtICmp(ICI, CI);
8561
8562   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8563   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8564     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8565     // of the (zext icmp) will be transformed.
8566     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8567     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8568     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8569         (transformZExtICmp(LHS, CI, false) ||
8570          transformZExtICmp(RHS, CI, false))) {
8571       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8572       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8573       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8574     }
8575   }
8576
8577   // zext(trunc(t) & C) -> (t & zext(C)).
8578   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8579     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8580       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8581         Value *TI0 = TI->getOperand(0);
8582         if (TI0->getType() == CI.getType())
8583           return
8584             BinaryOperator::CreateAnd(TI0,
8585                                 ConstantExpr::getZExt(C, CI.getType()));
8586       }
8587
8588   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8589   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8590     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8591       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8592         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8593             And->getOperand(1) == C)
8594           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8595             Value *TI0 = TI->getOperand(0);
8596             if (TI0->getType() == CI.getType()) {
8597               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8598               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8599               return BinaryOperator::CreateXor(NewAnd, ZC);
8600             }
8601           }
8602
8603   return 0;
8604 }
8605
8606 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8607   if (Instruction *I = commonIntCastTransforms(CI))
8608     return I;
8609   
8610   Value *Src = CI.getOperand(0);
8611   
8612   // Canonicalize sign-extend from i1 to a select.
8613   if (Src->getType() == Type::getInt1Ty(*Context))
8614     return SelectInst::Create(Src,
8615                               Constant::getAllOnesValue(CI.getType()),
8616                               Constant::getNullValue(CI.getType()));
8617
8618   // See if the value being truncated is already sign extended.  If so, just
8619   // eliminate the trunc/sext pair.
8620   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8621     Value *Op = cast<User>(Src)->getOperand(0);
8622     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8623     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8624     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8625     unsigned NumSignBits = ComputeNumSignBits(Op);
8626
8627     if (OpBits == DestBits) {
8628       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8629       // bits, it is already ready.
8630       if (NumSignBits > DestBits-MidBits)
8631         return ReplaceInstUsesWith(CI, Op);
8632     } else if (OpBits < DestBits) {
8633       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8634       // bits, just sext from i32.
8635       if (NumSignBits > OpBits-MidBits)
8636         return new SExtInst(Op, CI.getType(), "tmp");
8637     } else {
8638       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8639       // bits, just truncate to i32.
8640       if (NumSignBits > OpBits-MidBits)
8641         return new TruncInst(Op, CI.getType(), "tmp");
8642     }
8643   }
8644
8645   // If the input is a shl/ashr pair of a same constant, then this is a sign
8646   // extension from a smaller value.  If we could trust arbitrary bitwidth
8647   // integers, we could turn this into a truncate to the smaller bit and then
8648   // use a sext for the whole extension.  Since we don't, look deeper and check
8649   // for a truncate.  If the source and dest are the same type, eliminate the
8650   // trunc and extend and just do shifts.  For example, turn:
8651   //   %a = trunc i32 %i to i8
8652   //   %b = shl i8 %a, 6
8653   //   %c = ashr i8 %b, 6
8654   //   %d = sext i8 %c to i32
8655   // into:
8656   //   %a = shl i32 %i, 30
8657   //   %d = ashr i32 %a, 30
8658   Value *A = 0;
8659   ConstantInt *BA = 0, *CA = 0;
8660   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8661                         m_ConstantInt(CA))) &&
8662       BA == CA && isa<TruncInst>(A)) {
8663     Value *I = cast<TruncInst>(A)->getOperand(0);
8664     if (I->getType() == CI.getType()) {
8665       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8666       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8667       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8668       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8669       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8670       return BinaryOperator::CreateAShr(I, ShAmtV);
8671     }
8672   }
8673   
8674   return 0;
8675 }
8676
8677 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8678 /// in the specified FP type without changing its value.
8679 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8680                               LLVMContext *Context) {
8681   bool losesInfo;
8682   APFloat F = CFP->getValueAPF();
8683   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8684   if (!losesInfo)
8685     return ConstantFP::get(*Context, F);
8686   return 0;
8687 }
8688
8689 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8690 /// through it until we get the source value.
8691 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8692   if (Instruction *I = dyn_cast<Instruction>(V))
8693     if (I->getOpcode() == Instruction::FPExt)
8694       return LookThroughFPExtensions(I->getOperand(0), Context);
8695   
8696   // If this value is a constant, return the constant in the smallest FP type
8697   // that can accurately represent it.  This allows us to turn
8698   // (float)((double)X+2.0) into x+2.0f.
8699   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8700     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8701       return V;  // No constant folding of this.
8702     // See if the value can be truncated to float and then reextended.
8703     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8704       return V;
8705     if (CFP->getType() == Type::getDoubleTy(*Context))
8706       return V;  // Won't shrink.
8707     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8708       return V;
8709     // Don't try to shrink to various long double types.
8710   }
8711   
8712   return V;
8713 }
8714
8715 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8716   if (Instruction *I = commonCastTransforms(CI))
8717     return I;
8718   
8719   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8720   // smaller than the destination type, we can eliminate the truncate by doing
8721   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8722   // many builtins (sqrt, etc).
8723   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8724   if (OpI && OpI->hasOneUse()) {
8725     switch (OpI->getOpcode()) {
8726     default: break;
8727     case Instruction::FAdd:
8728     case Instruction::FSub:
8729     case Instruction::FMul:
8730     case Instruction::FDiv:
8731     case Instruction::FRem:
8732       const Type *SrcTy = OpI->getType();
8733       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8734       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8735       if (LHSTrunc->getType() != SrcTy && 
8736           RHSTrunc->getType() != SrcTy) {
8737         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8738         // If the source types were both smaller than the destination type of
8739         // the cast, do this xform.
8740         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8741             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8742           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8743           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8744           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8745         }
8746       }
8747       break;  
8748     }
8749   }
8750   return 0;
8751 }
8752
8753 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8754   return commonCastTransforms(CI);
8755 }
8756
8757 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8758   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8759   if (OpI == 0)
8760     return commonCastTransforms(FI);
8761
8762   // fptoui(uitofp(X)) --> X
8763   // fptoui(sitofp(X)) --> X
8764   // This is safe if the intermediate type has enough bits in its mantissa to
8765   // accurately represent all values of X.  For example, do not do this with
8766   // i64->float->i64.  This is also safe for sitofp case, because any negative
8767   // 'X' value would cause an undefined result for the fptoui. 
8768   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8769       OpI->getOperand(0)->getType() == FI.getType() &&
8770       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8771                     OpI->getType()->getFPMantissaWidth())
8772     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8773
8774   return commonCastTransforms(FI);
8775 }
8776
8777 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8778   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8779   if (OpI == 0)
8780     return commonCastTransforms(FI);
8781   
8782   // fptosi(sitofp(X)) --> X
8783   // fptosi(uitofp(X)) --> X
8784   // This is safe if the intermediate type has enough bits in its mantissa to
8785   // accurately represent all values of X.  For example, do not do this with
8786   // i64->float->i64.  This is also safe for sitofp case, because any negative
8787   // 'X' value would cause an undefined result for the fptoui. 
8788   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8789       OpI->getOperand(0)->getType() == FI.getType() &&
8790       (int)FI.getType()->getScalarSizeInBits() <=
8791                     OpI->getType()->getFPMantissaWidth())
8792     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8793   
8794   return commonCastTransforms(FI);
8795 }
8796
8797 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8798   return commonCastTransforms(CI);
8799 }
8800
8801 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8802   return commonCastTransforms(CI);
8803 }
8804
8805 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8806   // If the destination integer type is smaller than the intptr_t type for
8807   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8808   // trunc to be exposed to other transforms.  Don't do this for extending
8809   // ptrtoint's, because we don't know if the target sign or zero extends its
8810   // pointers.
8811   if (TD &&
8812       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8813     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8814                                        TD->getIntPtrType(CI.getContext()),
8815                                        "tmp");
8816     return new TruncInst(P, CI.getType());
8817   }
8818   
8819   return commonPointerCastTransforms(CI);
8820 }
8821
8822 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8823   // If the source integer type is larger than the intptr_t type for
8824   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8825   // allows the trunc to be exposed to other transforms.  Don't do this for
8826   // extending inttoptr's, because we don't know if the target sign or zero
8827   // extends to pointers.
8828   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8829       TD->getPointerSizeInBits()) {
8830     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8831                                     TD->getIntPtrType(CI.getContext()), "tmp");
8832     return new IntToPtrInst(P, CI.getType());
8833   }
8834   
8835   if (Instruction *I = commonCastTransforms(CI))
8836     return I;
8837
8838   return 0;
8839 }
8840
8841 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8842   // If the operands are integer typed then apply the integer transforms,
8843   // otherwise just apply the common ones.
8844   Value *Src = CI.getOperand(0);
8845   const Type *SrcTy = Src->getType();
8846   const Type *DestTy = CI.getType();
8847
8848   if (isa<PointerType>(SrcTy)) {
8849     if (Instruction *I = commonPointerCastTransforms(CI))
8850       return I;
8851   } else {
8852     if (Instruction *Result = commonCastTransforms(CI))
8853       return Result;
8854   }
8855
8856
8857   // Get rid of casts from one type to the same type. These are useless and can
8858   // be replaced by the operand.
8859   if (DestTy == Src->getType())
8860     return ReplaceInstUsesWith(CI, Src);
8861
8862   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8863     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8864     const Type *DstElTy = DstPTy->getElementType();
8865     const Type *SrcElTy = SrcPTy->getElementType();
8866     
8867     // If the address spaces don't match, don't eliminate the bitcast, which is
8868     // required for changing types.
8869     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8870       return 0;
8871     
8872     // If we are casting a alloca to a pointer to a type of the same
8873     // size, rewrite the allocation instruction to allocate the "right" type.
8874     // There is no need to modify malloc calls because it is their bitcast that
8875     // needs to be cleaned up.
8876     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8877       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8878         return V;
8879     
8880     // If the source and destination are pointers, and this cast is equivalent
8881     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8882     // This can enhance SROA and other transforms that want type-safe pointers.
8883     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8884     unsigned NumZeros = 0;
8885     while (SrcElTy != DstElTy && 
8886            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8887            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8888       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8889       ++NumZeros;
8890     }
8891
8892     // If we found a path from the src to dest, create the getelementptr now.
8893     if (SrcElTy == DstElTy) {
8894       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8895       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8896                                                ((Instruction*) NULL));
8897     }
8898   }
8899
8900   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8901     if (DestVTy->getNumElements() == 1) {
8902       if (!isa<VectorType>(SrcTy)) {
8903         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8904         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8905                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8906       }
8907       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8908     }
8909   }
8910
8911   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8912     if (SrcVTy->getNumElements() == 1) {
8913       if (!isa<VectorType>(DestTy)) {
8914         Value *Elem = 
8915           Builder->CreateExtractElement(Src,
8916                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8917         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8918       }
8919     }
8920   }
8921
8922   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8923     if (SVI->hasOneUse()) {
8924       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8925       // a bitconvert to a vector with the same # elts.
8926       if (isa<VectorType>(DestTy) && 
8927           cast<VectorType>(DestTy)->getNumElements() ==
8928                 SVI->getType()->getNumElements() &&
8929           SVI->getType()->getNumElements() ==
8930             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8931         CastInst *Tmp;
8932         // If either of the operands is a cast from CI.getType(), then
8933         // evaluating the shuffle in the casted destination's type will allow
8934         // us to eliminate at least one cast.
8935         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8936              Tmp->getOperand(0)->getType() == DestTy) ||
8937             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8938              Tmp->getOperand(0)->getType() == DestTy)) {
8939           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8940           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8941           // Return a new shuffle vector.  Use the same element ID's, as we
8942           // know the vector types match #elts.
8943           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8944         }
8945       }
8946     }
8947   }
8948   return 0;
8949 }
8950
8951 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8952 ///   %C = or %A, %B
8953 ///   %D = select %cond, %C, %A
8954 /// into:
8955 ///   %C = select %cond, %B, 0
8956 ///   %D = or %A, %C
8957 ///
8958 /// Assuming that the specified instruction is an operand to the select, return
8959 /// a bitmask indicating which operands of this instruction are foldable if they
8960 /// equal the other incoming value of the select.
8961 ///
8962 static unsigned GetSelectFoldableOperands(Instruction *I) {
8963   switch (I->getOpcode()) {
8964   case Instruction::Add:
8965   case Instruction::Mul:
8966   case Instruction::And:
8967   case Instruction::Or:
8968   case Instruction::Xor:
8969     return 3;              // Can fold through either operand.
8970   case Instruction::Sub:   // Can only fold on the amount subtracted.
8971   case Instruction::Shl:   // Can only fold on the shift amount.
8972   case Instruction::LShr:
8973   case Instruction::AShr:
8974     return 1;
8975   default:
8976     return 0;              // Cannot fold
8977   }
8978 }
8979
8980 /// GetSelectFoldableConstant - For the same transformation as the previous
8981 /// function, return the identity constant that goes into the select.
8982 static Constant *GetSelectFoldableConstant(Instruction *I,
8983                                            LLVMContext *Context) {
8984   switch (I->getOpcode()) {
8985   default: llvm_unreachable("This cannot happen!");
8986   case Instruction::Add:
8987   case Instruction::Sub:
8988   case Instruction::Or:
8989   case Instruction::Xor:
8990   case Instruction::Shl:
8991   case Instruction::LShr:
8992   case Instruction::AShr:
8993     return Constant::getNullValue(I->getType());
8994   case Instruction::And:
8995     return Constant::getAllOnesValue(I->getType());
8996   case Instruction::Mul:
8997     return ConstantInt::get(I->getType(), 1);
8998   }
8999 }
9000
9001 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9002 /// have the same opcode and only one use each.  Try to simplify this.
9003 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9004                                           Instruction *FI) {
9005   if (TI->getNumOperands() == 1) {
9006     // If this is a non-volatile load or a cast from the same type,
9007     // merge.
9008     if (TI->isCast()) {
9009       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9010         return 0;
9011     } else {
9012       return 0;  // unknown unary op.
9013     }
9014
9015     // Fold this by inserting a select from the input values.
9016     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9017                                           FI->getOperand(0), SI.getName()+".v");
9018     InsertNewInstBefore(NewSI, SI);
9019     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9020                             TI->getType());
9021   }
9022
9023   // Only handle binary operators here.
9024   if (!isa<BinaryOperator>(TI))
9025     return 0;
9026
9027   // Figure out if the operations have any operands in common.
9028   Value *MatchOp, *OtherOpT, *OtherOpF;
9029   bool MatchIsOpZero;
9030   if (TI->getOperand(0) == FI->getOperand(0)) {
9031     MatchOp  = TI->getOperand(0);
9032     OtherOpT = TI->getOperand(1);
9033     OtherOpF = FI->getOperand(1);
9034     MatchIsOpZero = true;
9035   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9036     MatchOp  = TI->getOperand(1);
9037     OtherOpT = TI->getOperand(0);
9038     OtherOpF = FI->getOperand(0);
9039     MatchIsOpZero = false;
9040   } else if (!TI->isCommutative()) {
9041     return 0;
9042   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9043     MatchOp  = TI->getOperand(0);
9044     OtherOpT = TI->getOperand(1);
9045     OtherOpF = FI->getOperand(0);
9046     MatchIsOpZero = true;
9047   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9048     MatchOp  = TI->getOperand(1);
9049     OtherOpT = TI->getOperand(0);
9050     OtherOpF = FI->getOperand(1);
9051     MatchIsOpZero = true;
9052   } else {
9053     return 0;
9054   }
9055
9056   // If we reach here, they do have operations in common.
9057   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9058                                          OtherOpF, SI.getName()+".v");
9059   InsertNewInstBefore(NewSI, SI);
9060
9061   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9062     if (MatchIsOpZero)
9063       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9064     else
9065       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9066   }
9067   llvm_unreachable("Shouldn't get here");
9068   return 0;
9069 }
9070
9071 static bool isSelect01(Constant *C1, Constant *C2) {
9072   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9073   if (!C1I)
9074     return false;
9075   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9076   if (!C2I)
9077     return false;
9078   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9079 }
9080
9081 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9082 /// facilitate further optimization.
9083 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9084                                             Value *FalseVal) {
9085   // See the comment above GetSelectFoldableOperands for a description of the
9086   // transformation we are doing here.
9087   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9088     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9089         !isa<Constant>(FalseVal)) {
9090       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9091         unsigned OpToFold = 0;
9092         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9093           OpToFold = 1;
9094         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9095           OpToFold = 2;
9096         }
9097
9098         if (OpToFold) {
9099           Constant *C = GetSelectFoldableConstant(TVI, Context);
9100           Value *OOp = TVI->getOperand(2-OpToFold);
9101           // Avoid creating select between 2 constants unless it's selecting
9102           // between 0 and 1.
9103           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9104             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9105             InsertNewInstBefore(NewSel, SI);
9106             NewSel->takeName(TVI);
9107             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9108               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9109             llvm_unreachable("Unknown instruction!!");
9110           }
9111         }
9112       }
9113     }
9114   }
9115
9116   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9117     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9118         !isa<Constant>(TrueVal)) {
9119       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9120         unsigned OpToFold = 0;
9121         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9122           OpToFold = 1;
9123         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9124           OpToFold = 2;
9125         }
9126
9127         if (OpToFold) {
9128           Constant *C = GetSelectFoldableConstant(FVI, Context);
9129           Value *OOp = FVI->getOperand(2-OpToFold);
9130           // Avoid creating select between 2 constants unless it's selecting
9131           // between 0 and 1.
9132           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9133             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9134             InsertNewInstBefore(NewSel, SI);
9135             NewSel->takeName(FVI);
9136             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9137               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9138             llvm_unreachable("Unknown instruction!!");
9139           }
9140         }
9141       }
9142     }
9143   }
9144
9145   return 0;
9146 }
9147
9148 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9149 /// ICmpInst as its first operand.
9150 ///
9151 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9152                                                    ICmpInst *ICI) {
9153   bool Changed = false;
9154   ICmpInst::Predicate Pred = ICI->getPredicate();
9155   Value *CmpLHS = ICI->getOperand(0);
9156   Value *CmpRHS = ICI->getOperand(1);
9157   Value *TrueVal = SI.getTrueValue();
9158   Value *FalseVal = SI.getFalseValue();
9159
9160   // Check cases where the comparison is with a constant that
9161   // can be adjusted to fit the min/max idiom. We may edit ICI in
9162   // place here, so make sure the select is the only user.
9163   if (ICI->hasOneUse())
9164     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9165       switch (Pred) {
9166       default: break;
9167       case ICmpInst::ICMP_ULT:
9168       case ICmpInst::ICMP_SLT: {
9169         // X < MIN ? T : F  -->  F
9170         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9171           return ReplaceInstUsesWith(SI, FalseVal);
9172         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9173         Constant *AdjustedRHS = SubOne(CI);
9174         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9175             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9176           Pred = ICmpInst::getSwappedPredicate(Pred);
9177           CmpRHS = AdjustedRHS;
9178           std::swap(FalseVal, TrueVal);
9179           ICI->setPredicate(Pred);
9180           ICI->setOperand(1, CmpRHS);
9181           SI.setOperand(1, TrueVal);
9182           SI.setOperand(2, FalseVal);
9183           Changed = true;
9184         }
9185         break;
9186       }
9187       case ICmpInst::ICMP_UGT:
9188       case ICmpInst::ICMP_SGT: {
9189         // X > MAX ? T : F  -->  F
9190         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9191           return ReplaceInstUsesWith(SI, FalseVal);
9192         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9193         Constant *AdjustedRHS = AddOne(CI);
9194         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9195             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9196           Pred = ICmpInst::getSwappedPredicate(Pred);
9197           CmpRHS = AdjustedRHS;
9198           std::swap(FalseVal, TrueVal);
9199           ICI->setPredicate(Pred);
9200           ICI->setOperand(1, CmpRHS);
9201           SI.setOperand(1, TrueVal);
9202           SI.setOperand(2, FalseVal);
9203           Changed = true;
9204         }
9205         break;
9206       }
9207       }
9208
9209       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9210       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9211       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9212       if (match(TrueVal, m_ConstantInt<-1>()) &&
9213           match(FalseVal, m_ConstantInt<0>()))
9214         Pred = ICI->getPredicate();
9215       else if (match(TrueVal, m_ConstantInt<0>()) &&
9216                match(FalseVal, m_ConstantInt<-1>()))
9217         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9218       
9219       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9220         // If we are just checking for a icmp eq of a single bit and zext'ing it
9221         // to an integer, then shift the bit to the appropriate place and then
9222         // cast to integer to avoid the comparison.
9223         const APInt &Op1CV = CI->getValue();
9224     
9225         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9226         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9227         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9228             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9229           Value *In = ICI->getOperand(0);
9230           Value *Sh = ConstantInt::get(In->getType(),
9231                                        In->getType()->getScalarSizeInBits()-1);
9232           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9233                                                         In->getName()+".lobit"),
9234                                    *ICI);
9235           if (In->getType() != SI.getType())
9236             In = CastInst::CreateIntegerCast(In, SI.getType(),
9237                                              true/*SExt*/, "tmp", ICI);
9238     
9239           if (Pred == ICmpInst::ICMP_SGT)
9240             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9241                                        In->getName()+".not"), *ICI);
9242     
9243           return ReplaceInstUsesWith(SI, In);
9244         }
9245       }
9246     }
9247
9248   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9249     // Transform (X == Y) ? X : Y  -> Y
9250     if (Pred == ICmpInst::ICMP_EQ)
9251       return ReplaceInstUsesWith(SI, FalseVal);
9252     // Transform (X != Y) ? X : Y  -> X
9253     if (Pred == ICmpInst::ICMP_NE)
9254       return ReplaceInstUsesWith(SI, TrueVal);
9255     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9256
9257   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9258     // Transform (X == Y) ? Y : X  -> X
9259     if (Pred == ICmpInst::ICMP_EQ)
9260       return ReplaceInstUsesWith(SI, FalseVal);
9261     // Transform (X != Y) ? Y : X  -> Y
9262     if (Pred == ICmpInst::ICMP_NE)
9263       return ReplaceInstUsesWith(SI, TrueVal);
9264     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9265   }
9266
9267   /// NOTE: if we wanted to, this is where to detect integer ABS
9268
9269   return Changed ? &SI : 0;
9270 }
9271
9272 /// isDefinedInBB - Return true if the value is an instruction defined in the
9273 /// specified basicblock.
9274 static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9275   const Instruction *I = dyn_cast<Instruction>(V);
9276   return I != 0 && I->getParent() == BB;
9277 }
9278
9279
9280 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9281   Value *CondVal = SI.getCondition();
9282   Value *TrueVal = SI.getTrueValue();
9283   Value *FalseVal = SI.getFalseValue();
9284
9285   // select true, X, Y  -> X
9286   // select false, X, Y -> Y
9287   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9288     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9289
9290   // select C, X, X -> X
9291   if (TrueVal == FalseVal)
9292     return ReplaceInstUsesWith(SI, TrueVal);
9293
9294   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9295     return ReplaceInstUsesWith(SI, FalseVal);
9296   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9297     return ReplaceInstUsesWith(SI, TrueVal);
9298   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9299     if (isa<Constant>(TrueVal))
9300       return ReplaceInstUsesWith(SI, TrueVal);
9301     else
9302       return ReplaceInstUsesWith(SI, FalseVal);
9303   }
9304
9305   if (SI.getType() == Type::getInt1Ty(*Context)) {
9306     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9307       if (C->getZExtValue()) {
9308         // Change: A = select B, true, C --> A = or B, C
9309         return BinaryOperator::CreateOr(CondVal, FalseVal);
9310       } else {
9311         // Change: A = select B, false, C --> A = and !B, C
9312         Value *NotCond =
9313           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9314                                              "not."+CondVal->getName()), SI);
9315         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9316       }
9317     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9318       if (C->getZExtValue() == false) {
9319         // Change: A = select B, C, false --> A = and B, C
9320         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9321       } else {
9322         // Change: A = select B, C, true --> A = or !B, C
9323         Value *NotCond =
9324           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9325                                              "not."+CondVal->getName()), SI);
9326         return BinaryOperator::CreateOr(NotCond, TrueVal);
9327       }
9328     }
9329     
9330     // select a, b, a  -> a&b
9331     // select a, a, b  -> a|b
9332     if (CondVal == TrueVal)
9333       return BinaryOperator::CreateOr(CondVal, FalseVal);
9334     else if (CondVal == FalseVal)
9335       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9336   }
9337
9338   // Selecting between two integer constants?
9339   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9340     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9341       // select C, 1, 0 -> zext C to int
9342       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9343         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9344       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9345         // select C, 0, 1 -> zext !C to int
9346         Value *NotCond =
9347           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9348                                                "not."+CondVal->getName()), SI);
9349         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9350       }
9351
9352       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9353         // If one of the constants is zero (we know they can't both be) and we
9354         // have an icmp instruction with zero, and we have an 'and' with the
9355         // non-constant value, eliminate this whole mess.  This corresponds to
9356         // cases like this: ((X & 27) ? 27 : 0)
9357         if (TrueValC->isZero() || FalseValC->isZero())
9358           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9359               cast<Constant>(IC->getOperand(1))->isNullValue())
9360             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9361               if (ICA->getOpcode() == Instruction::And &&
9362                   isa<ConstantInt>(ICA->getOperand(1)) &&
9363                   (ICA->getOperand(1) == TrueValC ||
9364                    ICA->getOperand(1) == FalseValC) &&
9365                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9366                 // Okay, now we know that everything is set up, we just don't
9367                 // know whether we have a icmp_ne or icmp_eq and whether the 
9368                 // true or false val is the zero.
9369                 bool ShouldNotVal = !TrueValC->isZero();
9370                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9371                 Value *V = ICA;
9372                 if (ShouldNotVal)
9373                   V = InsertNewInstBefore(BinaryOperator::Create(
9374                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9375                 return ReplaceInstUsesWith(SI, V);
9376               }
9377       }
9378     }
9379
9380   // See if we are selecting two values based on a comparison of the two values.
9381   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9382     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9383       // Transform (X == Y) ? X : Y  -> Y
9384       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9385         // This is not safe in general for floating point:  
9386         // consider X== -0, Y== +0.
9387         // It becomes safe if either operand is a nonzero constant.
9388         ConstantFP *CFPt, *CFPf;
9389         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9390               !CFPt->getValueAPF().isZero()) ||
9391             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9392              !CFPf->getValueAPF().isZero()))
9393         return ReplaceInstUsesWith(SI, FalseVal);
9394       }
9395       // Transform (X != Y) ? X : Y  -> X
9396       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9397         return ReplaceInstUsesWith(SI, TrueVal);
9398       // NOTE: if we wanted to, this is where to detect MIN/MAX
9399
9400     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9401       // Transform (X == Y) ? Y : X  -> X
9402       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9403         // This is not safe in general for floating point:  
9404         // consider X== -0, Y== +0.
9405         // It becomes safe if either operand is a nonzero constant.
9406         ConstantFP *CFPt, *CFPf;
9407         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9408               !CFPt->getValueAPF().isZero()) ||
9409             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9410              !CFPf->getValueAPF().isZero()))
9411           return ReplaceInstUsesWith(SI, FalseVal);
9412       }
9413       // Transform (X != Y) ? Y : X  -> Y
9414       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9415         return ReplaceInstUsesWith(SI, TrueVal);
9416       // NOTE: if we wanted to, this is where to detect MIN/MAX
9417     }
9418     // NOTE: if we wanted to, this is where to detect ABS
9419   }
9420
9421   // See if we are selecting two values based on a comparison of the two values.
9422   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9423     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9424       return Result;
9425
9426   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9427     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9428       if (TI->hasOneUse() && FI->hasOneUse()) {
9429         Instruction *AddOp = 0, *SubOp = 0;
9430
9431         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9432         if (TI->getOpcode() == FI->getOpcode())
9433           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9434             return IV;
9435
9436         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9437         // even legal for FP.
9438         if ((TI->getOpcode() == Instruction::Sub &&
9439              FI->getOpcode() == Instruction::Add) ||
9440             (TI->getOpcode() == Instruction::FSub &&
9441              FI->getOpcode() == Instruction::FAdd)) {
9442           AddOp = FI; SubOp = TI;
9443         } else if ((FI->getOpcode() == Instruction::Sub &&
9444                     TI->getOpcode() == Instruction::Add) ||
9445                    (FI->getOpcode() == Instruction::FSub &&
9446                     TI->getOpcode() == Instruction::FAdd)) {
9447           AddOp = TI; SubOp = FI;
9448         }
9449
9450         if (AddOp) {
9451           Value *OtherAddOp = 0;
9452           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9453             OtherAddOp = AddOp->getOperand(1);
9454           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9455             OtherAddOp = AddOp->getOperand(0);
9456           }
9457
9458           if (OtherAddOp) {
9459             // So at this point we know we have (Y -> OtherAddOp):
9460             //        select C, (add X, Y), (sub X, Z)
9461             Value *NegVal;  // Compute -Z
9462             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9463               NegVal = ConstantExpr::getNeg(C);
9464             } else {
9465               NegVal = InsertNewInstBefore(
9466                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9467                                               "tmp"), SI);
9468             }
9469
9470             Value *NewTrueOp = OtherAddOp;
9471             Value *NewFalseOp = NegVal;
9472             if (AddOp != TI)
9473               std::swap(NewTrueOp, NewFalseOp);
9474             Instruction *NewSel =
9475               SelectInst::Create(CondVal, NewTrueOp,
9476                                  NewFalseOp, SI.getName() + ".p");
9477
9478             NewSel = InsertNewInstBefore(NewSel, SI);
9479             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9480           }
9481         }
9482       }
9483
9484   // See if we can fold the select into one of our operands.
9485   if (SI.getType()->isInteger()) {
9486     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9487     if (FoldI)
9488       return FoldI;
9489   }
9490
9491   // See if we can fold the select into a phi node.  The true/false values have
9492   // to be live in the predecessor blocks.  If they are instructions in SI's
9493   // block, we can't map to the predecessor.
9494   if (isa<PHINode>(SI.getCondition()) &&
9495       (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9496        isa<PHINode>(SI.getTrueValue())) &&
9497       (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9498        isa<PHINode>(SI.getFalseValue())))
9499     if (Instruction *NV = FoldOpIntoPhi(SI))
9500       return NV;
9501
9502   if (BinaryOperator::isNot(CondVal)) {
9503     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9504     SI.setOperand(1, FalseVal);
9505     SI.setOperand(2, TrueVal);
9506     return &SI;
9507   }
9508
9509   return 0;
9510 }
9511
9512 /// EnforceKnownAlignment - If the specified pointer points to an object that
9513 /// we control, modify the object's alignment to PrefAlign. This isn't
9514 /// often possible though. If alignment is important, a more reliable approach
9515 /// is to simply align all global variables and allocation instructions to
9516 /// their preferred alignment from the beginning.
9517 ///
9518 static unsigned EnforceKnownAlignment(Value *V,
9519                                       unsigned Align, unsigned PrefAlign) {
9520
9521   User *U = dyn_cast<User>(V);
9522   if (!U) return Align;
9523
9524   switch (Operator::getOpcode(U)) {
9525   default: break;
9526   case Instruction::BitCast:
9527     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9528   case Instruction::GetElementPtr: {
9529     // If all indexes are zero, it is just the alignment of the base pointer.
9530     bool AllZeroOperands = true;
9531     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9532       if (!isa<Constant>(*i) ||
9533           !cast<Constant>(*i)->isNullValue()) {
9534         AllZeroOperands = false;
9535         break;
9536       }
9537
9538     if (AllZeroOperands) {
9539       // Treat this like a bitcast.
9540       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9541     }
9542     break;
9543   }
9544   }
9545
9546   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9547     // If there is a large requested alignment and we can, bump up the alignment
9548     // of the global.
9549     if (!GV->isDeclaration()) {
9550       if (GV->getAlignment() >= PrefAlign)
9551         Align = GV->getAlignment();
9552       else {
9553         GV->setAlignment(PrefAlign);
9554         Align = PrefAlign;
9555       }
9556     }
9557   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9558     // If there is a requested alignment and if this is an alloca, round up.
9559     if (AI->getAlignment() >= PrefAlign)
9560       Align = AI->getAlignment();
9561     else {
9562       AI->setAlignment(PrefAlign);
9563       Align = PrefAlign;
9564     }
9565   }
9566
9567   return Align;
9568 }
9569
9570 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9571 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9572 /// and it is more than the alignment of the ultimate object, see if we can
9573 /// increase the alignment of the ultimate object, making this check succeed.
9574 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9575                                                   unsigned PrefAlign) {
9576   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9577                       sizeof(PrefAlign) * CHAR_BIT;
9578   APInt Mask = APInt::getAllOnesValue(BitWidth);
9579   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9580   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9581   unsigned TrailZ = KnownZero.countTrailingOnes();
9582   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9583
9584   if (PrefAlign > Align)
9585     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9586   
9587     // We don't need to make any adjustment.
9588   return Align;
9589 }
9590
9591 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9592   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9593   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9594   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9595   unsigned CopyAlign = MI->getAlignment();
9596
9597   if (CopyAlign < MinAlign) {
9598     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9599                                              MinAlign, false));
9600     return MI;
9601   }
9602   
9603   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9604   // load/store.
9605   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9606   if (MemOpLength == 0) return 0;
9607   
9608   // Source and destination pointer types are always "i8*" for intrinsic.  See
9609   // if the size is something we can handle with a single primitive load/store.
9610   // A single load+store correctly handles overlapping memory in the memmove
9611   // case.
9612   unsigned Size = MemOpLength->getZExtValue();
9613   if (Size == 0) return MI;  // Delete this mem transfer.
9614   
9615   if (Size > 8 || (Size&(Size-1)))
9616     return 0;  // If not 1/2/4/8 bytes, exit.
9617   
9618   // Use an integer load+store unless we can find something better.
9619   Type *NewPtrTy =
9620                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9621   
9622   // Memcpy forces the use of i8* for the source and destination.  That means
9623   // that if you're using memcpy to move one double around, you'll get a cast
9624   // from double* to i8*.  We'd much rather use a double load+store rather than
9625   // an i64 load+store, here because this improves the odds that the source or
9626   // dest address will be promotable.  See if we can find a better type than the
9627   // integer datatype.
9628   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9629     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9630     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9631       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9632       // down through these levels if so.
9633       while (!SrcETy->isSingleValueType()) {
9634         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9635           if (STy->getNumElements() == 1)
9636             SrcETy = STy->getElementType(0);
9637           else
9638             break;
9639         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9640           if (ATy->getNumElements() == 1)
9641             SrcETy = ATy->getElementType();
9642           else
9643             break;
9644         } else
9645           break;
9646       }
9647       
9648       if (SrcETy->isSingleValueType())
9649         NewPtrTy = PointerType::getUnqual(SrcETy);
9650     }
9651   }
9652   
9653   
9654   // If the memcpy/memmove provides better alignment info than we can
9655   // infer, use it.
9656   SrcAlign = std::max(SrcAlign, CopyAlign);
9657   DstAlign = std::max(DstAlign, CopyAlign);
9658   
9659   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9660   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9661   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9662   InsertNewInstBefore(L, *MI);
9663   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9664
9665   // Set the size of the copy to 0, it will be deleted on the next iteration.
9666   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9667   return MI;
9668 }
9669
9670 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9671   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9672   if (MI->getAlignment() < Alignment) {
9673     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9674                                              Alignment, false));
9675     return MI;
9676   }
9677   
9678   // Extract the length and alignment and fill if they are constant.
9679   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9680   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9681   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9682     return 0;
9683   uint64_t Len = LenC->getZExtValue();
9684   Alignment = MI->getAlignment();
9685   
9686   // If the length is zero, this is a no-op
9687   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9688   
9689   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9690   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9691     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9692     
9693     Value *Dest = MI->getDest();
9694     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9695
9696     // Alignment 0 is identity for alignment 1 for memset, but not store.
9697     if (Alignment == 0) Alignment = 1;
9698     
9699     // Extract the fill value and store.
9700     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9701     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9702                                       Dest, false, Alignment), *MI);
9703     
9704     // Set the size of the copy to 0, it will be deleted on the next iteration.
9705     MI->setLength(Constant::getNullValue(LenC->getType()));
9706     return MI;
9707   }
9708
9709   return 0;
9710 }
9711
9712
9713 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9714 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9715 /// the heavy lifting.
9716 ///
9717 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9718   // If the caller function is nounwind, mark the call as nounwind, even if the
9719   // callee isn't.
9720   if (CI.getParent()->getParent()->doesNotThrow() &&
9721       !CI.doesNotThrow()) {
9722     CI.setDoesNotThrow();
9723     return &CI;
9724   }
9725   
9726   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9727   if (!II) return visitCallSite(&CI);
9728   
9729   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9730   // visitCallSite.
9731   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9732     bool Changed = false;
9733
9734     // memmove/cpy/set of zero bytes is a noop.
9735     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9736       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9737
9738       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9739         if (CI->getZExtValue() == 1) {
9740           // Replace the instruction with just byte operations.  We would
9741           // transform other cases to loads/stores, but we don't know if
9742           // alignment is sufficient.
9743         }
9744     }
9745
9746     // If we have a memmove and the source operation is a constant global,
9747     // then the source and dest pointers can't alias, so we can change this
9748     // into a call to memcpy.
9749     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9750       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9751         if (GVSrc->isConstant()) {
9752           Module *M = CI.getParent()->getParent()->getParent();
9753           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9754           const Type *Tys[1];
9755           Tys[0] = CI.getOperand(3)->getType();
9756           CI.setOperand(0, 
9757                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9758           Changed = true;
9759         }
9760
9761       // memmove(x,x,size) -> noop.
9762       if (MMI->getSource() == MMI->getDest())
9763         return EraseInstFromFunction(CI);
9764     }
9765
9766     // If we can determine a pointer alignment that is bigger than currently
9767     // set, update the alignment.
9768     if (isa<MemTransferInst>(MI)) {
9769       if (Instruction *I = SimplifyMemTransfer(MI))
9770         return I;
9771     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9772       if (Instruction *I = SimplifyMemSet(MSI))
9773         return I;
9774     }
9775           
9776     if (Changed) return II;
9777   }
9778   
9779   switch (II->getIntrinsicID()) {
9780   default: break;
9781   case Intrinsic::bswap:
9782     // bswap(bswap(x)) -> x
9783     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9784       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9785         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9786     break;
9787   case Intrinsic::ppc_altivec_lvx:
9788   case Intrinsic::ppc_altivec_lvxl:
9789   case Intrinsic::x86_sse_loadu_ps:
9790   case Intrinsic::x86_sse2_loadu_pd:
9791   case Intrinsic::x86_sse2_loadu_dq:
9792     // Turn PPC lvx     -> load if the pointer is known aligned.
9793     // Turn X86 loadups -> load if the pointer is known aligned.
9794     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9795       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9796                                          PointerType::getUnqual(II->getType()));
9797       return new LoadInst(Ptr);
9798     }
9799     break;
9800   case Intrinsic::ppc_altivec_stvx:
9801   case Intrinsic::ppc_altivec_stvxl:
9802     // Turn stvx -> store if the pointer is known aligned.
9803     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9804       const Type *OpPtrTy = 
9805         PointerType::getUnqual(II->getOperand(1)->getType());
9806       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9807       return new StoreInst(II->getOperand(1), Ptr);
9808     }
9809     break;
9810   case Intrinsic::x86_sse_storeu_ps:
9811   case Intrinsic::x86_sse2_storeu_pd:
9812   case Intrinsic::x86_sse2_storeu_dq:
9813     // Turn X86 storeu -> store if the pointer is known aligned.
9814     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9815       const Type *OpPtrTy = 
9816         PointerType::getUnqual(II->getOperand(2)->getType());
9817       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9818       return new StoreInst(II->getOperand(2), Ptr);
9819     }
9820     break;
9821     
9822   case Intrinsic::x86_sse_cvttss2si: {
9823     // These intrinsics only demands the 0th element of its input vector.  If
9824     // we can simplify the input based on that, do so now.
9825     unsigned VWidth =
9826       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9827     APInt DemandedElts(VWidth, 1);
9828     APInt UndefElts(VWidth, 0);
9829     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9830                                               UndefElts)) {
9831       II->setOperand(1, V);
9832       return II;
9833     }
9834     break;
9835   }
9836     
9837   case Intrinsic::ppc_altivec_vperm:
9838     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9839     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9840       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9841       
9842       // Check that all of the elements are integer constants or undefs.
9843       bool AllEltsOk = true;
9844       for (unsigned i = 0; i != 16; ++i) {
9845         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9846             !isa<UndefValue>(Mask->getOperand(i))) {
9847           AllEltsOk = false;
9848           break;
9849         }
9850       }
9851       
9852       if (AllEltsOk) {
9853         // Cast the input vectors to byte vectors.
9854         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9855         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9856         Value *Result = UndefValue::get(Op0->getType());
9857         
9858         // Only extract each element once.
9859         Value *ExtractedElts[32];
9860         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9861         
9862         for (unsigned i = 0; i != 16; ++i) {
9863           if (isa<UndefValue>(Mask->getOperand(i)))
9864             continue;
9865           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9866           Idx &= 31;  // Match the hardware behavior.
9867           
9868           if (ExtractedElts[Idx] == 0) {
9869             ExtractedElts[Idx] = 
9870               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9871                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9872                                             "tmp");
9873           }
9874         
9875           // Insert this value into the result vector.
9876           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9877                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9878                                                 "tmp");
9879         }
9880         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9881       }
9882     }
9883     break;
9884
9885   case Intrinsic::stackrestore: {
9886     // If the save is right next to the restore, remove the restore.  This can
9887     // happen when variable allocas are DCE'd.
9888     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9889       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9890         BasicBlock::iterator BI = SS;
9891         if (&*++BI == II)
9892           return EraseInstFromFunction(CI);
9893       }
9894     }
9895     
9896     // Scan down this block to see if there is another stack restore in the
9897     // same block without an intervening call/alloca.
9898     BasicBlock::iterator BI = II;
9899     TerminatorInst *TI = II->getParent()->getTerminator();
9900     bool CannotRemove = false;
9901     for (++BI; &*BI != TI; ++BI) {
9902       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9903         CannotRemove = true;
9904         break;
9905       }
9906       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9907         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9908           // If there is a stackrestore below this one, remove this one.
9909           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9910             return EraseInstFromFunction(CI);
9911           // Otherwise, ignore the intrinsic.
9912         } else {
9913           // If we found a non-intrinsic call, we can't remove the stack
9914           // restore.
9915           CannotRemove = true;
9916           break;
9917         }
9918       }
9919     }
9920     
9921     // If the stack restore is in a return/unwind block and if there are no
9922     // allocas or calls between the restore and the return, nuke the restore.
9923     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9924       return EraseInstFromFunction(CI);
9925     break;
9926   }
9927   }
9928
9929   return visitCallSite(II);
9930 }
9931
9932 // InvokeInst simplification
9933 //
9934 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9935   return visitCallSite(&II);
9936 }
9937
9938 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9939 /// passed through the varargs area, we can eliminate the use of the cast.
9940 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9941                                          const CastInst * const CI,
9942                                          const TargetData * const TD,
9943                                          const int ix) {
9944   if (!CI->isLosslessCast())
9945     return false;
9946
9947   // The size of ByVal arguments is derived from the type, so we
9948   // can't change to a type with a different size.  If the size were
9949   // passed explicitly we could avoid this check.
9950   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9951     return true;
9952
9953   const Type* SrcTy = 
9954             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9955   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9956   if (!SrcTy->isSized() || !DstTy->isSized())
9957     return false;
9958   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9959     return false;
9960   return true;
9961 }
9962
9963 // visitCallSite - Improvements for call and invoke instructions.
9964 //
9965 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9966   bool Changed = false;
9967
9968   // If the callee is a constexpr cast of a function, attempt to move the cast
9969   // to the arguments of the call/invoke.
9970   if (transformConstExprCastCall(CS)) return 0;
9971
9972   Value *Callee = CS.getCalledValue();
9973
9974   if (Function *CalleeF = dyn_cast<Function>(Callee))
9975     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9976       Instruction *OldCall = CS.getInstruction();
9977       // If the call and callee calling conventions don't match, this call must
9978       // be unreachable, as the call is undefined.
9979       new StoreInst(ConstantInt::getTrue(*Context),
9980                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
9981                                   OldCall);
9982       OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9983       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9984         return EraseInstFromFunction(*OldCall);
9985       return 0;
9986     }
9987
9988   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9989     // This instruction is not reachable, just remove it.  We insert a store to
9990     // undef so that we know that this code is not reachable, despite the fact
9991     // that we can't modify the CFG here.
9992     new StoreInst(ConstantInt::getTrue(*Context),
9993                UndefValue::get(Type::getInt1PtrTy(*Context)),
9994                   CS.getInstruction());
9995
9996     CS.getInstruction()->
9997       replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9998
9999     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10000       // Don't break the CFG, insert a dummy cond branch.
10001       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10002                          ConstantInt::getTrue(*Context), II);
10003     }
10004     return EraseInstFromFunction(*CS.getInstruction());
10005   }
10006
10007   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10008     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10009       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10010         return transformCallThroughTrampoline(CS);
10011
10012   const PointerType *PTy = cast<PointerType>(Callee->getType());
10013   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10014   if (FTy->isVarArg()) {
10015     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10016     // See if we can optimize any arguments passed through the varargs area of
10017     // the call.
10018     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10019            E = CS.arg_end(); I != E; ++I, ++ix) {
10020       CastInst *CI = dyn_cast<CastInst>(*I);
10021       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10022         *I = CI->getOperand(0);
10023         Changed = true;
10024       }
10025     }
10026   }
10027
10028   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10029     // Inline asm calls cannot throw - mark them 'nounwind'.
10030     CS.setDoesNotThrow();
10031     Changed = true;
10032   }
10033
10034   return Changed ? CS.getInstruction() : 0;
10035 }
10036
10037 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10038 // attempt to move the cast to the arguments of the call/invoke.
10039 //
10040 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10041   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10042   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10043   if (CE->getOpcode() != Instruction::BitCast || 
10044       !isa<Function>(CE->getOperand(0)))
10045     return false;
10046   Function *Callee = cast<Function>(CE->getOperand(0));
10047   Instruction *Caller = CS.getInstruction();
10048   const AttrListPtr &CallerPAL = CS.getAttributes();
10049
10050   // Okay, this is a cast from a function to a different type.  Unless doing so
10051   // would cause a type conversion of one of our arguments, change this call to
10052   // be a direct call with arguments casted to the appropriate types.
10053   //
10054   const FunctionType *FT = Callee->getFunctionType();
10055   const Type *OldRetTy = Caller->getType();
10056   const Type *NewRetTy = FT->getReturnType();
10057
10058   if (isa<StructType>(NewRetTy))
10059     return false; // TODO: Handle multiple return values.
10060
10061   // Check to see if we are changing the return type...
10062   if (OldRetTy != NewRetTy) {
10063     if (Callee->isDeclaration() &&
10064         // Conversion is ok if changing from one pointer type to another or from
10065         // a pointer to an integer of the same size.
10066         !((isa<PointerType>(OldRetTy) || !TD ||
10067            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10068           (isa<PointerType>(NewRetTy) || !TD ||
10069            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10070       return false;   // Cannot transform this return value.
10071
10072     if (!Caller->use_empty() &&
10073         // void -> non-void is handled specially
10074         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10075       return false;   // Cannot transform this return value.
10076
10077     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10078       Attributes RAttrs = CallerPAL.getRetAttributes();
10079       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10080         return false;   // Attribute not compatible with transformed value.
10081     }
10082
10083     // If the callsite is an invoke instruction, and the return value is used by
10084     // a PHI node in a successor, we cannot change the return type of the call
10085     // because there is no place to put the cast instruction (without breaking
10086     // the critical edge).  Bail out in this case.
10087     if (!Caller->use_empty())
10088       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10089         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10090              UI != E; ++UI)
10091           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10092             if (PN->getParent() == II->getNormalDest() ||
10093                 PN->getParent() == II->getUnwindDest())
10094               return false;
10095   }
10096
10097   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10098   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10099
10100   CallSite::arg_iterator AI = CS.arg_begin();
10101   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10102     const Type *ParamTy = FT->getParamType(i);
10103     const Type *ActTy = (*AI)->getType();
10104
10105     if (!CastInst::isCastable(ActTy, ParamTy))
10106       return false;   // Cannot transform this parameter value.
10107
10108     if (CallerPAL.getParamAttributes(i + 1) 
10109         & Attribute::typeIncompatible(ParamTy))
10110       return false;   // Attribute not compatible with transformed value.
10111
10112     // Converting from one pointer type to another or between a pointer and an
10113     // integer of the same size is safe even if we do not have a body.
10114     bool isConvertible = ActTy == ParamTy ||
10115       (TD && ((isa<PointerType>(ParamTy) ||
10116       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10117               (isa<PointerType>(ActTy) ||
10118               ActTy == TD->getIntPtrType(Caller->getContext()))));
10119     if (Callee->isDeclaration() && !isConvertible) return false;
10120   }
10121
10122   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10123       Callee->isDeclaration())
10124     return false;   // Do not delete arguments unless we have a function body.
10125
10126   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10127       !CallerPAL.isEmpty())
10128     // In this case we have more arguments than the new function type, but we
10129     // won't be dropping them.  Check that these extra arguments have attributes
10130     // that are compatible with being a vararg call argument.
10131     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10132       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10133         break;
10134       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10135       if (PAttrs & Attribute::VarArgsIncompatible)
10136         return false;
10137     }
10138
10139   // Okay, we decided that this is a safe thing to do: go ahead and start
10140   // inserting cast instructions as necessary...
10141   std::vector<Value*> Args;
10142   Args.reserve(NumActualArgs);
10143   SmallVector<AttributeWithIndex, 8> attrVec;
10144   attrVec.reserve(NumCommonArgs);
10145
10146   // Get any return attributes.
10147   Attributes RAttrs = CallerPAL.getRetAttributes();
10148
10149   // If the return value is not being used, the type may not be compatible
10150   // with the existing attributes.  Wipe out any problematic attributes.
10151   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10152
10153   // Add the new return attributes.
10154   if (RAttrs)
10155     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10156
10157   AI = CS.arg_begin();
10158   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10159     const Type *ParamTy = FT->getParamType(i);
10160     if ((*AI)->getType() == ParamTy) {
10161       Args.push_back(*AI);
10162     } else {
10163       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10164           false, ParamTy, false);
10165       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10166     }
10167
10168     // Add any parameter attributes.
10169     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10170       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10171   }
10172
10173   // If the function takes more arguments than the call was taking, add them
10174   // now.
10175   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10176     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10177
10178   // If we are removing arguments to the function, emit an obnoxious warning.
10179   if (FT->getNumParams() < NumActualArgs) {
10180     if (!FT->isVarArg()) {
10181       errs() << "WARNING: While resolving call to function '"
10182              << Callee->getName() << "' arguments were dropped!\n";
10183     } else {
10184       // Add all of the arguments in their promoted form to the arg list.
10185       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10186         const Type *PTy = getPromotedType((*AI)->getType());
10187         if (PTy != (*AI)->getType()) {
10188           // Must promote to pass through va_arg area!
10189           Instruction::CastOps opcode =
10190             CastInst::getCastOpcode(*AI, false, PTy, false);
10191           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10192         } else {
10193           Args.push_back(*AI);
10194         }
10195
10196         // Add any parameter attributes.
10197         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10198           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10199       }
10200     }
10201   }
10202
10203   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10204     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10205
10206   if (NewRetTy == Type::getVoidTy(*Context))
10207     Caller->setName("");   // Void type should not have a name.
10208
10209   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10210                                                      attrVec.end());
10211
10212   Instruction *NC;
10213   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10214     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10215                             Args.begin(), Args.end(),
10216                             Caller->getName(), Caller);
10217     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10218     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10219   } else {
10220     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10221                           Caller->getName(), Caller);
10222     CallInst *CI = cast<CallInst>(Caller);
10223     if (CI->isTailCall())
10224       cast<CallInst>(NC)->setTailCall();
10225     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10226     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10227   }
10228
10229   // Insert a cast of the return type as necessary.
10230   Value *NV = NC;
10231   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10232     if (NV->getType() != Type::getVoidTy(*Context)) {
10233       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10234                                                             OldRetTy, false);
10235       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10236
10237       // If this is an invoke instruction, we should insert it after the first
10238       // non-phi, instruction in the normal successor block.
10239       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10240         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10241         InsertNewInstBefore(NC, *I);
10242       } else {
10243         // Otherwise, it's a call, just insert cast right after the call instr
10244         InsertNewInstBefore(NC, *Caller);
10245       }
10246       Worklist.AddUsersToWorkList(*Caller);
10247     } else {
10248       NV = UndefValue::get(Caller->getType());
10249     }
10250   }
10251
10252
10253   if (!Caller->use_empty())
10254     Caller->replaceAllUsesWith(NV);
10255   
10256   EraseInstFromFunction(*Caller);
10257   return true;
10258 }
10259
10260 // transformCallThroughTrampoline - Turn a call to a function created by the
10261 // init_trampoline intrinsic into a direct call to the underlying function.
10262 //
10263 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10264   Value *Callee = CS.getCalledValue();
10265   const PointerType *PTy = cast<PointerType>(Callee->getType());
10266   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10267   const AttrListPtr &Attrs = CS.getAttributes();
10268
10269   // If the call already has the 'nest' attribute somewhere then give up -
10270   // otherwise 'nest' would occur twice after splicing in the chain.
10271   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10272     return 0;
10273
10274   IntrinsicInst *Tramp =
10275     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10276
10277   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10278   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10279   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10280
10281   const AttrListPtr &NestAttrs = NestF->getAttributes();
10282   if (!NestAttrs.isEmpty()) {
10283     unsigned NestIdx = 1;
10284     const Type *NestTy = 0;
10285     Attributes NestAttr = Attribute::None;
10286
10287     // Look for a parameter marked with the 'nest' attribute.
10288     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10289          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10290       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10291         // Record the parameter type and any other attributes.
10292         NestTy = *I;
10293         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10294         break;
10295       }
10296
10297     if (NestTy) {
10298       Instruction *Caller = CS.getInstruction();
10299       std::vector<Value*> NewArgs;
10300       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10301
10302       SmallVector<AttributeWithIndex, 8> NewAttrs;
10303       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10304
10305       // Insert the nest argument into the call argument list, which may
10306       // mean appending it.  Likewise for attributes.
10307
10308       // Add any result attributes.
10309       if (Attributes Attr = Attrs.getRetAttributes())
10310         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10311
10312       {
10313         unsigned Idx = 1;
10314         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10315         do {
10316           if (Idx == NestIdx) {
10317             // Add the chain argument and attributes.
10318             Value *NestVal = Tramp->getOperand(3);
10319             if (NestVal->getType() != NestTy)
10320               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10321             NewArgs.push_back(NestVal);
10322             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10323           }
10324
10325           if (I == E)
10326             break;
10327
10328           // Add the original argument and attributes.
10329           NewArgs.push_back(*I);
10330           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10331             NewAttrs.push_back
10332               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10333
10334           ++Idx, ++I;
10335         } while (1);
10336       }
10337
10338       // Add any function attributes.
10339       if (Attributes Attr = Attrs.getFnAttributes())
10340         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10341
10342       // The trampoline may have been bitcast to a bogus type (FTy).
10343       // Handle this by synthesizing a new function type, equal to FTy
10344       // with the chain parameter inserted.
10345
10346       std::vector<const Type*> NewTypes;
10347       NewTypes.reserve(FTy->getNumParams()+1);
10348
10349       // Insert the chain's type into the list of parameter types, which may
10350       // mean appending it.
10351       {
10352         unsigned Idx = 1;
10353         FunctionType::param_iterator I = FTy->param_begin(),
10354           E = FTy->param_end();
10355
10356         do {
10357           if (Idx == NestIdx)
10358             // Add the chain's type.
10359             NewTypes.push_back(NestTy);
10360
10361           if (I == E)
10362             break;
10363
10364           // Add the original type.
10365           NewTypes.push_back(*I);
10366
10367           ++Idx, ++I;
10368         } while (1);
10369       }
10370
10371       // Replace the trampoline call with a direct call.  Let the generic
10372       // code sort out any function type mismatches.
10373       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10374                                                 FTy->isVarArg());
10375       Constant *NewCallee =
10376         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10377         NestF : ConstantExpr::getBitCast(NestF, 
10378                                          PointerType::getUnqual(NewFTy));
10379       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10380                                                    NewAttrs.end());
10381
10382       Instruction *NewCaller;
10383       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10384         NewCaller = InvokeInst::Create(NewCallee,
10385                                        II->getNormalDest(), II->getUnwindDest(),
10386                                        NewArgs.begin(), NewArgs.end(),
10387                                        Caller->getName(), Caller);
10388         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10389         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10390       } else {
10391         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10392                                      Caller->getName(), Caller);
10393         if (cast<CallInst>(Caller)->isTailCall())
10394           cast<CallInst>(NewCaller)->setTailCall();
10395         cast<CallInst>(NewCaller)->
10396           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10397         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10398       }
10399       if (Caller->getType() != Type::getVoidTy(*Context))
10400         Caller->replaceAllUsesWith(NewCaller);
10401       Caller->eraseFromParent();
10402       Worklist.Remove(Caller);
10403       return 0;
10404     }
10405   }
10406
10407   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10408   // parameter, there is no need to adjust the argument list.  Let the generic
10409   // code sort out any function type mismatches.
10410   Constant *NewCallee =
10411     NestF->getType() == PTy ? NestF : 
10412                               ConstantExpr::getBitCast(NestF, PTy);
10413   CS.setCalledFunction(NewCallee);
10414   return CS.getInstruction();
10415 }
10416
10417 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10418 /// and if a/b/c and the add's all have a single use, turn this into a phi
10419 /// and a single binop.
10420 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10421   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10422   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10423   unsigned Opc = FirstInst->getOpcode();
10424   Value *LHSVal = FirstInst->getOperand(0);
10425   Value *RHSVal = FirstInst->getOperand(1);
10426     
10427   const Type *LHSType = LHSVal->getType();
10428   const Type *RHSType = RHSVal->getType();
10429   
10430   // Scan to see if all operands are the same opcode, and all have one use.
10431   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10432     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10433     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10434         // Verify type of the LHS matches so we don't fold cmp's of different
10435         // types or GEP's with different index types.
10436         I->getOperand(0)->getType() != LHSType ||
10437         I->getOperand(1)->getType() != RHSType)
10438       return 0;
10439
10440     // If they are CmpInst instructions, check their predicates
10441     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10442       if (cast<CmpInst>(I)->getPredicate() !=
10443           cast<CmpInst>(FirstInst)->getPredicate())
10444         return 0;
10445     
10446     // Keep track of which operand needs a phi node.
10447     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10448     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10449   }
10450
10451   // If both LHS and RHS would need a PHI, don't do this transformation,
10452   // because it would increase the number of PHIs entering the block,
10453   // which leads to higher register pressure. This is especially
10454   // bad when the PHIs are in the header of a loop.
10455   if (!LHSVal && !RHSVal)
10456     return 0;
10457   
10458   // Otherwise, this is safe to transform!
10459   
10460   Value *InLHS = FirstInst->getOperand(0);
10461   Value *InRHS = FirstInst->getOperand(1);
10462   PHINode *NewLHS = 0, *NewRHS = 0;
10463   if (LHSVal == 0) {
10464     NewLHS = PHINode::Create(LHSType,
10465                              FirstInst->getOperand(0)->getName() + ".pn");
10466     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10467     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10468     InsertNewInstBefore(NewLHS, PN);
10469     LHSVal = NewLHS;
10470   }
10471   
10472   if (RHSVal == 0) {
10473     NewRHS = PHINode::Create(RHSType,
10474                              FirstInst->getOperand(1)->getName() + ".pn");
10475     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10476     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10477     InsertNewInstBefore(NewRHS, PN);
10478     RHSVal = NewRHS;
10479   }
10480   
10481   // Add all operands to the new PHIs.
10482   if (NewLHS || NewRHS) {
10483     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10484       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10485       if (NewLHS) {
10486         Value *NewInLHS = InInst->getOperand(0);
10487         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10488       }
10489       if (NewRHS) {
10490         Value *NewInRHS = InInst->getOperand(1);
10491         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10492       }
10493     }
10494   }
10495     
10496   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10497     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10498   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10499   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10500                          LHSVal, RHSVal);
10501 }
10502
10503 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10504   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10505   
10506   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10507                                         FirstInst->op_end());
10508   // This is true if all GEP bases are allocas and if all indices into them are
10509   // constants.
10510   bool AllBasePointersAreAllocas = true;
10511
10512   // We don't want to replace this phi if the replacement would require
10513   // more than one phi, which leads to higher register pressure. This is
10514   // especially bad when the PHIs are in the header of a loop.
10515   bool NeededPhi = false;
10516   
10517   // Scan to see if all operands are the same opcode, and all have one use.
10518   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10519     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10520     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10521       GEP->getNumOperands() != FirstInst->getNumOperands())
10522       return 0;
10523
10524     // Keep track of whether or not all GEPs are of alloca pointers.
10525     if (AllBasePointersAreAllocas &&
10526         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10527          !GEP->hasAllConstantIndices()))
10528       AllBasePointersAreAllocas = false;
10529     
10530     // Compare the operand lists.
10531     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10532       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10533         continue;
10534       
10535       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10536       // if one of the PHIs has a constant for the index.  The index may be
10537       // substantially cheaper to compute for the constants, so making it a
10538       // variable index could pessimize the path.  This also handles the case
10539       // for struct indices, which must always be constant.
10540       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10541           isa<ConstantInt>(GEP->getOperand(op)))
10542         return 0;
10543       
10544       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10545         return 0;
10546
10547       // If we already needed a PHI for an earlier operand, and another operand
10548       // also requires a PHI, we'd be introducing more PHIs than we're
10549       // eliminating, which increases register pressure on entry to the PHI's
10550       // block.
10551       if (NeededPhi)
10552         return 0;
10553
10554       FixedOperands[op] = 0;  // Needs a PHI.
10555       NeededPhi = true;
10556     }
10557   }
10558   
10559   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10560   // bother doing this transformation.  At best, this will just save a bit of
10561   // offset calculation, but all the predecessors will have to materialize the
10562   // stack address into a register anyway.  We'd actually rather *clone* the
10563   // load up into the predecessors so that we have a load of a gep of an alloca,
10564   // which can usually all be folded into the load.
10565   if (AllBasePointersAreAllocas)
10566     return 0;
10567   
10568   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10569   // that is variable.
10570   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10571   
10572   bool HasAnyPHIs = false;
10573   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10574     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10575     Value *FirstOp = FirstInst->getOperand(i);
10576     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10577                                      FirstOp->getName()+".pn");
10578     InsertNewInstBefore(NewPN, PN);
10579     
10580     NewPN->reserveOperandSpace(e);
10581     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10582     OperandPhis[i] = NewPN;
10583     FixedOperands[i] = NewPN;
10584     HasAnyPHIs = true;
10585   }
10586
10587   
10588   // Add all operands to the new PHIs.
10589   if (HasAnyPHIs) {
10590     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10591       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10592       BasicBlock *InBB = PN.getIncomingBlock(i);
10593       
10594       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10595         if (PHINode *OpPhi = OperandPhis[op])
10596           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10597     }
10598   }
10599   
10600   Value *Base = FixedOperands[0];
10601   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10602     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10603                                       FixedOperands.end()) :
10604     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10605                               FixedOperands.end());
10606 }
10607
10608
10609 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10610 /// sink the load out of the block that defines it.  This means that it must be
10611 /// obvious the value of the load is not changed from the point of the load to
10612 /// the end of the block it is in.
10613 ///
10614 /// Finally, it is safe, but not profitable, to sink a load targetting a
10615 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10616 /// to a register.
10617 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10618   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10619   
10620   for (++BBI; BBI != E; ++BBI)
10621     if (BBI->mayWriteToMemory())
10622       return false;
10623   
10624   // Check for non-address taken alloca.  If not address-taken already, it isn't
10625   // profitable to do this xform.
10626   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10627     bool isAddressTaken = false;
10628     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10629          UI != E; ++UI) {
10630       if (isa<LoadInst>(UI)) continue;
10631       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10632         // If storing TO the alloca, then the address isn't taken.
10633         if (SI->getOperand(1) == AI) continue;
10634       }
10635       isAddressTaken = true;
10636       break;
10637     }
10638     
10639     if (!isAddressTaken && AI->isStaticAlloca())
10640       return false;
10641   }
10642   
10643   // If this load is a load from a GEP with a constant offset from an alloca,
10644   // then we don't want to sink it.  In its present form, it will be
10645   // load [constant stack offset].  Sinking it will cause us to have to
10646   // materialize the stack addresses in each predecessor in a register only to
10647   // do a shared load from register in the successor.
10648   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10649     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10650       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10651         return false;
10652   
10653   return true;
10654 }
10655
10656
10657 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10658 // operator and they all are only used by the PHI, PHI together their
10659 // inputs, and do the operation once, to the result of the PHI.
10660 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10661   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10662
10663   // Scan the instruction, looking for input operations that can be folded away.
10664   // If all input operands to the phi are the same instruction (e.g. a cast from
10665   // the same type or "+42") we can pull the operation through the PHI, reducing
10666   // code size and simplifying code.
10667   Constant *ConstantOp = 0;
10668   const Type *CastSrcTy = 0;
10669   bool isVolatile = false;
10670   if (isa<CastInst>(FirstInst)) {
10671     CastSrcTy = FirstInst->getOperand(0)->getType();
10672   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10673     // Can fold binop, compare or shift here if the RHS is a constant, 
10674     // otherwise call FoldPHIArgBinOpIntoPHI.
10675     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10676     if (ConstantOp == 0)
10677       return FoldPHIArgBinOpIntoPHI(PN);
10678   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10679     isVolatile = LI->isVolatile();
10680     // We can't sink the load if the loaded value could be modified between the
10681     // load and the PHI.
10682     if (LI->getParent() != PN.getIncomingBlock(0) ||
10683         !isSafeAndProfitableToSinkLoad(LI))
10684       return 0;
10685     
10686     // If the PHI is of volatile loads and the load block has multiple
10687     // successors, sinking it would remove a load of the volatile value from
10688     // the path through the other successor.
10689     if (isVolatile &&
10690         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10691       return 0;
10692     
10693   } else if (isa<GetElementPtrInst>(FirstInst)) {
10694     return FoldPHIArgGEPIntoPHI(PN);
10695   } else {
10696     return 0;  // Cannot fold this operation.
10697   }
10698
10699   // Check to see if all arguments are the same operation.
10700   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10701     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10702     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10703     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10704       return 0;
10705     if (CastSrcTy) {
10706       if (I->getOperand(0)->getType() != CastSrcTy)
10707         return 0;  // Cast operation must match.
10708     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10709       // We can't sink the load if the loaded value could be modified between 
10710       // the load and the PHI.
10711       if (LI->isVolatile() != isVolatile ||
10712           LI->getParent() != PN.getIncomingBlock(i) ||
10713           !isSafeAndProfitableToSinkLoad(LI))
10714         return 0;
10715       
10716       // If the PHI is of volatile loads and the load block has multiple
10717       // successors, sinking it would remove a load of the volatile value from
10718       // the path through the other successor.
10719       if (isVolatile &&
10720           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10721         return 0;
10722       
10723     } else if (I->getOperand(1) != ConstantOp) {
10724       return 0;
10725     }
10726   }
10727
10728   // Okay, they are all the same operation.  Create a new PHI node of the
10729   // correct type, and PHI together all of the LHS's of the instructions.
10730   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10731                                    PN.getName()+".in");
10732   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10733
10734   Value *InVal = FirstInst->getOperand(0);
10735   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10736
10737   // Add all operands to the new PHI.
10738   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10739     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10740     if (NewInVal != InVal)
10741       InVal = 0;
10742     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10743   }
10744
10745   Value *PhiVal;
10746   if (InVal) {
10747     // The new PHI unions all of the same values together.  This is really
10748     // common, so we handle it intelligently here for compile-time speed.
10749     PhiVal = InVal;
10750     delete NewPN;
10751   } else {
10752     InsertNewInstBefore(NewPN, PN);
10753     PhiVal = NewPN;
10754   }
10755
10756   // Insert and return the new operation.
10757   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10758     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10759   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10760     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10761   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10762     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10763                            PhiVal, ConstantOp);
10764   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10765   
10766   // If this was a volatile load that we are merging, make sure to loop through
10767   // and mark all the input loads as non-volatile.  If we don't do this, we will
10768   // insert a new volatile load and the old ones will not be deletable.
10769   if (isVolatile)
10770     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10771       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10772   
10773   return new LoadInst(PhiVal, "", isVolatile);
10774 }
10775
10776 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10777 /// that is dead.
10778 static bool DeadPHICycle(PHINode *PN,
10779                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10780   if (PN->use_empty()) return true;
10781   if (!PN->hasOneUse()) return false;
10782
10783   // Remember this node, and if we find the cycle, return.
10784   if (!PotentiallyDeadPHIs.insert(PN))
10785     return true;
10786   
10787   // Don't scan crazily complex things.
10788   if (PotentiallyDeadPHIs.size() == 16)
10789     return false;
10790
10791   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10792     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10793
10794   return false;
10795 }
10796
10797 /// PHIsEqualValue - Return true if this phi node is always equal to
10798 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10799 ///   z = some value; x = phi (y, z); y = phi (x, z)
10800 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10801                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10802   // See if we already saw this PHI node.
10803   if (!ValueEqualPHIs.insert(PN))
10804     return true;
10805   
10806   // Don't scan crazily complex things.
10807   if (ValueEqualPHIs.size() == 16)
10808     return false;
10809  
10810   // Scan the operands to see if they are either phi nodes or are equal to
10811   // the value.
10812   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10813     Value *Op = PN->getIncomingValue(i);
10814     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10815       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10816         return false;
10817     } else if (Op != NonPhiInVal)
10818       return false;
10819   }
10820   
10821   return true;
10822 }
10823
10824
10825 // PHINode simplification
10826 //
10827 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10828   // If LCSSA is around, don't mess with Phi nodes
10829   if (MustPreserveLCSSA) return 0;
10830   
10831   if (Value *V = PN.hasConstantValue())
10832     return ReplaceInstUsesWith(PN, V);
10833
10834   // If all PHI operands are the same operation, pull them through the PHI,
10835   // reducing code size.
10836   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10837       isa<Instruction>(PN.getIncomingValue(1)) &&
10838       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10839       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10840       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10841       // than themselves more than once.
10842       PN.getIncomingValue(0)->hasOneUse())
10843     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10844       return Result;
10845
10846   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10847   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10848   // PHI)... break the cycle.
10849   if (PN.hasOneUse()) {
10850     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10851     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10852       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10853       PotentiallyDeadPHIs.insert(&PN);
10854       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10855         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10856     }
10857    
10858     // If this phi has a single use, and if that use just computes a value for
10859     // the next iteration of a loop, delete the phi.  This occurs with unused
10860     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10861     // common case here is good because the only other things that catch this
10862     // are induction variable analysis (sometimes) and ADCE, which is only run
10863     // late.
10864     if (PHIUser->hasOneUse() &&
10865         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10866         PHIUser->use_back() == &PN) {
10867       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10868     }
10869   }
10870
10871   // We sometimes end up with phi cycles that non-obviously end up being the
10872   // same value, for example:
10873   //   z = some value; x = phi (y, z); y = phi (x, z)
10874   // where the phi nodes don't necessarily need to be in the same block.  Do a
10875   // quick check to see if the PHI node only contains a single non-phi value, if
10876   // so, scan to see if the phi cycle is actually equal to that value.
10877   {
10878     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10879     // Scan for the first non-phi operand.
10880     while (InValNo != NumOperandVals && 
10881            isa<PHINode>(PN.getIncomingValue(InValNo)))
10882       ++InValNo;
10883
10884     if (InValNo != NumOperandVals) {
10885       Value *NonPhiInVal = PN.getOperand(InValNo);
10886       
10887       // Scan the rest of the operands to see if there are any conflicts, if so
10888       // there is no need to recursively scan other phis.
10889       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10890         Value *OpVal = PN.getIncomingValue(InValNo);
10891         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10892           break;
10893       }
10894       
10895       // If we scanned over all operands, then we have one unique value plus
10896       // phi values.  Scan PHI nodes to see if they all merge in each other or
10897       // the value.
10898       if (InValNo == NumOperandVals) {
10899         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10900         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10901           return ReplaceInstUsesWith(PN, NonPhiInVal);
10902       }
10903     }
10904   }
10905   return 0;
10906 }
10907
10908 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10909   Value *PtrOp = GEP.getOperand(0);
10910   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10911   if (GEP.getNumOperands() == 1)
10912     return ReplaceInstUsesWith(GEP, PtrOp);
10913
10914   if (isa<UndefValue>(GEP.getOperand(0)))
10915     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10916
10917   bool HasZeroPointerIndex = false;
10918   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10919     HasZeroPointerIndex = C->isNullValue();
10920
10921   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10922     return ReplaceInstUsesWith(GEP, PtrOp);
10923
10924   // Eliminate unneeded casts for indices.
10925   if (TD) {
10926     bool MadeChange = false;
10927     unsigned PtrSize = TD->getPointerSizeInBits();
10928     
10929     gep_type_iterator GTI = gep_type_begin(GEP);
10930     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10931          I != E; ++I, ++GTI) {
10932       if (!isa<SequentialType>(*GTI)) continue;
10933       
10934       // If we are using a wider index than needed for this platform, shrink it
10935       // to what we need.  If narrower, sign-extend it to what we need.  This
10936       // explicit cast can make subsequent optimizations more obvious.
10937       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10938       if (OpBits == PtrSize)
10939         continue;
10940       
10941       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10942       MadeChange = true;
10943     }
10944     if (MadeChange) return &GEP;
10945   }
10946
10947   // Combine Indices - If the source pointer to this getelementptr instruction
10948   // is a getelementptr instruction, combine the indices of the two
10949   // getelementptr instructions into a single instruction.
10950   //
10951   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10952     // Note that if our source is a gep chain itself that we wait for that
10953     // chain to be resolved before we perform this transformation.  This
10954     // avoids us creating a TON of code in some cases.
10955     //
10956     if (GetElementPtrInst *SrcGEP =
10957           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10958       if (SrcGEP->getNumOperands() == 2)
10959         return 0;   // Wait until our source is folded to completion.
10960
10961     SmallVector<Value*, 8> Indices;
10962
10963     // Find out whether the last index in the source GEP is a sequential idx.
10964     bool EndsWithSequential = false;
10965     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10966          I != E; ++I)
10967       EndsWithSequential = !isa<StructType>(*I);
10968
10969     // Can we combine the two pointer arithmetics offsets?
10970     if (EndsWithSequential) {
10971       // Replace: gep (gep %P, long B), long A, ...
10972       // With:    T = long A+B; gep %P, T, ...
10973       //
10974       Value *Sum;
10975       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10976       Value *GO1 = GEP.getOperand(1);
10977       if (SO1 == Constant::getNullValue(SO1->getType())) {
10978         Sum = GO1;
10979       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10980         Sum = SO1;
10981       } else {
10982         // If they aren't the same type, then the input hasn't been processed
10983         // by the loop above yet (which canonicalizes sequential index types to
10984         // intptr_t).  Just avoid transforming this until the input has been
10985         // normalized.
10986         if (SO1->getType() != GO1->getType())
10987           return 0;
10988         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10989       }
10990
10991       // Update the GEP in place if possible.
10992       if (Src->getNumOperands() == 2) {
10993         GEP.setOperand(0, Src->getOperand(0));
10994         GEP.setOperand(1, Sum);
10995         return &GEP;
10996       }
10997       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10998       Indices.push_back(Sum);
10999       Indices.append(GEP.op_begin()+2, GEP.op_end());
11000     } else if (isa<Constant>(*GEP.idx_begin()) &&
11001                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11002                Src->getNumOperands() != 1) {
11003       // Otherwise we can do the fold if the first index of the GEP is a zero
11004       Indices.append(Src->op_begin()+1, Src->op_end());
11005       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11006     }
11007
11008     if (!Indices.empty())
11009       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11010               Src->isInBounds()) ?
11011         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11012                                           Indices.end(), GEP.getName()) :
11013         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11014                                   Indices.end(), GEP.getName());
11015   }
11016   
11017   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11018   if (Value *X = getBitCastOperand(PtrOp)) {
11019     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11020
11021     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11022     // want to change the gep until the bitcasts are eliminated.
11023     if (getBitCastOperand(X)) {
11024       Worklist.AddValue(PtrOp);
11025       return 0;
11026     }
11027     
11028     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11029     // into     : GEP [10 x i8]* X, i32 0, ...
11030     //
11031     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11032     //           into     : GEP i8* X, ...
11033     // 
11034     // This occurs when the program declares an array extern like "int X[];"
11035     if (HasZeroPointerIndex) {
11036       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11037       const PointerType *XTy = cast<PointerType>(X->getType());
11038       if (const ArrayType *CATy =
11039           dyn_cast<ArrayType>(CPTy->getElementType())) {
11040         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11041         if (CATy->getElementType() == XTy->getElementType()) {
11042           // -> GEP i8* X, ...
11043           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11044           return cast<GEPOperator>(&GEP)->isInBounds() ?
11045             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11046                                               GEP.getName()) :
11047             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11048                                       GEP.getName());
11049         }
11050         
11051         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11052           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11053           if (CATy->getElementType() == XATy->getElementType()) {
11054             // -> GEP [10 x i8]* X, i32 0, ...
11055             // At this point, we know that the cast source type is a pointer
11056             // to an array of the same type as the destination pointer
11057             // array.  Because the array type is never stepped over (there
11058             // is a leading zero) we can fold the cast into this GEP.
11059             GEP.setOperand(0, X);
11060             return &GEP;
11061           }
11062         }
11063       }
11064     } else if (GEP.getNumOperands() == 2) {
11065       // Transform things like:
11066       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11067       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11068       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11069       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11070       if (TD && isa<ArrayType>(SrcElTy) &&
11071           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11072           TD->getTypeAllocSize(ResElTy)) {
11073         Value *Idx[2];
11074         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11075         Idx[1] = GEP.getOperand(1);
11076         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11077           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11078           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11079         // V and GEP are both pointer types --> BitCast
11080         return new BitCastInst(NewGEP, GEP.getType());
11081       }
11082       
11083       // Transform things like:
11084       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11085       //   (where tmp = 8*tmp2) into:
11086       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11087       
11088       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11089         uint64_t ArrayEltSize =
11090             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11091         
11092         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11093         // allow either a mul, shift, or constant here.
11094         Value *NewIdx = 0;
11095         ConstantInt *Scale = 0;
11096         if (ArrayEltSize == 1) {
11097           NewIdx = GEP.getOperand(1);
11098           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11099         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11100           NewIdx = ConstantInt::get(CI->getType(), 1);
11101           Scale = CI;
11102         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11103           if (Inst->getOpcode() == Instruction::Shl &&
11104               isa<ConstantInt>(Inst->getOperand(1))) {
11105             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11106             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11107             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11108                                      1ULL << ShAmtVal);
11109             NewIdx = Inst->getOperand(0);
11110           } else if (Inst->getOpcode() == Instruction::Mul &&
11111                      isa<ConstantInt>(Inst->getOperand(1))) {
11112             Scale = cast<ConstantInt>(Inst->getOperand(1));
11113             NewIdx = Inst->getOperand(0);
11114           }
11115         }
11116         
11117         // If the index will be to exactly the right offset with the scale taken
11118         // out, perform the transformation. Note, we don't know whether Scale is
11119         // signed or not. We'll use unsigned version of division/modulo
11120         // operation after making sure Scale doesn't have the sign bit set.
11121         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11122             Scale->getZExtValue() % ArrayEltSize == 0) {
11123           Scale = ConstantInt::get(Scale->getType(),
11124                                    Scale->getZExtValue() / ArrayEltSize);
11125           if (Scale->getZExtValue() != 1) {
11126             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11127                                                        false /*ZExt*/);
11128             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11129           }
11130
11131           // Insert the new GEP instruction.
11132           Value *Idx[2];
11133           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11134           Idx[1] = NewIdx;
11135           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11136             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11137             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11138           // The NewGEP must be pointer typed, so must the old one -> BitCast
11139           return new BitCastInst(NewGEP, GEP.getType());
11140         }
11141       }
11142     }
11143   }
11144   
11145   /// See if we can simplify:
11146   ///   X = bitcast A* to B*
11147   ///   Y = gep X, <...constant indices...>
11148   /// into a gep of the original struct.  This is important for SROA and alias
11149   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11150   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11151     if (TD &&
11152         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11153       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11154       // a constant back from EmitGEPOffset.
11155       ConstantInt *OffsetV =
11156                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11157       int64_t Offset = OffsetV->getSExtValue();
11158       
11159       // If this GEP instruction doesn't move the pointer, just replace the GEP
11160       // with a bitcast of the real input to the dest type.
11161       if (Offset == 0) {
11162         // If the bitcast is of an allocation, and the allocation will be
11163         // converted to match the type of the cast, don't touch this.
11164         if (isa<AllocationInst>(BCI->getOperand(0)) ||
11165             isMalloc(BCI->getOperand(0))) {
11166           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11167           if (Instruction *I = visitBitCast(*BCI)) {
11168             if (I != BCI) {
11169               I->takeName(BCI);
11170               BCI->getParent()->getInstList().insert(BCI, I);
11171               ReplaceInstUsesWith(*BCI, I);
11172             }
11173             return &GEP;
11174           }
11175         }
11176         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11177       }
11178       
11179       // Otherwise, if the offset is non-zero, we need to find out if there is a
11180       // field at Offset in 'A's type.  If so, we can pull the cast through the
11181       // GEP.
11182       SmallVector<Value*, 8> NewIndices;
11183       const Type *InTy =
11184         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11185       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11186         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11187           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11188                                      NewIndices.end()) :
11189           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11190                              NewIndices.end());
11191         
11192         if (NGEP->getType() == GEP.getType())
11193           return ReplaceInstUsesWith(GEP, NGEP);
11194         NGEP->takeName(&GEP);
11195         return new BitCastInst(NGEP, GEP.getType());
11196       }
11197     }
11198   }    
11199     
11200   return 0;
11201 }
11202
11203 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11204   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11205   if (AI.isArrayAllocation()) {  // Check C != 1
11206     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11207       const Type *NewTy = 
11208         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11209       AllocationInst *New = 0;
11210
11211       // Create and insert the replacement instruction...
11212       if (isa<MallocInst>(AI))
11213         New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11214       else {
11215         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11216         New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11217       }
11218       New->setAlignment(AI.getAlignment());
11219
11220       // Scan to the end of the allocation instructions, to skip over a block of
11221       // allocas if possible...also skip interleaved debug info
11222       //
11223       BasicBlock::iterator It = New;
11224       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11225
11226       // Now that I is pointing to the first non-allocation-inst in the block,
11227       // insert our getelementptr instruction...
11228       //
11229       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11230       Value *Idx[2];
11231       Idx[0] = NullIdx;
11232       Idx[1] = NullIdx;
11233       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11234                                                    New->getName()+".sub", It);
11235
11236       // Now make everything use the getelementptr instead of the original
11237       // allocation.
11238       return ReplaceInstUsesWith(AI, V);
11239     } else if (isa<UndefValue>(AI.getArraySize())) {
11240       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11241     }
11242   }
11243
11244   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11245     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11246     // Note that we only do this for alloca's, because malloc should allocate
11247     // and return a unique pointer, even for a zero byte allocation.
11248     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11249       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11250
11251     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11252     if (AI.getAlignment() == 0)
11253       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11254   }
11255
11256   return 0;
11257 }
11258
11259 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11260   Value *Op = FI.getOperand(0);
11261
11262   // free undef -> unreachable.
11263   if (isa<UndefValue>(Op)) {
11264     // Insert a new store to null because we cannot modify the CFG here.
11265     new StoreInst(ConstantInt::getTrue(*Context),
11266            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11267     return EraseInstFromFunction(FI);
11268   }
11269   
11270   // If we have 'free null' delete the instruction.  This can happen in stl code
11271   // when lots of inlining happens.
11272   if (isa<ConstantPointerNull>(Op))
11273     return EraseInstFromFunction(FI);
11274   
11275   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11276   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11277     FI.setOperand(0, CI->getOperand(0));
11278     return &FI;
11279   }
11280   
11281   // Change free (gep X, 0,0,0,0) into free(X)
11282   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11283     if (GEPI->hasAllZeroIndices()) {
11284       Worklist.Add(GEPI);
11285       FI.setOperand(0, GEPI->getOperand(0));
11286       return &FI;
11287     }
11288   }
11289   
11290   // Change free(malloc) into nothing, if the malloc has a single use.
11291   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11292     if (MI->hasOneUse()) {
11293       EraseInstFromFunction(FI);
11294       return EraseInstFromFunction(*MI);
11295     }
11296   if (isMalloc(Op)) {
11297     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11298       if (Op->hasOneUse() && CI->hasOneUse()) {
11299         EraseInstFromFunction(FI);
11300         EraseInstFromFunction(*CI);
11301         return EraseInstFromFunction(*cast<Instruction>(Op));
11302       }
11303     } else {
11304       // Op is a call to malloc
11305       if (Op->hasOneUse()) {
11306         EraseInstFromFunction(FI);
11307         return EraseInstFromFunction(*cast<Instruction>(Op));
11308       }
11309     }
11310   }
11311
11312   return 0;
11313 }
11314
11315
11316 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11317 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11318                                         const TargetData *TD) {
11319   User *CI = cast<User>(LI.getOperand(0));
11320   Value *CastOp = CI->getOperand(0);
11321   LLVMContext *Context = IC.getContext();
11322
11323   if (TD) {
11324     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11325       // Instead of loading constant c string, use corresponding integer value
11326       // directly if string length is small enough.
11327       std::string Str;
11328       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11329         unsigned len = Str.length();
11330         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11331         unsigned numBits = Ty->getPrimitiveSizeInBits();
11332         // Replace LI with immediate integer store.
11333         if ((numBits >> 3) == len + 1) {
11334           APInt StrVal(numBits, 0);
11335           APInt SingleChar(numBits, 0);
11336           if (TD->isLittleEndian()) {
11337             for (signed i = len-1; i >= 0; i--) {
11338               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11339               StrVal = (StrVal << 8) | SingleChar;
11340             }
11341           } else {
11342             for (unsigned i = 0; i < len; i++) {
11343               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11344               StrVal = (StrVal << 8) | SingleChar;
11345             }
11346             // Append NULL at the end.
11347             SingleChar = 0;
11348             StrVal = (StrVal << 8) | SingleChar;
11349           }
11350           Value *NL = ConstantInt::get(*Context, StrVal);
11351           return IC.ReplaceInstUsesWith(LI, NL);
11352         }
11353       }
11354     }
11355   }
11356
11357   const PointerType *DestTy = cast<PointerType>(CI->getType());
11358   const Type *DestPTy = DestTy->getElementType();
11359   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11360
11361     // If the address spaces don't match, don't eliminate the cast.
11362     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11363       return 0;
11364
11365     const Type *SrcPTy = SrcTy->getElementType();
11366
11367     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11368          isa<VectorType>(DestPTy)) {
11369       // If the source is an array, the code below will not succeed.  Check to
11370       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11371       // constants.
11372       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11373         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11374           if (ASrcTy->getNumElements() != 0) {
11375             Value *Idxs[2];
11376             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11377             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11378             SrcTy = cast<PointerType>(CastOp->getType());
11379             SrcPTy = SrcTy->getElementType();
11380           }
11381
11382       if (IC.getTargetData() &&
11383           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11384             isa<VectorType>(SrcPTy)) &&
11385           // Do not allow turning this into a load of an integer, which is then
11386           // casted to a pointer, this pessimizes pointer analysis a lot.
11387           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11388           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11389                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11390
11391         // Okay, we are casting from one integer or pointer type to another of
11392         // the same size.  Instead of casting the pointer before the load, cast
11393         // the result of the loaded value.
11394         Value *NewLoad = 
11395           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11396         // Now cast the result of the load.
11397         return new BitCastInst(NewLoad, LI.getType());
11398       }
11399     }
11400   }
11401   return 0;
11402 }
11403
11404 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11405   Value *Op = LI.getOperand(0);
11406
11407   // Attempt to improve the alignment.
11408   if (TD) {
11409     unsigned KnownAlign =
11410       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11411     if (KnownAlign >
11412         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11413                                   LI.getAlignment()))
11414       LI.setAlignment(KnownAlign);
11415   }
11416
11417   // load (cast X) --> cast (load X) iff safe.
11418   if (isa<CastInst>(Op))
11419     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11420       return Res;
11421
11422   // None of the following transforms are legal for volatile loads.
11423   if (LI.isVolatile()) return 0;
11424   
11425   // Do really simple store-to-load forwarding and load CSE, to catch cases
11426   // where there are several consequtive memory accesses to the same location,
11427   // separated by a few arithmetic operations.
11428   BasicBlock::iterator BBI = &LI;
11429   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11430     return ReplaceInstUsesWith(LI, AvailableVal);
11431
11432   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11433     const Value *GEPI0 = GEPI->getOperand(0);
11434     // TODO: Consider a target hook for valid address spaces for this xform.
11435     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11436       // Insert a new store to null instruction before the load to indicate
11437       // that this code is not reachable.  We do this instead of inserting
11438       // an unreachable instruction directly because we cannot modify the
11439       // CFG.
11440       new StoreInst(UndefValue::get(LI.getType()),
11441                     Constant::getNullValue(Op->getType()), &LI);
11442       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11443     }
11444   } 
11445
11446   if (Constant *C = dyn_cast<Constant>(Op)) {
11447     // load null/undef -> undef
11448     // TODO: Consider a target hook for valid address spaces for this xform.
11449     if (isa<UndefValue>(C) ||
11450         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11451       // Insert a new store to null instruction before the load to indicate that
11452       // this code is not reachable.  We do this instead of inserting an
11453       // unreachable instruction directly because we cannot modify the CFG.
11454       new StoreInst(UndefValue::get(LI.getType()),
11455                     Constant::getNullValue(Op->getType()), &LI);
11456       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11457     }
11458
11459     // Instcombine load (constant global) into the value loaded.
11460     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11461       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11462         return ReplaceInstUsesWith(LI, GV->getInitializer());
11463
11464     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11465     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11466       if (CE->getOpcode() == Instruction::GetElementPtr) {
11467         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11468           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11469             if (Constant *V = 
11470                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11471               return ReplaceInstUsesWith(LI, V);
11472         if (CE->getOperand(0)->isNullValue()) {
11473           // Insert a new store to null instruction before the load to indicate
11474           // that this code is not reachable.  We do this instead of inserting
11475           // an unreachable instruction directly because we cannot modify the
11476           // CFG.
11477           new StoreInst(UndefValue::get(LI.getType()),
11478                         Constant::getNullValue(Op->getType()), &LI);
11479           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11480         }
11481
11482       } else if (CE->isCast()) {
11483         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11484           return Res;
11485       }
11486     }
11487   }
11488     
11489   // If this load comes from anywhere in a constant global, and if the global
11490   // is all undef or zero, we know what it loads.
11491   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11492     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11493       if (GV->getInitializer()->isNullValue())
11494         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11495       else if (isa<UndefValue>(GV->getInitializer()))
11496         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11497     }
11498   }
11499
11500   if (Op->hasOneUse()) {
11501     // Change select and PHI nodes to select values instead of addresses: this
11502     // helps alias analysis out a lot, allows many others simplifications, and
11503     // exposes redundancy in the code.
11504     //
11505     // Note that we cannot do the transformation unless we know that the
11506     // introduced loads cannot trap!  Something like this is valid as long as
11507     // the condition is always false: load (select bool %C, int* null, int* %G),
11508     // but it would not be valid if we transformed it to load from null
11509     // unconditionally.
11510     //
11511     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11512       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11513       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11514           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11515         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11516                                         SI->getOperand(1)->getName()+".val");
11517         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11518                                         SI->getOperand(2)->getName()+".val");
11519         return SelectInst::Create(SI->getCondition(), V1, V2);
11520       }
11521
11522       // load (select (cond, null, P)) -> load P
11523       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11524         if (C->isNullValue()) {
11525           LI.setOperand(0, SI->getOperand(2));
11526           return &LI;
11527         }
11528
11529       // load (select (cond, P, null)) -> load P
11530       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11531         if (C->isNullValue()) {
11532           LI.setOperand(0, SI->getOperand(1));
11533           return &LI;
11534         }
11535     }
11536   }
11537   return 0;
11538 }
11539
11540 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11541 /// when possible.  This makes it generally easy to do alias analysis and/or
11542 /// SROA/mem2reg of the memory object.
11543 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11544   User *CI = cast<User>(SI.getOperand(1));
11545   Value *CastOp = CI->getOperand(0);
11546
11547   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11548   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11549   if (SrcTy == 0) return 0;
11550   
11551   const Type *SrcPTy = SrcTy->getElementType();
11552
11553   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11554     return 0;
11555   
11556   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11557   /// to its first element.  This allows us to handle things like:
11558   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11559   /// on 32-bit hosts.
11560   SmallVector<Value*, 4> NewGEPIndices;
11561   
11562   // If the source is an array, the code below will not succeed.  Check to
11563   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11564   // constants.
11565   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11566     // Index through pointer.
11567     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11568     NewGEPIndices.push_back(Zero);
11569     
11570     while (1) {
11571       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11572         if (!STy->getNumElements()) /* Struct can be empty {} */
11573           break;
11574         NewGEPIndices.push_back(Zero);
11575         SrcPTy = STy->getElementType(0);
11576       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11577         NewGEPIndices.push_back(Zero);
11578         SrcPTy = ATy->getElementType();
11579       } else {
11580         break;
11581       }
11582     }
11583     
11584     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11585   }
11586
11587   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11588     return 0;
11589   
11590   // If the pointers point into different address spaces or if they point to
11591   // values with different sizes, we can't do the transformation.
11592   if (!IC.getTargetData() ||
11593       SrcTy->getAddressSpace() != 
11594         cast<PointerType>(CI->getType())->getAddressSpace() ||
11595       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11596       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11597     return 0;
11598
11599   // Okay, we are casting from one integer or pointer type to another of
11600   // the same size.  Instead of casting the pointer before 
11601   // the store, cast the value to be stored.
11602   Value *NewCast;
11603   Value *SIOp0 = SI.getOperand(0);
11604   Instruction::CastOps opcode = Instruction::BitCast;
11605   const Type* CastSrcTy = SIOp0->getType();
11606   const Type* CastDstTy = SrcPTy;
11607   if (isa<PointerType>(CastDstTy)) {
11608     if (CastSrcTy->isInteger())
11609       opcode = Instruction::IntToPtr;
11610   } else if (isa<IntegerType>(CastDstTy)) {
11611     if (isa<PointerType>(SIOp0->getType()))
11612       opcode = Instruction::PtrToInt;
11613   }
11614   
11615   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11616   // emit a GEP to index into its first field.
11617   if (!NewGEPIndices.empty())
11618     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11619                                            NewGEPIndices.end());
11620   
11621   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11622                                    SIOp0->getName()+".c");
11623   return new StoreInst(NewCast, CastOp);
11624 }
11625
11626 /// equivalentAddressValues - Test if A and B will obviously have the same
11627 /// value. This includes recognizing that %t0 and %t1 will have the same
11628 /// value in code like this:
11629 ///   %t0 = getelementptr \@a, 0, 3
11630 ///   store i32 0, i32* %t0
11631 ///   %t1 = getelementptr \@a, 0, 3
11632 ///   %t2 = load i32* %t1
11633 ///
11634 static bool equivalentAddressValues(Value *A, Value *B) {
11635   // Test if the values are trivially equivalent.
11636   if (A == B) return true;
11637   
11638   // Test if the values come form identical arithmetic instructions.
11639   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11640   // its only used to compare two uses within the same basic block, which
11641   // means that they'll always either have the same value or one of them
11642   // will have an undefined value.
11643   if (isa<BinaryOperator>(A) ||
11644       isa<CastInst>(A) ||
11645       isa<PHINode>(A) ||
11646       isa<GetElementPtrInst>(A))
11647     if (Instruction *BI = dyn_cast<Instruction>(B))
11648       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11649         return true;
11650   
11651   // Otherwise they may not be equivalent.
11652   return false;
11653 }
11654
11655 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11656 // return the llvm.dbg.declare.
11657 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11658   if (!V->hasNUses(2))
11659     return 0;
11660   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11661        UI != E; ++UI) {
11662     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11663       return DI;
11664     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11665       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11666         return DI;
11667       }
11668   }
11669   return 0;
11670 }
11671
11672 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11673   Value *Val = SI.getOperand(0);
11674   Value *Ptr = SI.getOperand(1);
11675
11676   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11677     EraseInstFromFunction(SI);
11678     ++NumCombined;
11679     return 0;
11680   }
11681   
11682   // If the RHS is an alloca with a single use, zapify the store, making the
11683   // alloca dead.
11684   // If the RHS is an alloca with a two uses, the other one being a 
11685   // llvm.dbg.declare, zapify the store and the declare, making the
11686   // alloca dead.  We must do this to prevent declare's from affecting
11687   // codegen.
11688   if (!SI.isVolatile()) {
11689     if (Ptr->hasOneUse()) {
11690       if (isa<AllocaInst>(Ptr)) {
11691         EraseInstFromFunction(SI);
11692         ++NumCombined;
11693         return 0;
11694       }
11695       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11696         if (isa<AllocaInst>(GEP->getOperand(0))) {
11697           if (GEP->getOperand(0)->hasOneUse()) {
11698             EraseInstFromFunction(SI);
11699             ++NumCombined;
11700             return 0;
11701           }
11702           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11703             EraseInstFromFunction(*DI);
11704             EraseInstFromFunction(SI);
11705             ++NumCombined;
11706             return 0;
11707           }
11708         }
11709       }
11710     }
11711     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11712       EraseInstFromFunction(*DI);
11713       EraseInstFromFunction(SI);
11714       ++NumCombined;
11715       return 0;
11716     }
11717   }
11718
11719   // Attempt to improve the alignment.
11720   if (TD) {
11721     unsigned KnownAlign =
11722       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11723     if (KnownAlign >
11724         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11725                                   SI.getAlignment()))
11726       SI.setAlignment(KnownAlign);
11727   }
11728
11729   // Do really simple DSE, to catch cases where there are several consecutive
11730   // stores to the same location, separated by a few arithmetic operations. This
11731   // situation often occurs with bitfield accesses.
11732   BasicBlock::iterator BBI = &SI;
11733   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11734        --ScanInsts) {
11735     --BBI;
11736     // Don't count debug info directives, lest they affect codegen,
11737     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11738     // It is necessary for correctness to skip those that feed into a
11739     // llvm.dbg.declare, as these are not present when debugging is off.
11740     if (isa<DbgInfoIntrinsic>(BBI) ||
11741         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11742       ScanInsts++;
11743       continue;
11744     }    
11745     
11746     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11747       // Prev store isn't volatile, and stores to the same location?
11748       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11749                                                           SI.getOperand(1))) {
11750         ++NumDeadStore;
11751         ++BBI;
11752         EraseInstFromFunction(*PrevSI);
11753         continue;
11754       }
11755       break;
11756     }
11757     
11758     // If this is a load, we have to stop.  However, if the loaded value is from
11759     // the pointer we're loading and is producing the pointer we're storing,
11760     // then *this* store is dead (X = load P; store X -> P).
11761     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11762       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11763           !SI.isVolatile()) {
11764         EraseInstFromFunction(SI);
11765         ++NumCombined;
11766         return 0;
11767       }
11768       // Otherwise, this is a load from some other location.  Stores before it
11769       // may not be dead.
11770       break;
11771     }
11772     
11773     // Don't skip over loads or things that can modify memory.
11774     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11775       break;
11776   }
11777   
11778   
11779   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11780
11781   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11782   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11783     if (!isa<UndefValue>(Val)) {
11784       SI.setOperand(0, UndefValue::get(Val->getType()));
11785       if (Instruction *U = dyn_cast<Instruction>(Val))
11786         Worklist.Add(U);  // Dropped a use.
11787       ++NumCombined;
11788     }
11789     return 0;  // Do not modify these!
11790   }
11791
11792   // store undef, Ptr -> noop
11793   if (isa<UndefValue>(Val)) {
11794     EraseInstFromFunction(SI);
11795     ++NumCombined;
11796     return 0;
11797   }
11798
11799   // If the pointer destination is a cast, see if we can fold the cast into the
11800   // source instead.
11801   if (isa<CastInst>(Ptr))
11802     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11803       return Res;
11804   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11805     if (CE->isCast())
11806       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11807         return Res;
11808
11809   
11810   // If this store is the last instruction in the basic block (possibly
11811   // excepting debug info instructions and the pointer bitcasts that feed
11812   // into them), and if the block ends with an unconditional branch, try
11813   // to move it to the successor block.
11814   BBI = &SI; 
11815   do {
11816     ++BBI;
11817   } while (isa<DbgInfoIntrinsic>(BBI) ||
11818            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11819   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11820     if (BI->isUnconditional())
11821       if (SimplifyStoreAtEndOfBlock(SI))
11822         return 0;  // xform done!
11823   
11824   return 0;
11825 }
11826
11827 /// SimplifyStoreAtEndOfBlock - Turn things like:
11828 ///   if () { *P = v1; } else { *P = v2 }
11829 /// into a phi node with a store in the successor.
11830 ///
11831 /// Simplify things like:
11832 ///   *P = v1; if () { *P = v2; }
11833 /// into a phi node with a store in the successor.
11834 ///
11835 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11836   BasicBlock *StoreBB = SI.getParent();
11837   
11838   // Check to see if the successor block has exactly two incoming edges.  If
11839   // so, see if the other predecessor contains a store to the same location.
11840   // if so, insert a PHI node (if needed) and move the stores down.
11841   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11842   
11843   // Determine whether Dest has exactly two predecessors and, if so, compute
11844   // the other predecessor.
11845   pred_iterator PI = pred_begin(DestBB);
11846   BasicBlock *OtherBB = 0;
11847   if (*PI != StoreBB)
11848     OtherBB = *PI;
11849   ++PI;
11850   if (PI == pred_end(DestBB))
11851     return false;
11852   
11853   if (*PI != StoreBB) {
11854     if (OtherBB)
11855       return false;
11856     OtherBB = *PI;
11857   }
11858   if (++PI != pred_end(DestBB))
11859     return false;
11860
11861   // Bail out if all the relevant blocks aren't distinct (this can happen,
11862   // for example, if SI is in an infinite loop)
11863   if (StoreBB == DestBB || OtherBB == DestBB)
11864     return false;
11865
11866   // Verify that the other block ends in a branch and is not otherwise empty.
11867   BasicBlock::iterator BBI = OtherBB->getTerminator();
11868   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11869   if (!OtherBr || BBI == OtherBB->begin())
11870     return false;
11871   
11872   // If the other block ends in an unconditional branch, check for the 'if then
11873   // else' case.  there is an instruction before the branch.
11874   StoreInst *OtherStore = 0;
11875   if (OtherBr->isUnconditional()) {
11876     --BBI;
11877     // Skip over debugging info.
11878     while (isa<DbgInfoIntrinsic>(BBI) ||
11879            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11880       if (BBI==OtherBB->begin())
11881         return false;
11882       --BBI;
11883     }
11884     // If this isn't a store, or isn't a store to the same location, bail out.
11885     OtherStore = dyn_cast<StoreInst>(BBI);
11886     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11887       return false;
11888   } else {
11889     // Otherwise, the other block ended with a conditional branch. If one of the
11890     // destinations is StoreBB, then we have the if/then case.
11891     if (OtherBr->getSuccessor(0) != StoreBB && 
11892         OtherBr->getSuccessor(1) != StoreBB)
11893       return false;
11894     
11895     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11896     // if/then triangle.  See if there is a store to the same ptr as SI that
11897     // lives in OtherBB.
11898     for (;; --BBI) {
11899       // Check to see if we find the matching store.
11900       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11901         if (OtherStore->getOperand(1) != SI.getOperand(1))
11902           return false;
11903         break;
11904       }
11905       // If we find something that may be using or overwriting the stored
11906       // value, or if we run out of instructions, we can't do the xform.
11907       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11908           BBI == OtherBB->begin())
11909         return false;
11910     }
11911     
11912     // In order to eliminate the store in OtherBr, we have to
11913     // make sure nothing reads or overwrites the stored value in
11914     // StoreBB.
11915     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11916       // FIXME: This should really be AA driven.
11917       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11918         return false;
11919     }
11920   }
11921   
11922   // Insert a PHI node now if we need it.
11923   Value *MergedVal = OtherStore->getOperand(0);
11924   if (MergedVal != SI.getOperand(0)) {
11925     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11926     PN->reserveOperandSpace(2);
11927     PN->addIncoming(SI.getOperand(0), SI.getParent());
11928     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11929     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11930   }
11931   
11932   // Advance to a place where it is safe to insert the new store and
11933   // insert it.
11934   BBI = DestBB->getFirstNonPHI();
11935   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11936                                     OtherStore->isVolatile()), *BBI);
11937   
11938   // Nuke the old stores.
11939   EraseInstFromFunction(SI);
11940   EraseInstFromFunction(*OtherStore);
11941   ++NumCombined;
11942   return true;
11943 }
11944
11945
11946 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11947   // Change br (not X), label True, label False to: br X, label False, True
11948   Value *X = 0;
11949   BasicBlock *TrueDest;
11950   BasicBlock *FalseDest;
11951   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11952       !isa<Constant>(X)) {
11953     // Swap Destinations and condition...
11954     BI.setCondition(X);
11955     BI.setSuccessor(0, FalseDest);
11956     BI.setSuccessor(1, TrueDest);
11957     return &BI;
11958   }
11959
11960   // Cannonicalize fcmp_one -> fcmp_oeq
11961   FCmpInst::Predicate FPred; Value *Y;
11962   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11963                              TrueDest, FalseDest)) &&
11964       BI.getCondition()->hasOneUse())
11965     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11966         FPred == FCmpInst::FCMP_OGE) {
11967       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11968       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11969       
11970       // Swap Destinations and condition.
11971       BI.setSuccessor(0, FalseDest);
11972       BI.setSuccessor(1, TrueDest);
11973       Worklist.Add(Cond);
11974       return &BI;
11975     }
11976
11977   // Cannonicalize icmp_ne -> icmp_eq
11978   ICmpInst::Predicate IPred;
11979   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11980                       TrueDest, FalseDest)) &&
11981       BI.getCondition()->hasOneUse())
11982     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11983         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11984         IPred == ICmpInst::ICMP_SGE) {
11985       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11986       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11987       // Swap Destinations and condition.
11988       BI.setSuccessor(0, FalseDest);
11989       BI.setSuccessor(1, TrueDest);
11990       Worklist.Add(Cond);
11991       return &BI;
11992     }
11993
11994   return 0;
11995 }
11996
11997 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11998   Value *Cond = SI.getCondition();
11999   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12000     if (I->getOpcode() == Instruction::Add)
12001       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12002         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12003         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12004           SI.setOperand(i,
12005                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12006                                                 AddRHS));
12007         SI.setOperand(0, I->getOperand(0));
12008         Worklist.Add(I);
12009         return &SI;
12010       }
12011   }
12012   return 0;
12013 }
12014
12015 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12016   Value *Agg = EV.getAggregateOperand();
12017
12018   if (!EV.hasIndices())
12019     return ReplaceInstUsesWith(EV, Agg);
12020
12021   if (Constant *C = dyn_cast<Constant>(Agg)) {
12022     if (isa<UndefValue>(C))
12023       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12024       
12025     if (isa<ConstantAggregateZero>(C))
12026       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12027
12028     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12029       // Extract the element indexed by the first index out of the constant
12030       Value *V = C->getOperand(*EV.idx_begin());
12031       if (EV.getNumIndices() > 1)
12032         // Extract the remaining indices out of the constant indexed by the
12033         // first index
12034         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12035       else
12036         return ReplaceInstUsesWith(EV, V);
12037     }
12038     return 0; // Can't handle other constants
12039   } 
12040   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12041     // We're extracting from an insertvalue instruction, compare the indices
12042     const unsigned *exti, *exte, *insi, *inse;
12043     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12044          exte = EV.idx_end(), inse = IV->idx_end();
12045          exti != exte && insi != inse;
12046          ++exti, ++insi) {
12047       if (*insi != *exti)
12048         // The insert and extract both reference distinctly different elements.
12049         // This means the extract is not influenced by the insert, and we can
12050         // replace the aggregate operand of the extract with the aggregate
12051         // operand of the insert. i.e., replace
12052         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12053         // %E = extractvalue { i32, { i32 } } %I, 0
12054         // with
12055         // %E = extractvalue { i32, { i32 } } %A, 0
12056         return ExtractValueInst::Create(IV->getAggregateOperand(),
12057                                         EV.idx_begin(), EV.idx_end());
12058     }
12059     if (exti == exte && insi == inse)
12060       // Both iterators are at the end: Index lists are identical. Replace
12061       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12062       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12063       // with "i32 42"
12064       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12065     if (exti == exte) {
12066       // The extract list is a prefix of the insert list. i.e. replace
12067       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12068       // %E = extractvalue { i32, { i32 } } %I, 1
12069       // with
12070       // %X = extractvalue { i32, { i32 } } %A, 1
12071       // %E = insertvalue { i32 } %X, i32 42, 0
12072       // by switching the order of the insert and extract (though the
12073       // insertvalue should be left in, since it may have other uses).
12074       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12075                                                  EV.idx_begin(), EV.idx_end());
12076       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12077                                      insi, inse);
12078     }
12079     if (insi == inse)
12080       // The insert list is a prefix of the extract list
12081       // We can simply remove the common indices from the extract and make it
12082       // operate on the inserted value instead of the insertvalue result.
12083       // i.e., replace
12084       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12085       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12086       // with
12087       // %E extractvalue { i32 } { i32 42 }, 0
12088       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12089                                       exti, exte);
12090   }
12091   // Can't simplify extracts from other values. Note that nested extracts are
12092   // already simplified implicitely by the above (extract ( extract (insert) )
12093   // will be translated into extract ( insert ( extract ) ) first and then just
12094   // the value inserted, if appropriate).
12095   return 0;
12096 }
12097
12098 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12099 /// is to leave as a vector operation.
12100 static bool CheapToScalarize(Value *V, bool isConstant) {
12101   if (isa<ConstantAggregateZero>(V)) 
12102     return true;
12103   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12104     if (isConstant) return true;
12105     // If all elts are the same, we can extract.
12106     Constant *Op0 = C->getOperand(0);
12107     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12108       if (C->getOperand(i) != Op0)
12109         return false;
12110     return true;
12111   }
12112   Instruction *I = dyn_cast<Instruction>(V);
12113   if (!I) return false;
12114   
12115   // Insert element gets simplified to the inserted element or is deleted if
12116   // this is constant idx extract element and its a constant idx insertelt.
12117   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12118       isa<ConstantInt>(I->getOperand(2)))
12119     return true;
12120   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12121     return true;
12122   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12123     if (BO->hasOneUse() &&
12124         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12125          CheapToScalarize(BO->getOperand(1), isConstant)))
12126       return true;
12127   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12128     if (CI->hasOneUse() &&
12129         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12130          CheapToScalarize(CI->getOperand(1), isConstant)))
12131       return true;
12132   
12133   return false;
12134 }
12135
12136 /// Read and decode a shufflevector mask.
12137 ///
12138 /// It turns undef elements into values that are larger than the number of
12139 /// elements in the input.
12140 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12141   unsigned NElts = SVI->getType()->getNumElements();
12142   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12143     return std::vector<unsigned>(NElts, 0);
12144   if (isa<UndefValue>(SVI->getOperand(2)))
12145     return std::vector<unsigned>(NElts, 2*NElts);
12146
12147   std::vector<unsigned> Result;
12148   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12149   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12150     if (isa<UndefValue>(*i))
12151       Result.push_back(NElts*2);  // undef -> 8
12152     else
12153       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12154   return Result;
12155 }
12156
12157 /// FindScalarElement - Given a vector and an element number, see if the scalar
12158 /// value is already around as a register, for example if it were inserted then
12159 /// extracted from the vector.
12160 static Value *FindScalarElement(Value *V, unsigned EltNo,
12161                                 LLVMContext *Context) {
12162   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12163   const VectorType *PTy = cast<VectorType>(V->getType());
12164   unsigned Width = PTy->getNumElements();
12165   if (EltNo >= Width)  // Out of range access.
12166     return UndefValue::get(PTy->getElementType());
12167   
12168   if (isa<UndefValue>(V))
12169     return UndefValue::get(PTy->getElementType());
12170   else if (isa<ConstantAggregateZero>(V))
12171     return Constant::getNullValue(PTy->getElementType());
12172   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12173     return CP->getOperand(EltNo);
12174   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12175     // If this is an insert to a variable element, we don't know what it is.
12176     if (!isa<ConstantInt>(III->getOperand(2))) 
12177       return 0;
12178     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12179     
12180     // If this is an insert to the element we are looking for, return the
12181     // inserted value.
12182     if (EltNo == IIElt) 
12183       return III->getOperand(1);
12184     
12185     // Otherwise, the insertelement doesn't modify the value, recurse on its
12186     // vector input.
12187     return FindScalarElement(III->getOperand(0), EltNo, Context);
12188   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12189     unsigned LHSWidth =
12190       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12191     unsigned InEl = getShuffleMask(SVI)[EltNo];
12192     if (InEl < LHSWidth)
12193       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12194     else if (InEl < LHSWidth*2)
12195       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12196     else
12197       return UndefValue::get(PTy->getElementType());
12198   }
12199   
12200   // Otherwise, we don't know.
12201   return 0;
12202 }
12203
12204 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12205   // If vector val is undef, replace extract with scalar undef.
12206   if (isa<UndefValue>(EI.getOperand(0)))
12207     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12208
12209   // If vector val is constant 0, replace extract with scalar 0.
12210   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12211     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12212   
12213   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12214     // If vector val is constant with all elements the same, replace EI with
12215     // that element. When the elements are not identical, we cannot replace yet
12216     // (we do that below, but only when the index is constant).
12217     Constant *op0 = C->getOperand(0);
12218     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12219       if (C->getOperand(i) != op0) {
12220         op0 = 0; 
12221         break;
12222       }
12223     if (op0)
12224       return ReplaceInstUsesWith(EI, op0);
12225   }
12226   
12227   // If extracting a specified index from the vector, see if we can recursively
12228   // find a previously computed scalar that was inserted into the vector.
12229   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12230     unsigned IndexVal = IdxC->getZExtValue();
12231     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12232       
12233     // If this is extracting an invalid index, turn this into undef, to avoid
12234     // crashing the code below.
12235     if (IndexVal >= VectorWidth)
12236       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12237     
12238     // This instruction only demands the single element from the input vector.
12239     // If the input vector has a single use, simplify it based on this use
12240     // property.
12241     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12242       APInt UndefElts(VectorWidth, 0);
12243       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12244       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12245                                                 DemandedMask, UndefElts)) {
12246         EI.setOperand(0, V);
12247         return &EI;
12248       }
12249     }
12250     
12251     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12252       return ReplaceInstUsesWith(EI, Elt);
12253     
12254     // If the this extractelement is directly using a bitcast from a vector of
12255     // the same number of elements, see if we can find the source element from
12256     // it.  In this case, we will end up needing to bitcast the scalars.
12257     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12258       if (const VectorType *VT = 
12259               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12260         if (VT->getNumElements() == VectorWidth)
12261           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12262                                              IndexVal, Context))
12263             return new BitCastInst(Elt, EI.getType());
12264     }
12265   }
12266   
12267   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12268     // Push extractelement into predecessor operation if legal and
12269     // profitable to do so
12270     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12271       if (I->hasOneUse() &&
12272           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12273         Value *newEI0 =
12274           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12275                                         EI.getName()+".lhs");
12276         Value *newEI1 =
12277           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12278                                         EI.getName()+".rhs");
12279         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12280       }
12281     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12282       // Extracting the inserted element?
12283       if (IE->getOperand(2) == EI.getOperand(1))
12284         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12285       // If the inserted and extracted elements are constants, they must not
12286       // be the same value, extract from the pre-inserted value instead.
12287       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12288         Worklist.AddValue(EI.getOperand(0));
12289         EI.setOperand(0, IE->getOperand(0));
12290         return &EI;
12291       }
12292     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12293       // If this is extracting an element from a shufflevector, figure out where
12294       // it came from and extract from the appropriate input element instead.
12295       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12296         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12297         Value *Src;
12298         unsigned LHSWidth =
12299           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12300
12301         if (SrcIdx < LHSWidth)
12302           Src = SVI->getOperand(0);
12303         else if (SrcIdx < LHSWidth*2) {
12304           SrcIdx -= LHSWidth;
12305           Src = SVI->getOperand(1);
12306         } else {
12307           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12308         }
12309         return ExtractElementInst::Create(Src,
12310                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12311                                           false));
12312       }
12313     }
12314     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12315   }
12316   return 0;
12317 }
12318
12319 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12320 /// elements from either LHS or RHS, return the shuffle mask and true. 
12321 /// Otherwise, return false.
12322 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12323                                          std::vector<Constant*> &Mask,
12324                                          LLVMContext *Context) {
12325   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12326          "Invalid CollectSingleShuffleElements");
12327   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12328
12329   if (isa<UndefValue>(V)) {
12330     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12331     return true;
12332   } else if (V == LHS) {
12333     for (unsigned i = 0; i != NumElts; ++i)
12334       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12335     return true;
12336   } else if (V == RHS) {
12337     for (unsigned i = 0; i != NumElts; ++i)
12338       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12339     return true;
12340   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12341     // If this is an insert of an extract from some other vector, include it.
12342     Value *VecOp    = IEI->getOperand(0);
12343     Value *ScalarOp = IEI->getOperand(1);
12344     Value *IdxOp    = IEI->getOperand(2);
12345     
12346     if (!isa<ConstantInt>(IdxOp))
12347       return false;
12348     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12349     
12350     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12351       // Okay, we can handle this if the vector we are insertinting into is
12352       // transitively ok.
12353       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12354         // If so, update the mask to reflect the inserted undef.
12355         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12356         return true;
12357       }      
12358     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12359       if (isa<ConstantInt>(EI->getOperand(1)) &&
12360           EI->getOperand(0)->getType() == V->getType()) {
12361         unsigned ExtractedIdx =
12362           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12363         
12364         // This must be extracting from either LHS or RHS.
12365         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12366           // Okay, we can handle this if the vector we are insertinting into is
12367           // transitively ok.
12368           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12369             // If so, update the mask to reflect the inserted value.
12370             if (EI->getOperand(0) == LHS) {
12371               Mask[InsertedIdx % NumElts] = 
12372                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12373             } else {
12374               assert(EI->getOperand(0) == RHS);
12375               Mask[InsertedIdx % NumElts] = 
12376                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12377               
12378             }
12379             return true;
12380           }
12381         }
12382       }
12383     }
12384   }
12385   // TODO: Handle shufflevector here!
12386   
12387   return false;
12388 }
12389
12390 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12391 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12392 /// that computes V and the LHS value of the shuffle.
12393 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12394                                      Value *&RHS, LLVMContext *Context) {
12395   assert(isa<VectorType>(V->getType()) && 
12396          (RHS == 0 || V->getType() == RHS->getType()) &&
12397          "Invalid shuffle!");
12398   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12399
12400   if (isa<UndefValue>(V)) {
12401     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12402     return V;
12403   } else if (isa<ConstantAggregateZero>(V)) {
12404     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12405     return V;
12406   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12407     // If this is an insert of an extract from some other vector, include it.
12408     Value *VecOp    = IEI->getOperand(0);
12409     Value *ScalarOp = IEI->getOperand(1);
12410     Value *IdxOp    = IEI->getOperand(2);
12411     
12412     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12413       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12414           EI->getOperand(0)->getType() == V->getType()) {
12415         unsigned ExtractedIdx =
12416           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12417         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12418         
12419         // Either the extracted from or inserted into vector must be RHSVec,
12420         // otherwise we'd end up with a shuffle of three inputs.
12421         if (EI->getOperand(0) == RHS || RHS == 0) {
12422           RHS = EI->getOperand(0);
12423           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12424           Mask[InsertedIdx % NumElts] = 
12425             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12426           return V;
12427         }
12428         
12429         if (VecOp == RHS) {
12430           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12431                                             RHS, Context);
12432           // Everything but the extracted element is replaced with the RHS.
12433           for (unsigned i = 0; i != NumElts; ++i) {
12434             if (i != InsertedIdx)
12435               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12436           }
12437           return V;
12438         }
12439         
12440         // If this insertelement is a chain that comes from exactly these two
12441         // vectors, return the vector and the effective shuffle.
12442         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12443                                          Context))
12444           return EI->getOperand(0);
12445         
12446       }
12447     }
12448   }
12449   // TODO: Handle shufflevector here!
12450   
12451   // Otherwise, can't do anything fancy.  Return an identity vector.
12452   for (unsigned i = 0; i != NumElts; ++i)
12453     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12454   return V;
12455 }
12456
12457 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12458   Value *VecOp    = IE.getOperand(0);
12459   Value *ScalarOp = IE.getOperand(1);
12460   Value *IdxOp    = IE.getOperand(2);
12461   
12462   // Inserting an undef or into an undefined place, remove this.
12463   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12464     ReplaceInstUsesWith(IE, VecOp);
12465   
12466   // If the inserted element was extracted from some other vector, and if the 
12467   // indexes are constant, try to turn this into a shufflevector operation.
12468   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12469     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12470         EI->getOperand(0)->getType() == IE.getType()) {
12471       unsigned NumVectorElts = IE.getType()->getNumElements();
12472       unsigned ExtractedIdx =
12473         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12474       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12475       
12476       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12477         return ReplaceInstUsesWith(IE, VecOp);
12478       
12479       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12480         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12481       
12482       // If we are extracting a value from a vector, then inserting it right
12483       // back into the same place, just use the input vector.
12484       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12485         return ReplaceInstUsesWith(IE, VecOp);      
12486       
12487       // If this insertelement isn't used by some other insertelement, turn it
12488       // (and any insertelements it points to), into one big shuffle.
12489       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12490         std::vector<Constant*> Mask;
12491         Value *RHS = 0;
12492         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12493         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12494         // We now have a shuffle of LHS, RHS, Mask.
12495         return new ShuffleVectorInst(LHS, RHS,
12496                                      ConstantVector::get(Mask));
12497       }
12498     }
12499   }
12500
12501   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12502   APInt UndefElts(VWidth, 0);
12503   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12504   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12505     return &IE;
12506
12507   return 0;
12508 }
12509
12510
12511 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12512   Value *LHS = SVI.getOperand(0);
12513   Value *RHS = SVI.getOperand(1);
12514   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12515
12516   bool MadeChange = false;
12517
12518   // Undefined shuffle mask -> undefined value.
12519   if (isa<UndefValue>(SVI.getOperand(2)))
12520     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12521
12522   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12523
12524   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12525     return 0;
12526
12527   APInt UndefElts(VWidth, 0);
12528   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12529   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12530     LHS = SVI.getOperand(0);
12531     RHS = SVI.getOperand(1);
12532     MadeChange = true;
12533   }
12534   
12535   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12536   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12537   if (LHS == RHS || isa<UndefValue>(LHS)) {
12538     if (isa<UndefValue>(LHS) && LHS == RHS) {
12539       // shuffle(undef,undef,mask) -> undef.
12540       return ReplaceInstUsesWith(SVI, LHS);
12541     }
12542     
12543     // Remap any references to RHS to use LHS.
12544     std::vector<Constant*> Elts;
12545     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12546       if (Mask[i] >= 2*e)
12547         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12548       else {
12549         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12550             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12551           Mask[i] = 2*e;     // Turn into undef.
12552           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12553         } else {
12554           Mask[i] = Mask[i] % e;  // Force to LHS.
12555           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12556         }
12557       }
12558     }
12559     SVI.setOperand(0, SVI.getOperand(1));
12560     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12561     SVI.setOperand(2, ConstantVector::get(Elts));
12562     LHS = SVI.getOperand(0);
12563     RHS = SVI.getOperand(1);
12564     MadeChange = true;
12565   }
12566   
12567   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12568   bool isLHSID = true, isRHSID = true;
12569     
12570   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12571     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12572     // Is this an identity shuffle of the LHS value?
12573     isLHSID &= (Mask[i] == i);
12574       
12575     // Is this an identity shuffle of the RHS value?
12576     isRHSID &= (Mask[i]-e == i);
12577   }
12578
12579   // Eliminate identity shuffles.
12580   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12581   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12582   
12583   // If the LHS is a shufflevector itself, see if we can combine it with this
12584   // one without producing an unusual shuffle.  Here we are really conservative:
12585   // we are absolutely afraid of producing a shuffle mask not in the input
12586   // program, because the code gen may not be smart enough to turn a merged
12587   // shuffle into two specific shuffles: it may produce worse code.  As such,
12588   // we only merge two shuffles if the result is one of the two input shuffle
12589   // masks.  In this case, merging the shuffles just removes one instruction,
12590   // which we know is safe.  This is good for things like turning:
12591   // (splat(splat)) -> splat.
12592   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12593     if (isa<UndefValue>(RHS)) {
12594       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12595
12596       std::vector<unsigned> NewMask;
12597       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12598         if (Mask[i] >= 2*e)
12599           NewMask.push_back(2*e);
12600         else
12601           NewMask.push_back(LHSMask[Mask[i]]);
12602       
12603       // If the result mask is equal to the src shuffle or this shuffle mask, do
12604       // the replacement.
12605       if (NewMask == LHSMask || NewMask == Mask) {
12606         unsigned LHSInNElts =
12607           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12608         std::vector<Constant*> Elts;
12609         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12610           if (NewMask[i] >= LHSInNElts*2) {
12611             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12612           } else {
12613             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12614           }
12615         }
12616         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12617                                      LHSSVI->getOperand(1),
12618                                      ConstantVector::get(Elts));
12619       }
12620     }
12621   }
12622
12623   return MadeChange ? &SVI : 0;
12624 }
12625
12626
12627
12628
12629 /// TryToSinkInstruction - Try to move the specified instruction from its
12630 /// current block into the beginning of DestBlock, which can only happen if it's
12631 /// safe to move the instruction past all of the instructions between it and the
12632 /// end of its block.
12633 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12634   assert(I->hasOneUse() && "Invariants didn't hold!");
12635
12636   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12637   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12638     return false;
12639
12640   // Do not sink alloca instructions out of the entry block.
12641   if (isa<AllocaInst>(I) && I->getParent() ==
12642         &DestBlock->getParent()->getEntryBlock())
12643     return false;
12644
12645   // We can only sink load instructions if there is nothing between the load and
12646   // the end of block that could change the value.
12647   if (I->mayReadFromMemory()) {
12648     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12649          Scan != E; ++Scan)
12650       if (Scan->mayWriteToMemory())
12651         return false;
12652   }
12653
12654   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12655
12656   CopyPrecedingStopPoint(I, InsertPos);
12657   I->moveBefore(InsertPos);
12658   ++NumSunkInst;
12659   return true;
12660 }
12661
12662
12663 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12664 /// all reachable code to the worklist.
12665 ///
12666 /// This has a couple of tricks to make the code faster and more powerful.  In
12667 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12668 /// them to the worklist (this significantly speeds up instcombine on code where
12669 /// many instructions are dead or constant).  Additionally, if we find a branch
12670 /// whose condition is a known constant, we only visit the reachable successors.
12671 ///
12672 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12673                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12674                                        InstCombiner &IC,
12675                                        const TargetData *TD) {
12676   SmallVector<BasicBlock*, 256> Worklist;
12677   Worklist.push_back(BB);
12678   
12679   std::vector<Instruction*> InstrsForInstCombineWorklist;
12680   InstrsForInstCombineWorklist.reserve(128);
12681
12682   while (!Worklist.empty()) {
12683     BB = Worklist.back();
12684     Worklist.pop_back();
12685     
12686     // We have now visited this block!  If we've already been here, ignore it.
12687     if (!Visited.insert(BB)) continue;
12688
12689     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12690       Instruction *Inst = BBI++;
12691       
12692       // DCE instruction if trivially dead.
12693       if (isInstructionTriviallyDead(Inst)) {
12694         ++NumDeadInst;
12695         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12696         Inst->eraseFromParent();
12697         continue;
12698       }
12699       
12700       // ConstantProp instruction if trivially constant.
12701       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12702         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12703                      << *Inst << '\n');
12704         Inst->replaceAllUsesWith(C);
12705         ++NumConstProp;
12706         Inst->eraseFromParent();
12707         continue;
12708       }
12709
12710       InstrsForInstCombineWorklist.push_back(Inst);
12711     }
12712
12713     // Recursively visit successors.  If this is a branch or switch on a
12714     // constant, only visit the reachable successor.
12715     TerminatorInst *TI = BB->getTerminator();
12716     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12717       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12718         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12719         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12720         Worklist.push_back(ReachableBB);
12721         continue;
12722       }
12723     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12724       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12725         // See if this is an explicit destination.
12726         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12727           if (SI->getCaseValue(i) == Cond) {
12728             BasicBlock *ReachableBB = SI->getSuccessor(i);
12729             Worklist.push_back(ReachableBB);
12730             continue;
12731           }
12732         
12733         // Otherwise it is the default destination.
12734         Worklist.push_back(SI->getSuccessor(0));
12735         continue;
12736       }
12737     }
12738     
12739     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12740       Worklist.push_back(TI->getSuccessor(i));
12741   }
12742   
12743   // Once we've found all of the instructions to add to instcombine's worklist,
12744   // add them in reverse order.  This way instcombine will visit from the top
12745   // of the function down.  This jives well with the way that it adds all uses
12746   // of instructions to the worklist after doing a transformation, thus avoiding
12747   // some N^2 behavior in pathological cases.
12748   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12749                               InstrsForInstCombineWorklist.size());
12750 }
12751
12752 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12753   MadeIRChange = false;
12754   TD = getAnalysisIfAvailable<TargetData>();
12755   
12756   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12757         << F.getNameStr() << "\n");
12758
12759   {
12760     // Do a depth-first traversal of the function, populate the worklist with
12761     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12762     // track of which blocks we visit.
12763     SmallPtrSet<BasicBlock*, 64> Visited;
12764     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12765
12766     // Do a quick scan over the function.  If we find any blocks that are
12767     // unreachable, remove any instructions inside of them.  This prevents
12768     // the instcombine code from having to deal with some bad special cases.
12769     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12770       if (!Visited.count(BB)) {
12771         Instruction *Term = BB->getTerminator();
12772         while (Term != BB->begin()) {   // Remove instrs bottom-up
12773           BasicBlock::iterator I = Term; --I;
12774
12775           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12776           // A debug intrinsic shouldn't force another iteration if we weren't
12777           // going to do one without it.
12778           if (!isa<DbgInfoIntrinsic>(I)) {
12779             ++NumDeadInst;
12780             MadeIRChange = true;
12781           }
12782           I->replaceAllUsesWith(UndefValue::get(I->getType()));
12783           I->eraseFromParent();
12784         }
12785       }
12786   }
12787
12788   while (!Worklist.isEmpty()) {
12789     Instruction *I = Worklist.RemoveOne();
12790     if (I == 0) continue;  // skip null values.
12791
12792     // Check to see if we can DCE the instruction.
12793     if (isInstructionTriviallyDead(I)) {
12794       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12795       EraseInstFromFunction(*I);
12796       ++NumDeadInst;
12797       MadeIRChange = true;
12798       continue;
12799     }
12800
12801     // Instruction isn't dead, see if we can constant propagate it.
12802     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12803       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12804
12805       // Add operands to the worklist.
12806       ReplaceInstUsesWith(*I, C);
12807       ++NumConstProp;
12808       EraseInstFromFunction(*I);
12809       MadeIRChange = true;
12810       continue;
12811     }
12812
12813     if (TD) {
12814       // See if we can constant fold its operands.
12815       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12816         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12817           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12818                                   F.getContext(), TD))
12819             if (NewC != CE) {
12820               *i = NewC;
12821               MadeIRChange = true;
12822             }
12823     }
12824
12825     // See if we can trivially sink this instruction to a successor basic block.
12826     if (I->hasOneUse()) {
12827       BasicBlock *BB = I->getParent();
12828       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12829       if (UserParent != BB) {
12830         bool UserIsSuccessor = false;
12831         // See if the user is one of our successors.
12832         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12833           if (*SI == UserParent) {
12834             UserIsSuccessor = true;
12835             break;
12836           }
12837
12838         // If the user is one of our immediate successors, and if that successor
12839         // only has us as a predecessors (we'd have to split the critical edge
12840         // otherwise), we can keep going.
12841         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12842             next(pred_begin(UserParent)) == pred_end(UserParent))
12843           // Okay, the CFG is simple enough, try to sink this instruction.
12844           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12845       }
12846     }
12847
12848     // Now that we have an instruction, try combining it to simplify it.
12849     Builder->SetInsertPoint(I->getParent(), I);
12850     
12851 #ifndef NDEBUG
12852     std::string OrigI;
12853 #endif
12854     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12855     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12856
12857     if (Instruction *Result = visit(*I)) {
12858       ++NumCombined;
12859       // Should we replace the old instruction with a new one?
12860       if (Result != I) {
12861         DEBUG(errs() << "IC: Old = " << *I << '\n'
12862                      << "    New = " << *Result << '\n');
12863
12864         // Everything uses the new instruction now.
12865         I->replaceAllUsesWith(Result);
12866
12867         // Push the new instruction and any users onto the worklist.
12868         Worklist.Add(Result);
12869         Worklist.AddUsersToWorkList(*Result);
12870
12871         // Move the name to the new instruction first.
12872         Result->takeName(I);
12873
12874         // Insert the new instruction into the basic block...
12875         BasicBlock *InstParent = I->getParent();
12876         BasicBlock::iterator InsertPos = I;
12877
12878         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12879           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12880             ++InsertPos;
12881
12882         InstParent->getInstList().insert(InsertPos, Result);
12883
12884         EraseInstFromFunction(*I);
12885       } else {
12886 #ifndef NDEBUG
12887         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12888                      << "    New = " << *I << '\n');
12889 #endif
12890
12891         // If the instruction was modified, it's possible that it is now dead.
12892         // if so, remove it.
12893         if (isInstructionTriviallyDead(I)) {
12894           EraseInstFromFunction(*I);
12895         } else {
12896           Worklist.Add(I);
12897           Worklist.AddUsersToWorkList(*I);
12898         }
12899       }
12900       MadeIRChange = true;
12901     }
12902   }
12903
12904   Worklist.Zap();
12905   return MadeIRChange;
12906 }
12907
12908
12909 bool InstCombiner::runOnFunction(Function &F) {
12910   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12911   Context = &F.getContext();
12912   
12913   
12914   /// Builder - This is an IRBuilder that automatically inserts new
12915   /// instructions into the worklist when they are created.
12916   IRBuilder<true, ConstantFolder, InstCombineIRInserter> 
12917     TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12918                InstCombineIRInserter(Worklist));
12919   Builder = &TheBuilder;
12920   
12921   bool EverMadeChange = false;
12922
12923   // Iterate while there is work to do.
12924   unsigned Iteration = 0;
12925   while (DoOneIteration(F, Iteration++))
12926     EverMadeChange = true;
12927   
12928   Builder = 0;
12929   return EverMadeChange;
12930 }
12931
12932 FunctionPass *llvm::createInstructionCombiningPass() {
12933   return new InstCombiner();
12934 }