LLVM API Documentation

InstructionCombining.cpp

Go to the documentation of this file.
00001 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // InstructionCombining - Combine instructions to form fewer, simple
00011 // instructions.  This pass does not modify the CFG.  This pass is where
00012 // algebraic simplification happens.
00013 //
00014 // This pass combines things like:
00015 //    %Y = add i32 %X, 1
00016 //    %Z = add i32 %Y, 1
00017 // into:
00018 //    %Z = add i32 %X, 2
00019 //
00020 // This is a simple worklist driven algorithm.
00021 //
00022 // This pass guarantees that the following canonicalizations are performed on
00023 // the program:
00024 //    1. If a binary operator has a constant operand, it is moved to the RHS
00025 //    2. Bitwise operators with constant operands are always grouped so that
00026 //       shifts are performed first, then or's, then and's, then xor's.
00027 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
00028 //    4. All cmp instructions on boolean values are replaced with logical ops
00029 //    5. add X, X is represented as (X*2) => (X << 1)
00030 //    6. Multiplies with a power-of-two constant argument are transformed into
00031 //       shifts.
00032 //   ... etc.
00033 //
00034 //===----------------------------------------------------------------------===//
00035 
00036 #define DEBUG_TYPE "instcombine"
00037 #include "llvm/Transforms/Scalar.h"
00038 #include "llvm/IntrinsicInst.h"
00039 #include "llvm/Pass.h"
00040 #include "llvm/DerivedTypes.h"
00041 #include "llvm/GlobalVariable.h"
00042 #include "llvm/Analysis/ConstantFolding.h"
00043 #include "llvm/Analysis/ValueTracking.h"
00044 #include "llvm/Target/TargetData.h"
00045 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00046 #include "llvm/Transforms/Utils/Local.h"
00047 #include "llvm/Support/CallSite.h"
00048 #include "llvm/Support/ConstantRange.h"
00049 #include "llvm/Support/Debug.h"
00050 #include "llvm/Support/GetElementPtrTypeIterator.h"
00051 #include "llvm/Support/InstVisitor.h"
00052 #include "llvm/Support/MathExtras.h"
00053 #include "llvm/Support/PatternMatch.h"
00054 #include "llvm/Support/Compiler.h"
00055 #include "llvm/ADT/DenseMap.h"
00056 #include "llvm/ADT/SmallVector.h"
00057 #include "llvm/ADT/SmallPtrSet.h"
00058 #include "llvm/ADT/Statistic.h"
00059 #include "llvm/ADT/STLExtras.h"
00060 #include <algorithm>
00061 #include <climits>
00062 #include <sstream>
00063 using namespace llvm;
00064 using namespace llvm::PatternMatch;
00065 
00066 STATISTIC(NumCombined , "Number of insts combined");
00067 STATISTIC(NumConstProp, "Number of constant folds");
00068 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
00069 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
00070 STATISTIC(NumSunkInst , "Number of instructions sunk");
00071 
00072 namespace {
00073   class VISIBILITY_HIDDEN InstCombiner
00074     : public FunctionPass,
00075       public InstVisitor<InstCombiner, Instruction*> {
00076     // Worklist of all of the instructions that need to be simplified.
00077     SmallVector<Instruction*, 256> Worklist;
00078     DenseMap<Instruction*, unsigned> WorklistMap;
00079     TargetData *TD;
00080     bool MustPreserveLCSSA;
00081   public:
00082     static char ID; // Pass identification, replacement for typeid
00083     InstCombiner() : FunctionPass(&ID) {}
00084 
00085     /// AddToWorkList - Add the specified instruction to the worklist if it
00086     /// isn't already in it.
00087     void AddToWorkList(Instruction *I) {
00088       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
00089         Worklist.push_back(I);
00090     }
00091     
00092     // RemoveFromWorkList - remove I from the worklist if it exists.
00093     void RemoveFromWorkList(Instruction *I) {
00094       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
00095       if (It == WorklistMap.end()) return; // Not in worklist.
00096       
00097       // Don't bother moving everything down, just null out the slot.
00098       Worklist[It->second] = 0;
00099       
00100       WorklistMap.erase(It);
00101     }
00102     
00103     Instruction *RemoveOneFromWorkList() {
00104       Instruction *I = Worklist.back();
00105       Worklist.pop_back();
00106       WorklistMap.erase(I);
00107       return I;
00108     }
00109 
00110     
00111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
00112     /// the instruction to the work lists because they might get more simplified
00113     /// now.
00114     ///
00115     void AddUsersToWorkList(Value &I) {
00116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
00117            UI != UE; ++UI)
00118         AddToWorkList(cast<Instruction>(*UI));
00119     }
00120 
00121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
00122     /// the work lists because they might get more simplified now.
00123     ///
00124     void AddUsesToWorkList(Instruction &I) {
00125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
00126         if (Instruction *Op = dyn_cast<Instruction>(*i))
00127           AddToWorkList(Op);
00128     }
00129     
00130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
00131     /// dead.  Add all of its operands to the worklist, turning them into
00132     /// undef's to reduce the number of uses of those instructions.
00133     ///
00134     /// Return the specified operand before it is turned into an undef.
00135     ///
00136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
00137       Value *R = I.getOperand(op);
00138       
00139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
00140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
00141           AddToWorkList(Op);
00142           // Set the operand to undef to drop the use.
00143           *i = UndefValue::get(Op->getType());
00144         }
00145       
00146       return R;
00147     }
00148 
00149   public:
00150     virtual bool runOnFunction(Function &F);
00151     
00152     bool DoOneIteration(Function &F, unsigned ItNum);
00153 
00154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00155       AU.addRequired<TargetData>();
00156       AU.addPreservedID(LCSSAID);
00157       AU.setPreservesCFG();
00158     }
00159 
00160     TargetData &getTargetData() const { return *TD; }
00161 
00162     // Visitation implementation - Implement instruction combining for different
00163     // instruction types.  The semantics are as follows:
00164     // Return Value:
00165     //    null        - No change was made
00166     //     I          - Change was made, I is still valid, I may be dead though
00167     //   otherwise    - Change was made, replace I with returned instruction
00168     //
00169     Instruction *visitAdd(BinaryOperator &I);
00170     Instruction *visitSub(BinaryOperator &I);
00171     Instruction *visitMul(BinaryOperator &I);
00172     Instruction *visitURem(BinaryOperator &I);
00173     Instruction *visitSRem(BinaryOperator &I);
00174     Instruction *visitFRem(BinaryOperator &I);
00175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
00176     Instruction *commonRemTransforms(BinaryOperator &I);
00177     Instruction *commonIRemTransforms(BinaryOperator &I);
00178     Instruction *commonDivTransforms(BinaryOperator &I);
00179     Instruction *commonIDivTransforms(BinaryOperator &I);
00180     Instruction *visitUDiv(BinaryOperator &I);
00181     Instruction *visitSDiv(BinaryOperator &I);
00182     Instruction *visitFDiv(BinaryOperator &I);
00183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
00184     Instruction *visitAnd(BinaryOperator &I);
00185     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
00186     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
00187                                      Value *A, Value *B, Value *C);
00188     Instruction *visitOr (BinaryOperator &I);
00189     Instruction *visitXor(BinaryOperator &I);
00190     Instruction *visitShl(BinaryOperator &I);
00191     Instruction *visitAShr(BinaryOperator &I);
00192     Instruction *visitLShr(BinaryOperator &I);
00193     Instruction *commonShiftTransforms(BinaryOperator &I);
00194     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
00195                                       Constant *RHSC);
00196     Instruction *visitFCmpInst(FCmpInst &I);
00197     Instruction *visitICmpInst(ICmpInst &I);
00198     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
00199     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
00200                                                 Instruction *LHS,
00201                                                 ConstantInt *RHS);
00202     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
00203                                 ConstantInt *DivRHS);
00204 
00205     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
00206                              ICmpInst::Predicate Cond, Instruction &I);
00207     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
00208                                      BinaryOperator &I);
00209     Instruction *commonCastTransforms(CastInst &CI);
00210     Instruction *commonIntCastTransforms(CastInst &CI);
00211     Instruction *commonPointerCastTransforms(CastInst &CI);
00212     Instruction *visitTrunc(TruncInst &CI);
00213     Instruction *visitZExt(ZExtInst &CI);
00214     Instruction *visitSExt(SExtInst &CI);
00215     Instruction *visitFPTrunc(FPTruncInst &CI);
00216     Instruction *visitFPExt(CastInst &CI);
00217     Instruction *visitFPToUI(FPToUIInst &FI);
00218     Instruction *visitFPToSI(FPToSIInst &FI);
00219     Instruction *visitUIToFP(CastInst &CI);
00220     Instruction *visitSIToFP(CastInst &CI);
00221     Instruction *visitPtrToInt(CastInst &CI);
00222     Instruction *visitIntToPtr(IntToPtrInst &CI);
00223     Instruction *visitBitCast(BitCastInst &CI);
00224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
00225                                 Instruction *FI);
00226     Instruction *visitSelectInst(SelectInst &SI);
00227     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
00228     Instruction *visitCallInst(CallInst &CI);
00229     Instruction *visitInvokeInst(InvokeInst &II);
00230     Instruction *visitPHINode(PHINode &PN);
00231     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
00232     Instruction *visitAllocationInst(AllocationInst &AI);
00233     Instruction *visitFreeInst(FreeInst &FI);
00234     Instruction *visitLoadInst(LoadInst &LI);
00235     Instruction *visitStoreInst(StoreInst &SI);
00236     Instruction *visitBranchInst(BranchInst &BI);
00237     Instruction *visitSwitchInst(SwitchInst &SI);
00238     Instruction *visitInsertElementInst(InsertElementInst &IE);
00239     Instruction *visitExtractElementInst(ExtractElementInst &EI);
00240     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
00241     Instruction *visitExtractValueInst(ExtractValueInst &EV);
00242 
00243     // visitInstruction - Specify what to return for unhandled instructions...
00244     Instruction *visitInstruction(Instruction &I) { return 0; }
00245 
00246   private:
00247     Instruction *visitCallSite(CallSite CS);
00248     bool transformConstExprCastCall(CallSite CS);
00249     Instruction *transformCallThroughTrampoline(CallSite CS);
00250     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
00251                                    bool DoXform = true);
00252     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
00253 
00254   public:
00255     // InsertNewInstBefore - insert an instruction New before instruction Old
00256     // in the program.  Add the new instruction to the worklist.
00257     //
00258     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
00259       assert(New && New->getParent() == 0 &&
00260              "New instruction already inserted into a basic block!");
00261       BasicBlock *BB = Old.getParent();
00262       BB->getInstList().insert(&Old, New);  // Insert inst
00263       AddToWorkList(New);
00264       return New;
00265     }
00266 
00267     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
00268     /// This also adds the cast to the worklist.  Finally, this returns the
00269     /// cast.
00270     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
00271                             Instruction &Pos) {
00272       if (V->getType() == Ty) return V;
00273 
00274       if (Constant *CV = dyn_cast<Constant>(V))
00275         return ConstantExpr::getCast(opc, CV, Ty);
00276       
00277       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
00278       AddToWorkList(C);
00279       return C;
00280     }
00281         
00282     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
00283       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
00284     }
00285 
00286 
00287     // ReplaceInstUsesWith - This method is to be used when an instruction is
00288     // found to be dead, replacable with another preexisting expression.  Here
00289     // we add all uses of I to the worklist, replace all uses of I with the new
00290     // value, then return I, so that the inst combiner will know that I was
00291     // modified.
00292     //
00293     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
00294       AddUsersToWorkList(I);         // Add all modified instrs to worklist
00295       if (&I != V) {
00296         I.replaceAllUsesWith(V);
00297         return &I;
00298       } else {
00299         // If we are replacing the instruction with itself, this must be in a
00300         // segment of unreachable code, so just clobber the instruction.
00301         I.replaceAllUsesWith(UndefValue::get(I.getType()));
00302         return &I;
00303       }
00304     }
00305 
00306     // EraseInstFromFunction - When dealing with an instruction that has side
00307     // effects or produces a void value, we can't rely on DCE to delete the
00308     // instruction.  Instead, visit methods should return the value returned by
00309     // this function.
00310     Instruction *EraseInstFromFunction(Instruction &I) {
00311       assert(I.use_empty() && "Cannot erase instruction that is used!");
00312       AddUsesToWorkList(I);
00313       RemoveFromWorkList(&I);
00314       I.eraseFromParent();
00315       return 0;  // Don't do anything with FI
00316     }
00317         
00318     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
00319                            APInt &KnownOne, unsigned Depth = 0) const {
00320       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
00321     }
00322     
00323     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
00324                            unsigned Depth = 0) const {
00325       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
00326     }
00327     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
00328       return llvm::ComputeNumSignBits(Op, TD, Depth);
00329     }
00330 
00331   private:
00332 
00333     /// SimplifyCommutative - This performs a few simplifications for 
00334     /// commutative operators.
00335     bool SimplifyCommutative(BinaryOperator &I);
00336 
00337     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
00338     /// most-complex to least-complex order.
00339     bool SimplifyCompare(CmpInst &I);
00340 
00341     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
00342     /// based on the demanded bits.
00343     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
00344                                    APInt& KnownZero, APInt& KnownOne,
00345                                    unsigned Depth);
00346     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
00347                               APInt& KnownZero, APInt& KnownOne,
00348                               unsigned Depth=0);
00349         
00350     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
00351     /// SimplifyDemandedBits knows about.  See if the instruction has any
00352     /// properties that allow us to simplify its operands.
00353     bool SimplifyDemandedInstructionBits(Instruction &Inst);
00354         
00355     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
00356                                       uint64_t &UndefElts, unsigned Depth = 0);
00357       
00358     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
00359     // PHI node as operand #0, see if we can fold the instruction into the PHI
00360     // (which is only possible if all operands to the PHI are constants).
00361     Instruction *FoldOpIntoPhi(Instruction &I);
00362 
00363     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
00364     // operator and they all are only used by the PHI, PHI together their
00365     // inputs, and do the operation once, to the result of the PHI.
00366     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
00367     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
00368     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
00369 
00370     
00371     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
00372                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
00373     
00374     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
00375                               bool isSub, Instruction &I);
00376     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
00377                                  bool isSigned, bool Inside, Instruction &IB);
00378     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
00379     Instruction *MatchBSwap(BinaryOperator &I);
00380     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
00381     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
00382     Instruction *SimplifyMemSet(MemSetInst *MI);
00383 
00384 
00385     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
00386 
00387     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
00388                                     unsigned CastOpc, int &NumCastsRemoved);
00389     unsigned GetOrEnforceKnownAlignment(Value *V,
00390                                         unsigned PrefAlign = 0);
00391 
00392   };
00393 }
00394 
00395 char InstCombiner::ID = 0;
00396 static RegisterPass<InstCombiner>
00397 X("instcombine", "Combine redundant instructions");
00398 
00399 // getComplexity:  Assign a complexity or rank value to LLVM Values...
00400 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
00401 static unsigned getComplexity(Value *V) {
00402   if (isa<Instruction>(V)) {
00403     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
00404       return 3;
00405     return 4;
00406   }
00407   if (isa<Argument>(V)) return 3;
00408   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
00409 }
00410 
00411 // isOnlyUse - Return true if this instruction will be deleted if we stop using
00412 // it.
00413 static bool isOnlyUse(Value *V) {
00414   return V->hasOneUse() || isa<Constant>(V);
00415 }
00416 
00417 // getPromotedType - Return the specified type promoted as it would be to pass
00418 // though a va_arg area...
00419 static const Type *getPromotedType(const Type *Ty) {
00420   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
00421     if (ITy->getBitWidth() < 32)
00422       return Type::Int32Ty;
00423   }
00424   return Ty;
00425 }
00426 
00427 /// getBitCastOperand - If the specified operand is a CastInst, a constant
00428 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
00429 /// operand value, otherwise return null.
00430 static Value *getBitCastOperand(Value *V) {
00431   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
00432     // BitCastInst?
00433     return I->getOperand(0);
00434   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
00435     // GetElementPtrInst?
00436     if (GEP->hasAllZeroIndices())
00437       return GEP->getOperand(0);
00438   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00439     if (CE->getOpcode() == Instruction::BitCast)
00440       // BitCast ConstantExp?
00441       return CE->getOperand(0);
00442     else if (CE->getOpcode() == Instruction::GetElementPtr) {
00443       // GetElementPtr ConstantExp?
00444       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
00445            I != E; ++I) {
00446         ConstantInt *CI = dyn_cast<ConstantInt>(I);
00447         if (!CI || !CI->isZero())
00448           // Any non-zero indices? Not cast-like.
00449           return 0;
00450       }
00451       // All-zero indices? This is just like casting.
00452       return CE->getOperand(0);
00453     }
00454   }
00455   return 0;
00456 }
00457 
00458 /// This function is a wrapper around CastInst::isEliminableCastPair. It
00459 /// simply extracts arguments and returns what that function returns.
00460 static Instruction::CastOps 
00461 isEliminableCastPair(
00462   const CastInst *CI, ///< The first cast instruction
00463   unsigned opcode,       ///< The opcode of the second cast instruction
00464   const Type *DstTy,     ///< The target type for the second cast instruction
00465   TargetData *TD         ///< The target data for pointer size
00466 ) {
00467   
00468   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
00469   const Type *MidTy = CI->getType();                  // B from above
00470 
00471   // Get the opcodes of the two Cast instructions
00472   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
00473   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
00474 
00475   return Instruction::CastOps(
00476       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
00477                                      DstTy, TD->getIntPtrType()));
00478 }
00479 
00480 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
00481 /// in any code being generated.  It does not require codegen if V is simple
00482 /// enough or if the cast can be folded into other casts.
00483 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
00484                               const Type *Ty, TargetData *TD) {
00485   if (V->getType() == Ty || isa<Constant>(V)) return false;
00486   
00487   // If this is another cast that can be eliminated, it isn't codegen either.
00488   if (const CastInst *CI = dyn_cast<CastInst>(V))
00489     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
00490       return false;
00491   return true;
00492 }
00493 
00494 // SimplifyCommutative - This performs a few simplifications for commutative
00495 // operators:
00496 //
00497 //  1. Order operands such that they are listed from right (least complex) to
00498 //     left (most complex).  This puts constants before unary operators before
00499 //     binary operators.
00500 //
00501 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
00502 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
00503 //
00504 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
00505   bool Changed = false;
00506   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
00507     Changed = !I.swapOperands();
00508 
00509   if (!I.isAssociative()) return Changed;
00510   Instruction::BinaryOps Opcode = I.getOpcode();
00511   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
00512     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
00513       if (isa<Constant>(I.getOperand(1))) {
00514         Constant *Folded = ConstantExpr::get(I.getOpcode(),
00515                                              cast<Constant>(I.getOperand(1)),
00516                                              cast<Constant>(Op->getOperand(1)));
00517         I.setOperand(0, Op->getOperand(0));
00518         I.setOperand(1, Folded);
00519         return true;
00520       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
00521         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
00522             isOnlyUse(Op) && isOnlyUse(Op1)) {
00523           Constant *C1 = cast<Constant>(Op->getOperand(1));
00524           Constant *C2 = cast<Constant>(Op1->getOperand(1));
00525 
00526           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
00527           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
00528           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
00529                                                     Op1->getOperand(0),
00530                                                     Op1->getName(), &I);
00531           AddToWorkList(New);
00532           I.setOperand(0, New);
00533           I.setOperand(1, Folded);
00534           return true;
00535         }
00536     }
00537   return Changed;
00538 }
00539 
00540 /// SimplifyCompare - For a CmpInst this function just orders the operands
00541 /// so that theyare listed from right (least complex) to left (most complex).
00542 /// This puts constants before unary operators before binary operators.
00543 bool InstCombiner::SimplifyCompare(CmpInst &I) {
00544   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
00545     return false;
00546   I.swapOperands();
00547   // Compare instructions are not associative so there's nothing else we can do.
00548   return true;
00549 }
00550 
00551 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
00552 // if the LHS is a constant zero (which is the 'negate' form).
00553 //
00554 static inline Value *dyn_castNegVal(Value *V) {
00555   if (BinaryOperator::isNeg(V))
00556     return BinaryOperator::getNegArgument(V);
00557 
00558   // Constants can be considered to be negated values if they can be folded.
00559   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
00560     return ConstantExpr::getNeg(C);
00561 
00562   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
00563     if (C->getType()->getElementType()->isInteger())
00564       return ConstantExpr::getNeg(C);
00565 
00566   return 0;
00567 }
00568 
00569 static inline Value *dyn_castNotVal(Value *V) {
00570   if (BinaryOperator::isNot(V))
00571     return BinaryOperator::getNotArgument(V);
00572 
00573   // Constants can be considered to be not'ed values...
00574   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
00575     return ConstantInt::get(~C->getValue());
00576   return 0;
00577 }
00578 
00579 // dyn_castFoldableMul - If this value is a multiply that can be folded into
00580 // other computations (because it has a constant operand), return the
00581 // non-constant operand of the multiply, and set CST to point to the multiplier.
00582 // Otherwise, return null.
00583 //
00584 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
00585   if (V->hasOneUse() && V->getType()->isInteger())
00586     if (Instruction *I = dyn_cast<Instruction>(V)) {
00587       if (I->getOpcode() == Instruction::Mul)
00588         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
00589           return I->getOperand(0);
00590       if (I->getOpcode() == Instruction::Shl)
00591         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
00592           // The multiplier is really 1 << CST.
00593           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
00594           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
00595           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
00596           return I->getOperand(0);
00597         }
00598     }
00599   return 0;
00600 }
00601 
00602 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
00603 /// expression, return it.
00604 static User *dyn_castGetElementPtr(Value *V) {
00605   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
00606   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00607     if (CE->getOpcode() == Instruction::GetElementPtr)
00608       return cast<User>(V);
00609   return false;
00610 }
00611 
00612 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
00613 /// opcode value. Otherwise return UserOp1.
00614 static unsigned getOpcode(const Value *V) {
00615   if (const Instruction *I = dyn_cast<Instruction>(V))
00616     return I->getOpcode();
00617   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00618     return CE->getOpcode();
00619   // Use UserOp1 to mean there's no opcode.
00620   return Instruction::UserOp1;
00621 }
00622 
00623 /// AddOne - Add one to a ConstantInt
00624 static ConstantInt *AddOne(ConstantInt *C) {
00625   APInt Val(C->getValue());
00626   return ConstantInt::get(++Val);
00627 }
00628 /// SubOne - Subtract one from a ConstantInt
00629 static ConstantInt *SubOne(ConstantInt *C) {
00630   APInt Val(C->getValue());
00631   return ConstantInt::get(--Val);
00632 }
00633 /// Add - Add two ConstantInts together
00634 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
00635   return ConstantInt::get(C1->getValue() + C2->getValue());
00636 }
00637 /// And - Bitwise AND two ConstantInts together
00638 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
00639   return ConstantInt::get(C1->getValue() & C2->getValue());
00640 }
00641 /// Subtract - Subtract one ConstantInt from another
00642 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
00643   return ConstantInt::get(C1->getValue() - C2->getValue());
00644 }
00645 /// Multiply - Multiply two ConstantInts together
00646 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
00647   return ConstantInt::get(C1->getValue() * C2->getValue());
00648 }
00649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
00650 /// this size.
00651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
00652   uint32_t W = C1->getBitWidth();
00653   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
00654   if (sign) {
00655     LHSExt.sext(W * 2);
00656     RHSExt.sext(W * 2);
00657   } else {
00658     LHSExt.zext(W * 2);
00659     RHSExt.zext(W * 2);
00660   }
00661 
00662   APInt MulExt = LHSExt * RHSExt;
00663 
00664   if (sign) {
00665     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
00666     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
00667     return MulExt.slt(Min) || MulExt.sgt(Max);
00668   } else 
00669     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
00670 }
00671 
00672 
00673 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
00674 /// specified instruction is a constant integer.  If so, check to see if there
00675 /// are any bits set in the constant that are not demanded.  If so, shrink the
00676 /// constant and return true.
00677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
00678                                    APInt Demanded) {
00679   assert(I && "No instruction?");
00680   assert(OpNo < I->getNumOperands() && "Operand index too large");
00681 
00682   // If the operand is not a constant integer, nothing to do.
00683   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
00684   if (!OpC) return false;
00685 
00686   // If there are no bits set that aren't demanded, nothing to do.
00687   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
00688   if ((~Demanded & OpC->getValue()) == 0)
00689     return false;
00690 
00691   // This instruction is producing bits that are not demanded. Shrink the RHS.
00692   Demanded &= OpC->getValue();
00693   I->setOperand(OpNo, ConstantInt::get(Demanded));
00694   return true;
00695 }
00696 
00697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
00698 // set of known zero and one bits, compute the maximum and minimum values that
00699 // could have the specified known zero and known one bits, returning them in
00700 // min/max.
00701 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
00702                                                    const APInt& KnownZero,
00703                                                    const APInt& KnownOne,
00704                                                    APInt& Min, APInt& Max) {
00705   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
00706   assert(KnownZero.getBitWidth() == BitWidth && 
00707          KnownOne.getBitWidth() == BitWidth &&
00708          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
00709          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
00710   APInt UnknownBits = ~(KnownZero|KnownOne);
00711 
00712   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
00713   // bit if it is unknown.
00714   Min = KnownOne;
00715   Max = KnownOne|UnknownBits;
00716   
00717   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
00718     Min.set(BitWidth-1);
00719     Max.clear(BitWidth-1);
00720   }
00721 }
00722 
00723 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
00724 // a set of known zero and one bits, compute the maximum and minimum values that
00725 // could have the specified known zero and known one bits, returning them in
00726 // min/max.
00727 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
00728                                                      const APInt &KnownZero,
00729                                                      const APInt &KnownOne,
00730                                                      APInt &Min, APInt &Max) {
00731   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
00732   assert(KnownZero.getBitWidth() == BitWidth && 
00733          KnownOne.getBitWidth() == BitWidth &&
00734          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
00735          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
00736   APInt UnknownBits = ~(KnownZero|KnownOne);
00737   
00738   // The minimum value is when the unknown bits are all zeros.
00739   Min = KnownOne;
00740   // The maximum value is when the unknown bits are all ones.
00741   Max = KnownOne|UnknownBits;
00742 }
00743 
00744 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
00745 /// SimplifyDemandedBits knows about.  See if the instruction has any
00746 /// properties that allow us to simplify its operands.
00747 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
00748   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
00749   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00750   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
00751   
00752   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
00753                                      KnownZero, KnownOne, 0);
00754   if (V == 0) return false;
00755   if (V == &Inst) return true;
00756   ReplaceInstUsesWith(Inst, V);
00757   return true;
00758 }
00759 
00760 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
00761 /// specified instruction operand if possible, updating it in place.  It returns
00762 /// true if it made any change and false otherwise.
00763 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
00764                                         APInt &KnownZero, APInt &KnownOne,
00765                                         unsigned Depth) {
00766   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
00767                                           KnownZero, KnownOne, Depth);
00768   if (NewVal == 0) return false;
00769   U.set(NewVal);
00770   return true;
00771 }
00772 
00773 
00774 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
00775 /// value based on the demanded bits.  When this function is called, it is known
00776 /// that only the bits set in DemandedMask of the result of V are ever used
00777 /// downstream. Consequently, depending on the mask and V, it may be possible
00778 /// to replace V with a constant or one of its operands. In such cases, this
00779 /// function does the replacement and returns true. In all other cases, it
00780 /// returns false after analyzing the expression and setting KnownOne and known
00781 /// to be one in the expression.  KnownZero contains all the bits that are known
00782 /// to be zero in the expression. These are provided to potentially allow the
00783 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
00784 /// the expression. KnownOne and KnownZero always follow the invariant that 
00785 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
00786 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
00787 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
00788 /// and KnownOne must all be the same.
00789 ///
00790 /// This returns null if it did not change anything and it permits no
00791 /// simplification.  This returns V itself if it did some simplification of V's
00792 /// operands based on the information about what bits are demanded. This returns
00793 /// some other non-null value if it found out that V is equal to another value
00794 /// in the context where the specified bits are demanded, but not for all users.
00795 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
00796                                              APInt &KnownZero, APInt &KnownOne,
00797                                              unsigned Depth) {
00798   assert(V != 0 && "Null pointer of Value???");
00799   assert(Depth <= 6 && "Limit Search Depth");
00800   uint32_t BitWidth = DemandedMask.getBitWidth();
00801   const IntegerType *VTy = cast<IntegerType>(V->getType());
00802   assert(VTy->getBitWidth() == BitWidth && 
00803          KnownZero.getBitWidth() == BitWidth && 
00804          KnownOne.getBitWidth() == BitWidth &&
00805          "Value *V, DemandedMask, KnownZero and KnownOne \
00806           must have same BitWidth");
00807   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00808     // We know all of the bits for a constant!
00809     KnownOne = CI->getValue() & DemandedMask;
00810     KnownZero = ~KnownOne & DemandedMask;
00811     return 0;
00812   }
00813   
00814   KnownZero.clear();
00815   KnownOne.clear();
00816   if (DemandedMask == 0) {   // Not demanding any bits from V.
00817     if (isa<UndefValue>(V))
00818       return 0;
00819     return UndefValue::get(VTy);
00820   }
00821   
00822   if (Depth == 6)        // Limit search depth.
00823     return 0;
00824   
00825   Instruction *I = dyn_cast<Instruction>(V);
00826   if (!I) return 0;        // Only analyze instructions.
00827   
00828   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00829   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
00830 
00831   // If there are multiple uses of this value and we aren't at the root, then
00832   // we can't do any simplifications of the operands, because DemandedMask
00833   // only reflects the bits demanded by *one* of the users.
00834   if (Depth != 0 && !I->hasOneUse()) {
00835     // Despite the fact that we can't simplify this instruction in all User's
00836     // context, we can at least compute the knownzero/knownone bits, and we can
00837     // do simplifications that apply to *just* the one user if we know that
00838     // this instruction has a simpler value in that context.
00839     if (I->getOpcode() == Instruction::And) {
00840       // If either the LHS or the RHS are Zero, the result is zero.
00841       ComputeMaskedBits(I->getOperand(1), DemandedMask,
00842                         RHSKnownZero, RHSKnownOne, Depth+1);
00843       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
00844                         LHSKnownZero, LHSKnownOne, Depth+1);
00845       
00846       // If all of the demanded bits are known 1 on one side, return the other.
00847       // These bits cannot contribute to the result of the 'and' in this
00848       // context.
00849       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
00850           (DemandedMask & ~LHSKnownZero))
00851         return I->getOperand(0);
00852       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
00853           (DemandedMask & ~RHSKnownZero))
00854         return I->getOperand(1);
00855       
00856       // If all of the demanded bits in the inputs are known zeros, return zero.
00857       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
00858         return Constant::getNullValue(VTy);
00859       
00860     } else if (I->getOpcode() == Instruction::Or) {
00861       // We can simplify (X|Y) -> X or Y in the user's context if we know that
00862       // only bits from X or Y are demanded.
00863       
00864       // If either the LHS or the RHS are One, the result is One.
00865       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
00866                         RHSKnownZero, RHSKnownOne, Depth+1);
00867       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
00868                         LHSKnownZero, LHSKnownOne, Depth+1);
00869       
00870       // If all of the demanded bits are known zero on one side, return the
00871       // other.  These bits cannot contribute to the result of the 'or' in this
00872       // context.
00873       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
00874           (DemandedMask & ~LHSKnownOne))
00875         return I->getOperand(0);
00876       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
00877           (DemandedMask & ~RHSKnownOne))
00878         return I->getOperand(1);
00879       
00880       // If all of the potentially set bits on one side are known to be set on
00881       // the other side, just use the 'other' side.
00882       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
00883           (DemandedMask & (~RHSKnownZero)))
00884         return I->getOperand(0);
00885       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
00886           (DemandedMask & (~LHSKnownZero)))
00887         return I->getOperand(1);
00888     }
00889     
00890     // Compute the KnownZero/KnownOne bits to simplify things downstream.
00891     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
00892     return 0;
00893   }
00894   
00895   // If this is the root being simplified, allow it to have multiple uses,
00896   // just set the DemandedMask to all bits so that we can try to simplify the
00897   // operands.  This allows visitTruncInst (for example) to simplify the
00898   // operand of a trunc without duplicating all the logic below.
00899   if (Depth == 0 && !V->hasOneUse())
00900     DemandedMask = APInt::getAllOnesValue(BitWidth);
00901   
00902   switch (I->getOpcode()) {
00903   default:
00904     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
00905     break;
00906   case Instruction::And:
00907     // If either the LHS or the RHS are Zero, the result is zero.
00908     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00909                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00910         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
00911                              LHSKnownZero, LHSKnownOne, Depth+1))
00912       return I;
00913     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
00914     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
00915 
00916     // If all of the demanded bits are known 1 on one side, return the other.
00917     // These bits cannot contribute to the result of the 'and'.
00918     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
00919         (DemandedMask & ~LHSKnownZero))
00920       return I->getOperand(0);
00921     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
00922         (DemandedMask & ~RHSKnownZero))
00923       return I->getOperand(1);
00924     
00925     // If all of the demanded bits in the inputs are known zeros, return zero.
00926     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
00927       return Constant::getNullValue(VTy);
00928       
00929     // If the RHS is a constant, see if we can simplify it.
00930     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
00931       return I;
00932       
00933     // Output known-1 bits are only known if set in both the LHS & RHS.
00934     RHSKnownOne &= LHSKnownOne;
00935     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00936     RHSKnownZero |= LHSKnownZero;
00937     break;
00938   case Instruction::Or:
00939     // If either the LHS or the RHS are One, the result is One.
00940     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
00941                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00942         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
00943                              LHSKnownZero, LHSKnownOne, Depth+1))
00944       return I;
00945     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
00946     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
00947     
00948     // If all of the demanded bits are known zero on one side, return the other.
00949     // These bits cannot contribute to the result of the 'or'.
00950     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
00951         (DemandedMask & ~LHSKnownOne))
00952       return I->getOperand(0);
00953     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
00954         (DemandedMask & ~RHSKnownOne))
00955       return I->getOperand(1);
00956 
00957     // If all of the potentially set bits on one side are known to be set on
00958     // the other side, just use the 'other' side.
00959     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
00960         (DemandedMask & (~RHSKnownZero)))
00961       return I->getOperand(0);
00962     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
00963         (DemandedMask & (~LHSKnownZero)))
00964       return I->getOperand(1);
00965         
00966     // If the RHS is a constant, see if we can simplify it.
00967     if (ShrinkDemandedConstant(I, 1, DemandedMask))
00968       return I;
00969           
00970     // Output known-0 bits are only known if clear in both the LHS & RHS.
00971     RHSKnownZero &= LHSKnownZero;
00972     // Output known-1 are known to be set if set in either the LHS | RHS.
00973     RHSKnownOne |= LHSKnownOne;
00974     break;
00975   case Instruction::Xor: {
00976     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00977                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00978         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
00979                              LHSKnownZero, LHSKnownOne, Depth+1))
00980       return I;
00981     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
00982     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
00983     
00984     // If all of the demanded bits are known zero on one side, return the other.
00985     // These bits cannot contribute to the result of the 'xor'.
00986     if ((DemandedMask & RHSKnownZero) == DemandedMask)
00987       return I->getOperand(0);
00988     if ((DemandedMask & LHSKnownZero) == DemandedMask)
00989       return I->getOperand(1);
00990     
00991     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00992     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
00993                          (RHSKnownOne & LHSKnownOne);
00994     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00995     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
00996                         (RHSKnownOne & LHSKnownZero);
00997     
00998     // If all of the demanded bits are known to be zero on one side or the
00999     // other, turn this into an *inclusive* or.
01000     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
01001     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
01002       Instruction *Or =
01003         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
01004                                  I->getName());
01005       return InsertNewInstBefore(Or, *I);
01006     }
01007     
01008     // If all of the demanded bits on one side are known, and all of the set
01009     // bits on that side are also known to be set on the other side, turn this
01010     // into an AND, as we know the bits will be cleared.
01011     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
01012     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
01013       // all known
01014       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
01015         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
01016         Instruction *And = 
01017           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
01018         return InsertNewInstBefore(And, *I);
01019       }
01020     }
01021     
01022     // If the RHS is a constant, see if we can simplify it.
01023     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
01024     if (ShrinkDemandedConstant(I, 1, DemandedMask))
01025       return I;
01026     
01027     RHSKnownZero = KnownZeroOut;
01028     RHSKnownOne  = KnownOneOut;
01029     break;
01030   }
01031   case Instruction::Select:
01032     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
01033                              RHSKnownZero, RHSKnownOne, Depth+1) ||
01034         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
01035                              LHSKnownZero, LHSKnownOne, Depth+1))
01036       return I;
01037     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
01038     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
01039     
01040     // If the operands are constants, see if we can simplify them.
01041     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
01042         ShrinkDemandedConstant(I, 2, DemandedMask))
01043       return I;
01044     
01045     // Only known if known in both the LHS and RHS.
01046     RHSKnownOne &= LHSKnownOne;
01047     RHSKnownZero &= LHSKnownZero;
01048     break;
01049   case Instruction::Trunc: {
01050     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
01051     DemandedMask.zext(truncBf);
01052     RHSKnownZero.zext(truncBf);
01053     RHSKnownOne.zext(truncBf);
01054     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
01055                              RHSKnownZero, RHSKnownOne, Depth+1))
01056       return I;
01057     DemandedMask.trunc(BitWidth);
01058     RHSKnownZero.trunc(BitWidth);
01059     RHSKnownOne.trunc(BitWidth);
01060     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
01061     break;
01062   }
01063   case Instruction::BitCast:
01064     if (!I->getOperand(0)->getType()->isInteger())
01065       return false;  // vector->int or fp->int?
01066     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
01067                              RHSKnownZero, RHSKnownOne, Depth+1))
01068       return I;
01069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
01070     break;
01071   case Instruction::ZExt: {
01072     // Compute the bits in the result that are not present in the input.
01073     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
01074     
01075     DemandedMask.trunc(SrcBitWidth);
01076     RHSKnownZero.trunc(SrcBitWidth);
01077     RHSKnownOne.trunc(SrcBitWidth);
01078     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
01079                              RHSKnownZero, RHSKnownOne, Depth+1))
01080       return I;
01081     DemandedMask.zext(BitWidth);
01082     RHSKnownZero.zext(BitWidth);
01083     RHSKnownOne.zext(BitWidth);
01084     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
01085     // The top bits are known to be zero.
01086     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
01087     break;
01088   }
01089   case Instruction::SExt: {
01090     // Compute the bits in the result that are not present in the input.
01091     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
01092     
01093     APInt InputDemandedBits = DemandedMask & 
01094                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
01095 
01096     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
01097     // If any of the sign extended bits are demanded, we know that the sign
01098     // bit is demanded.
01099     if ((NewBits & DemandedMask) != 0)
01100       InputDemandedBits.set(SrcBitWidth-1);
01101       
01102     InputDemandedBits.trunc(SrcBitWidth);
01103     RHSKnownZero.trunc(SrcBitWidth);
01104     RHSKnownOne.trunc(SrcBitWidth);
01105     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
01106                              RHSKnownZero, RHSKnownOne, Depth+1))
01107       return I;
01108     InputDemandedBits.zext(BitWidth);
01109     RHSKnownZero.zext(BitWidth);
01110     RHSKnownOne.zext(BitWidth);
01111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
01112       
01113     // If the sign bit of the input is known set or clear, then we know the
01114     // top bits of the result.
01115 
01116     // If the input sign bit is known zero, or if the NewBits are not demanded
01117     // convert this into a zero extension.
01118     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
01119       // Convert to ZExt cast
01120       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
01121       return InsertNewInstBefore(NewCast, *I);
01122     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
01123       RHSKnownOne |= NewBits;
01124     }
01125     break;
01126   }
01127   case Instruction::Add: {
01128     // Figure out what the input bits are.  If the top bits of the and result
01129     // are not demanded, then the add doesn't demand them from its input
01130     // either.
01131     unsigned NLZ = DemandedMask.countLeadingZeros();
01132       
01133     // If there is a constant on the RHS, there are a variety of xformations
01134     // we can do.
01135     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
01136       // If null, this should be simplified elsewhere.  Some of the xforms here
01137       // won't work if the RHS is zero.
01138       if (RHS->isZero())
01139         break;
01140       
01141       // If the top bit of the output is demanded, demand everything from the
01142       // input.  Otherwise, we demand all the input bits except NLZ top bits.
01143       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
01144 
01145       // Find information about known zero/one bits in the input.
01146       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
01147                                LHSKnownZero, LHSKnownOne, Depth+1))
01148         return I;
01149 
01150       // If the RHS of the add has bits set that can't affect the input, reduce
01151       // the constant.
01152       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
01153         return I;
01154       
01155       // Avoid excess work.
01156       if (LHSKnownZero == 0 && LHSKnownOne == 0)
01157         break;
01158       
01159       // Turn it into OR if input bits are zero.
01160       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
01161         Instruction *Or =
01162           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
01163                                    I->getName());
01164         return InsertNewInstBefore(Or, *I);
01165       }
01166       
01167       // We can say something about the output known-zero and known-one bits,
01168       // depending on potential carries from the input constant and the
01169       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
01170       // bits set and the RHS constant is 0x01001, then we know we have a known
01171       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
01172       
01173       // To compute this, we first compute the potential carry bits.  These are
01174       // the bits which may be modified.  I'm not aware of a better way to do
01175       // this scan.
01176       const APInt &RHSVal = RHS->getValue();
01177       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
01178       
01179       // Now that we know which bits have carries, compute the known-1/0 sets.
01180       
01181       // Bits are known one if they are known zero in one operand and one in the
01182       // other, and there is no input carry.
01183       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
01184                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
01185       
01186       // Bits are known zero if they are known zero in both operands and there
01187       // is no input carry.
01188       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
01189     } else {
01190       // If the high-bits of this ADD are not demanded, then it does not demand
01191       // the high bits of its LHS or RHS.
01192       if (DemandedMask[BitWidth-1] == 0) {
01193         // Right fill the mask of bits for this ADD to demand the most
01194         // significant bit and all those below it.
01195         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
01196         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
01197                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
01198             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
01199                                  LHSKnownZero, LHSKnownOne, Depth+1))
01200           return I;
01201       }
01202     }
01203     break;
01204   }
01205   case Instruction::Sub:
01206     // If the high-bits of this SUB are not demanded, then it does not demand
01207     // the high bits of its LHS or RHS.
01208     if (DemandedMask[BitWidth-1] == 0) {
01209       // Right fill the mask of bits for this SUB to demand the most
01210       // significant bit and all those below it.
01211       uint32_t NLZ = DemandedMask.countLeadingZeros();
01212       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
01213       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
01214                                LHSKnownZero, LHSKnownOne, Depth+1) ||
01215           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
01216                                LHSKnownZero, LHSKnownOne, Depth+1))
01217         return I;
01218     }
01219     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
01220     // the known zeros and ones.
01221     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
01222     break;
01223   case Instruction::Shl:
01224     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01225       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01226       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
01227       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
01228                                RHSKnownZero, RHSKnownOne, Depth+1))
01229         return I;
01230       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
01231       RHSKnownZero <<= ShiftAmt;
01232       RHSKnownOne  <<= ShiftAmt;
01233       // low bits known zero.
01234       if (ShiftAmt)
01235         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
01236     }
01237     break;
01238   case Instruction::LShr:
01239     // For a logical shift right
01240     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01241       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01242       
01243       // Unsigned shift right.
01244       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
01245       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
01246                                RHSKnownZero, RHSKnownOne, Depth+1))
01247         return I;
01248       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
01249       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
01250       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
01251       if (ShiftAmt) {
01252         // Compute the new bits that are at the top now.
01253         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
01254         RHSKnownZero |= HighBits;  // high bits known zero.
01255       }
01256     }
01257     break;
01258   case Instruction::AShr:
01259     // If this is an arithmetic shift right and only the low-bit is set, we can
01260     // always convert this into a logical shr, even if the shift amount is
01261     // variable.  The low bit of the shift cannot be an input sign bit unless
01262     // the shift amount is >= the size of the datatype, which is undefined.
01263     if (DemandedMask == 1) {
01264       // Perform the logical shift right.
01265       Instruction *NewVal = BinaryOperator::CreateLShr(
01266                         I->getOperand(0), I->getOperand(1), I->getName());
01267       return InsertNewInstBefore(NewVal, *I);
01268     }    
01269 
01270     // If the sign bit is the only bit demanded by this ashr, then there is no
01271     // need to do it, the shift doesn't change the high bit.
01272     if (DemandedMask.isSignBit())
01273       return I->getOperand(0);
01274     
01275     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01276       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
01277       
01278       // Signed shift right.
01279       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
01280       // If any of the "high bits" are demanded, we should set the sign bit as
01281       // demanded.
01282       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
01283         DemandedMaskIn.set(BitWidth-1);
01284       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
01285                                RHSKnownZero, RHSKnownOne, Depth+1))
01286         return I;
01287       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
01288       // Compute the new bits that are at the top now.
01289       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
01290       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
01291       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
01292         
01293       // Handle the sign bits.
01294       APInt SignBit(APInt::getSignBit(BitWidth));
01295       // Adjust to where it is now in the mask.
01296       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
01297         
01298       // If the input sign bit is known to be zero, or if none of the top bits
01299       // are demanded, turn this into an unsigned shift right.
01300       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
01301           (HighBits & ~DemandedMask) == HighBits) {
01302         // Perform the logical shift right.
01303         Instruction *NewVal = BinaryOperator::CreateLShr(
01304                           I->getOperand(0), SA, I->getName());
01305         return InsertNewInstBefore(NewVal, *I);
01306       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
01307         RHSKnownOne |= HighBits;
01308       }
01309     }
01310     break;
01311   case Instruction::SRem:
01312     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
01313       APInt RA = Rem->getValue().abs();
01314       if (RA.isPowerOf2()) {
01315         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
01316           return I->getOperand(0);
01317 
01318         APInt LowBits = RA - 1;
01319         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
01320         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
01321                                  LHSKnownZero, LHSKnownOne, Depth+1))
01322           return I;
01323 
01324         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
01325           LHSKnownZero |= ~LowBits;
01326 
01327         KnownZero |= LHSKnownZero & DemandedMask;
01328 
01329         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
01330       }
01331     }
01332     break;
01333   case Instruction::URem: {
01334     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
01335     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
01336     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
01337                              KnownZero2, KnownOne2, Depth+1) ||
01338         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
01339                              KnownZero2, KnownOne2, Depth+1))
01340       return I;
01341 
01342     unsigned Leaders = KnownZero2.countLeadingOnes();
01343     Leaders = std::max(Leaders,
01344                        KnownZero2.countLeadingOnes());
01345     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
01346     break;
01347   }
01348   case Instruction::Call:
01349     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01350       switch (II->getIntrinsicID()) {
01351       default: break;
01352       case Intrinsic::bswap: {
01353         // If the only bits demanded come from one byte of the bswap result,
01354         // just shift the input byte into position to eliminate the bswap.
01355         unsigned NLZ = DemandedMask.countLeadingZeros();
01356         unsigned NTZ = DemandedMask.countTrailingZeros();
01357           
01358         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
01359         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
01360         // have 14 leading zeros, round to 8.
01361         NLZ &= ~7;
01362         NTZ &= ~7;
01363         // If we need exactly one byte, we can do this transformation.
01364         if (BitWidth-NLZ-NTZ == 8) {
01365           unsigned ResultBit = NTZ;
01366           unsigned InputBit = BitWidth-NTZ-8;
01367           
01368           // Replace this with either a left or right shift to get the byte into
01369           // the right place.
01370           Instruction *NewVal;
01371           if (InputBit > ResultBit)
01372             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
01373                     ConstantInt::get(I->getType(), InputBit-ResultBit));
01374           else
01375             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
01376                     ConstantInt::get(I->getType(), ResultBit-InputBit));
01377           NewVal->takeName(I);
01378           return InsertNewInstBefore(NewVal, *I);
01379         }
01380           
01381         // TODO: Could compute known zero/one bits based on the input.
01382         break;
01383       }
01384       }
01385     }
01386     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
01387     break;
01388   }
01389   
01390   // If the client is only demanding bits that we know, return the known
01391   // constant.
01392   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
01393     return ConstantInt::get(RHSKnownOne);
01394   return false;
01395 }
01396 
01397 
01398 /// SimplifyDemandedVectorElts - The specified value produces a vector with
01399 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
01400 /// actually used by the caller.  This method analyzes which elements of the
01401 /// operand are undef and returns that information in UndefElts.
01402 ///
01403 /// If the information about demanded elements can be used to simplify the
01404 /// operation, the operation is simplified, then the resultant value is
01405 /// returned.  This returns null if no change was made.
01406 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
01407                                                 uint64_t &UndefElts,
01408                                                 unsigned Depth) {
01409   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
01410   assert(VWidth <= 64 && "Vector too wide to analyze!");
01411   uint64_t EltMask = ~0ULL >> (64-VWidth);
01412   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
01413 
01414   if (isa<UndefValue>(V)) {
01415     // If the entire vector is undefined, just return this info.
01416     UndefElts = EltMask;
01417     return 0;
01418   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
01419     UndefElts = EltMask;
01420     return UndefValue::get(V->getType());
01421   }
01422 
01423   UndefElts = 0;
01424   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
01425     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
01426     Constant *Undef = UndefValue::get(EltTy);
01427 
01428     std::vector<Constant*> Elts;
01429     for (unsigned i = 0; i != VWidth; ++i)
01430       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
01431         Elts.push_back(Undef);
01432         UndefElts |= (1ULL << i);
01433       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
01434         Elts.push_back(Undef);
01435         UndefElts |= (1ULL << i);
01436       } else {                               // Otherwise, defined.
01437         Elts.push_back(CP->getOperand(i));
01438       }
01439 
01440     // If we changed the constant, return it.
01441     Constant *NewCP = ConstantVector::get(Elts);
01442     return NewCP != CP ? NewCP : 0;
01443   } else if (isa<ConstantAggregateZero>(V)) {
01444     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
01445     // set to undef.
01446     
01447     // Check if this is identity. If so, return 0 since we are not simplifying
01448     // anything.
01449     if (DemandedElts == ((1ULL << VWidth) -1))
01450       return 0;
01451     
01452     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
01453     Constant *Zero = Constant::getNullValue(EltTy);
01454     Constant *Undef = UndefValue::get(EltTy);
01455     std::vector<Constant*> Elts;
01456     for (unsigned i = 0; i != VWidth; ++i)
01457       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
01458     UndefElts = DemandedElts ^ EltMask;
01459     return ConstantVector::get(Elts);
01460   }
01461   
01462   // Limit search depth.
01463   if (Depth == 10)
01464     return false;
01465 
01466   // If multiple users are using the root value, procede with
01467   // simplification conservatively assuming that all elements
01468   // are needed.
01469   if (!V->hasOneUse()) {
01470     // Quit if we find multiple users of a non-root value though.
01471     // They'll be handled when it's their turn to be visited by
01472     // the main instcombine process.
01473     if (Depth != 0)
01474       // TODO: Just compute the UndefElts information recursively.
01475       return false;
01476 
01477     // Conservatively assume that all elements are needed.
01478     DemandedElts = EltMask;
01479   }
01480   
01481   Instruction *I = dyn_cast<Instruction>(V);
01482   if (!I) return false;        // Only analyze instructions.
01483   
01484   bool MadeChange = false;
01485   uint64_t UndefElts2;
01486   Value *TmpV;
01487   switch (I->getOpcode()) {
01488   default: break;
01489     
01490   case Instruction::InsertElement: {
01491     // If this is a variable index, we don't know which element it overwrites.
01492     // demand exactly the same input as we produce.
01493     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
01494     if (Idx == 0) {
01495       // Note that we can't propagate undef elt info, because we don't know
01496       // which elt is getting updated.
01497       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01498                                         UndefElts2, Depth+1);
01499       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01500       break;
01501     }
01502     
01503     // If this is inserting an element that isn't demanded, remove this
01504     // insertelement.
01505     unsigned IdxNo = Idx->getZExtValue();
01506     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
01507       return AddSoonDeadInstToWorklist(*I, 0);
01508     
01509     // Otherwise, the element inserted overwrites whatever was there, so the
01510     // input demanded set is simpler than the output set.
01511     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
01512                                       DemandedElts & ~(1ULL << IdxNo),
01513                                       UndefElts, Depth+1);
01514     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01515 
01516     // The inserted element is defined.
01517     UndefElts &= ~(1ULL << IdxNo);
01518     break;
01519   }
01520   case Instruction::ShuffleVector: {
01521     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
01522     uint64_t LHSVWidth =
01523       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
01524     uint64_t LeftDemanded = 0, RightDemanded = 0;
01525     for (unsigned i = 0; i < VWidth; i++) {
01526       if (DemandedElts & (1ULL << i)) {
01527         unsigned MaskVal = Shuffle->getMaskValue(i);
01528         if (MaskVal != -1u) {
01529           assert(MaskVal < LHSVWidth * 2 &&
01530                  "shufflevector mask index out of range!");
01531           if (MaskVal < LHSVWidth)
01532             LeftDemanded |= 1ULL << MaskVal;
01533           else
01534             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
01535         }
01536       }
01537     }
01538 
01539     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
01540                                       UndefElts2, Depth+1);
01541     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01542 
01543     uint64_t UndefElts3;
01544     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
01545                                       UndefElts3, Depth+1);
01546     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01547 
01548     bool NewUndefElts = false;
01549     for (unsigned i = 0; i < VWidth; i++) {
01550       unsigned MaskVal = Shuffle->getMaskValue(i);
01551       if (MaskVal == -1u) {
01552         uint64_t NewBit = 1ULL << i;
01553         UndefElts |= NewBit;
01554       } else if (MaskVal < LHSVWidth) {
01555         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
01556         NewUndefElts |= NewBit;
01557         UndefElts |= NewBit;
01558       } else {
01559         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
01560         NewUndefElts |= NewBit;
01561         UndefElts |= NewBit;
01562       }
01563     }
01564 
01565     if (NewUndefElts) {
01566       // Add additional discovered undefs.
01567       std::vector<Constant*> Elts;
01568       for (unsigned i = 0; i < VWidth; ++i) {
01569         if (UndefElts & (1ULL << i))
01570           Elts.push_back(UndefValue::get(Type::Int32Ty));
01571         else
01572           Elts.push_back(ConstantInt::get(Type::Int32Ty,
01573                                           Shuffle->getMaskValue(i)));
01574       }
01575       I->setOperand(2, ConstantVector::get(Elts));
01576       MadeChange = true;
01577     }
01578     break;
01579   }
01580   case Instruction::BitCast: {
01581     // Vector->vector casts only.
01582     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
01583     if (!VTy) break;
01584     unsigned InVWidth = VTy->getNumElements();
01585     uint64_t InputDemandedElts = 0;
01586     unsigned Ratio;
01587 
01588     if (VWidth == InVWidth) {
01589       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
01590       // elements as are demanded of us.
01591       Ratio = 1;
01592       InputDemandedElts = DemandedElts;
01593     } else if (VWidth > InVWidth) {
01594       // Untested so far.
01595       break;
01596       
01597       // If there are more elements in the result than there are in the source,
01598       // then an input element is live if any of the corresponding output
01599       // elements are live.
01600       Ratio = VWidth/InVWidth;
01601       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
01602         if (DemandedElts & (1ULL << OutIdx))
01603           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
01604       }
01605     } else {
01606       // Untested so far.
01607       break;
01608       
01609       // If there are more elements in the source than there are in the result,
01610       // then an input element is live if the corresponding output element is
01611       // live.
01612       Ratio = InVWidth/VWidth;
01613       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
01614         if (DemandedElts & (1ULL << InIdx/Ratio))
01615           InputDemandedElts |= 1ULL << InIdx;
01616     }
01617     
01618     // div/rem demand all inputs, because they don't want divide by zero.
01619     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
01620                                       UndefElts2, Depth+1);
01621     if (TmpV) {
01622       I->setOperand(0, TmpV);
01623       MadeChange = true;
01624     }
01625     
01626     UndefElts = UndefElts2;
01627     if (VWidth > InVWidth) {
01628       assert(0 && "Unimp");
01629       // If there are more elements in the result than there are in the source,
01630       // then an output element is undef if the corresponding input element is
01631       // undef.
01632       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
01633         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
01634           UndefElts |= 1ULL << OutIdx;
01635     } else if (VWidth < InVWidth) {
01636       assert(0 && "Unimp");
01637       // If there are more elements in the source than there are in the result,
01638       // then a result element is undef if all of the corresponding input
01639       // elements are undef.
01640       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
01641       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
01642         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
01643           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
01644     }
01645     break;
01646   }
01647   case Instruction::And:
01648   case Instruction::Or:
01649   case Instruction::Xor:
01650   case Instruction::Add:
01651   case Instruction::Sub:
01652   case Instruction::Mul:
01653     // div/rem demand all inputs, because they don't want divide by zero.
01654     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01655                                       UndefElts, Depth+1);
01656     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01657     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
01658                                       UndefElts2, Depth+1);
01659     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01660       
01661     // Output elements are undefined if both are undefined.  Consider things
01662     // like undef&0.  The result is known zero, not undef.
01663     UndefElts &= UndefElts2;
01664     break;
01665     
01666   case Instruction::Call: {
01667     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
01668     if (!II) break;
01669     switch (II->getIntrinsicID()) {
01670     default: break;
01671       
01672     // Binary vector operations that work column-wise.  A dest element is a
01673     // function of the corresponding input elements from the two inputs.
01674     case Intrinsic::x86_sse_sub_ss:
01675     case Intrinsic::x86_sse_mul_ss:
01676     case Intrinsic::x86_sse_min_ss:
01677     case Intrinsic::x86_sse_max_ss:
01678     case Intrinsic::x86_sse2_sub_sd:
01679     case Intrinsic::x86_sse2_mul_sd:
01680     case Intrinsic::x86_sse2_min_sd:
01681     case Intrinsic::x86_sse2_max_sd:
01682       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
01683                                         UndefElts, Depth+1);
01684       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
01685       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
01686                                         UndefElts2, Depth+1);
01687       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
01688 
01689       // If only the low elt is demanded and this is a scalarizable intrinsic,
01690       // scalarize it now.
01691       if (DemandedElts == 1) {
01692         switch (II->getIntrinsicID()) {
01693         default: break;
01694         case Intrinsic::x86_sse_sub_ss:
01695         case Intrinsic::x86_sse_mul_ss:
01696         case Intrinsic::x86_sse2_sub_sd:
01697         case Intrinsic::x86_sse2_mul_sd:
01698           // TODO: Lower MIN/MAX/ABS/etc
01699           Value *LHS = II->getOperand(1);
01700           Value *RHS = II->getOperand(2);
01701           // Extract the element as scalars.
01702           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
01703           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
01704           
01705           switch (II->getIntrinsicID()) {
01706           default: assert(0 && "Case stmts out of sync!");
01707           case Intrinsic::x86_sse_sub_ss:
01708           case Intrinsic::x86_sse2_sub_sd:
01709             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
01710                                                         II->getName()), *II);
01711             break;
01712           case Intrinsic::x86_sse_mul_ss:
01713           case Intrinsic::x86_sse2_mul_sd:
01714             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
01715                                                          II->getName()), *II);
01716             break;
01717           }
01718           
01719           Instruction *New =
01720             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
01721                                       II->getName());
01722           InsertNewInstBefore(New, *II);
01723           AddSoonDeadInstToWorklist(*II, 0);
01724           return New;
01725         }            
01726       }
01727         
01728       // Output elements are undefined if both are undefined.  Consider things
01729       // like undef&0.  The result is known zero, not undef.
01730       UndefElts &= UndefElts2;
01731       break;
01732     }
01733     break;
01734   }
01735   }
01736   return MadeChange ? I : 0;
01737 }
01738 
01739 
01740 /// AssociativeOpt - Perform an optimization on an associative operator.  This
01741 /// function is designed to check a chain of associative operators for a
01742 /// potential to apply a certain optimization.  Since the optimization may be
01743 /// applicable if the expression was reassociated, this checks the chain, then
01744 /// reassociates the expression as necessary to expose the optimization
01745 /// opportunity.  This makes use of a special Functor, which must define
01746 /// 'shouldApply' and 'apply' methods.
01747 ///
01748 template<typename Functor>
01749 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
01750   unsigned Opcode = Root.getOpcode();
01751   Value *LHS = Root.getOperand(0);
01752 
01753   // Quick check, see if the immediate LHS matches...
01754   if (F.shouldApply(LHS))
01755     return F.apply(Root);
01756 
01757   // Otherwise, if the LHS is not of the same opcode as the root, return.
01758   Instruction *LHSI = dyn_cast<Instruction>(LHS);
01759   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
01760     // Should we apply this transform to the RHS?
01761     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
01762 
01763     // If not to the RHS, check to see if we should apply to the LHS...
01764     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
01765       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
01766       ShouldApply = true;
01767     }
01768 
01769     // If the functor wants to apply the optimization to the RHS of LHSI,
01770     // reassociate the expression from ((? op A) op B) to (? op (A op B))
01771     if (ShouldApply) {
01772       // Now all of the instructions are in the current basic block, go ahead
01773       // and perform the reassociation.
01774       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
01775 
01776       // First move the selected RHS to the LHS of the root...
01777       Root.setOperand(0, LHSI->getOperand(1));
01778 
01779       // Make what used to be the LHS of the root be the user of the root...
01780       Value *ExtraOperand = TmpLHSI->getOperand(1);
01781       if (&Root == TmpLHSI) {
01782         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
01783         return 0;
01784       }
01785       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
01786       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
01787       BasicBlock::iterator ARI = &Root; ++ARI;
01788       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
01789       ARI = Root;
01790 
01791       // Now propagate the ExtraOperand down the chain of instructions until we
01792       // get to LHSI.
01793       while (TmpLHSI != LHSI) {
01794         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
01795         // Move the instruction to immediately before the chain we are
01796         // constructing to avoid breaking dominance properties.
01797         NextLHSI->moveBefore(ARI);
01798         ARI = NextLHSI;
01799 
01800         Value *NextOp = NextLHSI->getOperand(1);
01801         NextLHSI->setOperand(1, ExtraOperand);
01802         TmpLHSI = NextLHSI;
01803         ExtraOperand = NextOp;
01804       }
01805 
01806       // Now that the instructions are reassociated, have the functor perform
01807       // the transformation...
01808       return F.apply(Root);
01809     }
01810 
01811     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
01812   }
01813   return 0;
01814 }
01815 
01816 namespace {
01817 
01818 // AddRHS - Implements: X + X --> X << 1
01819 struct AddRHS {
01820   Value *RHS;
01821   AddRHS(Value *rhs) : RHS(rhs) {}
01822   bool shouldApply(Value *LHS) const { return LHS == RHS; }
01823   Instruction *apply(BinaryOperator &Add) const {
01824     return BinaryOperator::CreateShl(Add.getOperand(0),
01825                                      ConstantInt::get(Add.getType(), 1));
01826   }
01827 };
01828 
01829 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
01830 //                 iff C1&C2 == 0
01831 struct AddMaskingAnd {
01832   Constant *C2;
01833   AddMaskingAnd(Constant *c) : C2(c) {}
01834   bool shouldApply(Value *LHS) const {
01835     ConstantInt *C1;
01836     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
01837            ConstantExpr::getAnd(C1, C2)->isNullValue();
01838   }
01839   Instruction *apply(BinaryOperator &Add) const {
01840     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
01841   }
01842 };
01843 
01844 }
01845 
01846 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
01847                                              InstCombiner *IC) {
01848   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
01849     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
01850   }
01851 
01852   // Figure out if the constant is the left or the right argument.
01853   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
01854   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
01855 
01856   if (Constant *SOC = dyn_cast<Constant>(SO)) {
01857     if (ConstIsRHS)
01858       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
01859     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
01860   }
01861 
01862   Value *Op0 = SO, *Op1 = ConstOperand;
01863   if (!ConstIsRHS)
01864     std::swap(Op0, Op1);
01865   Instruction *New;
01866   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
01867     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
01868   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
01869     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
01870                           SO->getName()+".cmp");
01871   else {
01872     assert(0 && "Unknown binary instruction type!");
01873     abort();
01874   }
01875   return IC->InsertNewInstBefore(New, I);
01876 }
01877 
01878 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
01879 // constant as the other operand, try to fold the binary operator into the
01880 // select arguments.  This also works for Cast instructions, which obviously do
01881 // not have a second operand.
01882 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
01883                                      InstCombiner *IC) {
01884   // Don't modify shared select instructions
01885   if (!SI->hasOneUse()) return 0;
01886   Value *TV = SI->getOperand(1);
01887   Value *FV = SI->getOperand(2);
01888 
01889   if (isa<Constant>(TV) || isa<Constant>(FV)) {
01890     // Bool selects with constant operands can be folded to logical ops.
01891     if (SI->getType() == Type::Int1Ty) return 0;
01892 
01893     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
01894     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
01895 
01896     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
01897                               SelectFalseVal);
01898   }
01899   return 0;
01900 }
01901 
01902 
01903 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
01904 /// node as operand #0, see if we can fold the instruction into the PHI (which
01905 /// is only possible if all operands to the PHI are constants).
01906 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
01907   PHINode *PN = cast<PHINode>(I.getOperand(0));
01908   unsigned NumPHIValues = PN->getNumIncomingValues();
01909   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
01910 
01911   // Check to see if all of the operands of the PHI are constants.  If there is
01912   // one non-constant value, remember the BB it is.  If there is more than one
01913   // or if *it* is a PHI, bail out.
01914   BasicBlock *NonConstBB = 0;
01915   for (unsigned i = 0; i != NumPHIValues; ++i)
01916     if (!isa<Constant>(PN->getIncomingValue(i))) {
01917       if (NonConstBB) return 0;  // More than one non-const value.
01918       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
01919       NonConstBB = PN->getIncomingBlock(i);
01920       
01921       // If the incoming non-constant value is in I's block, we have an infinite
01922       // loop.
01923       if (NonConstBB == I.getParent())
01924         return 0;
01925     }
01926   
01927   // If there is exactly one non-constant value, we can insert a copy of the
01928   // operation in that block.  However, if this is a critical edge, we would be
01929   // inserting the computation one some other paths (e.g. inside a loop).  Only
01930   // do this if the pred block is unconditionally branching into the phi block.
01931   if (NonConstBB) {
01932     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
01933     if (!BI || !BI->isUnconditional()) return 0;
01934   }
01935 
01936   // Okay, we can do the transformation: create the new PHI node.
01937   PHINode *NewPN = PHINode::Create(I.getType(), "");
01938   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
01939   InsertNewInstBefore(NewPN, *PN);
01940   NewPN->takeName(PN);
01941 
01942   // Next, add all of the operands to the PHI.
01943   if (I.getNumOperands() == 2) {
01944     Constant *C = cast<Constant>(I.getOperand(1));
01945     for (unsigned i = 0; i != NumPHIValues; ++i) {
01946       Value *InV = 0;
01947       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
01948         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
01949           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
01950         else
01951           InV = ConstantExpr::get(I.getOpcode(), InC, C);
01952       } else {
01953         assert(PN->getIncomingBlock(i) == NonConstBB);
01954         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
01955           InV = BinaryOperator::Create(BO->getOpcode(),
01956                                        PN->getIncomingValue(i), C, "phitmp",
01957                                        NonConstBB->getTerminator());
01958         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
01959           InV = CmpInst::Create(CI->getOpcode(), 
01960                                 CI->getPredicate(),
01961                                 PN->getIncomingValue(i), C, "phitmp",
01962                                 NonConstBB->getTerminator());
01963         else
01964           assert(0 && "Unknown binop!");
01965         
01966         AddToWorkList(cast<Instruction>(InV));
01967       }
01968       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
01969     }
01970   } else { 
01971     CastInst *CI = cast<CastInst>(&I);
01972     const Type *RetTy = CI->getType();
01973     for (unsigned i = 0; i != NumPHIValues; ++i) {
01974       Value *InV;
01975       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
01976         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
01977       } else {
01978         assert(PN->getIncomingBlock(i) == NonConstBB);
01979         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
01980                                I.getType(), "phitmp", 
01981                                NonConstBB->getTerminator());
01982         AddToWorkList(cast<Instruction>(InV));
01983       }
01984       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
01985     }
01986   }
01987   return ReplaceInstUsesWith(I, NewPN);
01988 }
01989 
01990 
01991 /// WillNotOverflowSignedAdd - Return true if we can prove that:
01992 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
01993 /// This basically requires proving that the add in the original type would not
01994 /// overflow to change the sign bit or have a carry out.
01995 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
01996   // There are different heuristics we can use for this.  Here are some simple
01997   // ones.
01998   
01999   // Add has the property that adding any two 2's complement numbers can only 
02000   // have one carry bit which can change a sign.  As such, if LHS and RHS each
02001   // have at least two sign bits, we know that the addition of the two values will
02002   // sign extend fine.
02003   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
02004     return true;
02005   
02006   
02007   // If one of the operands only has one non-zero bit, and if the other operand
02008   // has a known-zero bit in a more significant place than it (not including the
02009   // sign bit) the ripple may go up to and fill the zero, but won't change the
02010   // sign.  For example, (X & ~4) + 1.
02011   
02012   // TODO: Implement.
02013   
02014   return false;
02015 }
02016 
02017 
02018 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
02019   bool Changed = SimplifyCommutative(I);
02020   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
02021 
02022   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
02023     // X + undef -> undef
02024     if (isa<UndefValue>(RHS))
02025       return ReplaceInstUsesWith(I, RHS);
02026 
02027     // X + 0 --> X
02028     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
02029       if (RHSC->isNullValue())
02030         return ReplaceInstUsesWith(I, LHS);
02031     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
02032       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
02033                               (I.getType())->getValueAPF()))
02034         return ReplaceInstUsesWith(I, LHS);
02035     }
02036 
02037     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
02038       // X + (signbit) --> X ^ signbit
02039       const APInt& Val = CI->getValue();
02040       uint32_t BitWidth = Val.getBitWidth();
02041       if (Val == APInt::getSignBit(BitWidth))
02042         return BinaryOperator::CreateXor(LHS, RHS);
02043       
02044       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
02045       // (X & 254)+1 -> (X&254)|1
02046       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
02047         return &I;
02048 
02049       // zext(i1) - 1  ->  select i1, 0, -1
02050       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
02051         if (CI->isAllOnesValue() &&
02052             ZI->getOperand(0)->getType() == Type::Int1Ty)
02053           return SelectInst::Create(ZI->getOperand(0),
02054                                     Constant::getNullValue(I.getType()),
02055                                     ConstantInt::getAllOnesValue(I.getType()));
02056     }
02057 
02058     if (isa<PHINode>(LHS))
02059       if (Instruction *NV = FoldOpIntoPhi(I))
02060         return NV;
02061     
02062     ConstantInt *XorRHS = 0;
02063     Value *XorLHS = 0;
02064     if (isa<ConstantInt>(RHSC) &&
02065         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
02066       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
02067       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
02068       
02069       uint32_t Size = TySizeBits / 2;
02070       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
02071       APInt CFF80Val(-C0080Val);
02072       do {
02073         if (TySizeBits > Size) {
02074           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
02075           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
02076           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
02077               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
02078             // This is a sign extend if the top bits are known zero.
02079             if (!MaskedValueIsZero(XorLHS, 
02080                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
02081               Size = 0;  // Not a sign ext, but can't be any others either.
02082             break;
02083           }
02084         }
02085         Size >>= 1;
02086         C0080Val = APIntOps::lshr(C0080Val, Size);
02087         CFF80Val = APIntOps::ashr(CFF80Val, Size);
02088       } while (Size >= 1);
02089       
02090       // FIXME: This shouldn't be necessary. When the backends can handle types
02091       // with funny bit widths then this switch statement should be removed. It
02092       // is just here to get the size of the "middle" type back up to something
02093       // that the back ends can handle.
02094       const Type *MiddleType = 0;
02095       switch (Size) {
02096         default: break;
02097         case 32: MiddleType = Type::Int32Ty; break;
02098         case 16: MiddleType = Type::Int16Ty; break;
02099         case  8: MiddleType = Type::Int8Ty; break;
02100       }
02101       if (MiddleType) {
02102         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
02103         InsertNewInstBefore(NewTrunc, I);
02104         return new SExtInst(NewTrunc, I.getType(), I.getName());
02105       }
02106     }
02107   }
02108 
02109   if (I.getType() == Type::Int1Ty)
02110     return BinaryOperator::CreateXor(LHS, RHS);
02111 
02112   // X + X --> X << 1
02113   if (I.getType()->isInteger()) {
02114     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
02115 
02116     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
02117       if (RHSI->getOpcode() == Instruction::Sub)
02118         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
02119           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
02120     }
02121     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
02122       if (LHSI->getOpcode() == Instruction::Sub)
02123         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
02124           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
02125     }
02126   }
02127 
02128   // -A + B  -->  B - A
02129   // -A + -B  -->  -(A + B)
02130   if (Value *LHSV = dyn_castNegVal(LHS)) {
02131     if (LHS->getType()->isIntOrIntVector()) {
02132       if (Value *RHSV = dyn_castNegVal(RHS)) {
02133         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
02134         InsertNewInstBefore(NewAdd, I);
02135         return BinaryOperator::CreateNeg(NewAdd);
02136       }
02137     }
02138     
02139     return BinaryOperator::CreateSub(RHS, LHSV);
02140   }
02141 
02142   // A + -B  -->  A - B
02143   if (!isa<Constant>(RHS))
02144     if (Value *V = dyn_castNegVal(RHS))
02145       return BinaryOperator::CreateSub(LHS, V);
02146 
02147 
02148   ConstantInt *C2;
02149   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
02150     if (X == RHS)   // X*C + X --> X * (C+1)
02151       return BinaryOperator::CreateMul(RHS, AddOne(C2));
02152 
02153     // X*C1 + X*C2 --> X * (C1+C2)
02154     ConstantInt *C1;
02155     if (X == dyn_castFoldableMul(RHS, C1))
02156       return BinaryOperator::CreateMul(X, Add(C1, C2));
02157   }
02158 
02159   // X + X*C --> X * (C+1)
02160   if (dyn_castFoldableMul(RHS, C2) == LHS)
02161     return BinaryOperator::CreateMul(LHS, AddOne(C2));
02162 
02163   // X + ~X --> -1   since   ~X = -X-1
02164   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
02165     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
02166   
02167 
02168   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
02169   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
02170     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
02171       return R;
02172   
02173   // A+B --> A|B iff A and B have no bits set in common.
02174   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
02175     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
02176     APInt LHSKnownOne(IT->getBitWidth(), 0);
02177     APInt LHSKnownZero(IT->getBitWidth(), 0);
02178     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
02179     if (LHSKnownZero != 0) {
02180       APInt RHSKnownOne(IT->getBitWidth(), 0);
02181       APInt RHSKnownZero(IT->getBitWidth(), 0);
02182       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
02183       
02184       // No bits in common -> bitwise or.
02185       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
02186         return BinaryOperator::CreateOr(LHS, RHS);
02187     }
02188   }
02189 
02190   // W*X + Y*Z --> W * (X+Z)  iff W == Y
02191   if (I.getType()->isIntOrIntVector()) {
02192     Value *W, *X, *Y, *Z;
02193     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
02194         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
02195       if (W != Y) {
02196         if (W == Z) {
02197           std::swap(Y, Z);
02198         } else if (Y == X) {
02199           std::swap(W, X);
02200         } else if (X == Z) {
02201           std::swap(Y, Z);
02202           std::swap(W, X);
02203         }
02204       }
02205 
02206       if (W == Y) {
02207         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
02208                                                             LHS->getName()), I);
02209         return BinaryOperator::CreateMul(W, NewAdd);
02210       }
02211     }
02212   }
02213 
02214   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
02215     Value *X = 0;
02216     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
02217       return BinaryOperator::CreateSub(SubOne(CRHS), X);
02218 
02219     // (X & FF00) + xx00  -> (X+xx00) & FF00
02220     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
02221       Constant *Anded = And(CRHS, C2);
02222       if (Anded == CRHS) {
02223         // See if all bits from the first bit set in the Add RHS up are included
02224         // in the mask.  First, get the rightmost bit.
02225         const APInt& AddRHSV = CRHS->getValue();
02226 
02227         // Form a mask of all bits from the lowest bit added through the top.
02228         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
02229 
02230         // See if the and mask includes all of these bits.
02231         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
02232 
02233         if (AddRHSHighBits == AddRHSHighBitsAnd) {
02234           // Okay, the xform is safe.  Insert the new add pronto.
02235           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
02236                                                             LHS->getName()), I);
02237           return BinaryOperator::CreateAnd(NewAdd, C2);
02238         }
02239       }
02240     }
02241 
02242     // Try to fold constant add into select arguments.
02243     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
02244       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
02245         return R;
02246   }
02247 
02248   // add (cast *A to intptrtype) B -> 
02249   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
02250   {
02251     CastInst *CI = dyn_cast<CastInst>(LHS);
02252     Value *Other = RHS;
02253     if (!CI) {
02254       CI = dyn_cast<CastInst>(RHS);
02255       Other = LHS;
02256     }
02257     if (CI && CI->getType()->isSized() && 
02258         (CI->getType()->getPrimitiveSizeInBits() == 
02259          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
02260         && isa<PointerType>(CI->getOperand(0)->getType())) {
02261       unsigned AS =
02262         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
02263       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
02264                                       PointerType::get(Type::Int8Ty, AS), I);
02265       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
02266       return new PtrToIntInst(I2, CI->getType());
02267     }
02268   }
02269   
02270   // add (select X 0 (sub n A)) A  -->  select X A n
02271   {
02272     SelectInst *SI = dyn_cast<SelectInst>(LHS);
02273     Value *A = RHS;
02274     if (!SI) {
02275       SI = dyn_cast<SelectInst>(RHS);
02276       A = LHS;
02277     }
02278     if (SI && SI->hasOneUse()) {
02279       Value *TV = SI->getTrueValue();
02280       Value *FV = SI->getFalseValue();
02281       Value *N;
02282 
02283       // Can we fold the add into the argument of the select?
02284       // We check both true and false select arguments for a matching subtract.
02285       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
02286         // Fold the add into the true select value.
02287         return SelectInst::Create(SI->getCondition(), N, A);
02288       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
02289         // Fold the add into the false select value.
02290         return SelectInst::Create(SI->getCondition(), A, N);
02291     }
02292   }
02293   
02294   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
02295   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
02296     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
02297       return ReplaceInstUsesWith(I, LHS);
02298 
02299   // Check for (add (sext x), y), see if we can merge this into an
02300   // integer add followed by a sext.
02301   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
02302     // (add (sext x), cst) --> (sext (add x, cst'))
02303     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
02304       Constant *CI = 
02305         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
02306       if (LHSConv->hasOneUse() &&
02307           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
02308           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
02309         // Insert the new, smaller add.
02310         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
02311                                                         CI, "addconv");
02312         InsertNewInstBefore(NewAdd, I);
02313         return new SExtInst(NewAdd, I.getType());
02314       }
02315     }
02316     
02317     // (add (sext x), (sext y)) --> (sext (add int x, y))
02318     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
02319       // Only do this if x/y have the same type, if at last one of them has a
02320       // single use (so we don't increase the number of sexts), and if the
02321       // integer add will not overflow.
02322       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
02323           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
02324           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
02325                                    RHSConv->getOperand(0))) {
02326         // Insert the new integer add.
02327         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
02328                                                         RHSConv->getOperand(0),
02329                                                         "addconv");
02330         InsertNewInstBefore(NewAdd, I);
02331         return new SExtInst(NewAdd, I.getType());
02332       }
02333     }
02334   }
02335   
02336   // Check for (add double (sitofp x), y), see if we can merge this into an
02337   // integer add followed by a promotion.
02338   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
02339     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
02340     // ... if the constant fits in the integer value.  This is useful for things
02341     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
02342     // requires a constant pool load, and generally allows the add to be better
02343     // instcombined.
02344     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
02345       Constant *CI = 
02346       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
02347       if (LHSConv->hasOneUse() &&
02348           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
02349           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
02350         // Insert the new integer add.
02351         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
02352                                                         CI, "addconv");
02353         InsertNewInstBefore(NewAdd, I);
02354         return new SIToFPInst(NewAdd, I.getType());
02355       }
02356     }
02357     
02358     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
02359     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
02360       // Only do this if x/y have the same type, if at last one of them has a
02361       // single use (so we don't increase the number of int->fp conversions),
02362       // and if the integer add will not overflow.
02363       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
02364           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
02365           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
02366                                    RHSConv->getOperand(0))) {
02367         // Insert the new integer add.
02368         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
02369                                                         RHSConv->getOperand(0),
02370                                                         "addconv");
02371         InsertNewInstBefore(NewAdd, I);
02372         return new SIToFPInst(NewAdd, I.getType());
02373       }
02374     }
02375   }
02376   
02377   return Changed ? &I : 0;
02378 }
02379 
02380 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
02381   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02382 
02383   if (Op0 == Op1 &&                        // sub X, X  -> 0
02384       !I.getType()->isFPOrFPVector())
02385     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
02386 
02387   // If this is a 'B = x-(-A)', change to B = x+A...
02388   if (Value *V = dyn_castNegVal(Op1))
02389     return BinaryOperator::CreateAdd(Op0, V);
02390 
02391   if (isa<UndefValue>(Op0))
02392     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
02393   if (isa<UndefValue>(Op1))
02394     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
02395 
02396   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
02397     // Replace (-1 - A) with (~A)...
02398     if (C->isAllOnesValue())
02399       return BinaryOperator::CreateNot(Op1);
02400 
02401     // C - ~X == X + (1+C)
02402     Value *X = 0;
02403     if (match(Op1, m_Not(m_Value(X))))
02404       return BinaryOperator::CreateAdd(X, AddOne(C));
02405 
02406     // -(X >>u 31) -> (X >>s 31)
02407     // -(X >>s 31) -> (X >>u 31)
02408     if (C->isZero()) {
02409       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
02410         if (SI->getOpcode() == Instruction::LShr) {
02411           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
02412             // Check to see if we are shifting out everything but the sign bit.
02413             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
02414                 SI->getType()->getPrimitiveSizeInBits()-1) {
02415               // Ok, the transformation is safe.  Insert AShr.
02416               return BinaryOperator::Create(Instruction::AShr, 
02417                                           SI->getOperand(0), CU, SI->getName());
02418             }
02419           }
02420         }
02421         else if (SI->getOpcode() == Instruction::AShr) {
02422           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
02423             // Check to see if we are shifting out everything but the sign bit.
02424             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
02425                 SI->getType()->getPrimitiveSizeInBits()-1) {
02426               // Ok, the transformation is safe.  Insert LShr. 
02427               return BinaryOperator::CreateLShr(
02428                                           SI->getOperand(0), CU, SI->getName());
02429             }
02430           }
02431         }
02432       }
02433     }
02434 
02435     // Try to fold constant sub into select arguments.
02436     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
02437       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
02438         return R;
02439   }
02440 
02441   if (I.getType() == Type::Int1Ty)
02442     return BinaryOperator::CreateXor(Op0, Op1);
02443 
02444   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
02445     if (Op1I->getOpcode() == Instruction::Add &&
02446         !Op0->getType()->isFPOrFPVector()) {
02447       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
02448         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
02449       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
02450         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
02451       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
02452         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
02453           // C1-(X+C2) --> (C1-C2)-X
02454           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
02455                                            Op1I->getOperand(0));
02456       }
02457     }
02458 
02459     if (Op1I->hasOneUse()) {
02460       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
02461       // is not used by anyone else...
02462       //
02463       if (Op1I->getOpcode() == Instruction::Sub &&
02464           !Op1I->getType()->isFPOrFPVector()) {
02465         // Swap the two operands of the subexpr...
02466         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
02467         Op1I->setOperand(0, IIOp1);
02468         Op1I->setOperand(1, IIOp0);
02469 
02470         // Create the new top level add instruction...
02471         return BinaryOperator::CreateAdd(Op0, Op1);
02472       }
02473 
02474       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
02475       //
02476       if (Op1I->getOpcode() == Instruction::And &&
02477           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
02478         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
02479 
02480         Value *NewNot =
02481           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
02482         return BinaryOperator::CreateAnd(Op0, NewNot);
02483       }
02484 
02485       // 0 - (X sdiv C)  -> (X sdiv -C)
02486       if (Op1I->getOpcode() == Instruction::SDiv)
02487         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
02488           if (CSI->isZero())
02489             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
02490               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
02491                                                ConstantExpr::getNeg(DivRHS));
02492 
02493       // X - X*C --> X * (1-C)
02494       ConstantInt *C2 = 0;
02495       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
02496         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
02497         return BinaryOperator::CreateMul(Op0, CP1);
02498       }
02499     }
02500   }
02501 
02502   if (!Op0->getType()->isFPOrFPVector())
02503     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
02504       if (Op0I->getOpcode() == Instruction::Add) {
02505         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
02506           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
02507         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
02508           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
02509       } else if (Op0I->getOpcode() == Instruction::Sub) {
02510         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
02511           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
02512       }
02513     }
02514 
02515   ConstantInt *C1;
02516   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
02517     if (X == Op1)  // X*C - X --> X * (C-1)
02518       return BinaryOperator::CreateMul(Op1, SubOne(C1));
02519 
02520     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
02521     if (X == dyn_castFoldableMul(Op1, C2))
02522       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
02523   }
02524   return 0;
02525 }
02526 
02527 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
02528 /// comparison only checks the sign bit.  If it only checks the sign bit, set
02529 /// TrueIfSigned if the result of the comparison is true when the input value is
02530 /// signed.
02531 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
02532                            bool &TrueIfSigned) {
02533   switch (pred) {
02534   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
02535     TrueIfSigned = true;
02536     return RHS->isZero();
02537   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
02538     TrueIfSigned = true;
02539     return RHS->isAllOnesValue();
02540   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
02541     TrueIfSigned = false;
02542     return RHS->isAllOnesValue();
02543   case ICmpInst::ICMP_UGT:
02544     // True if LHS u> RHS and RHS == high-bit-mask - 1
02545     TrueIfSigned = true;
02546     return RHS->getValue() ==
02547       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
02548   case ICmpInst::ICMP_UGE: 
02549     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
02550     TrueIfSigned = true;
02551     return RHS->getValue().isSignBit();
02552   default:
02553     return false;
02554   }
02555 }
02556 
02557 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
02558   bool Changed = SimplifyCommutative(I);
02559   Value *Op0 = I.getOperand(0);
02560 
02561   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
02562     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
02563 
02564   // Simplify mul instructions with a constant RHS...
02565   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
02566     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02567 
02568       // ((X << C1)*C2) == (X * (C2 << C1))
02569       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
02570         if (SI->getOpcode() == Instruction::Shl)
02571           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
02572             return BinaryOperator::CreateMul(SI->getOperand(0),
02573                                              ConstantExpr::getShl(CI, ShOp));
02574 
02575       if (CI->isZero())
02576         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
02577       if (CI->equalsInt(1))                  // X * 1  == X
02578         return ReplaceInstUsesWith(I, Op0);
02579       if (CI->isAllOnesValue())              // X * -1 == 0 - X
02580         return BinaryOperator::CreateNeg(Op0, I.getName());
02581 
02582       const APInt& Val = cast<ConstantInt>(CI)->getValue();
02583       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
02584         return BinaryOperator::CreateShl(Op0,
02585                  ConstantInt::get(Op0->getType(), Val.logBase2()));
02586       }
02587     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
02588       if (Op1F->isNullValue())
02589         return ReplaceInstUsesWith(I, Op1);
02590 
02591       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
02592       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
02593       if (Op1F->isExactlyValue(1.0))
02594         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
02595     } else if (isa<VectorType>(Op1->getType())) {
02596       if (isa<ConstantAggregateZero>(Op1))
02597         return ReplaceInstUsesWith(I, Op1);
02598 
02599       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
02600         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
02601           return BinaryOperator::CreateNeg(Op0, I.getName());
02602 
02603         // As above, vector X*splat(1.0) -> X in all defined cases.
02604         if (Constant *Splat = Op1V->getSplatValue()) {
02605           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
02606             if (F->isExactlyValue(1.0))
02607               return ReplaceInstUsesWith(I, Op0);
02608           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
02609             if (CI->equalsInt(1))
02610               return ReplaceInstUsesWith(I, Op0);
02611         }
02612       }
02613     }
02614     
02615     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
02616       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
02617           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
02618         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
02619         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
02620                                                      Op1, "tmp");
02621         InsertNewInstBefore(Add, I);
02622         Value *C1C2 = ConstantExpr::getMul(Op1, 
02623                                            cast<Constant>(Op0I->getOperand(1)));
02624         return BinaryOperator::CreateAdd(Add, C1C2);
02625         
02626       }
02627 
02628     // Try to fold constant mul into select arguments.
02629     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02630       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
02631         return R;
02632 
02633     if (isa<PHINode>(Op0))
02634       if (Instruction *NV = FoldOpIntoPhi(I))
02635         return NV;
02636   }
02637 
02638   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
02639     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
02640       return BinaryOperator::CreateMul(Op0v, Op1v);
02641 
02642   // (X / Y) *  Y = X - (X % Y)
02643   // (X / Y) * -Y = (X % Y) - X
02644   {
02645     Value *Op1 = I.getOperand(1);
02646     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
02647     if (!BO ||
02648         (BO->getOpcode() != Instruction::UDiv && 
02649          BO->getOpcode() != Instruction::SDiv)) {
02650       Op1 = Op0;
02651       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
02652     }
02653     Value *Neg = dyn_castNegVal(Op1);
02654     if (BO && BO->hasOneUse() &&
02655         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
02656         (BO->getOpcode() == Instruction::UDiv ||
02657          BO->getOpcode() == Instruction::SDiv)) {
02658       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
02659 
02660       Instruction *Rem;
02661       if (BO->getOpcode() == Instruction::UDiv)
02662         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
02663       else
02664         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
02665 
02666       InsertNewInstBefore(Rem, I);
02667       Rem->takeName(BO);
02668 
02669       if (Op1BO == Op1)
02670         return BinaryOperator::CreateSub(Op0BO, Rem);
02671       else
02672         return BinaryOperator::CreateSub(Rem, Op0BO);
02673     }
02674   }
02675 
02676   if (I.getType() == Type::Int1Ty)
02677     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
02678 
02679   // If one of the operands of the multiply is a cast from a boolean value, then
02680   // we know the bool is either zero or one, so this is a 'masking' multiply.
02681   // See if we can simplify things based on how the boolean was originally
02682   // formed.
02683   CastInst *BoolCast = 0;
02684   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
02685     if (CI->getOperand(0)->getType() == Type::Int1Ty)
02686       BoolCast = CI;
02687   if (!BoolCast)
02688     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
02689       if (CI->getOperand(0)->getType() == Type::Int1Ty)
02690         BoolCast = CI;
02691   if (BoolCast) {
02692     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
02693       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
02694       const Type *SCOpTy = SCIOp0->getType();
02695       bool TIS = false;
02696       
02697       // If the icmp is true iff the sign bit of X is set, then convert this
02698       // multiply into a shift/and combination.
02699       if (isa<ConstantInt>(SCIOp1) &&
02700           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
02701           TIS) {
02702         // Shift the X value right to turn it into "all signbits".
02703         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
02704                                           SCOpTy->getPrimitiveSizeInBits()-1);
02705         Value *V =
02706           InsertNewInstBefore(
02707             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
02708                                             BoolCast->getOperand(0)->getName()+
02709                                             ".mask"), I);
02710 
02711         // If the multiply type is not the same as the source type, sign extend
02712         // or truncate to the multiply type.
02713         if (I.getType() != V->getType()) {
02714           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
02715           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
02716           Instruction::CastOps opcode = 
02717             (SrcBits == DstBits ? Instruction::BitCast : 
02718              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
02719           V = InsertCastBefore(opcode, V, I.getType(), I);
02720         }
02721 
02722         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
02723         return BinaryOperator::CreateAnd(V, OtherOp);
02724       }
02725     }
02726   }
02727 
02728   return Changed ? &I : 0;
02729 }
02730 
02731 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
02732 /// instruction.
02733 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
02734   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
02735   
02736   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
02737   int NonNullOperand = -1;
02738   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
02739     if (ST->isNullValue())
02740       NonNullOperand = 2;
02741   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
02742   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
02743     if (ST->isNullValue())
02744       NonNullOperand = 1;
02745   
02746   if (NonNullOperand == -1)
02747     return false;
02748   
02749   Value *SelectCond = SI->getOperand(0);
02750   
02751   // Change the div/rem to use 'Y' instead of the select.
02752   I.setOperand(1, SI->getOperand(NonNullOperand));
02753   
02754   // Okay, we know we replace the operand of the div/rem with 'Y' with no
02755   // problem.  However, the select, or the condition of the select may have
02756   // multiple uses.  Based on our knowledge that the operand must be non-zero,
02757   // propagate the known value for the select into other uses of it, and
02758   // propagate a known value of the condition into its other users.
02759   
02760   // If the select and condition only have a single use, don't bother with this,
02761   // early exit.
02762   if (SI->use_empty() && SelectCond->hasOneUse())
02763     return true;
02764   
02765   // Scan the current block backward, looking for other uses of SI.
02766   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
02767   
02768   while (BBI != BBFront) {
02769     --BBI;
02770     // If we found a call to a function, we can't assume it will return, so
02771     // information from below it cannot be propagated above it.
02772     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
02773       break;
02774     
02775     // Replace uses of the select or its condition with the known values.
02776     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
02777          I != E; ++I) {
02778       if (*I == SI) {
02779         *I = SI->getOperand(NonNullOperand);
02780         AddToWorkList(BBI);
02781       } else if (*I == SelectCond) {
02782         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
02783                                    ConstantInt::getFalse();
02784         AddToWorkList(BBI);
02785       }
02786     }
02787     
02788     // If we past the instruction, quit looking for it.
02789     if (&*BBI == SI)
02790       SI = 0;
02791     if (&*BBI == SelectCond)
02792       SelectCond = 0;
02793     
02794     // If we ran out of things to eliminate, break out of the loop.
02795     if (SelectCond == 0 && SI == 0)
02796       break;
02797     
02798   }
02799   return true;
02800 }
02801 
02802 
02803 /// This function implements the transforms on div instructions that work
02804 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
02805 /// used by the visitors to those instructions.
02806 /// @brief Transforms common to all three div instructions
02807 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
02808   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02809 
02810   // undef / X -> 0        for integer.
02811   // undef / X -> undef    for FP (the undef could be a snan).
02812   if (isa<UndefValue>(Op0)) {
02813     if (Op0->getType()->isFPOrFPVector())
02814       return ReplaceInstUsesWith(I, Op0);
02815     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
02816   }
02817 
02818   // X / undef -> undef
02819   if (isa<UndefValue>(Op1))
02820     return ReplaceInstUsesWith(I, Op1);
02821 
02822   return 0;
02823 }
02824 
02825 /// This function implements the transforms common to both integer division
02826 /// instructions (udiv and sdiv). It is called by the visitors to those integer
02827 /// division instructions.
02828 /// @brief Common integer divide transforms
02829 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
02830   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02831 
02832   // (sdiv X, X) --> 1     (udiv X, X) --> 1
02833   if (Op0 == Op1) {
02834     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
02835       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
02836       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
02837       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
02838     }
02839 
02840     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
02841     return ReplaceInstUsesWith(I, CI);
02842   }
02843   
02844   if (Instruction *Common = commonDivTransforms(I))
02845     return Common;
02846   
02847   // Handle cases involving: [su]div X, (select Cond, Y, Z)
02848   // This does not apply for fdiv.
02849   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
02850     return &I;
02851 
02852   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02853     // div X, 1 == X
02854     if (RHS->equalsInt(1))
02855       return ReplaceInstUsesWith(I, Op0);
02856 
02857     // (X / C1) / C2  -> X / (C1*C2)
02858     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
02859       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
02860         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
02861           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
02862             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
02863           else 
02864             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
02865                                           Multiply(RHS, LHSRHS));
02866         }
02867 
02868     if (!RHS->isZero()) { // avoid X udiv 0
02869       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02870         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
02871           return R;
02872       if (isa<PHINode>(Op0))
02873         if (Instruction *NV = FoldOpIntoPhi(I))
02874           return NV;
02875     }
02876   }
02877 
02878   // 0 / X == 0, we don't need to preserve faults!
02879   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
02880     if (LHS->equalsInt(0))
02881       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
02882 
02883   // It can't be division by zero, hence it must be division by one.
02884   if (I.getType() == Type::Int1Ty)
02885     return ReplaceInstUsesWith(I, Op0);
02886 
02887   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
02888     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
02889       // div X, 1 == X
02890       if (X->isOne())
02891         return ReplaceInstUsesWith(I, Op0);
02892   }
02893 
02894   return 0;
02895 }
02896 
02897 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
02898   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02899 
02900   // Handle the integer div common cases
02901   if (Instruction *Common = commonIDivTransforms(I))
02902     return Common;
02903 
02904   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
02905     // X udiv C^2 -> X >> C
02906     // Check to see if this is an unsigned division with an exact power of 2,
02907     // if so, convert to a right shift.
02908     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
02909       return BinaryOperator::CreateLShr(Op0, 
02910                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
02911 
02912     // X udiv C, where C >= signbit
02913     if (C->getValue().isNegative()) {
02914       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
02915                                       I);
02916       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
02917                                 ConstantInt::get(I.getType(), 1));
02918     }
02919   }
02920 
02921   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
02922   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
02923     if (RHSI->getOpcode() == Instruction::Shl &&
02924         isa<ConstantInt>(RHSI->getOperand(0))) {
02925       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
02926       if (C1.isPowerOf2()) {
02927         Value *N = RHSI->getOperand(1);
02928         const Type *NTy = N->getType();
02929         if (uint32_t C2 = C1.logBase2()) {
02930           Constant *C2V = ConstantInt::get(NTy, C2);
02931           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
02932         }
02933         return BinaryOperator::CreateLShr(Op0, N);
02934       }
02935     }
02936   }
02937   
02938   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
02939   // where C1&C2 are powers of two.
02940   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
02941     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
02942       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
02943         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
02944         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
02945           // Compute the shift amounts
02946           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
02947           // Construct the "on true" case of the select
02948           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
02949           Instruction *TSI = BinaryOperator::CreateLShr(
02950                                                  Op0, TC, SI->getName()+".t");
02951           TSI = InsertNewInstBefore(TSI, I);
02952   
02953           // Construct the "on false" case of the select
02954           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
02955           Instruction *FSI = BinaryOperator::CreateLShr(
02956                                                  Op0, FC, SI->getName()+".f");
02957           FSI = InsertNewInstBefore(FSI, I);
02958 
02959           // construct the select instruction and return it.
02960           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
02961         }
02962       }
02963   return 0;
02964 }
02965 
02966 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
02967   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02968 
02969   // Handle the integer div common cases
02970   if (Instruction *Common = commonIDivTransforms(I))
02971     return Common;
02972 
02973   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02974     // sdiv X, -1 == -X
02975     if (RHS->isAllOnesValue())
02976       return BinaryOperator::CreateNeg(Op0);
02977   }
02978 
02979   // If the sign bits of both operands are zero (i.e. we can prove they are
02980   // unsigned inputs), turn this into a udiv.
02981   if (I.getType()->isInteger()) {
02982     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
02983     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
02984       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
02985       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
02986     }
02987   }      
02988   
02989   return 0;
02990 }
02991 
02992 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
02993   return commonDivTransforms(I);
02994 }
02995 
02996 /// This function implements the transforms on rem instructions that work
02997 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
02998 /// is used by the visitors to those instructions.
02999 /// @brief Transforms common to all three rem instructions
03000 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
03001   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03002 
03003   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
03004     if (I.getType()->isFPOrFPVector())
03005       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
03006     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
03007   }
03008   if (isa<UndefValue>(Op1))
03009     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
03010 
03011   // Handle cases involving: rem X, (select Cond, Y, Z)
03012   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
03013     return &I;
03014 
03015   return 0;
03016 }
03017 
03018 /// This function implements the transforms common to both integer remainder
03019 /// instructions (urem and srem). It is called by the visitors to those integer
03020 /// remainder instructions.
03021 /// @brief Common integer remainder transforms
03022 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
03023   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03024 
03025   if (Instruction *common = commonRemTransforms(I))
03026     return common;
03027 
03028   // 0 % X == 0 for integer, we don't need to preserve faults!
03029   if (Constant *LHS = dyn_cast<Constant>(Op0))
03030     if (LHS->isNullValue())
03031       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
03032 
03033   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
03034     // X % 0 == undef, we don't need to preserve faults!
03035     if (RHS->equalsInt(0))
03036       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
03037     
03038     if (RHS->equalsInt(1))  // X % 1 == 0
03039       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
03040 
03041     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
03042       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
03043         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
03044           return R;
03045       } else if (isa<PHINode>(Op0I)) {
03046         if (Instruction *NV = FoldOpIntoPhi(I))
03047           return NV;
03048       }
03049 
03050       // See if we can fold away this rem instruction.
03051       if (SimplifyDemandedInstructionBits(I))
03052         return &I;
03053     }
03054   }
03055 
03056   return 0;
03057 }
03058 
03059 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
03060   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03061 
03062   if (Instruction *common = commonIRemTransforms(I))
03063     return common;
03064   
03065   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
03066     // X urem C^2 -> X and C
03067     // Check to see if this is an unsigned remainder with an exact power of 2,
03068     // if so, convert to a bitwise and.
03069     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
03070       if (C->getValue().isPowerOf2())
03071         return BinaryOperator::CreateAnd(Op0, SubOne(C));
03072   }
03073 
03074   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
03075     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
03076     if (RHSI->getOpcode() == Instruction::Shl &&
03077         isa<ConstantInt>(RHSI->getOperand(0))) {
03078       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
03079         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
03080         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
03081                                                                    "tmp"), I);
03082         return BinaryOperator::CreateAnd(Op0, Add);
03083       }
03084     }
03085   }
03086 
03087   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
03088   // where C1&C2 are powers of two.
03089   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
03090     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
03091       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
03092         // STO == 0 and SFO == 0 handled above.
03093         if ((STO->getValue().isPowerOf2()) && 
03094             (SFO->getValue().isPowerOf2())) {
03095           Value *TrueAnd = InsertNewInstBefore(
03096             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
03097           Value *FalseAnd = InsertNewInstBefore(
03098             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
03099           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
03100         }
03101       }
03102   }
03103   
03104   return 0;
03105 }
03106 
03107 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
03108   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03109 
03110   // Handle the integer rem common cases
03111   if (Instruction *common = commonIRemTransforms(I))
03112     return common;
03113   
03114   if (Value *RHSNeg = dyn_castNegVal(Op1))
03115     if (!isa<Constant>(RHSNeg) ||
03116         (isa<ConstantInt>(RHSNeg) &&
03117          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
03118       // X % -Y -> X % Y
03119       AddUsesToWorkList(I);
03120       I.setOperand(1, RHSNeg);
03121       return &I;
03122     }
03123 
03124   // If the sign bits of both operands are zero (i.e. we can prove they are
03125   // unsigned inputs), turn this into a urem.
03126   if (I.getType()->isInteger()) {
03127     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
03128     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
03129       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
03130       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
03131     }
03132   }
03133 
03134   // If it's a constant vector, flip any negative values positive.
03135   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
03136     unsigned VWidth = RHSV->getNumOperands();
03137 
03138     bool hasNegative = false;
03139     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
03140       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
03141         if (RHS->getValue().isNegative())
03142           hasNegative = true;
03143 
03144     if (hasNegative) {
03145       std::vector<Constant *> Elts(VWidth);
03146       for (unsigned i = 0; i != VWidth; ++i) {
03147         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
03148           if (RHS->getValue().isNegative())
03149             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
03150           else
03151             Elts[i] = RHS;
03152         }
03153       }
03154 
03155       Constant *NewRHSV = ConstantVector::get(Elts);
03156       if (NewRHSV != RHSV) {
03157         AddUsesToWorkList(I);
03158         I.setOperand(1, NewRHSV);
03159         return &I;
03160       }
03161     }
03162   }
03163 
03164   return 0;
03165 }
03166 
03167 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
03168   return commonRemTransforms(I);
03169 }
03170 
03171 // isOneBitSet - Return true if there is exactly one bit set in the specified
03172 // constant.
03173 static bool isOneBitSet(const ConstantInt *CI) {
03174   return CI->getValue().isPowerOf2();
03175 }
03176 
03177 // isHighOnes - Return true if the constant is of the form 1+0+.
03178 // This is the same as lowones(~X).
03179 static bool isHighOnes(const ConstantInt *CI) {
03180   return (~CI->getValue() + 1).isPowerOf2();
03181 }
03182 
03183 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
03184 /// are carefully arranged to allow folding of expressions such as:
03185 ///
03186 ///      (A < B) | (A > B) --> (A != B)
03187 ///
03188 /// Note that this is only valid if the first and second predicates have the
03189 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
03190 ///
03191 /// Three bits are used to represent the condition, as follows:
03192 ///   0  A > B
03193 ///   1  A == B
03194 ///   2  A < B
03195 ///
03196 /// <=>  Value  Definition
03197 /// 000     0   Always false
03198 /// 001     1   A >  B
03199 /// 010     2   A == B
03200 /// 011     3   A >= B
03201 /// 100     4   A <  B
03202 /// 101     5   A != B
03203 /// 110     6   A <= B
03204 /// 111     7   Always true
03205 ///  
03206 static unsigned getICmpCode(const ICmpInst *ICI) {
03207   switch (ICI->getPredicate()) {
03208     // False -> 0
03209   case ICmpInst::ICMP_UGT: return 1;  // 001
03210   case ICmpInst::ICMP_SGT: return 1;  // 001
03211   case ICmpInst::ICMP_EQ:  return 2;  // 010
03212   case ICmpInst::ICMP_UGE: return 3;  // 011
03213   case ICmpInst::ICMP_SGE: return 3;  // 011
03214   case ICmpInst::ICMP_ULT: return 4;  // 100
03215   case ICmpInst::ICMP_SLT: return 4;  // 100
03216   case ICmpInst::ICMP_NE:  return 5;  // 101
03217   case ICmpInst::ICMP_ULE: return 6;  // 110
03218   case ICmpInst::ICMP_SLE: return 6;  // 110
03219     // True -> 7
03220   default:
03221     assert(0 && "Invalid ICmp predicate!");
03222     return 0;
03223   }
03224 }
03225 
03226 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
03227 /// predicate into a three bit mask. It also returns whether it is an ordered
03228 /// predicate by reference.
03229 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
03230   isOrdered = false;
03231   switch (CC) {
03232   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
03233   case FCmpInst::FCMP_UNO:                   return 0;  // 000
03234   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
03235   case FCmpInst::FCMP_UGT:                   return 1;  // 001
03236   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
03237   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
03238   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
03239   case FCmpInst::FCMP_UGE:                   return 3;  // 011
03240   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
03241   case FCmpInst::FCMP_ULT:                   return 4;  // 100
03242   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
03243   case FCmpInst::FCMP_UNE:                   return 5;  // 101
03244   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
03245   case FCmpInst::FCMP_ULE:                   return 6;  // 110
03246     // True -> 7
03247   default:
03248     // Not expecting FCMP_FALSE and FCMP_TRUE;
03249     assert(0 && "Unexpected FCmp predicate!");
03250     return 0;
03251   }
03252 }
03253 
03254 /// getICmpValue - This is the complement of getICmpCode, which turns an
03255 /// opcode and two operands into either a constant true or false, or a brand 
03256 /// new ICmp instruction. The sign is passed in to determine which kind
03257 /// of predicate to use in the new icmp instruction.
03258 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
03259   switch (code) {
03260   default: assert(0 && "Illegal ICmp code!");
03261   case  0: return ConstantInt::getFalse();
03262   case  1: 
03263     if (sign)
03264       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
03265     else
03266       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
03267   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
03268   case  3: 
03269     if (sign)
03270       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
03271     else
03272       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
03273   case  4: 
03274     if (sign)
03275       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
03276     else
03277       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
03278   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
03279   case  6: 
03280     if (sign)
03281       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
03282     else
03283       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
03284   case  7: return ConstantInt::getTrue();
03285   }
03286 }
03287 
03288 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
03289 /// opcode and two operands into either a FCmp instruction. isordered is passed
03290 /// in to determine which kind of predicate to use in the new fcmp instruction.
03291 static Value *getFCmpValue(bool isordered, unsigned code,
03292                            Value *LHS, Value *RHS) {
03293   switch (code) {
03294   default: assert(0 && "Illegal FCmp code!");
03295   case  0:
03296     if (isordered)
03297       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
03298     else
03299       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
03300   case  1: 
03301     if (isordered)
03302       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
03303     else
03304       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
03305   case  2: 
03306     if (isordered)
03307       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
03308     else
03309       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
03310   case  3: 
03311     if (isordered)
03312       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
03313     else
03314       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
03315   case  4: 
03316     if (isordered)
03317       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
03318     else
03319       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
03320   case  5: 
03321     if (isordered)
03322       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
03323     else
03324       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
03325   case  6: 
03326     if (isordered)
03327       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
03328     else
03329       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
03330   case  7: return ConstantInt::getTrue();
03331   }
03332 }
03333 
03334 /// PredicatesFoldable - Return true if both predicates match sign or if at
03335 /// least one of them is an equality comparison (which is signless).
03336 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
03337   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
03338          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
03339          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
03340 }
03341 
03342 namespace { 
03343 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
03344 struct FoldICmpLogical {
03345   InstCombiner &IC;
03346   Value *LHS, *RHS;
03347   ICmpInst::Predicate pred;
03348   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
03349     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
03350       pred(ICI->getPredicate()) {}
03351   bool shouldApply(Value *V) const {
03352     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
03353       if (PredicatesFoldable(pred, ICI->getPredicate()))
03354         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
03355                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
03356     return false;
03357   }
03358   Instruction *apply(Instruction &Log) const {
03359     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
03360     if (ICI->getOperand(0) != LHS) {
03361       assert(ICI->getOperand(1) == LHS);
03362       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
03363     }
03364 
03365     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
03366     unsigned LHSCode = getICmpCode(ICI);
03367     unsigned RHSCode = getICmpCode(RHSICI);
03368     unsigned Code;
03369     switch (Log.getOpcode()) {
03370     case Instruction::And: Code = LHSCode & RHSCode; break;
03371     case Instruction::Or:  Code = LHSCode | RHSCode; break;
03372     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
03373     default: assert(0 && "Illegal logical opcode!"); return 0;
03374     }
03375 
03376     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
03377                     ICmpInst::isSignedPredicate(ICI->getPredicate());
03378       
03379     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
03380     if (Instruction *I = dyn_cast<Instruction>(RV))
03381       return I;
03382     // Otherwise, it's a constant boolean value...
03383     return IC.ReplaceInstUsesWith(Log, RV);
03384   }
03385 };
03386 } // end anonymous namespace
03387 
03388 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
03389 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
03390 // guaranteed to be a binary operator.
03391 Instruction *InstCombiner::OptAndOp(Instruction *Op,
03392                                     ConstantInt *OpRHS,
03393                                     ConstantInt *AndRHS,
03394                                     BinaryOperator &TheAnd) {
03395   Value *X = Op->getOperand(0);
03396   Constant *Together = 0;
03397   if (!Op->isShift())
03398     Together = And(AndRHS, OpRHS);
03399 
03400   switch (Op->getOpcode()) {
03401   case Instruction::Xor:
03402     if (Op->hasOneUse()) {
03403       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
03404       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
03405       InsertNewInstBefore(And, TheAnd);
03406       And->takeName(Op);
03407       return BinaryOperator::CreateXor(And, Together);
03408     }
03409     break;
03410   case Instruction::Or:
03411     if (Together == AndRHS) // (X | C) & C --> C
03412       return ReplaceInstUsesWith(TheAnd, AndRHS);
03413 
03414     if (Op->hasOneUse() && Together != OpRHS) {
03415       // (X | C1) & C2 --> (X | (C1&C2)) & C2
03416       Instruction *Or = BinaryOperator::CreateOr(X, Together);
03417       InsertNewInstBefore(Or, TheAnd);
03418       Or->takeName(Op);
03419       return BinaryOperator::CreateAnd(Or, AndRHS);
03420     }
03421     break;
03422   case Instruction::Add:
03423     if (Op->hasOneUse()) {
03424       // Adding a one to a single bit bit-field should be turned into an XOR
03425       // of the bit.  First thing to check is to see if this AND is with a
03426       // single bit constant.
03427       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
03428 
03429       // If there is only one bit set...
03430       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
03431         // Ok, at this point, we know that we are masking the result of the
03432         // ADD down to exactly one bit.  If the constant we are adding has
03433         // no bits set below this bit, then we can eliminate the ADD.
03434         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
03435 
03436         // Check to see if any bits below the one bit set in AndRHSV are set.
03437         if ((AddRHS & (AndRHSV-1)) == 0) {
03438           // If not, the only thing that can effect the output of the AND is
03439           // the bit specified by AndRHSV.  If that bit is set, the effect of
03440           // the XOR is to toggle the bit.  If it is clear, then the ADD has
03441           // no effect.
03442           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
03443             TheAnd.setOperand(0, X);
03444             return &TheAnd;
03445           } else {
03446             // Pull the XOR out of the AND.
03447             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
03448             InsertNewInstBefore(NewAnd, TheAnd);
03449             NewAnd->takeName(Op);
03450             return BinaryOperator::CreateXor(NewAnd, AndRHS);
03451           }
03452         }
03453       }
03454     }
03455     break;
03456 
03457   case Instruction::Shl: {
03458     // We know that the AND will not produce any of the bits shifted in, so if
03459     // the anded constant includes them, clear them now!
03460     //
03461     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
03462     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
03463     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
03464     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
03465 
03466     if (CI->getValue() == ShlMask) { 
03467     // Masking out bits that the shift already masks
03468       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
03469     } else if (CI != AndRHS) {                  // Reducing bits set in and.
03470       TheAnd.setOperand(1, CI);
03471       return &TheAnd;
03472     }
03473     break;
03474   }
03475   case Instruction::LShr:
03476   {
03477     // We know that the AND will not produce any of the bits shifted in, so if
03478     // the anded constant includes them, clear them now!  This only applies to
03479     // unsigned shifts, because a signed shr may bring in set bits!
03480     //
03481     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
03482     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
03483     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
03484     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
03485 
03486     if (CI->getValue() == ShrMask) {   
03487     // Masking out bits that the shift already masks.
03488       return ReplaceInstUsesWith(TheAnd, Op);
03489     } else if (CI != AndRHS) {
03490       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
03491       return &TheAnd;
03492     }
03493     break;
03494   }
03495   case Instruction::AShr:
03496     // Signed shr.
03497     // See if this is shifting in some sign extension, then masking it out
03498     // with an and.
03499     if (Op->hasOneUse()) {
03500       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
03501       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
03502       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
03503       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
03504       if (C == AndRHS) {          // Masking out bits shifted in.
03505         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
03506         // Make the argument unsigned.
03507         Value *ShVal = Op->getOperand(0);
03508         ShVal = InsertNewInstBefore(
03509             BinaryOperator::CreateLShr(ShVal, OpRHS, 
03510                                    Op->getName()), TheAnd);
03511         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
03512       }
03513     }
03514     break;
03515   }
03516   return 0;
03517 }
03518 
03519 
03520 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
03521 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
03522 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
03523 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
03524 /// insert new instructions.
03525 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
03526                                            bool isSigned, bool Inside, 
03527                                            Instruction &IB) {
03528   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
03529             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
03530          "Lo is not <= Hi in range emission code!");
03531     
03532   if (Inside) {
03533     if (Lo == Hi)  // Trivially false.
03534       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
03535 
03536     // V >= Min && V < Hi --> V < Hi
03537     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
03538       ICmpInst::Predicate pred = (isSigned ? 
03539         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
03540       return new ICmpInst(pred, V, Hi);
03541     }
03542 
03543     // Emit V-Lo <u Hi-Lo
03544     Constant *NegLo = ConstantExpr::getNeg(Lo);
03545     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
03546     InsertNewInstBefore(Add, IB);
03547     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
03548     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
03549   }
03550 
03551   if (Lo == Hi)  // Trivially true.
03552     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
03553 
03554   // V < Min || V >= Hi -> V > Hi-1
03555   Hi = SubOne(cast<ConstantInt>(Hi));
03556   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
03557     ICmpInst::Predicate pred = (isSigned ? 
03558         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
03559     return new ICmpInst(pred, V, Hi);
03560   }
03561 
03562   // Emit V-Lo >u Hi-1-Lo
03563   // Note that Hi has already had one subtracted from it, above.
03564   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
03565   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
03566   InsertNewInstBefore(Add, IB);
03567   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
03568   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
03569 }
03570 
03571 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
03572 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
03573 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
03574 // not, since all 1s are not contiguous.
03575 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
03576   const APInt& V = Val->getValue();
03577   uint32_t BitWidth = Val->getType()->getBitWidth();
03578   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
03579 
03580   // look for the first zero bit after the run of ones
03581   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
03582   // look for the first non-zero bit
03583   ME = V.getActiveBits(); 
03584   return true;
03585 }
03586 
03587 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
03588 /// where isSub determines whether the operator is a sub.  If we can fold one of
03589 /// the following xforms:
03590 /// 
03591 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
03592 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
03593 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
03594 ///
03595 /// return (A +/- B).
03596 ///
03597 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
03598                                         ConstantInt *Mask, bool isSub,
03599                                         Instruction &I) {
03600   Instruction *LHSI = dyn_cast<Instruction>(LHS);
03601   if (!LHSI || LHSI->getNumOperands() != 2 ||
03602       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
03603 
03604   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
03605 
03606   switch (LHSI->getOpcode()) {
03607   default: return 0;
03608   case Instruction::And:
03609     if (And(N, Mask) == Mask) {
03610       // If the AndRHS is a power of two minus one (0+1+), this is simple.
03611       if ((Mask->getValue().countLeadingZeros() + 
03612            Mask->getValue().countPopulation()) == 
03613           Mask->getValue().getBitWidth())
03614         break;
03615 
03616       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
03617       // part, we don't need any explicit masks to take them out of A.  If that
03618       // is all N is, ignore it.
03619       uint32_t MB = 0, ME = 0;
03620       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
03621         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
03622         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
03623         if (MaskedValueIsZero(RHS, Mask))
03624           break;
03625       }
03626     }
03627     return 0;
03628   case Instruction::Or:
03629   case Instruction::Xor:
03630     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
03631     if ((Mask->getValue().countLeadingZeros() + 
03632          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
03633         && And(N, Mask)->isZero())
03634       break;
03635     return 0;
03636   }
03637   
03638   Instruction *New;
03639   if (isSub)
03640     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
03641   else
03642     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
03643   return InsertNewInstBefore(New, I);
03644 }
03645 
03646 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
03647 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
03648                                           ICmpInst *LHS, ICmpInst *RHS) {
03649   Value *Val, *Val2;
03650   ConstantInt *LHSCst, *RHSCst;
03651   ICmpInst::Predicate LHSCC, RHSCC;
03652   
03653   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
03654   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
03655       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
03656     return 0;
03657   
03658   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
03659   // where C is a power of 2
03660   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
03661       LHSCst->getValue().isPowerOf2()) {
03662     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
03663     InsertNewInstBefore(NewOr, I);
03664     return new ICmpInst(LHSCC, NewOr, LHSCst);
03665   }
03666   
03667   // From here on, we only handle:
03668   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
03669   if (Val != Val2) return 0;
03670   
03671   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
03672   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
03673       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
03674       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
03675       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
03676     return 0;
03677   
03678   // We can't fold (ugt x, C) & (sgt x, C2).
03679   if (!PredicatesFoldable(LHSCC, RHSCC))
03680     return 0;
03681     
03682   // Ensure that the larger constant is on the RHS.
03683   bool ShouldSwap;
03684   if (ICmpInst::isSignedPredicate(LHSCC) ||
03685       (ICmpInst::isEquality(LHSCC) && 
03686        ICmpInst::isSignedPredicate(RHSCC)))
03687     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
03688   else
03689     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
03690     
03691   if (ShouldSwap) {
03692     std::swap(LHS, RHS);
03693     std::swap(LHSCst, RHSCst);
03694     std::swap(LHSCC, RHSCC);
03695   }
03696 
03697   // At this point, we know we have have two icmp instructions
03698   // comparing a value against two constants and and'ing the result
03699   // together.  Because of the above check, we know that we only have
03700   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
03701   // (from the FoldICmpLogical check above), that the two constants 
03702   // are not equal and that the larger constant is on the RHS
03703   assert(LHSCst != RHSCst && "Compares not folded above?");
03704 
03705   switch (LHSCC) {
03706   default: assert(0 && "Unknown integer condition code!");
03707   case ICmpInst::ICMP_EQ:
03708     switch (RHSCC) {
03709     default: assert(0 && "Unknown integer condition code!");
03710     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
03711     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
03712     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
03713       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
03714     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
03715     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
03716     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
03717       return ReplaceInstUsesWith(I, LHS);
03718     }
03719   case ICmpInst::ICMP_NE:
03720     switch (RHSCC) {
03721     default: assert(0 && "Unknown integer condition code!");
03722     case ICmpInst::ICMP_ULT:
03723       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
03724         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
03725       break;                        // (X != 13 & X u< 15) -> no change
03726     case ICmpInst::ICMP_SLT:
03727       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
03728         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
03729       break;                        // (X != 13 & X s< 15) -> no change
03730     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
03731     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
03732     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
03733       return ReplaceInstUsesWith(I, RHS);
03734     case ICmpInst::ICMP_NE:
03735       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
03736         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
03737         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
03738                                                      Val->getName()+".off");
03739         InsertNewInstBefore(Add, I);
03740         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
03741                             ConstantInt::get(Add->getType(), 1));
03742       }
03743       break;                        // (X != 13 & X != 15) -> no change
03744     }
03745     break;
03746   case ICmpInst::ICMP_ULT:
03747     switch (RHSCC) {
03748     default: assert(0 && "Unknown integer condition code!");
03749     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
03750     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
03751       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
03752     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
03753       break;
03754     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
03755     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
03756       return ReplaceInstUsesWith(I, LHS);
03757     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
03758       break;
03759     }
03760     break;
03761   case ICmpInst::ICMP_SLT:
03762     switch (RHSCC) {
03763     default: assert(0 && "Unknown integer condition code!");
03764     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
03765     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
03766       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
03767     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
03768       break;
03769     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
03770     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
03771       return ReplaceInstUsesWith(I, LHS);
03772     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
03773       break;
03774     }
03775     break;
03776   case ICmpInst::ICMP_UGT:
03777     switch (RHSCC) {
03778     default: assert(0 && "Unknown integer condition code!");
03779     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
03780     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
03781       return ReplaceInstUsesWith(I, RHS);
03782     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
03783       break;
03784     case ICmpInst::ICMP_NE:
03785       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
03786         return new ICmpInst(LHSCC, Val, RHSCst);
03787       break;                        // (X u> 13 & X != 15) -> no change
03788     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
03789       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
03790     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
03791       break;
03792     }
03793     break;
03794   case ICmpInst::ICMP_SGT:
03795     switch (RHSCC) {
03796     default: assert(0 && "Unknown integer condition code!");
03797     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
03798     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
03799       return ReplaceInstUsesWith(I, RHS);
03800     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
03801       break;
03802     case ICmpInst::ICMP_NE:
03803       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
03804         return new ICmpInst(LHSCC, Val, RHSCst);
03805       break;                        // (X s> 13 & X != 15) -> no change
03806     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
03807       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
03808     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
03809       break;
03810     }
03811     break;
03812   }
03813  
03814   return 0;
03815 }
03816 
03817 
03818 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
03819   bool Changed = SimplifyCommutative(I);
03820   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03821 
03822   if (isa<UndefValue>(Op1))                         // X & undef -> 0
03823     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
03824 
03825   // and X, X = X
03826   if (Op0 == Op1)
03827     return ReplaceInstUsesWith(I, Op1);
03828 
03829   // See if we can simplify any instructions used by the instruction whose sole 
03830   // purpose is to compute bits we don't care about.
03831   if (!isa<VectorType>(I.getType())) {
03832     if (SimplifyDemandedInstructionBits(I))
03833       return &I;
03834   } else {
03835     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
03836       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
03837         return ReplaceInstUsesWith(I, I.getOperand(0));
03838     } else if (isa<ConstantAggregateZero>(Op1)) {
03839       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
03840     }
03841   }
03842   
03843   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
03844     const APInt& AndRHSMask = AndRHS->getValue();
03845     APInt NotAndRHS(~AndRHSMask);
03846 
03847     // Optimize a variety of ((val OP C1) & C2) combinations...
03848     if (isa<BinaryOperator>(Op0)) {
03849       Instruction *Op0I = cast<Instruction>(Op0);
03850       Value *Op0LHS = Op0I->getOperand(0);
03851       Value *Op0RHS = Op0I->getOperand(1);
03852       switch (Op0I->getOpcode()) {
03853       case Instruction::Xor:
03854       case Instruction::Or:
03855         // If the mask is only needed on one incoming arm, push it up.
03856         if (Op0I->hasOneUse()) {
03857           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
03858             // Not masking anything out for the LHS, move to RHS.
03859             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
03860                                                    Op0RHS->getName()+".masked");
03861             InsertNewInstBefore(NewRHS, I);
03862             return BinaryOperator::Create(
03863                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
03864           }
03865           if (!isa<Constant>(Op0RHS) &&
03866               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
03867             // Not masking anything out for the RHS, move to LHS.
03868             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
03869                                                    Op0LHS->getName()+".masked");
03870             InsertNewInstBefore(NewLHS, I);
03871             return BinaryOperator::Create(
03872                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
03873           }
03874         }
03875 
03876         break;
03877       case Instruction::Add:
03878         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
03879         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
03880         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
03881         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
03882           return BinaryOperator::CreateAnd(V, AndRHS);
03883         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
03884           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
03885         break;
03886 
03887       case Instruction::Sub:
03888         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
03889         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
03890         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
03891         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
03892           return BinaryOperator::CreateAnd(V, AndRHS);
03893 
03894         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
03895         // has 1's for all bits that the subtraction with A might affect.
03896         if (Op0I->hasOneUse()) {
03897           uint32_t BitWidth = AndRHSMask.getBitWidth();
03898           uint32_t Zeros = AndRHSMask.countLeadingZeros();
03899           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
03900 
03901           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
03902           if (!(A && A->isZero()) &&               // avoid infinite recursion.
03903               MaskedValueIsZero(Op0LHS, Mask)) {
03904             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
03905             InsertNewInstBefore(NewNeg, I);
03906             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
03907           }
03908         }
03909         break;
03910 
03911       case Instruction::Shl:
03912       case Instruction::LShr:
03913         // (1 << x) & 1 --> zext(x == 0)
03914         // (1 >> x) & 1 --> zext(x == 0)
03915         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
03916           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
03917                                            Constant::getNullValue(I.getType()));
03918           InsertNewInstBefore(NewICmp, I);
03919           return new ZExtInst(NewICmp, I.getType());
03920         }
03921         break;
03922       }
03923 
03924       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
03925         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
03926           return Res;
03927     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
03928       // If this is an integer truncation or change from signed-to-unsigned, and
03929       // if the source is an and/or with immediate, transform it.  This
03930       // frequently occurs for bitfield accesses.
03931       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
03932         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
03933             CastOp->getNumOperands() == 2)
03934           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
03935             if (CastOp->getOpcode() == Instruction::And) {
03936               // Change: and (cast (and X, C1) to T), C2
03937               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
03938               // This will fold the two constants together, which may allow 
03939               // other simplifications.
03940               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
03941                 CastOp->getOperand(0), I.getType(), 
03942                 CastOp->getName()+".shrunk");
03943               NewCast = InsertNewInstBefore(NewCast, I);
03944               // trunc_or_bitcast(C1)&C2
03945               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
03946               C3 = ConstantExpr::getAnd(C3, AndRHS);
03947               return BinaryOperator::CreateAnd(NewCast, C3);
03948             } else if (CastOp->getOpcode() == Instruction::Or) {
03949               // Change: and (cast (or X, C1) to T), C2
03950               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
03951               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
03952               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
03953                 return ReplaceInstUsesWith(I, AndRHS);
03954             }
03955           }
03956       }
03957     }
03958 
03959     // Try to fold constant and into select arguments.
03960     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
03961       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
03962         return R;
03963     if (isa<PHINode>(Op0))
03964       if (Instruction *NV = FoldOpIntoPhi(I))
03965         return NV;
03966   }
03967 
03968   Value *Op0NotVal = dyn_castNotVal(Op0);
03969   Value *Op1NotVal = dyn_castNotVal(Op1);
03970 
03971   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
03972     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
03973 
03974   // (~A & ~B) == (~(A | B)) - De Morgan's Law
03975   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
03976     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
03977                                                I.getName()+".demorgan");
03978     InsertNewInstBefore(Or, I);
03979     return BinaryOperator::CreateNot(Or);
03980   }
03981   
03982   {
03983     Value *A = 0, *B = 0, *C = 0, *D = 0;
03984     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
03985       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
03986         return ReplaceInstUsesWith(I, Op1);
03987     
03988       // (A|B) & ~(A&B) -> A^B
03989       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
03990         if ((A == C && B == D) || (A == D && B == C))
03991           return BinaryOperator::CreateXor(A, B);
03992       }
03993     }
03994     
03995     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
03996       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
03997         return ReplaceInstUsesWith(I, Op0);
03998 
03999       // ~(A&B) & (A|B) -> A^B
04000       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
04001         if ((A == C && B == D) || (A == D && B == C))
04002           return BinaryOperator::CreateXor(A, B);
04003       }
04004     }
04005     
04006     if (Op0->hasOneUse() &&
04007         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
04008       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
04009         I.swapOperands();     // Simplify below
04010         std::swap(Op0, Op1);
04011       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
04012         cast<BinaryOperator>(Op0)->swapOperands();
04013         I.swapOperands();     // Simplify below
04014         std::swap(Op0, Op1);
04015       }
04016     }
04017 
04018     if (Op1->hasOneUse() &&
04019         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
04020       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
04021         cast<BinaryOperator>(Op1)->swapOperands();
04022         std::swap(A, B);
04023       }
04024       if (A == Op0) {                                // A&(A^B) -> A & ~B
04025         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
04026         InsertNewInstBefore(NotB, I);
04027         return BinaryOperator::CreateAnd(A, NotB);
04028       }
04029     }
04030 
04031     // (A&((~A)|B)) -> A&B
04032     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
04033         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
04034       return BinaryOperator::CreateAnd(A, Op1);
04035     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
04036         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
04037       return BinaryOperator::CreateAnd(A, Op0);
04038   }
04039   
04040   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
04041     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
04042     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
04043       return R;
04044 
04045     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
04046       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
04047         return Res;
04048   }
04049 
04050   // fold (and (cast A), (cast B)) -> (cast (and A, B))
04051   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
04052     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
04053       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
04054         const Type *SrcTy = Op0C->getOperand(0)->getType();
04055         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
04056             // Only do this if the casts both really cause code to be generated.
04057             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
04058                               I.getType(), TD) &&
04059             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
04060                               I.getType(), TD)) {
04061           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
04062                                                          Op1C->getOperand(0),
04063                                                          I.getName());
04064           InsertNewInstBefore(NewOp, I);
04065           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
04066         }
04067       }
04068     
04069   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
04070   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
04071     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
04072       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
04073           SI0->getOperand(1) == SI1->getOperand(1) &&
04074           (SI0->hasOneUse() || SI1->hasOneUse())) {
04075         Instruction *NewOp =
04076           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
04077                                                         SI1->getOperand(0),
04078                                                         SI0->getName()), I);
04079         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
04080                                       SI1->getOperand(1));
04081       }
04082   }
04083 
04084   // If and'ing two fcmp, try combine them into one.
04085   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
04086     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
04087       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
04088           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
04089         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
04090         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
04091           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
04092             // If either of the constants are nans, then the whole thing returns
04093             // false.
04094             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
04095               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
04096             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
04097                                 RHS->getOperand(0));
04098           }
04099       } else {
04100         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
04101         FCmpInst::Predicate Op0CC, Op1CC;
04102         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
04103             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
04104           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
04105             // Swap RHS operands to match LHS.
04106             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
04107             std::swap(Op1LHS, Op1RHS);
04108           }
04109           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
04110             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
04111             if (Op0CC == Op1CC)
04112               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
04113             else if (Op0CC == FCmpInst::FCMP_FALSE ||
04114                      Op1CC == FCmpInst::FCMP_FALSE)
04115               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
04116             else if (Op0CC == FCmpInst::FCMP_TRUE)
04117               return ReplaceInstUsesWith(I, Op1);
04118             else if (Op1CC == FCmpInst::FCMP_TRUE)
04119               return ReplaceInstUsesWith(I, Op0);
04120             bool Op0Ordered;
04121             bool Op1Ordered;
04122             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
04123             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
04124             if (Op1Pred == 0) {
04125               std::swap(Op0, Op1);
04126               std::swap(Op0Pred, Op1Pred);
04127               std::swap(Op0Ordered, Op1Ordered);
04128             }
04129             if (Op0Pred == 0) {
04130               // uno && ueq -> uno && (uno || eq) -> ueq
04131               // ord && olt -> ord && (ord && lt) -> olt
04132               if (Op0Ordered == Op1Ordered)
04133                 return ReplaceInstUsesWith(I, Op1);
04134               // uno && oeq -> uno && (ord && eq) -> false
04135               // uno && ord -> false
04136               if (!Op0Ordered)
04137                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
04138               // ord && ueq -> ord && (uno || eq) -> oeq
04139               return cast<Instruction>(getFCmpValue(true, Op1Pred,
04140                                                     Op0LHS, Op0RHS));
04141             }
04142           }
04143         }
04144       }
04145     }
04146   }
04147 
04148   return Changed ? &I : 0;
04149 }
04150 
04151 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
04152 /// capable of providing pieces of a bswap.  The subexpression provides pieces
04153 /// of a bswap if it is proven that each of the non-zero bytes in the output of
04154 /// the expression came from the corresponding "byte swapped" byte in some other
04155 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
04156 /// we know that the expression deposits the low byte of %X into the high byte
04157 /// of the bswap result and that all other bytes are zero.  This expression is
04158 /// accepted, the high byte of ByteValues is set to X to indicate a correct
04159 /// match.
04160 ///
04161 /// This function returns true if the match was unsuccessful and false if so.
04162 /// On entry to the function the "OverallLeftShift" is a signed integer value
04163 /// indicating the number of bytes that the subexpression is later shifted.  For
04164 /// example, if the expression is later right shifted by 16 bits, the
04165 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
04166 /// byte of ByteValues is actually being set.
04167 ///
04168 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
04169 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
04170 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
04171 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
04172 /// always in the local (OverallLeftShift) coordinate space.
04173 ///
04174 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
04175                               SmallVector<Value*, 8> &ByteValues) {
04176   if (Instruction *I = dyn_cast<Instruction>(V)) {
04177     // If this is an or instruction, it may be an inner node of the bswap.
04178     if (I->getOpcode() == Instruction::Or) {
04179       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
04180                                ByteValues) ||
04181              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
04182                                ByteValues);
04183     }
04184   
04185     // If this is a logical shift by a constant multiple of 8, recurse with
04186     // OverallLeftShift and ByteMask adjusted.
04187     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
04188       unsigned ShAmt = 
04189         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
04190       // Ensure the shift amount is defined and of a byte value.
04191       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
04192         return true;
04193 
04194       unsigned ByteShift = ShAmt >> 3;
04195       if (I->getOpcode() == Instruction::Shl) {
04196         // X << 2 -> collect(X, +2)
04197         OverallLeftShift += ByteShift;
04198         ByteMask >>= ByteShift;
04199       } else {
04200         // X >>u 2 -> collect(X, -2)
04201         OverallLeftShift -= ByteShift;
04202         ByteMask <<= ByteShift;
04203         ByteMask &= (~0U >> (32-ByteValues.size()));
04204       }
04205 
04206       if (OverallLeftShift >= (int)ByteValues.size()) return true;
04207       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
04208 
04209       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
04210                                ByteValues);
04211     }
04212 
04213     // If this is a logical 'and' with a mask that clears bytes, clear the
04214     // corresponding bytes in ByteMask.
04215     if (I->getOpcode() == Instruction::And &&
04216         isa<ConstantInt>(I->getOperand(1))) {
04217       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
04218       unsigned NumBytes = ByteValues.size();
04219       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
04220       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
04221       
04222       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
04223         // If this byte is masked out by a later operation, we don't care what
04224         // the and mask is.
04225         if ((ByteMask & (1 << i)) == 0)
04226           continue;
04227         
04228         // If the AndMask is all zeros for this byte, clear the bit.
04229         APInt MaskB = AndMask & Byte;
04230         if (MaskB == 0) {
04231           ByteMask &= ~(1U << i);
04232           continue;
04233         }
04234         
04235         // If the AndMask is not all ones for this byte, it's not a bytezap.
04236         if (MaskB != Byte)
04237           return true;
04238 
04239         // Otherwise, this byte is kept.
04240       }
04241 
04242       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
04243                                ByteValues);
04244     }
04245   }
04246   
04247   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
04248   // the input value to the bswap.  Some observations: 1) if more than one byte
04249   // is demanded from this input, then it could not be successfully assembled
04250   // into a byteswap.  At least one of the two bytes would not be aligned with
04251   // their ultimate destination.
04252   if (!isPowerOf2_32(ByteMask)) return true;
04253   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
04254   
04255   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
04256   // is demanded, it needs to go into byte 0 of the result.  This means that the
04257   // byte needs to be shifted until it lands in the right byte bucket.  The
04258   // shift amount depends on the position: if the byte is coming from the high
04259   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
04260   // low part, it must be shifted left.
04261   unsigned DestByteNo = InputByteNo + OverallLeftShift;
04262   if (InputByteNo < ByteValues.size()/2) {
04263     if (ByteValues.size()-1-DestByteNo != InputByteNo)
04264       return true;
04265   } else {
04266     if (ByteValues.size()-1-DestByteNo != InputByteNo)
04267       return true;
04268   }
04269   
04270   // If the destination byte value is already defined, the values are or'd
04271   // together, which isn't a bswap (unless it's an or of the same bits).
04272   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
04273     return true;
04274   ByteValues[DestByteNo] = V;
04275   return false;
04276 }
04277 
04278 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
04279 /// If so, insert the new bswap intrinsic and return it.
04280 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
04281   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
04282   if (!ITy || ITy->getBitWidth() % 16 || 
04283       // ByteMask only allows up to 32-byte values.
04284       ITy->getBitWidth() > 32*8) 
04285     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
04286   
04287   /// ByteValues - For each byte of the result, we keep track of which value
04288   /// defines each byte.
04289   SmallVector<Value*, 8> ByteValues;
04290   ByteValues.resize(ITy->getBitWidth()/8);
04291     
04292   // Try to find all the pieces corresponding to the bswap.
04293   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
04294   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
04295     return 0;
04296   
04297   // Check to see if all of the bytes come from the same value.
04298   Value *V = ByteValues[0];
04299   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
04300   
04301   // Check to make sure that all of the bytes come from the same value.
04302   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
04303     if (ByteValues[i] != V)
04304       return 0;
04305   const Type *Tys[] = { ITy };
04306   Module *M = I.getParent()->getParent()->getParent();
04307   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
04308   return CallInst::Create(F, V);
04309 }
04310 
04311 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
04312 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
04313 /// we can simplify this expression to "cond ? C : D or B".
04314 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
04315                                          Value *C, Value *D) {
04316   // If A is not a select of -1/0, this cannot match.
04317   Value *Cond = 0;
04318   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
04319     return 0;
04320 
04321   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
04322   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
04323     return SelectInst::Create(Cond, C, B);
04324   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
04325     return SelectInst::Create(Cond, C, B);
04326   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
04327   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
04328     return SelectInst::Create(Cond, C, D);
04329   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
04330     return SelectInst::Create(Cond, C, D);
04331   return 0;
04332 }
04333 
04334 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
04335 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
04336                                          ICmpInst *LHS, ICmpInst *RHS) {
04337   Value *Val, *Val2;
04338   ConstantInt *LHSCst, *RHSCst;
04339   ICmpInst::Predicate LHSCC, RHSCC;
04340   
04341   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
04342   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
04343       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
04344     return 0;
04345   
04346   // From here on, we only handle:
04347   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
04348   if (Val != Val2) return 0;
04349   
04350   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
04351   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
04352       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
04353       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
04354       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
04355     return 0;
04356   
04357   // We can't fold (ugt x, C) | (sgt x, C2).
04358   if (!PredicatesFoldable(LHSCC, RHSCC))
04359     return 0;
04360   
04361   // Ensure that the larger constant is on the RHS.
04362   bool ShouldSwap;
04363   if (ICmpInst::isSignedPredicate(LHSCC) ||
04364       (ICmpInst::isEquality(LHSCC) && 
04365        ICmpInst::isSignedPredicate(RHSCC)))
04366     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
04367   else
04368     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
04369   
04370   if (ShouldSwap) {
04371     std::swap(LHS, RHS);
04372     std::swap(LHSCst, RHSCst);
04373     std::swap(LHSCC, RHSCC);
04374   }
04375   
04376   // At this point, we know we have have two icmp instructions
04377   // comparing a value against two constants and or'ing the result
04378   // together.  Because of the above check, we know that we only have
04379   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
04380   // FoldICmpLogical check above), that the two constants are not
04381   // equal.
04382   assert(LHSCst != RHSCst && "Compares not folded above?");
04383 
04384   switch (LHSCC) {
04385   default: assert(0 && "Unknown integer condition code!");
04386   case ICmpInst::ICMP_EQ:
04387     switch (RHSCC) {
04388     default: assert(0 && "Unknown integer condition code!");
04389     case ICmpInst::ICMP_EQ:
04390       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
04391         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
04392         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
04393                                                      Val->getName()+".off");
04394         InsertNewInstBefore(Add, I);
04395         AddCST = Subtract(AddOne(RHSCst), LHSCst);
04396         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
04397       }
04398       break;                         // (X == 13 | X == 15) -> no change
04399     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
04400     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
04401       break;
04402     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
04403     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
04404     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
04405       return ReplaceInstUsesWith(I, RHS);
04406     }
04407     break;
04408   case ICmpInst::ICMP_NE:
04409     switch (RHSCC) {
04410     default: assert(0 && "Unknown integer condition code!");
04411     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
04412     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
04413     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
04414       return ReplaceInstUsesWith(I, LHS);
04415     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
04416     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
04417     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
04418       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
04419     }
04420     break;
04421   case ICmpInst::ICMP_ULT:
04422     switch (RHSCC) {
04423     default: assert(0 && "Unknown integer condition code!");
04424     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
04425       break;
04426     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
04427       // If RHSCst is [us]MAXINT, it is always false.  Not handling
04428       // this can cause overflow.
04429       if (RHSCst->isMaxValue(false))
04430         return ReplaceInstUsesWith(I, LHS);
04431       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
04432     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
04433       break;
04434     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
04435     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
04436       return ReplaceInstUsesWith(I, RHS);
04437     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
04438       break;
04439     }
04440     break;
04441   case ICmpInst::ICMP_SLT:
04442     switch (RHSCC) {
04443     default: assert(0 && "Unknown integer condition code!");
04444     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
04445       break;
04446     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
04447       // If RHSCst is [us]MAXINT, it is always false.  Not handling
04448       // this can cause overflow.
04449       if (RHSCst->isMaxValue(true))
04450         return ReplaceInstUsesWith(I, LHS);
04451       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
04452     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
04453       break;
04454     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
04455     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
04456       return ReplaceInstUsesWith(I, RHS);
04457     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
04458       break;
04459     }
04460     break;
04461   case ICmpInst::ICMP_UGT:
04462     switch (RHSCC) {
04463     default: assert(0 && "Unknown integer condition code!");
04464     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
04465     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
04466       return ReplaceInstUsesWith(I, LHS);
04467     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
04468       break;
04469     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
04470     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
04471       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
04472     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
04473       break;
04474     }
04475     break;
04476   case ICmpInst::ICMP_SGT:
04477     switch (RHSCC) {
04478     default: assert(0 && "Unknown integer condition code!");
04479     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
04480     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
04481       return ReplaceInstUsesWith(I, LHS);
04482     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
04483       break;
04484     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
04485     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
04486       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
04487     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
04488       break;
04489     }
04490     break;
04491   }
04492   return 0;
04493 }
04494 
04495 /// FoldOrWithConstants - This helper function folds:
04496 ///
04497 ///     ((A | B) & C1) | (B & C2)
04498 ///
04499 /// into:
04500 /// 
04501 ///     (A & C1) | B
04502 ///
04503 /// when the XOR of the two constants is "all ones" (-1).
04504 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
04505                                                Value *A, Value *B, Value *C) {
04506   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
04507   if (!CI1) return 0;
04508 
04509   Value *V1 = 0;
04510   ConstantInt *CI2 = 0;
04511   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
04512 
04513   APInt Xor = CI1->getValue() ^ CI2->getValue();
04514   if (!Xor.isAllOnesValue()) return 0;
04515 
04516   if (V1 == A || V1 == B) {
04517     Instruction *NewOp =
04518       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
04519     return BinaryOperator::CreateOr(NewOp, V1);
04520   }
04521 
04522   return 0;
04523 }
04524 
04525 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
04526   bool Changed = SimplifyCommutative(I);
04527   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
04528 
04529   if (isa<UndefValue>(Op1))                       // X | undef -> -1
04530     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
04531 
04532   // or X, X = X
04533   if (Op0 == Op1)
04534     return ReplaceInstUsesWith(I, Op0);
04535 
04536   // See if we can simplify any instructions used by the instruction whose sole 
04537   // purpose is to compute bits we don't care about.
04538   if (!isa<VectorType>(I.getType())) {
04539     if (SimplifyDemandedInstructionBits(I))
04540       return &I;
04541   } else if (isa<ConstantAggregateZero>(Op1)) {
04542     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
04543   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
04544     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
04545       return ReplaceInstUsesWith(I, I.getOperand(1));
04546   }
04547     
04548 
04549   
04550   // or X, -1 == -1
04551   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
04552     ConstantInt *C1 = 0; Value *X = 0;
04553     // (X & C1) | C2 --> (X | C2) & (C1|C2)
04554     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
04555       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
04556       InsertNewInstBefore(Or, I);
04557       Or->takeName(Op0);
04558       return BinaryOperator::CreateAnd(Or, 
04559                ConstantInt::get(RHS->getValue() | C1->getValue()));
04560     }
04561 
04562     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
04563     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
04564       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
04565       InsertNewInstBefore(Or, I);
04566       Or->takeName(Op0);
04567       return BinaryOperator::CreateXor(Or,
04568                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
04569     }
04570 
04571     // Try to fold constant and into select arguments.
04572     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
04573       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
04574         return R;
04575     if (isa<PHINode>(Op0))
04576       if (Instruction *NV = FoldOpIntoPhi(I))
04577         return NV;
04578   }
04579 
04580   Value *A = 0, *B = 0;
04581   ConstantInt *C1 = 0, *C2 = 0;
04582 
04583   if (match(Op0, m_And(m_Value(A), m_Value(B))))
04584     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
04585       return ReplaceInstUsesWith(I, Op1);
04586   if (match(Op1, m_And(m_Value(A), m_Value(B))))
04587     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
04588       return ReplaceInstUsesWith(I, Op0);
04589 
04590   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
04591   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
04592   if (match(Op0, m_Or(m_Value(), m_Value())) ||
04593       match(Op1, m_Or(m_Value(), m_Value())) ||
04594       (match(Op0, m_Shift(m_Value(), m_Value())) &&
04595        match(Op1, m_Shift(m_Value(), m_Value())))) {
04596     if (Instruction *BSwap = MatchBSwap(I))
04597       return BSwap;
04598   }
04599   
04600   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
04601   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
04602       MaskedValueIsZero(Op1, C1->getValue())) {
04603     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
04604     InsertNewInstBefore(NOr, I);
04605     NOr->takeName(Op0);
04606     return BinaryOperator::CreateXor(NOr, C1);
04607   }
04608 
04609   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
04610   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
04611       MaskedValueIsZero(Op0, C1->getValue())) {
04612     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
04613     InsertNewInstBefore(NOr, I);
04614     NOr->takeName(Op0);
04615     return BinaryOperator::CreateXor(NOr, C1);
04616   }
04617 
04618   // (A & C)|(B & D)
04619   Value *C = 0, *D = 0;
04620   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
04621       match(Op1, m_And(m_Value(B), m_Value(D)))) {
04622     Value *V1 = 0, *V2 = 0, *V3 = 0;
04623     C1 = dyn_cast<ConstantInt>(C);
04624     C2 = dyn_cast<ConstantInt>(D);
04625     if (C1 && C2) {  // (A & C1)|(B & C2)
04626       // If we have: ((V + N) & C1) | (V & C2)
04627       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
04628       // replace with V+N.
04629       if (C1->getValue() == ~C2->getValue()) {
04630         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
04631             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
04632           // Add commutes, try both ways.
04633           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
04634             return ReplaceInstUsesWith(I, A);
04635           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
04636             return ReplaceInstUsesWith(I, A);
04637         }
04638         // Or commutes, try both ways.
04639         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
04640             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
04641           // Add commutes, try both ways.
04642           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
04643             return ReplaceInstUsesWith(I, B);
04644           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
04645             return ReplaceInstUsesWith(I, B);
04646         }
04647       }
04648       V1 = 0; V2 = 0; V3 = 0;
04649     }
04650     
04651     // Check to see if we have any common things being and'ed.  If so, find the
04652     // terms for V1 & (V2|V3).
04653     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
04654       if (A == B)      // (A & C)|(A & D) == A & (C|D)
04655         V1 = A, V2 = C, V3 = D;
04656       else if (A == D) // (A & C)|(B & A) == A & (B|C)
04657         V1 = A, V2 = B, V3 = C;
04658       else if (C == B) // (A & C)|(C & D) == C & (A|D)
04659         V1 = C, V2 = A, V3 = D;
04660       else if (C == D) // (A & C)|(B & C) == C & (A|B)
04661         V1 = C, V2 = A, V3 = B;
04662       
04663       if (V1) {
04664         Value *Or =
04665           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
04666         return BinaryOperator::CreateAnd(V1, Or);
04667       }
04668     }
04669 
04670     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
04671     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
04672       return Match;
04673     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
04674       return Match;
04675     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
04676       return Match;
04677     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
04678       return Match;
04679 
04680     // ((A&~B)|(~A&B)) -> A^B
04681     if ((match(C, m_Not(m_Specific(D))) &&
04682          match(B, m_Not(m_Specific(A)))))
04683       return BinaryOperator::CreateXor(A, D);
04684     // ((~B&A)|(~A&B)) -> A^B
04685     if ((match(A, m_Not(m_Specific(D))) &&
04686          match(B, m_Not(m_Specific(C)))))
04687       return BinaryOperator::CreateXor(C, D);
04688     // ((A&~B)|(B&~A)) -> A^B
04689     if ((match(C, m_Not(m_Specific(B))) &&
04690          match(D, m_Not(m_Specific(A)))))
04691       return BinaryOperator::CreateXor(A, B);
04692     // ((~B&A)|(B&~A)) -> A^B
04693     if ((match(A, m_Not(m_Specific(B))) &&
04694          match(D, m_Not(m_Specific(C)))))
04695       return BinaryOperator::CreateXor(C, B);
04696   }
04697   
04698   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
04699   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
04700     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
04701       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
04702           SI0->getOperand(1) == SI1->getOperand(1) &&
04703           (SI0->hasOneUse() || SI1->hasOneUse())) {
04704         Instruction *NewOp =
04705         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
04706                                                      SI1->getOperand(0),
04707                                                      SI0->getName()), I);
04708         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
04709                                       SI1->getOperand(1));
04710       }
04711   }
04712 
04713   // ((A|B)&1)|(B&-2) -> (A&1) | B
04714   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
04715       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
04716     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
04717     if (Ret) return Ret;
04718   }
04719   // (B&-2)|((A|B)&1) -> (A&1) | B
04720   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
04721       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
04722     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
04723     if (Ret) return Ret;
04724   }
04725 
04726   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
04727     if (A == Op1)   // ~A | A == -1
04728       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
04729   } else {
04730     A = 0;
04731   }
04732   // Note, A is still live here!
04733   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
04734     if (Op0 == B)
04735       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
04736 
04737     // (~A | ~B) == (~(A & B)) - De Morgan's Law
04738     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
04739       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
04740                                               I.getName()+".demorgan"), I);
04741       return BinaryOperator::CreateNot(And);
04742     }
04743   }
04744 
04745   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
04746   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
04747     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
04748       return R;
04749 
04750     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
04751       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
04752         return Res;
04753   }
04754     
04755   // fold (or (cast A), (cast B)) -> (cast (or A, B))
04756   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
04757     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
04758       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
04759         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
04760             !isa<ICmpInst>(Op1C->getOperand(0))) {
04761           const Type *SrcTy = Op0C->getOperand(0)->getType();
04762           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
04763               // Only do this if the casts both really cause code to be
04764               // generated.
04765               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
04766                                 I.getType(), TD) &&
04767               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
04768                                 I.getType(), TD)) {
04769             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
04770                                                           Op1C->getOperand(0),
04771                                                           I.getName());
04772             InsertNewInstBefore(NewOp, I);
04773             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
04774           }
04775         }
04776       }
04777   }
04778   
04779     
04780   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
04781   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
04782     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
04783       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
04784           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
04785           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
04786         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
04787           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
04788             // If either of the constants are nans, then the whole thing returns
04789             // true.
04790             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
04791               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
04792             
04793             // Otherwise, no need to compare the two constants, compare the
04794             // rest.
04795             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
04796                                 RHS->getOperand(0));
04797           }
04798       } else {
04799         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
04800         FCmpInst::Predicate Op0CC, Op1CC;
04801         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
04802             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
04803           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
04804             // Swap RHS operands to match LHS.
04805             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
04806             std::swap(Op1LHS, Op1RHS);
04807           }
04808           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
04809             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
04810             if (Op0CC == Op1CC)
04811               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
04812             else if (Op0CC == FCmpInst::FCMP_TRUE ||
04813                      Op1CC == FCmpInst::FCMP_TRUE)
04814               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
04815             else if (Op0CC == FCmpInst::FCMP_FALSE)
04816               return ReplaceInstUsesWith(I, Op1);
04817             else if (Op1CC == FCmpInst::FCMP_FALSE)
04818               return ReplaceInstUsesWith(I, Op0);
04819             bool Op0Ordered;
04820             bool Op1Ordered;
04821             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
04822             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
04823             if (Op0Ordered == Op1Ordered) {
04824               // If both are ordered or unordered, return a new fcmp with
04825               // or'ed predicates.
04826               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
04827                                        Op0LHS, Op0RHS);
04828               if (Instruction *I = dyn_cast<Instruction>(RV))
04829                 return I;
04830               // Otherwise, it's a constant boolean value...
04831               return ReplaceInstUsesWith(I, RV);
04832             }
04833           }
04834         }
04835       }
04836     }
04837   }
04838 
04839   return Changed ? &I : 0;
04840 }
04841 
04842 namespace {
04843 
04844 // XorSelf - Implements: X ^ X --> 0
04845 struct XorSelf {
04846   Value *RHS;
04847   XorSelf(Value *rhs) : RHS(rhs) {}
04848   bool shouldApply(Value *LHS) const { return LHS == RHS; }
04849   Instruction *apply(BinaryOperator &Xor) const {
04850     return &Xor;
04851   }
04852 };
04853 
04854 }
04855 
04856 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
04857   bool Changed = SimplifyCommutative(I);
04858   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
04859 
04860   if (isa<UndefValue>(Op1)) {
04861     if (isa<UndefValue>(Op0))
04862       // Handle undef ^ undef -> 0 special case. This is a common
04863       // idiom (misuse).
04864       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
04865     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
04866   }
04867 
04868   // xor X, X = 0, even if X is nested in a sequence of Xor's.
04869   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
04870     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
04871     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
04872   }
04873   
04874   // See if we can simplify any instructions used by the instruction whose sole 
04875   // purpose is to compute bits we don't care about.
04876   if (!isa<VectorType>(I.getType())) {
04877     if (SimplifyDemandedInstructionBits(I))
04878       return &I;
04879   } else if (isa<ConstantAggregateZero>(Op1)) {
04880     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
04881   }
04882 
04883   // Is this a ~ operation?
04884   if (Value *NotOp = dyn_castNotVal(&I)) {
04885     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
04886     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
04887     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
04888       if (Op0I->getOpcode() == Instruction::And || 
04889           Op0I->getOpcode() == Instruction::Or) {
04890         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
04891         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
04892           Instruction *NotY =
04893             BinaryOperator::CreateNot(Op0I->getOperand(1),
04894                                       Op0I->getOperand(1)->getName()+".not");
04895           InsertNewInstBefore(NotY, I);
04896           if (Op0I->getOpcode() == Instruction::And)
04897             return BinaryOperator::CreateOr(Op0NotVal, NotY);
04898           else
04899             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
04900         }
04901       }
04902     }
04903   }
04904   
04905   
04906   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
04907     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
04908       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
04909       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
04910         return new ICmpInst(ICI->getInversePredicate(),
04911                             ICI->getOperand(0), ICI->getOperand(1));
04912 
04913       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
04914         return new FCmpInst(FCI->getInversePredicate(),
04915                             FCI->getOperand(0), FCI->getOperand(1));
04916     }
04917 
04918     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
04919     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
04920       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
04921         if (CI->hasOneUse() && Op0C->hasOneUse()) {
04922           Instruction::CastOps Opcode = Op0C->getOpcode();
04923           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
04924             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
04925                                              Op0C->getDestTy())) {
04926               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
04927                                      CI->getOpcode(), CI->getInversePredicate(),
04928                                      CI->getOperand(0), CI->getOperand(1)), I);
04929               NewCI->takeName(CI);
04930               return CastInst::Create(Opcode, NewCI, Op0C->getType());
04931             }
04932           }
04933         }
04934       }
04935     }
04936 
04937     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
04938       // ~(c-X) == X-c-1 == X+(-c-1)
04939       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
04940         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
04941           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
04942           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
04943                                               ConstantInt::get(I.getType(), 1));
04944           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
04945         }
04946           
04947       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
04948         if (Op0I->getOpcode() == Instruction::Add) {
04949           // ~(X-c) --> (-c-1)-X
04950           if (RHS->isAllOnesValue()) {
04951             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
04952             return BinaryOperator::CreateSub(
04953                            ConstantExpr::getSub(NegOp0CI,
04954                                              ConstantInt::get(I.getType(), 1)),
04955                                           Op0I->getOperand(0));
04956           } else if (RHS->getValue().isSignBit()) {
04957             // (X + C) ^ signbit -> (X + C + signbit)
04958             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
04959             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
04960 
04961           }
04962         } else if (Op0I->getOpcode() == Instruction::Or) {
04963           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
04964           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
04965             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
04966             // Anything in both C1 and C2 is known to be zero, remove it from
04967             // NewRHS.
04968             Constant *CommonBits = And(Op0CI, RHS);
04969             NewRHS = ConstantExpr::getAnd(NewRHS, 
04970                                           ConstantExpr::getNot(CommonBits));
04971             AddToWorkList(Op0I);
04972             I.setOperand(0, Op0I->getOperand(0));
04973             I.setOperand(1, NewRHS);
04974             return &I;
04975           }
04976         }
04977       }
04978     }
04979 
04980     // Try to fold constant and into select arguments.
04981     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
04982       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
04983         return R;
04984     if (isa<PHINode>(Op0))
04985       if (Instruction *NV = FoldOpIntoPhi(I))
04986         return NV;
04987   }
04988 
04989   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
04990     if (X == Op1)
04991       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
04992 
04993   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
04994     if (X == Op0)
04995       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
04996 
04997   
04998   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
04999   if (Op1I) {
05000     Value *A, *B;
05001     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
05002       if (A == Op0) {              // B^(B|A) == (A|B)^B
05003         Op1I->swapOperands();
05004         I.swapOperands();
05005         std::swap(Op0, Op1);
05006       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
05007         I.swapOperands();     // Simplified below.
05008         std::swap(Op0, Op1);
05009       }
05010     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
05011       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
05012     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
05013       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
05014     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
05015       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
05016         Op1I->swapOperands();
05017         std::swap(A, B);
05018       }
05019       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
05020         I.swapOperands();     // Simplified below.
05021         std::swap(Op0, Op1);
05022       }
05023     }
05024   }
05025   
05026   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
05027   if (Op0I) {
05028     Value *A, *B;
05029     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
05030       if (A == Op1)                                  // (B|A)^B == (A|B)^B
05031         std::swap(A, B);
05032       if (B == Op1) {                                // (A|B)^B == A & ~B
05033         Instruction *NotB =
05034           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
05035         return BinaryOperator::CreateAnd(A, NotB);
05036       }
05037     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
05038       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
05039     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
05040       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
05041     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
05042       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
05043         std::swap(A, B);
05044       if (B == Op1 &&                                      // (B&A)^A == ~B & A
05045           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
05046         Instruction *N =
05047           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
05048         return BinaryOperator::CreateAnd(N, Op1);
05049       }
05050     }
05051   }
05052   
05053   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
05054   if (Op0I && Op1I && Op0I->isShift() && 
05055       Op0I->getOpcode() == Op1I->getOpcode() && 
05056       Op0I->getOperand(1) == Op1I->getOperand(1) &&
05057       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
05058     Instruction *NewOp =
05059       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
05060                                                     Op1I->getOperand(0),
05061                                                     Op0I->getName()), I);
05062     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
05063                                   Op1I->getOperand(1));
05064   }
05065     
05066   if (Op0I && Op1I) {
05067     Value *A, *B, *C, *D;
05068     // (A & B)^(A | B) -> A ^ B
05069     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
05070         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
05071       if ((A == C && B == D) || (A == D && B == C)) 
05072         return BinaryOperator::CreateXor(A, B);
05073     }
05074     // (A | B)^(A & B) -> A ^ B
05075     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
05076         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
05077       if ((A == C && B == D) || (A == D && B == C)) 
05078         return BinaryOperator::CreateXor(A, B);
05079     }
05080     
05081     // (A & B)^(C & D)
05082     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
05083         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
05084         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
05085       // (X & Y)^(X & Y) -> (Y^Z) & X
05086       Value *X = 0, *Y = 0, *Z = 0;
05087       if (A == C)
05088         X = A, Y = B, Z = D;
05089       else if (A == D)
05090         X = A, Y = B, Z = C;
05091       else if (B == C)
05092         X = B, Y = A, Z = D;
05093       else if (B == D)
05094         X = B, Y = A, Z = C;
05095       
05096       if (X) {
05097         Instruction *NewOp =
05098         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
05099         return BinaryOperator::CreateAnd(NewOp, X);
05100       }
05101     }
05102   }
05103     
05104   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
05105   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
05106     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
05107       return R;
05108 
05109   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
05110   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
05111     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
05112       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
05113         const Type *SrcTy = Op0C->getOperand(0)->getType();
05114         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
05115             // Only do this if the casts both really cause code to be generated.
05116             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
05117                               I.getType(), TD) &&
05118             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
05119                               I.getType(), TD)) {
05120           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
05121                                                          Op1C->getOperand(0),
05122                                                          I.getName());
05123           InsertNewInstBefore(NewOp, I);
05124           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
05125         }
05126       }
05127   }
05128 
05129   return Changed ? &I : 0;
05130 }
05131 
05132 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
05133 /// overflowed for this type.
05134 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
05135                             ConstantInt *In2, bool IsSigned = false) {
05136   Result = cast<ConstantInt>(Add(In1, In2));
05137 
05138   if (IsSigned)
05139     if (In2->getValue().isNegative())
05140       return Result->getValue().sgt(In1->getValue());
05141     else
05142       return Result->getValue().slt(In1->getValue());
05143   else
05144     return Result->getValue().ult(In1->getValue());
05145 }
05146 
05147 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
05148 /// overflowed for this type.
05149 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
05150                             ConstantInt *In2, bool IsSigned = false) {
05151   Result = cast<ConstantInt>(Subtract(In1, In2));
05152 
05153   if (IsSigned)
05154     if (In2->getValue().isNegative())
05155       return Result->getValue().slt(In1->getValue());
05156     else
05157       return Result->getValue().sgt(In1->getValue());
05158   else
05159     return Result->getValue().ugt(In1->getValue());
05160 }
05161 
05162 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
05163 /// code necessary to compute the offset from the base pointer (without adding
05164 /// in the base pointer).  Return the result as a signed integer of intptr size.
05165 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
05166   TargetData &TD = IC.getTargetData();
05167   gep_type_iterator GTI = gep_type_begin(GEP);
05168   const Type *IntPtrTy = TD.getIntPtrType();
05169   Value *Result = Constant::getNullValue(IntPtrTy);
05170 
05171   // Build a mask for high order bits.
05172   unsigned IntPtrWidth = TD.getPointerSizeInBits();
05173   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
05174 
05175   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
05176        ++i, ++GTI) {
05177     Value *Op = *i;
05178     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
05179     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
05180       if (OpC->isZero()) continue;
05181       
05182       // Handle a struct index, which adds its field offset to the pointer.
05183       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
05184         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
05185         
05186         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
05187           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
05188         else
05189           Result = IC.InsertNewInstBefore(
05190                    BinaryOperator::CreateAdd(Result,
05191                                              ConstantInt::get(IntPtrTy, Size),
05192                                              GEP->getName()+".offs"), I);
05193         continue;
05194       }
05195       
05196       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
05197       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
05198       Scale = ConstantExpr::getMul(OC, Scale);
05199       if (Constant *RC = dyn_cast<Constant>(Result))
05200         Result = ConstantExpr::getAdd(RC, Scale);
05201       else {
05202         // Emit an add instruction.
05203         Result = IC.InsertNewInstBefore(
05204            BinaryOperator::CreateAdd(Result, Scale,
05205                                      GEP->getName()+".offs"), I);
05206       }
05207       continue;
05208     }
05209     // Convert to correct type.
05210     if (Op->getType() != IntPtrTy) {
05211       if (Constant *OpC = dyn_cast<Constant>(Op))
05212         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
05213       else
05214         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
05215                                                  Op->getName()+".c"), I);
05216     }
05217     if (Size != 1) {
05218       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
05219       if (Constant *OpC = dyn_cast<Constant>(Op))
05220         Op = ConstantExpr::getMul(OpC, Scale);
05221       else    // We'll let instcombine(mul) convert this to a shl if possible.
05222         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
05223                                                   GEP->getName()+".idx"), I);
05224     }
05225 
05226     // Emit an add instruction.
05227     if (isa<Constant>(Op) && isa<Constant>(Result))
05228       Result = ConstantExpr::getAdd(cast<Constant>(Op),
05229                                     cast<Constant>(Result));
05230     else
05231       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
05232                                                   GEP->getName()+".offs"), I);
05233   }
05234   return Result;
05235 }
05236 
05237 
05238 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
05239 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
05240 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
05241 /// complex, and scales are involved.  The above expression would also be legal
05242 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
05243 /// later form is less amenable to optimization though, and we are allowed to
05244 /// generate the first by knowing that pointer arithmetic doesn't overflow.
05245 ///
05246 /// If we can't emit an optimized form for this expression, this returns null.
05247 /// 
05248 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
05249                                           InstCombiner &IC) {
05250   TargetData &TD = IC.getTargetData();
05251   gep_type_iterator GTI = gep_type_begin(GEP);
05252 
05253   // Check to see if this gep only has a single variable index.  If so, and if
05254   // any constant indices are a multiple of its scale, then we can compute this
05255   // in terms of the scale of the variable index.  For example, if the GEP
05256   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
05257   // because the expression will cross zero at the same point.
05258   unsigned i, e = GEP->getNumOperands();
05259   int64_t Offset = 0;
05260   for (i = 1; i != e; ++i, ++GTI) {
05261     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
05262       // Compute the aggregate offset of constant indices.
05263       if (CI->isZero()) continue;
05264 
05265       // Handle a struct index, which adds its field offset to the pointer.
05266       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
05267         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
05268       } else {
05269         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
05270         Offset += Size*CI->getSExtValue();
05271       }
05272     } else {
05273       // Found our variable index.
05274       break;
05275     }
05276   }
05277   
05278   // If there are no variable indices, we must have a constant offset, just
05279   // evaluate it the general way.
05280   if (i == e) return 0;
05281   
05282   Value *VariableIdx = GEP->getOperand(i);
05283   // Determine the scale factor of the variable element.  For example, this is
05284   // 4 if the variable index is into an array of i32.
05285   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
05286   
05287   // Verify that there are no other variable indices.  If so, emit the hard way.
05288   for (++i, ++GTI; i != e; ++i, ++GTI) {
05289     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
05290     if (!CI) return 0;
05291    
05292     // Compute the aggregate offset of constant indices.
05293     if (CI->isZero()) continue;
05294     
05295     // Handle a struct index, which adds its field offset to the pointer.
05296     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
05297       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
05298     } else {
05299       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
05300       Offset += Size*CI->getSExtValue();
05301     }
05302   }
05303   
05304   // Okay, we know we have a single variable index, which must be a
05305   // pointer/array/vector index.  If there is no offset, life is simple, return
05306   // the index.
05307   unsigned IntPtrWidth = TD.getPointerSizeInBits();
05308   if (Offset == 0) {
05309     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
05310     // we don't need to bother extending: the extension won't affect where the
05311     // computation crosses zero.
05312     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
05313       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
05314                                   VariableIdx->getNameStart(), &I);
05315     return VariableIdx;
05316   }
05317   
05318   // Otherwise, there is an index.  The computation we will do will be modulo
05319   // the pointer size, so get it.
05320   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
05321   
05322   Offset &= PtrSizeMask;
05323   VariableScale &= PtrSizeMask;
05324 
05325   // To do this transformation, any constant index must be a multiple of the
05326   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
05327   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
05328   // multiple of the variable scale.
05329   int64_t NewOffs = Offset / (int64_t)VariableScale;
05330   if (Offset != NewOffs*(int64_t)VariableScale)
05331     return 0;
05332 
05333   // Okay, we can do this evaluation.  Start by converting the index to intptr.
05334   const Type *IntPtrTy = TD.getIntPtrType();
05335   if (VariableIdx->getType() != IntPtrTy)
05336     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
05337                                               true /*SExt*/, 
05338                                               VariableIdx->getNameStart(), &I);
05339   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
05340   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
05341 }
05342 
05343 
05344 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
05345 /// else.  At this point we know that the GEP is on the LHS of the comparison.
05346 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
05347                                        ICmpInst::Predicate Cond,
05348                                        Instruction &I) {
05349   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
05350 
05351   // Look through bitcasts.
05352   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
05353     RHS = BCI->getOperand(0);
05354 
05355   Value *PtrBase = GEPLHS->getOperand(0);
05356   if (PtrBase == RHS) {
05357     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
05358     // This transformation (ignoring the base and scales) is valid because we
05359     // know pointers can't overflow.  See if we can output an optimized form.
05360     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
05361     
05362     // If not, synthesize the offset the hard way.
05363     if (Offset == 0)
05364       Offset = EmitGEPOffset(GEPLHS, I, *this);
05365     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
05366                         Constant::getNullValue(Offset->getType()));
05367   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
05368     // If the base pointers are different, but the indices are the same, just
05369     // compare the base pointer.
05370     if (PtrBase != GEPRHS->getOperand(0)) {
05371       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
05372       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
05373                         GEPRHS->getOperand(0)->getType();
05374       if (IndicesTheSame)
05375         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
05376           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
05377             IndicesTheSame = false;
05378             break;
05379           }
05380 
05381       // If all indices are the same, just compare the base pointers.
05382       if (IndicesTheSame)
05383         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
05384                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
05385 
05386       // Otherwise, the base pointers are different and the indices are
05387       // different, bail out.
05388       return 0;
05389     }
05390 
05391     // If one of the GEPs has all zero indices, recurse.
05392     bool AllZeros = true;
05393     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
05394       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
05395           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
05396         AllZeros = false;
05397         break;
05398       }
05399     if (AllZeros)
05400       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
05401                           ICmpInst::getSwappedPredicate(Cond), I);
05402 
05403     // If the other GEP has all zero indices, recurse.
05404     AllZeros = true;
05405     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
05406       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
05407           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
05408         AllZeros = false;
05409         break;
05410       }
05411     if (AllZeros)
05412       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
05413 
05414     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
05415       // If the GEPs only differ by one index, compare it.
05416       unsigned NumDifferences = 0;  // Keep track of # differences.
05417       unsigned DiffOperand = 0;     // The operand that differs.
05418       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
05419         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
05420           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
05421                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
05422             // Irreconcilable differences.
05423             NumDifferences = 2;
05424             break;
05425           } else {
05426             if (NumDifferences++) break;
05427             DiffOperand = i;
05428           }
05429         }
05430 
05431       if (NumDifferences == 0)   // SAME GEP?
05432         return ReplaceInstUsesWith(I, // No comparison is needed here.
05433                                    ConstantInt::get(Type::Int1Ty,
05434                                              ICmpInst::isTrueWhenEqual(Cond)));
05435 
05436       else if (NumDifferences == 1) {
05437         Value *LHSV = GEPLHS->getOperand(DiffOperand);
05438         Value *RHSV = GEPRHS->getOperand(DiffOperand);
05439         // Make sure we do a signed comparison here.
05440         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
05441       }
05442     }
05443 
05444     // Only lower this if the icmp is the only user of the GEP or if we expect
05445     // the result to fold to a constant!
05446     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
05447         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
05448       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
05449       Value *L = EmitGEPOffset(GEPLHS, I, *this);
05450       Value *R = EmitGEPOffset(GEPRHS, I, *this);
05451       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
05452     }
05453   }
05454   return 0;
05455 }
05456 
05457 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
05458 ///
05459 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
05460                                                 Instruction *LHSI,
05461                                                 Constant *RHSC) {
05462   if (!isa<ConstantFP>(RHSC)) return 0;
05463   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
05464   
05465   // Get the width of the mantissa.  We don't want to hack on conversions that
05466   // might lose information from the integer, e.g. "i64 -> float"
05467   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
05468   if (MantissaWidth == -1) return 0;  // Unknown.
05469   
05470   // Check to see that the input is converted from an integer type that is small
05471   // enough that preserves all bits.  TODO: check here for "known" sign bits.
05472   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
05473   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
05474   
05475   // If this is a uitofp instruction, we need an extra bit to hold the sign.
05476   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
05477   if (LHSUnsigned)
05478     ++InputSize;
05479   
05480   // If the conversion would lose info, don't hack on this.
05481   if ((int)InputSize > MantissaWidth)
05482     return 0;
05483   
05484   // Otherwise, we can potentially simplify the comparison.  We know that it
05485   // will always come through as an integer value and we know the constant is
05486   // not a NAN (it would have been previously simplified).
05487   assert(!RHS.isNaN() && "NaN comparison not already folded!");
05488   
05489   ICmpInst::Predicate Pred;
05490   switch (I.getPredicate()) {
05491   default: assert(0 && "Unexpected predicate!");
05492   case FCmpInst::FCMP_UEQ:
05493   case FCmpInst::FCMP_OEQ:
05494     Pred = ICmpInst::ICMP_EQ;
05495     break;
05496   case FCmpInst::FCMP_UGT:
05497   case FCmpInst::FCMP_OGT:
05498     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
05499     break;
05500   case FCmpInst::FCMP_UGE:
05501   case FCmpInst::FCMP_OGE:
05502     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
05503     break;
05504   case FCmpInst::FCMP_ULT:
05505   case FCmpInst::FCMP_OLT:
05506     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
05507     break;
05508   case FCmpInst::FCMP_ULE:
05509   case FCmpInst::FCMP_OLE:
05510     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
05511     break;
05512   case FCmpInst::FCMP_UNE:
05513   case FCmpInst::FCMP_ONE:
05514     Pred = ICmpInst::ICMP_NE;
05515     break;
05516   case FCmpInst::FCMP_ORD:
05517     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05518   case FCmpInst::FCMP_UNO:
05519     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05520   }
05521   
05522   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
05523   
05524   // Now we know that the APFloat is a normal number, zero or inf.
05525   
05526   // See if the FP constant is too large for the integer.  For example,
05527   // comparing an i8 to 300.0.
05528   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
05529   
05530   if (!LHSUnsigned) {
05531     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
05532     // and large values.
05533     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
05534     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
05535                           APFloat::rmNearestTiesToEven);
05536     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
05537       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
05538           Pred == ICmpInst::ICMP_SLE)
05539         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05540       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05541     }
05542   } else {
05543     // If the RHS value is > UnsignedMax, fold the comparison. This handles
05544     // +INF and large values.
05545     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
05546     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
05547                           APFloat::rmNearestTiesToEven);
05548     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
05549       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
05550           Pred == ICmpInst::ICMP_ULE)
05551         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05552       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05553     }
05554   }
05555   
05556   if (!LHSUnsigned) {
05557     // See if the RHS value is < SignedMin.
05558     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
05559     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
05560                           APFloat::rmNearestTiesToEven);
05561     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
05562       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
05563           Pred == ICmpInst::ICMP_SGE)
05564         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
05565       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05566     }
05567   }
05568 
05569   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
05570   // [0, UMAX], but it may still be fractional.  See if it is fractional by
05571   // casting the FP value to the integer value and back, checking for equality.
05572   // Don't do this for zero, because -0.0 is not fractional.
05573   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
05574   if (!RHS.isZero() &&
05575       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
05576     // If we had a comparison against a fractional value, we have to adjust the
05577     // compare predicate and sometimes the value.  RHSC is rounded towards zero
05578     // at this point.
05579     switch (Pred) {
05580     default: assert(0 && "Unexpected integer comparison!");
05581     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
05582       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05583     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
05584       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05585     case ICmpInst::ICMP_ULE:
05586       // (float)int <= 4.4   --> int <= 4
05587       // (float)int <= -4.4  --> false
05588       if (RHS.isNegative())
05589         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05590       break;
05591     case ICmpInst::ICMP_SLE:
05592       // (float)int <= 4.4   --> int <= 4
05593       // (float)int <= -4.4  --> int < -4
05594       if (RHS.isNegative())
05595         Pred = ICmpInst::ICMP_SLT;
05596       break;
05597     case ICmpInst::ICMP_ULT:
05598       // (float)int < -4.4   --> false
05599       // (float)int < 4.4    --> int <= 4
05600       if (RHS.isNegative())
05601         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05602       Pred = ICmpInst::ICMP_ULE;
05603       break;
05604     case ICmpInst::ICMP_SLT:
05605       // (float)int < -4.4   --> int < -4
05606       // (float)int < 4.4    --> int <= 4
05607       if (!RHS.isNegative())
05608         Pred = ICmpInst::ICMP_SLE;
05609       break;
05610     case ICmpInst::ICMP_UGT:
05611       // (float)int > 4.4    --> int > 4
05612       // (float)int > -4.4   --> true
05613       if (RHS.isNegative())
05614         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05615       break;
05616     case ICmpInst::ICMP_SGT:
05617       // (float)int > 4.4    --> int > 4
05618       // (float)int > -4.4   --> int >= -4
05619       if (RHS.isNegative())
05620         Pred = ICmpInst::ICMP_SGE;
05621       break;
05622     case ICmpInst::ICMP_UGE:
05623       // (float)int >= -4.4   --> true
05624       // (float)int >= 4.4    --> int > 4
05625       if (!RHS.isNegative())
05626         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05627       Pred = ICmpInst::ICMP_UGT;
05628       break;
05629     case ICmpInst::ICMP_SGE:
05630       // (float)int >= -4.4   --> int >= -4
05631       // (float)int >= 4.4    --> int > 4
05632       if (!RHS.isNegative())
05633         Pred = ICmpInst::ICMP_SGT;
05634       break;
05635     }
05636   }
05637 
05638   // Lower this FP comparison into an appropriate integer version of the
05639   // comparison.
05640   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
05641 }
05642 
05643 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
05644   bool Changed = SimplifyCompare(I);
05645   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
05646 
05647   // Fold trivial predicates.
05648   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
05649     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05650   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
05651     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05652   
05653   // Simplify 'fcmp pred X, X'
05654   if (Op0 == Op1) {
05655     switch (I.getPredicate()) {
05656     default: assert(0 && "Unknown predicate!");
05657     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
05658     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
05659     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
05660       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05661     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
05662     case FCmpInst::FCMP_OLT:    // True if ordered and less than
05663     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
05664       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05665       
05666     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
05667     case FCmpInst::FCMP_ULT:    // True if unordered or less than
05668     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
05669     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
05670       // Canonicalize these to be 'fcmp uno %X, 0.0'.
05671       I.setPredicate(FCmpInst::FCMP_UNO);
05672       I.setOperand(1, Constant::getNullValue(Op0->getType()));
05673       return &I;
05674       
05675     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
05676     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
05677     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
05678     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
05679       // Canonicalize these to be 'fcmp ord %X, 0.0'.
05680       I.setPredicate(FCmpInst::FCMP_ORD);
05681       I.setOperand(1, Constant::getNullValue(Op0->getType()));
05682       return &I;
05683     }
05684   }
05685     
05686   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
05687     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
05688 
05689   // Handle fcmp with constant RHS
05690   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
05691     // If the constant is a nan, see if we can fold the comparison based on it.
05692     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
05693       if (CFP->getValueAPF().isNaN()) {
05694         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
05695           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05696         assert(FCmpInst::isUnordered(I.getPredicate()) &&
05697                "Comparison must be either ordered or unordered!");
05698         // True if unordered.
05699         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05700       }
05701     }
05702     
05703     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
05704       switch (LHSI->getOpcode()) {
05705       case Instruction::PHI:
05706         // Only fold fcmp into the PHI if the phi and fcmp are in the same
05707         // block.  If in the same block, we're encouraging jump threading.  If
05708         // not, we are just pessimizing the code by making an i1 phi.
05709         if (LHSI->getParent() == I.getParent())
05710           if (Instruction *NV = FoldOpIntoPhi(I))
05711             return NV;
05712         break;
05713       case Instruction::SIToFP:
05714       case Instruction::UIToFP:
05715         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
05716           return NV;
05717         break;
05718       case Instruction::Select:
05719         // If either operand of the select is a constant, we can fold the
05720         // comparison into the select arms, which will cause one to be
05721         // constant folded and the select turned into a bitwise or.
05722         Value *Op1 = 0, *Op2 = 0;
05723         if (LHSI->hasOneUse()) {
05724           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
05725             // Fold the known value into the constant operand.
05726             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
05727             // Insert a new FCmp of the other select operand.
05728             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
05729                                                       LHSI->getOperand(2), RHSC,
05730                                                       I.getName()), I);
05731           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
05732             // Fold the known value into the constant operand.
05733             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
05734             // Insert a new FCmp of the other select operand.
05735             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
05736                                                       LHSI->getOperand(1), RHSC,
05737                                                       I.getName()), I);
05738           }
05739         }
05740 
05741         if (Op1)
05742           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
05743         break;
05744       }
05745   }
05746 
05747   return Changed ? &I : 0;
05748 }
05749 
05750 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
05751   bool Changed = SimplifyCompare(I);
05752   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
05753   const Type *Ty = Op0->getType();
05754 
05755   // icmp X, X
05756   if (Op0 == Op1)
05757     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
05758                                                    I.isTrueWhenEqual()));
05759 
05760   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
05761     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
05762   
05763   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
05764   // addresses never equal each other!  We already know that Op0 != Op1.
05765   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
05766        isa<ConstantPointerNull>(Op0)) &&
05767       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
05768        isa<ConstantPointerNull>(Op1)))
05769     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
05770                                                    !I.isTrueWhenEqual()));
05771 
05772   // icmp's with boolean values can always be turned into bitwise operations
05773   if (Ty == Type::Int1Ty) {
05774     switch (I.getPredicate()) {
05775     default: assert(0 && "Invalid icmp instruction!");
05776     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
05777       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
05778       InsertNewInstBefore(Xor, I);
05779       return BinaryOperator::CreateNot(Xor);
05780     }
05781     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
05782       return BinaryOperator::CreateXor(Op0, Op1);
05783 
05784     case ICmpInst::ICMP_UGT:
05785       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
05786       // FALL THROUGH
05787     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
05788       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
05789       InsertNewInstBefore(Not, I);
05790       return BinaryOperator::CreateAnd(Not, Op1);
05791     }
05792     case ICmpInst::ICMP_SGT:
05793       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
05794       // FALL THROUGH
05795     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
05796       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
05797       InsertNewInstBefore(Not, I);
05798       return BinaryOperator::CreateAnd(Not, Op0);
05799     }
05800     case ICmpInst::ICMP_UGE:
05801       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
05802       // FALL THROUGH
05803     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
05804       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
05805       InsertNewInstBefore(Not, I);
05806       return BinaryOperator::CreateOr(Not, Op1);
05807     }
05808     case ICmpInst::ICMP_SGE:
05809       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
05810       // FALL THROUGH
05811     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
05812       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
05813       InsertNewInstBefore(Not, I);
05814       return BinaryOperator::CreateOr(Not, Op0);
05815     }
05816     }
05817   }
05818 
05819   // See if we are doing a comparison with a constant.
05820   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
05821     Value *A, *B;
05822     
05823     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
05824     if (I.isEquality() && CI->isNullValue() &&
05825         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
05826       // (icmp cond A B) if cond is equality
05827       return new ICmpInst(I.getPredicate(), A, B);
05828     }
05829     
05830     // If we have an icmp le or icmp ge instruction, turn it into the
05831     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
05832     // them being folded in the code below.
05833     switch (I.getPredicate()) {
05834     default: break;
05835     case ICmpInst::ICMP_ULE:
05836       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
05837         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05838       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
05839     case ICmpInst::ICMP_SLE:
05840       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
05841         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05842       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
05843     case ICmpInst::ICMP_UGE:
05844       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
05845         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05846       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
05847     case ICmpInst::ICMP_SGE:
05848       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
05849         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05850       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
05851     }
05852     
05853     // See if we can fold the comparison based on range information we can get
05854     // by checking whether bits are known to be zero or one in the input.
05855     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
05856     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
05857     
05858     // If this comparison is a normal comparison, it demands all
05859     // bits, if it is a sign bit comparison, it only demands the sign bit.
05860     bool UnusedBit;
05861     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
05862     
05863     if (SimplifyDemandedBits(I.getOperandUse(0), 
05864                              isSignBit ? APInt::getSignBit(BitWidth)
05865                                        : APInt::getAllOnesValue(BitWidth),
05866                              KnownZero, KnownOne, 0))
05867       return &I;
05868         
05869     // Given the known and unknown bits, compute a range that the LHS could be
05870     // in.  Compute the Min, Max and RHS values based on the known bits. For the
05871     // EQ and NE we use unsigned values.
05872     APInt Min(BitWidth, 0), Max(BitWidth, 0);
05873     if (ICmpInst::isSignedPredicate(I.getPredicate()))
05874       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
05875     else
05876       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
05877     
05878     // If Min and Max are known to be the same, then SimplifyDemandedBits
05879     // figured out that the LHS is a constant.  Just constant fold this now so
05880     // that code below can assume that Min != Max.
05881     if (Min == Max)
05882       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
05883                                                           ConstantInt::get(Min),
05884                                                           CI));
05885     
05886     // Based on the range information we know about the LHS, see if we can
05887     // simplify this comparison.  For example, (x&4) < 8  is always true.
05888     const APInt &RHSVal = CI->getValue();
05889     switch (I.getPredicate()) {  // LE/GE have been folded already.
05890     default: assert(0 && "Unknown icmp opcode!");
05891     case ICmpInst::ICMP_EQ:
05892       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
05893         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05894       break;
05895     case ICmpInst::ICMP_NE:
05896       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
05897         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05898       break;
05899     case ICmpInst::ICMP_ULT:
05900       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
05901         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05902       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
05903         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05904       if (RHSVal == Max)                      // A <u MAX -> A != MAX
05905         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
05906       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
05907         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
05908         
05909       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
05910       if (CI->isMinValue(true))
05911         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
05912                             ConstantInt::getAllOnesValue(Op0->getType()));
05913       break;
05914     case ICmpInst::ICMP_UGT:
05915       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
05916         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05917       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
05918         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05919         
05920       if (RHSVal == Min)                      // A >u MIN -> A != MIN
05921         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
05922       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
05923         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
05924       
05925       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
05926       if (CI->isMaxValue(true))
05927         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
05928                             ConstantInt::getNullValue(Op0->getType()));
05929       break;
05930     case ICmpInst::ICMP_SLT:
05931       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
05932         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05933       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
05934         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05935       if (RHSVal == Max)                      // A <s MAX -> A != MAX
05936         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
05937       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
05938         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
05939       break;
05940     case ICmpInst::ICMP_SGT: 
05941       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
05942         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
05943       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
05944         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
05945         
05946       if (RHSVal == Min)                      // A >s MIN -> A != MIN
05947         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
05948       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
05949         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
05950       break;
05951     }
05952   }
05953 
05954   // Test if the ICmpInst instruction is used exclusively by a select as
05955   // part of a minimum or maximum operation. If so, refrain from doing
05956   // any other folding. This helps out other analyses which understand
05957   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
05958   // and CodeGen. And in this case, at least one of the comparison
05959   // operands has at least one user besides the compare (the select),
05960   // which would often largely negate the benefit of folding anyway.
05961   if (I.hasOneUse())
05962     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
05963       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
05964           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
05965         return 0;
05966 
05967   // See if we are doing a comparison between a constant and an instruction that
05968   // can be folded into the comparison.
05969   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
05970     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
05971     // instruction, see if that instruction also has constants so that the 
05972     // instruction can be folded into the icmp 
05973     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
05974       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
05975         return Res;
05976   }
05977 
05978   // Handle icmp with constant (but not simple integer constant) RHS
05979   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
05980     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
05981       switch (LHSI->getOpcode()) {
05982       case Instruction::GetElementPtr:
05983         if (RHSC->isNullValue()) {
05984           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
05985           bool isAllZeros = true;
05986           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
05987             if (!isa<Constant>(LHSI->getOperand(i)) ||
05988                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
05989               isAllZeros = false;
05990               break;
05991             }
05992           if (isAllZeros)
05993             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
05994                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
05995         }
05996         break;
05997 
05998       case Instruction::PHI:
05999         // Only fold icmp into the PHI if the phi and fcmp are in the same
06000         // block.  If in the same block, we're encouraging jump threading.  If
06001         // not, we are just pessimizing the code by making an i1 phi.
06002         if (LHSI->getParent() == I.getParent())
06003           if (Instruction *NV = FoldOpIntoPhi(I))
06004             return NV;
06005         break;
06006       case Instruction::Select: {
06007         // If either operand of the select is a constant, we can fold the
06008         // comparison into the select arms, which will cause one to be
06009         // constant folded and the select turned into a bitwise or.
06010         Value *Op1 = 0, *Op2 = 0;
06011         if (LHSI->hasOneUse()) {
06012           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
06013             // Fold the known value into the constant operand.
06014             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
06015             // Insert a new ICmp of the other select operand.
06016             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
06017                                                    LHSI->getOperand(2), RHSC,
06018                                                    I.getName()), I);
06019           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
06020             // Fold the known value into the constant operand.
06021             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
06022             // Insert a new ICmp of the other select operand.
06023             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
06024                                                    LHSI->getOperand(1), RHSC,
06025                                                    I.getName()), I);
06026           }
06027         }
06028 
06029         if (Op1)
06030           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
06031         break;
06032       }
06033       case Instruction::Malloc:
06034         // If we have (malloc != null), and if the malloc has a single use, we
06035         // can assume it is successful and remove the malloc.
06036         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
06037           AddToWorkList(LHSI);
06038           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
06039                                                          !I.isTrueWhenEqual()));
06040         }
06041         break;
06042       }
06043   }
06044 
06045   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
06046   if (User *GEP = dyn_castGetElementPtr(Op0))
06047     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
06048       return NI;
06049   if (User *GEP = dyn_castGetElementPtr(Op1))
06050     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
06051                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
06052       return NI;
06053 
06054   // Test to see if the operands of the icmp are casted versions of other
06055   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
06056   // now.
06057   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
06058     if (isa<PointerType>(Op0->getType()) && 
06059         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
06060       // We keep moving the cast from the left operand over to the right
06061       // operand, where it can often be eliminated completely.
06062       Op0 = CI->getOperand(0);
06063 
06064       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
06065       // so eliminate it as well.
06066       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
06067         Op1 = CI2->getOperand(0);
06068 
06069       // If Op1 is a constant, we can fold the cast into the constant.
06070       if (Op0->getType() != Op1->getType()) {
06071         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
06072           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
06073         } else {
06074           // Otherwise, cast the RHS right before the icmp
06075           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
06076         }
06077       }
06078       return new ICmpInst(I.getPredicate(), Op0, Op1);
06079     }
06080   }
06081   
06082   if (isa<CastInst>(Op0)) {
06083     // Handle the special case of: icmp (cast bool to X), <cst>
06084     // This comes up when you have code like
06085     //   int X = A < B;
06086     //   if (X) ...
06087     // For generality, we handle any zero-extension of any operand comparison
06088     // with a constant or another cast from the same type.
06089     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
06090       if (Instruction *R = visitICmpInstWithCastAndCast(I))
06091         return R;
06092   }
06093   
06094   // See if it's the same type of instruction on the left and right.
06095   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
06096     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
06097       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
06098           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
06099         switch (Op0I->getOpcode()) {
06100         default: break;
06101         case Instruction::Add:
06102         case Instruction::Sub:
06103         case Instruction::Xor:
06104           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
06105             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
06106                                 Op1I->getOperand(0));
06107           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
06108           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
06109             if (CI->getValue().isSignBit()) {
06110               ICmpInst::Predicate Pred = I.isSignedPredicate()
06111                                              ? I.getUnsignedPredicate()
06112                                              : I.getSignedPredicate();
06113               return new ICmpInst(Pred, Op0I->getOperand(0),
06114                                   Op1I->getOperand(0));
06115             }
06116             
06117             if (CI->getValue().isMaxSignedValue()) {
06118               ICmpInst::Predicate Pred = I.isSignedPredicate()
06119                                              ? I.getUnsignedPredicate()
06120                                              : I.getSignedPredicate();
06121               Pred = I.getSwappedPredicate(Pred);
06122               return new ICmpInst(Pred, Op0I->getOperand(0),
06123                                   Op1I->getOperand(0));
06124             }
06125           }
06126           break;
06127         case Instruction::Mul:
06128           if (!I.isEquality())
06129             break;
06130 
06131           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
06132             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
06133             // Mask = -1 >> count-trailing-zeros(Cst).
06134             if (!CI->isZero() && !CI->isOne()) {
06135               const APInt &AP = CI->getValue();
06136               ConstantInt *Mask = ConstantInt::get(
06137                                       APInt::getLowBitsSet(AP.getBitWidth(),
06138                                                            AP.getBitWidth() -
06139                                                       AP.countTrailingZeros()));
06140               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
06141                                                             Mask);
06142               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
06143                                                             Mask);
06144               InsertNewInstBefore(And1, I);
06145               InsertNewInstBefore(And2, I);
06146               return new ICmpInst(I.getPredicate(), And1, And2);
06147             }
06148           }
06149           break;
06150         }
06151       }
06152     }
06153   }
06154   
06155   // ~x < ~y --> y < x
06156   { Value *A, *B;
06157     if (match(Op0, m_Not(m_Value(A))) &&
06158         match(Op1, m_Not(m_Value(B))))
06159       return new ICmpInst(I.getPredicate(), B, A);
06160   }
06161   
06162   if (I.isEquality()) {
06163     Value *A, *B, *C, *D;
06164     
06165     // -x == -y --> x == y
06166     if (match(Op0, m_Neg(m_Value(A))) &&
06167         match(Op1, m_Neg(m_Value(B))))
06168       return new ICmpInst(I.getPredicate(), A, B);
06169     
06170     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
06171       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
06172         Value *OtherVal = A == Op1 ? B : A;
06173         return new ICmpInst(I.getPredicate(), OtherVal,
06174                             Constant::getNullValue(A->getType()));
06175       }
06176 
06177       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
06178         // A^c1 == C^c2 --> A == C^(c1^c2)
06179         ConstantInt *C1, *C2;
06180         if (match(B, m_ConstantInt(C1)) &&
06181             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
06182           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
06183           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
06184           return new ICmpInst(I.getPredicate(), A,
06185                               InsertNewInstBefore(Xor, I));
06186         }
06187         
06188         // A^B == A^D -> B == D
06189         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
06190         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
06191         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
06192         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
06193       }
06194     }
06195     
06196     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
06197         (A == Op0 || B == Op0)) {
06198       // A == (A^B)  ->  B == 0
06199       Value *OtherVal = A == Op0 ? B : A;
06200       return new ICmpInst(I.getPredicate(), OtherVal,
06201                           Constant::getNullValue(A->getType()));
06202     }
06203 
06204     // (A-B) == A  ->  B == 0
06205     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
06206       return new ICmpInst(I.getPredicate(), B, 
06207                           Constant::getNullValue(B->getType()));
06208 
06209     // A == (A-B)  ->  B == 0
06210     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
06211       return new ICmpInst(I.getPredicate(), B,
06212                           Constant::getNullValue(B->getType()));
06213     
06214     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
06215     if (Op0->hasOneUse() && Op1->hasOneUse() &&
06216         match(Op0, m_And(m_Value(A), m_Value(B))) && 
06217         match(Op1, m_And(m_Value(C), m_Value(D)))) {
06218       Value *X = 0, *Y = 0, *Z = 0;
06219       
06220       if (A == C) {
06221         X = B; Y = D; Z = A;
06222       } else if (A == D) {
06223         X = B; Y = C; Z = A;
06224       } else if (B == C) {
06225         X = A; Y = D; Z = B;
06226       } else if (B == D) {
06227         X = A; Y = C; Z = B;
06228       }
06229       
06230       if (X) {   // Build (X^Y) & Z
06231         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
06232         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
06233         I.setOperand(0, Op1);
06234         I.setOperand(1, Constant::getNullValue(Op1->getType()));
06235         return &I;
06236       }
06237     }
06238   }
06239   return Changed ? &I : 0;
06240 }
06241 
06242 
06243 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
06244 /// and CmpRHS are both known to be integer constants.
06245 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
06246                                           ConstantInt *DivRHS) {
06247   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
06248   const APInt &CmpRHSV = CmpRHS->getValue();
06249   
06250   // FIXME: If the operand types don't match the type of the divide 
06251   // then don't attempt this transform. The code below doesn't have the
06252   // logic to deal with a signed divide and an unsigned compare (and
06253   // vice versa). This is because (x /s C1) <s C2  produces different 
06254   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
06255   // (x /u C1) <u C2.  Simply casting the operands and result won't 
06256   // work. :(  The if statement below tests that condition and bails 
06257   // if it finds it. 
06258   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
06259   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
06260     return 0;
06261   if (DivRHS->isZero())
06262     return 0; // The ProdOV computation fails on divide by zero.
06263   if (DivIsSigned && DivRHS->isAllOnesValue())
06264     return 0; // The overflow computation also screws up here
06265   if (DivRHS->isOne())
06266     return 0; // Not worth bothering, and eliminates some funny cases
06267               // with INT_MIN.
06268 
06269   // Compute Prod = CI * DivRHS. We are essentially solving an equation
06270   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
06271   // C2 (CI). By solving for X we can turn this into a range check 
06272   // instead of computing a divide. 
06273   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
06274 
06275   // Determine if the product overflows by seeing if the product is
06276   // not equal to the divide. Make sure we do the same kind of divide
06277   // as in the LHS instruction that we're folding. 
06278   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
06279                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
06280 
06281   // Get the ICmp opcode
06282   ICmpInst::Predicate Pred = ICI.getPredicate();
06283 
06284   // Figure out the interval that is being checked.  For example, a comparison
06285   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
06286   // Compute this interval based on the constants involved and the signedness of
06287   // the compare/divide.  This computes a half-open interval, keeping track of
06288   // whether either value in the interval overflows.  After analysis each
06289   // overflow variable is set to 0 if it's corresponding bound variable is valid
06290   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
06291   int LoOverflow = 0, HiOverflow = 0;
06292   ConstantInt *LoBound = 0, *HiBound = 0;
06293   
06294   if (!DivIsSigned) {  // udiv
06295     // e.g. X/5 op 3  --> [15, 20)
06296     LoBound = Prod;
06297     HiOverflow = LoOverflow = ProdOV;
06298     if (!HiOverflow)
06299       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
06300   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
06301     if (CmpRHSV == 0) {       // (X / pos) op 0
06302       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
06303       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
06304       HiBound = DivRHS;
06305     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
06306       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
06307       HiOverflow = LoOverflow = ProdOV;
06308       if (!HiOverflow)
06309         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
06310     } else {                       // (X / pos) op neg
06311       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
06312       HiBound = AddOne(Prod);
06313       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
06314       if (!LoOverflow) {
06315         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
06316         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
06317                                      true) ? -1 : 0;
06318        }
06319     }
06320   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
06321     if (CmpRHSV == 0) {       // (X / neg) op 0
06322       // e.g. X/-5 op 0  --> [-4, 5)
06323       LoBound = AddOne(DivRHS);
06324       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
06325       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
06326         HiOverflow = 1;            // [INTMIN+1, overflow)
06327         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
06328       }
06329     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
06330       // e.g. X/-5 op 3  --> [-19, -14)
06331       HiBound = AddOne(Prod);
06332       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
06333       if (!LoOverflow)
06334         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
06335     } else {                       // (X / neg) op neg
06336       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
06337       LoOverflow = HiOverflow = ProdOV;
06338       if (!HiOverflow)
06339         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
06340     }
06341     
06342     // Dividing by a negative swaps the condition.  LT <-> GT
06343     Pred = ICmpInst::getSwappedPredicate(Pred);
06344   }
06345 
06346   Value *X = DivI->getOperand(0);
06347   switch (Pred) {
06348   default: assert(0 && "Unhandled icmp opcode!");
06349   case ICmpInst::ICMP_EQ:
06350     if (LoOverflow && HiOverflow)
06351       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
06352     else if (HiOverflow)
06353       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
06354                           ICmpInst::ICMP_UGE, X, LoBound);
06355     else if (LoOverflow)
06356       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
06357                           ICmpInst::ICMP_ULT, X, HiBound);
06358     else
06359       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
06360   case ICmpInst::ICMP_NE:
06361     if (LoOverflow && HiOverflow)
06362       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
06363     else if (HiOverflow)
06364       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
06365                           ICmpInst::ICMP_ULT, X, LoBound);
06366     else if (LoOverflow)
06367       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
06368                           ICmpInst::ICMP_UGE, X, HiBound);
06369     else
06370       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
06371   case ICmpInst::ICMP_ULT:
06372   case ICmpInst::ICMP_SLT:
06373     if (LoOverflow == +1)   // Low bound is greater than input range.
06374       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
06375     if (LoOverflow == -1)   // Low bound is less than input range.
06376       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
06377     return new ICmpInst(Pred, X, LoBound);
06378   case ICmpInst::ICMP_UGT:
06379   case ICmpInst::ICMP_SGT:
06380     if (HiOverflow == +1)       // High bound greater than input range.
06381       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
06382     else if (HiOverflow == -1)  // High bound less than input range.
06383       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
06384     if (Pred == ICmpInst::ICMP_UGT)
06385       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
06386     else
06387       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
06388   }
06389 }
06390 
06391 
06392 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
06393 ///
06394 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
06395                                                           Instruction *LHSI,
06396                                                           ConstantInt *RHS) {
06397   const APInt &RHSV = RHS->getValue();
06398   
06399   switch (LHSI->getOpcode()) {
06400   case Instruction::Trunc:
06401     if (ICI.isEquality() && LHSI->hasOneUse()) {
06402       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
06403       // of the high bits truncated out of x are known.
06404       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
06405              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
06406       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
06407       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
06408       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
06409       
06410       // If all the high bits are known, we can do this xform.
06411       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
06412         // Pull in the high bits from known-ones set.
06413         APInt NewRHS(RHS->getValue());
06414         NewRHS.zext(SrcBits);
06415         NewRHS |= KnownOne;
06416         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
06417                             ConstantInt::get(NewRHS));
06418       }
06419     }
06420     break;
06421       
06422   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
06423     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
06424       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
06425       // fold the xor.
06426       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
06427           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
06428         Value *CompareVal = LHSI->getOperand(0);
06429         
06430         // If the sign bit of the XorCST is not set, there is no change to
06431         // the operation, just stop using the Xor.
06432         if (!XorCST->getValue().isNegative()) {
06433           ICI.setOperand(0, CompareVal);
06434           AddToWorkList(LHSI);
06435           return &ICI;
06436         }
06437         
06438         // Was the old condition true if the operand is positive?
06439         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
06440         
06441         // If so, the new one isn't.
06442         isTrueIfPositive ^= true;
06443         
06444         if (isTrueIfPositive)
06445           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
06446         else
06447           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
06448       }
06449 
06450       if (LHSI->hasOneUse()) {
06451         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
06452         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
06453           const APInt &SignBit = XorCST->getValue();
06454           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
06455                                          ? ICI.getUnsignedPredicate()
06456                                          : ICI.getSignedPredicate();
06457           return new ICmpInst(Pred, LHSI->getOperand(0),
06458                               ConstantInt::get(RHSV ^ SignBit));
06459         }
06460 
06461         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
06462         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
06463           const APInt &NotSignBit = XorCST->getValue();
06464           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
06465                                          ? ICI.getUnsignedPredicate()
06466                                          : ICI.getSignedPredicate();
06467           Pred = ICI.getSwappedPredicate(Pred);
06468           return new ICmpInst(Pred, LHSI->getOperand(0),
06469                               ConstantInt::get(RHSV ^ NotSignBit));
06470         }
06471       }
06472     }
06473     break;
06474   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
06475     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
06476         LHSI->getOperand(0)->hasOneUse()) {
06477       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
06478       
06479       // If the LHS is an AND of a truncating cast, we can widen the
06480       // and/compare to be the input width without changing the value
06481       // produced, eliminating a cast.
06482       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
06483         // We can do this transformation if either the AND constant does not
06484         // have its sign bit set or if it is an equality comparison. 
06485         // Extending a relational comparison when we're checking the sign
06486         // bit would not work.
06487         if (Cast->hasOneUse() &&
06488             (ICI.isEquality() ||
06489              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
06490           uint32_t BitWidth = 
06491             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
06492           APInt NewCST = AndCST->getValue();
06493           NewCST.zext(BitWidth);
06494           APInt NewCI = RHSV;
06495           NewCI.zext(BitWidth);
06496           Instruction *NewAnd = 
06497             BinaryOperator::CreateAnd(Cast->getOperand(0),
06498                                       ConstantInt::get(NewCST),LHSI->getName());
06499           InsertNewInstBefore(NewAnd, ICI);
06500           return new ICmpInst(ICI.getPredicate(), NewAnd,
06501                               ConstantInt::get(NewCI));
06502         }
06503       }
06504       
06505       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
06506       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
06507       // happens a LOT in code produced by the C front-end, for bitfield
06508       // access.
06509       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
06510       if (Shift && !Shift->isShift())
06511         Shift = 0;
06512       
06513       ConstantInt *ShAmt;
06514       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
06515       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
06516       const Type *AndTy = AndCST->getType();          // Type of the and.
06517       
06518       // We can fold this as long as we can't shift unknown bits
06519       // into the mask.  This can only happen with signed shift
06520       // rights, as they sign-extend.
06521       if (ShAmt) {
06522         bool CanFold = Shift->isLogicalShift();
06523         if (!CanFold) {
06524           // To test for the bad case of the signed shr, see if any
06525           // of the bits shifted in could be tested after the mask.
06526           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
06527           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
06528           
06529           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
06530           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
06531                AndCST->getValue()) == 0)
06532             CanFold = true;
06533         }
06534         
06535         if (CanFold) {
06536           Constant *NewCst;
06537           if (Shift->getOpcode() == Instruction::Shl)
06538             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
06539           else
06540             NewCst = ConstantExpr::getShl(RHS, ShAmt);
06541           
06542           // Check to see if we are shifting out any of the bits being
06543           // compared.
06544           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
06545             // If we shifted bits out, the fold is not going to work out.
06546             // As a special case, check to see if this means that the
06547             // result is always true or false now.
06548             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
06549               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
06550             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
06551               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
06552           } else {
06553             ICI.setOperand(1, NewCst);
06554             Constant *NewAndCST;
06555             if (Shift->getOpcode() == Instruction::Shl)
06556               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
06557             else
06558               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
06559             LHSI->setOperand(1, NewAndCST);
06560             LHSI->setOperand(0, Shift->getOperand(0));
06561             AddToWorkList(Shift); // Shift is dead.
06562             AddUsesToWorkList(ICI);
06563             return &ICI;
06564           }
06565         }
06566       }
06567       
06568       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
06569       // preferable because it allows the C<<Y expression to be hoisted out
06570       // of a loop if Y is invariant and X is not.
06571       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
06572           ICI.isEquality() && !Shift->isArithmeticShift() &&
06573           isa<Instruction>(Shift->getOperand(0))) {
06574         // Compute C << Y.
06575         Value *NS;
06576         if (Shift->getOpcode() == Instruction::LShr) {
06577           NS = BinaryOperator::CreateShl(AndCST, 
06578                                          Shift->getOperand(1), "tmp");
06579         } else {
06580           // Insert a logical shift.
06581           NS = BinaryOperator::CreateLShr(AndCST,
06582                                           Shift->getOperand(1), "tmp");
06583         }
06584         InsertNewInstBefore(cast<Instruction>(NS), ICI);
06585         
06586         // Compute X & (C << Y).
06587         Instruction *NewAnd = 
06588           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
06589         InsertNewInstBefore(NewAnd, ICI);
06590         
06591         ICI.setOperand(0, NewAnd);
06592         return &ICI;
06593       }
06594     }
06595     break;
06596     
06597   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
06598     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
06599     if (!ShAmt) break;
06600     
06601     uint32_t TypeBits = RHSV.getBitWidth();
06602     
06603     // Check that the shift amount is in range.  If not, don't perform
06604     // undefined shifts.  When the shift is visited it will be
06605     // simplified.
06606     if (ShAmt->uge(TypeBits))
06607       break;
06608     
06609     if (ICI.isEquality()) {
06610       // If we are comparing against bits always shifted out, the
06611       // comparison cannot succeed.
06612       Constant *Comp =
06613         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
06614       if (Comp != RHS) {// Comparing against a bit that we know is zero.
06615         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
06616         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
06617         return ReplaceInstUsesWith(ICI, Cst);
06618       }
06619       
06620       if (LHSI->hasOneUse()) {
06621         // Otherwise strength reduce the shift into an and.
06622         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
06623         Constant *Mask =
06624           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
06625         
06626         Instruction *AndI =
06627           BinaryOperator::CreateAnd(LHSI->getOperand(0),
06628                                     Mask, LHSI->getName()+".mask");
06629         Value *And = InsertNewInstBefore(AndI, ICI);
06630         return new ICmpInst(ICI.getPredicate(), And,
06631                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
06632       }
06633     }
06634     
06635     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
06636     bool TrueIfSigned = false;
06637     if (LHSI->hasOneUse() &&
06638         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
06639       // (X << 31) <s 0  --> (X&1) != 0
06640       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
06641                                            (TypeBits-ShAmt->getZExtValue()-1));
06642       Instruction *AndI =
06643         BinaryOperator::CreateAnd(LHSI->getOperand(0),
06644                                   Mask, LHSI->getName()+".mask");
06645       Value *And = InsertNewInstBefore(AndI, ICI);
06646       
06647       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
06648                           And, Constant::getNullValue(And->getType()));
06649     }
06650     break;
06651   }
06652     
06653   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
06654   case Instruction::AShr: {
06655     // Only handle equality comparisons of shift-by-constant.
06656     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
06657     if (!ShAmt || !ICI.isEquality()) break;
06658 
06659     // Check that the shift amount is in range.  If not, don't perform
06660     // undefined shifts.  When the shift is visited it will be
06661     // simplified.
06662     uint32_t TypeBits = RHSV.getBitWidth();
06663     if (ShAmt->uge(TypeBits))
06664       break;
06665     
06666     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
06667       
06668     // If we are comparing against bits always shifted out, the
06669     // comparison cannot succeed.
06670     APInt Comp = RHSV << ShAmtVal;
06671     if (LHSI->getOpcode() == Instruction::LShr)
06672       Comp = Comp.lshr(ShAmtVal);
06673     else
06674       Comp = Comp.ashr(ShAmtVal);
06675     
06676     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
06677       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
06678       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
06679       return ReplaceInstUsesWith(ICI, Cst);
06680     }
06681     
06682     // Otherwise, check to see if the bits shifted out are known to be zero.
06683     // If so, we can compare against the unshifted value:
06684     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
06685     if (LHSI->hasOneUse() &&
06686         MaskedValueIsZero(LHSI->getOperand(0), 
06687                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
06688       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
06689                           ConstantExpr::getShl(RHS, ShAmt));
06690     }
06691       
06692     if (LHSI->hasOneUse()) {
06693       // Otherwise strength reduce the shift into an and.
06694       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
06695       Constant *Mask = ConstantInt::get(Val);
06696       
06697       Instruction *AndI =
06698         BinaryOperator::CreateAnd(LHSI->getOperand(0),
06699                                   Mask, LHSI->getName()+".mask");
06700       Value *And = InsertNewInstBefore(AndI, ICI);
06701       return new ICmpInst(ICI.getPredicate(), And,
06702                           ConstantExpr::getShl(RHS, ShAmt));
06703     }
06704     break;
06705   }
06706     
06707   case Instruction::SDiv:
06708   case Instruction::UDiv:
06709     // Fold: icmp pred ([us]div X, C1), C2 -> range test
06710     // Fold this div into the comparison, producing a range check. 
06711     // Determine, based on the divide type, what the range is being 
06712     // checked.  If there is an overflow on the low or high side, remember 
06713     // it, otherwise compute the range [low, hi) bounding the new value.
06714     // See: InsertRangeTest above for the kinds of replacements possible.
06715     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
06716       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
06717                                           DivRHS))
06718         return R;
06719     break;
06720 
06721   case Instruction::Add:
06722     // Fold: icmp pred (add, X, C1), C2
06723 
06724     if (!ICI.isEquality()) {
06725       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
06726       if (!LHSC) break;
06727       const APInt &LHSV = LHSC->getValue();
06728 
06729       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
06730                             .subtract(LHSV);
06731 
06732       if (ICI.isSignedPredicate()) {
06733         if (CR.getLower().isSignBit()) {
06734           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
06735                               ConstantInt::get(CR.getUpper()));
06736         } else if (CR.getUpper().isSignBit()) {
06737           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
06738                               ConstantInt::get(CR.getLower()));
06739         }
06740       } else {
06741         if (CR.getLower().isMinValue()) {
06742           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
06743                               ConstantInt::get(CR.getUpper()));
06744         } else if (CR.getUpper().isMinValue()) {
06745           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
06746                               ConstantInt::get(CR.getLower()));
06747         }
06748       }
06749     }
06750     break;
06751   }
06752   
06753   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
06754   if (ICI.isEquality()) {
06755     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
06756     
06757     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
06758     // the second operand is a constant, simplify a bit.
06759     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
06760       switch (BO->getOpcode()) {
06761       case Instruction::SRem:
06762         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
06763         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
06764           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
06765           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
06766             Instruction *NewRem =
06767               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
06768                                          BO->getName());
06769             InsertNewInstBefore(NewRem, ICI);
06770             return new ICmpInst(ICI.getPredicate(), NewRem, 
06771                                 Constant::getNullValue(BO->getType()));
06772           }
06773         }
06774         break;
06775       case Instruction::Add:
06776         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
06777         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
06778           if (BO->hasOneUse())
06779             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
06780                                 Subtract(RHS, BOp1C));
06781         } else if (RHSV == 0) {
06782           // Replace ((add A, B) != 0) with (A != -B) if A or B is
06783           // efficiently invertible, or if the add has just this one use.
06784           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
06785           
06786           if (Value *NegVal = dyn_castNegVal(BOp1))
06787             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
06788           else if (Value *NegVal = dyn_castNegVal(BOp0))
06789             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
06790           else if (BO->hasOneUse()) {
06791             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
06792             InsertNewInstBefore(Neg, ICI);
06793             Neg->takeName(BO);
06794             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
06795           }
06796         }
06797         break;
06798       case Instruction::Xor:
06799         // For the xor case, we can xor two constants together, eliminating
06800         // the explicit xor.
06801         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
06802           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
06803                               ConstantExpr::getXor(RHS, BOC));
06804         
06805         // FALLTHROUGH
06806       case Instruction::Sub:
06807         // Replace (([sub|xor] A, B) != 0) with (A != B)
06808         if (RHSV == 0)
06809           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
06810                               BO->getOperand(1));
06811         break;
06812         
06813       case Instruction::Or:
06814         // If bits are being or'd in that are not present in the constant we
06815         // are comparing against, then the comparison could never succeed!
06816         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
06817           Constant *NotCI = ConstantExpr::getNot(RHS);
06818           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
06819             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
06820                                                              isICMP_NE));
06821         }
06822         break;
06823         
06824       case Instruction::And:
06825         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
06826           // If bits are being compared against that are and'd out, then the
06827           // comparison can never succeed!
06828           if ((RHSV & ~BOC->getValue()) != 0)
06829             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
06830                                                              isICMP_NE));
06831           
06832           // If we have ((X & C) == C), turn it into ((X & C) != 0).
06833           if (RHS == BOC && RHSV.isPowerOf2())
06834             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
06835                                 ICmpInst::ICMP_NE, LHSI,
06836                                 Constant::getNullValue(RHS->getType()));
06837           
06838           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
06839           if (BOC->getValue().isSignBit()) {
06840             Value *X = BO->getOperand(0);
06841             Constant *Zero = Constant::getNullValue(X->getType());
06842             ICmpInst::Predicate pred = isICMP_NE ? 
06843               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
06844             return new ICmpInst(pred, X, Zero);
06845           }
06846           
06847           // ((X & ~7) == 0) --> X < 8
06848           if (RHSV == 0 && isHighOnes(BOC)) {
06849             Value *X = BO->getOperand(0);
06850             Constant *NegX = ConstantExpr::getNeg(BOC);
06851             ICmpInst::Predicate pred = isICMP_NE ? 
06852               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
06853             return new ICmpInst(pred, X, NegX);
06854           }
06855         }
06856       default: break;
06857       }
06858     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
06859       // Handle icmp {eq|ne} <intrinsic>, intcst.
06860       if (II->getIntrinsicID() == Intrinsic::bswap) {
06861         AddToWorkList(II);
06862         ICI.setOperand(0, II->getOperand(1));
06863         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
06864         return &ICI;
06865       }
06866     }
06867   }
06868   return 0;
06869 }
06870 
06871 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
06872 /// We only handle extending casts so far.
06873 ///
06874 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
06875   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
06876   Value *LHSCIOp        = LHSCI->getOperand(0);
06877   const Type *SrcTy     = LHSCIOp->getType();
06878   const Type *DestTy    = LHSCI->getType();
06879   Value *RHSCIOp;
06880 
06881   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
06882   // integer type is the same size as the pointer type.
06883   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
06884       getTargetData().getPointerSizeInBits() == 
06885          cast<IntegerType>(DestTy)->getBitWidth()) {
06886     Value *RHSOp = 0;
06887     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
06888       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
06889     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
06890       RHSOp = RHSC->getOperand(0);
06891       // If the pointer types don't match, insert a bitcast.
06892       if (LHSCIOp->getType() != RHSOp->getType())
06893         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
06894     }
06895 
06896     if (RHSOp)
06897       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
06898   }
06899   
06900   // The code below only handles extension cast instructions, so far.
06901   // Enforce this.
06902   if (LHSCI->getOpcode() != Instruction::ZExt &&
06903       LHSCI->getOpcode() != Instruction::SExt)
06904     return 0;
06905 
06906   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
06907   bool isSignedCmp = ICI.isSignedPredicate();
06908 
06909   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
06910     // Not an extension from the same type?
06911     RHSCIOp = CI->getOperand(0);
06912     if (RHSCIOp->getType() != LHSCIOp->getType()) 
06913       return 0;
06914     
06915     // If the signedness of the two casts doesn't agree (i.e. one is a sext
06916     // and the other is a zext), then we can't handle this.
06917     if (CI->getOpcode() != LHSCI->getOpcode())
06918       return 0;
06919 
06920     // Deal with equality cases early.
06921     if (ICI.isEquality())
06922       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
06923 
06924     // A signed comparison of sign extended values simplifies into a
06925     // signed comparison.
06926     if (isSignedCmp && isSignedExt)
06927       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
06928 
06929     // The other three cases all fold into an unsigned comparison.
06930     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
06931   }
06932 
06933   // If we aren't dealing with a constant on the RHS, exit early
06934   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
06935   if (!CI)
06936     return 0;
06937 
06938   // Compute the constant that would happen if we truncated to SrcTy then
06939   // reextended to DestTy.
06940   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
06941   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
06942 
06943   // If the re-extended constant didn't change...
06944   if (Res2 == CI) {
06945     // Make sure that sign of the Cmp and the sign of the Cast are the same.
06946     // For example, we might have:
06947     //    %A = sext short %X to uint
06948     //    %B = icmp ugt uint %A, 1330
06949     // It is incorrect to transform this into 
06950     //    %B = icmp ugt short %X, 1330 
06951     // because %A may have negative value. 
06952     //
06953     // However, we allow this when the compare is EQ/NE, because they are
06954     // signless.
06955     if (isSignedExt == isSignedCmp || ICI.isEquality())
06956       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
06957     return 0;
06958   }
06959 
06960   // The re-extended constant changed so the constant cannot be represented 
06961   // in the shorter type. Consequently, we cannot emit a simple comparison.
06962 
06963   // First, handle some easy cases. We know the result cannot be equal at this
06964   // point so handle the ICI.isEquality() cases
06965   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
06966     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
06967   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
06968     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
06969 
06970   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
06971   // should have been folded away previously and not enter in here.
06972   Value *Result;
06973   if (isSignedCmp) {
06974     // We're performing a signed comparison.
06975     if (cast<ConstantInt>(CI)->getValue().isNegative())
06976       Result = ConstantInt::getFalse();          // X < (small) --> false
06977     else
06978       Result = ConstantInt::getTrue();           // X < (large) --> true
06979   } else {
06980     // We're performing an unsigned comparison.
06981     if (isSignedExt) {
06982       // We're performing an unsigned comp with a sign extended value.
06983       // This is true if the input is >= 0. [aka >s -1]
06984       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
06985       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
06986                                    NegOne, ICI.getName()), ICI);
06987     } else {
06988       // Unsigned extend & unsigned compare -> always true.
06989       Result = ConstantInt::getTrue();
06990     }
06991   }
06992 
06993   // Finally, return the value computed.
06994   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
06995       ICI.getPredicate() == ICmpInst::ICMP_SLT)
06996     return ReplaceInstUsesWith(ICI, Result);
06997 
06998   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
06999           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
07000          "ICmp should be folded!");
07001   if (Constant *CI = dyn_cast<Constant>(Result))
07002     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
07003   return BinaryOperator::CreateNot(Result);
07004 }
07005 
07006 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
07007   return commonShiftTransforms(I);
07008 }
07009 
07010 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
07011   return commonShiftTransforms(I);
07012 }
07013 
07014 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
07015   if (Instruction *R = commonShiftTransforms(I))
07016     return R;
07017   
07018   Value *Op0 = I.getOperand(0);
07019   
07020   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
07021   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
07022     if (CSI->isAllOnesValue())
07023       return ReplaceInstUsesWith(I, CSI);
07024   
07025   // See if we can turn a signed shr into an unsigned shr.
07026   if (!isa<VectorType>(I.getType()) &&
07027       MaskedValueIsZero(Op0,
07028                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
07029     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
07030   
07031   return 0;
07032 }
07033 
07034 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
07035   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
07036   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
07037 
07038   // shl X, 0 == X and shr X, 0 == X
07039   // shl 0, X == 0 and shr 0, X == 0
07040   if (Op1 == Constant::getNullValue(Op1->getType()) ||
07041       Op0 == Constant::getNullValue(Op0->getType()))
07042     return ReplaceInstUsesWith(I, Op0);
07043   
07044   if (isa<UndefValue>(Op0)) {            
07045     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
07046       return ReplaceInstUsesWith(I, Op0);
07047     else                                    // undef << X -> 0, undef >>u X -> 0
07048       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
07049   }
07050   if (isa<UndefValue>(Op1)) {
07051     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
07052       return ReplaceInstUsesWith(I, Op0);          
07053     else                                     // X << undef, X >>u undef -> 0
07054       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
07055   }
07056 
07057   // Try to fold constant and into select arguments.
07058   if (isa<Constant>(Op0))
07059     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
07060       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
07061         return R;
07062 
07063   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
07064     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
07065       return Res;
07066   return 0;
07067 }
07068 
07069 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
07070                                                BinaryOperator &I) {
07071   bool isLeftShift = I.getOpcode() == Instruction::Shl;
07072 
07073   // See if we can simplify any instructions used by the instruction whose sole 
07074   // purpose is to compute bits we don't care about.
07075   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
07076   if (SimplifyDemandedInstructionBits(I))
07077     return &I;
07078   
07079   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
07080   // of a signed value.
07081   //
07082   if (Op1->uge(TypeBits)) {
07083     if (I.getOpcode() != Instruction::AShr)
07084       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
07085     else {
07086       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
07087       return &I;
07088     }
07089   }
07090   
07091   // ((X*C1) << C2) == (X * (C1 << C2))
07092   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
07093     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
07094       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
07095         return BinaryOperator::CreateMul(BO->getOperand(0),
07096                                          ConstantExpr::getShl(BOOp, Op1));
07097   
07098   // Try to fold constant and into select arguments.
07099   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
07100     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
07101       return R;
07102   if (isa<PHINode>(Op0))
07103     if (Instruction *NV = FoldOpIntoPhi(I))
07104       return NV;
07105   
07106   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
07107   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
07108     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
07109     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
07110     // place.  Don't try to do this transformation in this case.  Also, we
07111     // require that the input operand is a shift-by-constant so that we have
07112     // confidence that the shifts will get folded together.  We could do this
07113     // xform in more cases, but it is unlikely to be profitable.
07114     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
07115         isa<ConstantInt>(TrOp->getOperand(1))) {
07116       // Okay, we'll do this xform.  Make the shift of shift.
07117       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
07118       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
07119                                                 I.getName());
07120       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
07121 
07122       // For logical shifts, the truncation has the effect of making the high
07123       // part of the register be zeros.  Emulate this by inserting an AND to
07124       // clear the top bits as needed.  This 'and' will usually be zapped by
07125       // other xforms later if dead.
07126       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
07127       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
07128       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
07129       
07130       // The mask we constructed says what the trunc would do if occurring
07131       // between the shifts.  We want to know the effect *after* the second
07132       // shift.  We know that it is a logical shift by a constant, so adjust the
07133       // mask as appropriate.
07134       if (I.getOpcode() == Instruction::Shl)
07135         MaskV <<= Op1->getZExtValue();
07136       else {
07137         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
07138         MaskV = MaskV.lshr(Op1->getZExtValue());
07139       }
07140 
07141       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
07142                                                    TI->getName());
07143       InsertNewInstBefore(And, I); // shift1 & 0x00FF
07144 
07145       // Return the value truncated to the interesting size.
07146       return new TruncInst(And, I.getType());
07147     }
07148   }
07149   
07150   if (Op0->hasOneUse()) {
07151     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
07152       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
07153       Value *V1, *V2;
07154       ConstantInt *CC;
07155       switch (Op0BO->getOpcode()) {
07156         default: break;
07157         case Instruction::Add:
07158         case Instruction::And:
07159         case Instruction::Or:
07160         case Instruction::Xor: {
07161           // These operators commute.
07162           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
07163           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
07164               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
07165             Instruction *YS = BinaryOperator::CreateShl(
07166                                             Op0BO->getOperand(0), Op1,
07167                                             Op0BO->getName());
07168             InsertNewInstBefore(YS, I); // (Y << C)
07169             Instruction *X = 
07170               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
07171                                      Op0BO->getOperand(1)->getName());
07172             InsertNewInstBefore(X, I);  // (X + (Y << C))
07173             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
07174             return BinaryOperator::CreateAnd(X, ConstantInt::get(
07175                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
07176           }
07177           
07178           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
07179           Value *Op0BOOp1 = Op0BO->getOperand(1);
07180           if (isLeftShift && Op0BOOp1->hasOneUse() &&
07181               match(Op0BOOp1, 
07182                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
07183                           m_ConstantInt(CC))) &&
07184               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
07185             Instruction *YS = BinaryOperator::CreateShl(
07186                                                      Op0BO->getOperand(0), Op1,
07187                                                      Op0BO->getName());
07188             InsertNewInstBefore(YS, I); // (Y << C)
07189             Instruction *XM =
07190               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
07191                                         V1->getName()+".mask");
07192             InsertNewInstBefore(XM, I); // X & (CC << C)
07193             
07194             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
07195           }
07196         }
07197           
07198         // FALL THROUGH.
07199         case Instruction::Sub: {
07200           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
07201           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
07202               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
07203             Instruction *YS = BinaryOperator::CreateShl(
07204                                                      Op0BO->getOperand(1), Op1,
07205                                                      Op0BO->getName());
07206             InsertNewInstBefore(YS, I); // (Y << C)
07207             Instruction *X =
07208               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
07209                                      Op0BO->getOperand(0)->getName());
07210             InsertNewInstBefore(X, I);  // (X + (Y << C))
07211             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
07212             return BinaryOperator::CreateAnd(X, ConstantInt::get(
07213                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
07214           }
07215           
07216           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
07217           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
07218               match(Op0BO->getOperand(0),
07219                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
07220                           m_ConstantInt(CC))) && V2 == Op1 &&
07221               cast<BinaryOperator>(Op0BO->getOperand(0))
07222                   ->getOperand(0)->hasOneUse()) {
07223             Instruction *YS = BinaryOperator::CreateShl(
07224                                                      Op0BO->getOperand(1), Op1,
07225                                                      Op0BO->getName());
07226             InsertNewInstBefore(YS, I); // (Y << C)
07227             Instruction *XM =
07228               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
07229                                         V1->getName()+".mask");
07230             InsertNewInstBefore(XM, I); // X & (CC << C)
07231             
07232             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
07233           }
07234           
07235           break;
07236         }
07237       }
07238       
07239       
07240       // If the operand is an bitwise operator with a constant RHS, and the
07241       // shift is the only use, we can pull it out of the shift.
07242       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
07243         bool isValid = true;     // Valid only for And, Or, Xor
07244         bool highBitSet = false; // Transform if high bit of constant set?
07245         
07246         switch (Op0BO->getOpcode()) {
07247           default: isValid = false; break;   // Do not perform transform!
07248           case Instruction::Add:
07249             isValid = isLeftShift;
07250             break;
07251           case Instruction::Or:
07252           case Instruction::Xor:
07253             highBitSet = false;
07254             break;
07255           case Instruction::And:
07256             highBitSet = true;
07257             break;
07258         }
07259         
07260         // If this is a signed shift right, and the high bit is modified
07261         // by the logical operation, do not perform the transformation.
07262         // The highBitSet boolean indicates the value of the high bit of
07263         // the constant which would cause it to be modified for this
07264         // operation.
07265         //
07266         if (isValid && I.getOpcode() == Instruction::AShr)
07267           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
07268         
07269         if (isValid) {
07270           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
07271           
07272           Instruction *NewShift =
07273             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
07274           InsertNewInstBefore(NewShift, I);
07275           NewShift->takeName(Op0BO);
07276           
07277           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
07278                                         NewRHS);
07279         }
07280       }
07281     }
07282   }
07283   
07284   // Find out if this is a shift of a shift by a constant.
07285   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
07286   if (ShiftOp && !ShiftOp->isShift())
07287     ShiftOp = 0;
07288   
07289   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
07290     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
07291     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
07292     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
07293     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
07294     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
07295     Value *X = ShiftOp->getOperand(0);
07296     
07297     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
07298     if (AmtSum > TypeBits)
07299       AmtSum = TypeBits;
07300     
07301     const IntegerType *Ty = cast<IntegerType>(I.getType());
07302     
07303     // Check for (X << c1) << c2  and  (X >> c1) >> c2
07304     if (I.getOpcode() == ShiftOp->getOpcode()) {
07305       return BinaryOperator::Create(I.getOpcode(), X,
07306                                     ConstantInt::get(Ty, AmtSum));
07307     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
07308                I.getOpcode() == Instruction::AShr) {
07309       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
07310       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
07311     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
07312                I.getOpcode() == Instruction::LShr) {
07313       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
07314       Instruction *Shift =
07315         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
07316       InsertNewInstBefore(Shift, I);
07317 
07318       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
07319       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
07320     }
07321     
07322     // Okay, if we get here, one shift must be left, and the other shift must be
07323     // right.  See if the amounts are equal.
07324     if (ShiftAmt1 == ShiftAmt2) {
07325       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
07326       if (I.getOpcode() == Instruction::Shl) {
07327         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
07328         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
07329       }
07330       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
07331       if (I.getOpcode() == Instruction::LShr) {
07332         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
07333         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
07334       }
07335       // We can simplify ((X << C) >>s C) into a trunc + sext.
07336       // NOTE: we could do this for any C, but that would make 'unusual' integer
07337       // types.  For now, just stick to ones well-supported by the code
07338       // generators.
07339       const Type *SExtType = 0;
07340       switch (Ty->getBitWidth() - ShiftAmt1) {
07341       case 1  :
07342       case 8  :
07343       case 16 :
07344       case 32 :
07345       case 64 :
07346       case 128:
07347         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
07348         break;
07349       default: break;
07350       }
07351       if (SExtType) {
07352         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
07353         InsertNewInstBefore(NewTrunc, I);
07354         return new SExtInst(NewTrunc, Ty);
07355       }
07356       // Otherwise, we can't handle it yet.
07357     } else if (ShiftAmt1 < ShiftAmt2) {
07358       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
07359       
07360       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
07361       if (I.getOpcode() == Instruction::Shl) {
07362         assert(ShiftOp->getOpcode() == Instruction::LShr ||
07363                ShiftOp->getOpcode() == Instruction::AShr);
07364         Instruction *Shift =
07365           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
07366         InsertNewInstBefore(Shift, I);
07367         
07368         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
07369         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
07370       }
07371       
07372       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
07373       if (I.getOpcode() == Instruction::LShr) {
07374         assert(ShiftOp->getOpcode() == Instruction::Shl);
07375         Instruction *Shift =
07376           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
07377         InsertNewInstBefore(Shift, I);
07378         
07379         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
07380         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
07381       }
07382       
07383       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
07384     } else {
07385       assert(ShiftAmt2 < ShiftAmt1);
07386       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
07387 
07388       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
07389       if (I.getOpcode() == Instruction::Shl) {
07390         assert(ShiftOp->getOpcode() == Instruction::LShr ||
07391                ShiftOp->getOpcode() == Instruction::AShr);
07392         Instruction *Shift =
07393           BinaryOperator::Create(ShiftOp->getOpcode(), X,
07394                                  ConstantInt::get(Ty, ShiftDiff));
07395         InsertNewInstBefore(Shift, I);
07396         
07397         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
07398         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
07399       }
07400       
07401       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
07402       if (I.getOpcode() == Instruction::LShr) {
07403         assert(ShiftOp->getOpcode() == Instruction::Shl);
07404         Instruction *Shift =
07405           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
07406         InsertNewInstBefore(Shift, I);
07407         
07408         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
07409         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
07410       }
07411       
07412       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
07413     }
07414   }
07415   return 0;
07416 }
07417 
07418 
07419 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
07420 /// expression.  If so, decompose it, returning some value X, such that Val is
07421 /// X*Scale+Offset.
07422 ///
07423 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
07424                                         int &Offset) {
07425   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
07426   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
07427     Offset = CI->getZExtValue();
07428     Scale  = 0;
07429     return ConstantInt::get(Type::Int32Ty, 0);
07430   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
07431     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
07432       if (I->getOpcode() == Instruction::Shl) {
07433         // This is a value scaled by '1 << the shift amt'.
07434         Scale = 1U << RHS->getZExtValue();
07435         Offset = 0;
07436         return I->getOperand(0);
07437       } else if (I->getOpcode() == Instruction::Mul) {
07438         // This value is scaled by 'RHS'.
07439         Scale = RHS->getZExtValue();
07440         Offset = 0;
07441         return I->getOperand(0);
07442       } else if (I->getOpcode() == Instruction::Add) {
07443         // We have X+C.  Check to see if we really have (X*C2)+C1, 
07444         // where C1 is divisible by C2.
07445         unsigned SubScale;
07446         Value *SubVal = 
07447           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
07448         Offset += RHS->getZExtValue();
07449         Scale = SubScale;
07450         return SubVal;
07451       }
07452     }
07453   }
07454 
07455   // Otherwise, we can't look past this.
07456   Scale = 1;
07457   Offset = 0;
07458   return Val;
07459 }
07460 
07461 
07462 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
07463 /// try to eliminate the cast by moving the type information into the alloc.
07464 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
07465                                                    AllocationInst &AI) {
07466   const PointerType *PTy = cast<PointerType>(CI.getType());
07467   
07468   // Remove any uses of AI that are dead.
07469   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
07470   
07471   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
07472     Instruction *User = cast<Instruction>(*UI++);
07473     if (isInstructionTriviallyDead(User)) {
07474       while (UI != E && *UI == User)
07475         ++UI; // If this instruction uses AI more than once, don't break UI.
07476       
07477       ++NumDeadInst;
07478       DOUT << "IC: DCE: " << *User;
07479       EraseInstFromFunction(*User);
07480     }
07481   }
07482   
07483   // Get the type really allocated and the type casted to.
07484   const Type *AllocElTy = AI.getAllocatedType();
07485   const Type *CastElTy = PTy->getElementType();
07486   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
07487 
07488   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
07489   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
07490   if (CastElTyAlign < AllocElTyAlign) return 0;
07491 
07492   // If the allocation has multiple uses, only promote it if we are strictly
07493   // increasing the alignment of the resultant allocation.  If we keep it the
07494   // same, we open the door to infinite loops of various kinds.
07495   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
07496 
07497   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
07498   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
07499   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
07500 
07501   // See if we can satisfy the modulus by pulling a scale out of the array
07502   // size argument.
07503   unsigned ArraySizeScale;
07504   int ArrayOffset;
07505   Value *NumElements = // See if the array size is a decomposable linear expr.
07506     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
07507  
07508   // If we can now satisfy the modulus, by using a non-1 scale, we really can
07509   // do the xform.
07510   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
07511       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
07512 
07513   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
07514   Value *Amt = 0;
07515   if (Scale == 1) {
07516     Amt = NumElements;
07517   } else {
07518     // If the allocation size is constant, form a constant mul expression
07519     Amt = ConstantInt::get(Type::Int32Ty, Scale);
07520     if (isa<ConstantInt>(NumElements))
07521       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
07522     // otherwise multiply the amount and the number of elements
07523     else if (Scale != 1) {
07524       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
07525       Amt = InsertNewInstBefore(Tmp, AI);
07526     }
07527   }
07528   
07529   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
07530     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
07531     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
07532     Amt = InsertNewInstBefore(Tmp, AI);
07533   }
07534   
07535   AllocationInst *New;
07536   if (isa<MallocInst>(AI))
07537     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
07538   else
07539     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
07540   InsertNewInstBefore(New, AI);
07541   New->takeName(&AI);
07542   
07543   // If the allocation has multiple uses, insert a cast and change all things
07544   // that used it to use the new cast.  This will also hack on CI, but it will
07545   // die soon.
07546   if (!AI.hasOneUse()) {
07547     AddUsesToWorkList(AI);
07548     // New is the allocation instruction, pointer typed. AI is the original
07549     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
07550     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
07551     InsertNewInstBefore(NewCast, AI);
07552     AI.replaceAllUsesWith(NewCast);
07553   }
07554   return ReplaceInstUsesWith(CI, New);
07555 }
07556 
07557 /// CanEvaluateInDifferentType - Return true if we can take the specified value
07558 /// and return it as type Ty without inserting any new casts and without
07559 /// changing the computed value.  This is used by code that tries to decide
07560 /// whether promoting or shrinking integer operations to wider or smaller types
07561 /// will allow us to eliminate a truncate or extend.
07562 ///
07563 /// This is a truncation operation if Ty is smaller than V->getType(), or an
07564 /// extension operation if Ty is larger.
07565 ///
07566 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
07567 /// should return true if trunc(V) can be computed by computing V in the smaller
07568 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
07569 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
07570 /// efficiently truncated.
07571 ///
07572 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
07573 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
07574 /// the final result.
07575 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
07576                                               unsigned CastOpc,
07577                                               int &NumCastsRemoved){
07578   // We can always evaluate constants in another type.
07579   if (isa<ConstantInt>(V))
07580     return true;
07581   
07582   Instruction *I = dyn_cast<Instruction>(V);
07583   if (!I) return false;
07584   
07585   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
07586   
07587   // If this is an extension or truncate, we can often eliminate it.
07588   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
07589     // If this is a cast from the destination type, we can trivially eliminate
07590     // it, and this will remove a cast overall.
07591     if (I->getOperand(0)->getType() == Ty) {
07592       // If the first operand is itself a cast, and is eliminable, do not count
07593       // this as an eliminable cast.  We would prefer to eliminate those two
07594       // casts first.
07595       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
07596         ++NumCastsRemoved;
07597       return true;
07598     }
07599   }
07600 
07601   // We can't extend or shrink something that has multiple uses: doing so would
07602   // require duplicating the instruction in general, which isn't profitable.
07603   if (!I->hasOneUse()) return false;
07604 
07605   unsigned Opc = I->getOpcode();
07606   switch (Opc) {
07607   case Instruction::Add:
07608   case Instruction::Sub:
07609   case Instruction::Mul:
07610   case Instruction::And:
07611   case Instruction::Or:
07612   case Instruction::Xor:
07613     // These operators can all arbitrarily be extended or truncated.
07614     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
07615                                       NumCastsRemoved) &&
07616            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
07617                                       NumCastsRemoved);
07618 
07619   case Instruction::Shl:
07620     // If we are truncating the result of this SHL, and if it's a shift of a
07621     // constant amount, we can always perform a SHL in a smaller type.
07622     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
07623       uint32_t BitWidth = Ty->getBitWidth();
07624       if (BitWidth < OrigTy->getBitWidth() && 
07625           CI->getLimitedValue(BitWidth) < BitWidth)
07626         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
07627                                           NumCastsRemoved);
07628     }
07629     break;
07630   case Instruction::LShr:
07631     // If this is a truncate of a logical shr, we can truncate it to a smaller
07632     // lshr iff we know that the bits we would otherwise be shifting in are
07633     // already zeros.
07634     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
07635       uint32_t OrigBitWidth = OrigTy->getBitWidth();
07636       uint32_t BitWidth = Ty->getBitWidth();
07637       if (BitWidth < OrigBitWidth &&
07638           MaskedValueIsZero(I->getOperand(0),
07639             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
07640           CI->getLimitedValue(BitWidth) < BitWidth) {
07641         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
07642                                           NumCastsRemoved);
07643       }
07644     }
07645     break;
07646   case Instruction::ZExt:
07647   case Instruction::SExt:
07648   case Instruction::Trunc:
07649     // If this is the same kind of case as our original (e.g. zext+zext), we
07650     // can safely replace it.  Note that replacing it does not reduce the number
07651     // of casts in the input.
07652     if (Opc == CastOpc)
07653       return true;
07654 
07655     // sext (zext ty1), ty2 -> zext ty2
07656     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
07657       return true;
07658     break;
07659   case Instruction::Select: {
07660     SelectInst *SI = cast<SelectInst>(I);
07661     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
07662                                       NumCastsRemoved) &&
07663            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
07664                                       NumCastsRemoved);
07665   }
07666   case Instruction::PHI: {
07667     // We can change a phi if we can change all operands.
07668     PHINode *PN = cast<PHINode>(I);
07669     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
07670       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
07671                                       NumCastsRemoved))
07672         return false;
07673     return true;
07674   }
07675   default:
07676     // TODO: Can handle more cases here.
07677     break;
07678   }
07679   
07680   return false;
07681 }
07682 
07683 /// EvaluateInDifferentType - Given an expression that 
07684 /// CanEvaluateInDifferentType returns true for, actually insert the code to
07685 /// evaluate the expression.
07686 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
07687                                              bool isSigned) {
07688   if (Constant *C = dyn_cast<Constant>(V))
07689     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
07690 
07691   // Otherwise, it must be an instruction.
07692   Instruction *I = cast<Instruction>(V);
07693   Instruction *Res = 0;
07694   unsigned Opc = I->getOpcode();
07695   switch (Opc) {
07696   case Instruction::Add:
07697   case Instruction::Sub:
07698   case Instruction::Mul:
07699   case Instruction::And:
07700   case Instruction::Or:
07701   case Instruction::Xor:
07702   case Instruction::AShr:
07703   case Instruction::LShr:
07704   case Instruction::Shl: {
07705     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
07706     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
07707     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
07708     break;
07709   }    
07710   case Instruction::Trunc:
07711   case Instruction::ZExt:
07712   case Instruction::SExt:
07713     // If the source type of the cast is the type we're trying for then we can
07714     // just return the source.  There's no need to insert it because it is not
07715     // new.
07716     if (I->getOperand(0)->getType() == Ty)
07717       return I->getOperand(0);
07718     
07719     // Otherwise, must be the same type of cast, so just reinsert a new one.
07720     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
07721                            Ty);
07722     break;
07723   case Instruction::Select: {
07724     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
07725     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
07726     Res = SelectInst::Create(I->getOperand(0), True, False);
07727     break;
07728   }
07729   case Instruction::PHI: {
07730     PHINode *OPN = cast<PHINode>(I);
07731     PHINode *NPN = PHINode::Create(Ty);
07732     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
07733       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
07734       NPN->addIncoming(V, OPN->getIncomingBlock(i));
07735     }
07736     Res = NPN;
07737     break;
07738   }
07739   default: 
07740     // TODO: Can handle more cases here.
07741     assert(0 && "Unreachable!");
07742     break;
07743   }
07744   
07745   Res->takeName(I);
07746   return InsertNewInstBefore(Res, *I);
07747 }
07748 
07749 /// @brief Implement the transforms common to all CastInst visitors.
07750 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
07751   Value *Src = CI.getOperand(0);
07752 
07753   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
07754   // eliminate it now.
07755   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
07756     if (Instruction::CastOps opc = 
07757         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
07758       // The first cast (CSrc) is eliminable so we need to fix up or replace
07759       // the second cast (CI). CSrc will then have a good chance of being dead.
07760       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
07761     }
07762   }
07763 
07764   // If we are casting a select then fold the cast into the select
07765   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
07766     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
07767       return NV;
07768 
07769   // If we are casting a PHI then fold the cast into the PHI
07770   if (isa<PHINode>(Src))
07771     if (Instruction *NV = FoldOpIntoPhi(CI))
07772       return NV;
07773   
07774   return 0;
07775 }
07776 
07777 /// FindElementAtOffset - Given a type and a constant offset, determine whether
07778 /// or not there is a sequence of GEP indices into the type that will land us at
07779 /// the specified offset.  If so, fill them into NewIndices and return the
07780 /// resultant element type, otherwise return null.
07781 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
07782                                        SmallVectorImpl<Value*> &NewIndices,
07783                                        const TargetData *TD) {
07784   if (!Ty->isSized()) return 0;
07785   
07786   // Start with the index over the outer type.  Note that the type size
07787   // might be zero (even if the offset isn't zero) if the indexed type
07788   // is something like [0 x {int, int}]
07789   const Type *IntPtrTy = TD->getIntPtrType();
07790   int64_t FirstIdx = 0;
07791   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
07792     FirstIdx = Offset/TySize;
07793     Offset -= FirstIdx*TySize;
07794     
07795     // Handle hosts where % returns negative instead of values [0..TySize).
07796     if (Offset < 0) {
07797       --FirstIdx;
07798       Offset += TySize;
07799       assert(Offset >= 0);
07800     }
07801     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
07802   }
07803   
07804   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
07805     
07806   // Index into the types.  If we fail, set OrigBase to null.
07807   while (Offset) {
07808     // Indexing into tail padding between struct/array elements.
07809     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
07810       return 0;
07811     
07812     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
07813       const StructLayout *SL = TD->getStructLayout(STy);
07814       assert(Offset < (int64_t)SL->getSizeInBytes() &&
07815              "Offset must stay within the indexed type");
07816       
07817       unsigned Elt = SL->getElementContainingOffset(Offset);
07818       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
07819       
07820       Offset -= SL->getElementOffset(Elt);
07821       Ty = STy->getElementType(Elt);
07822     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
07823       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
07824       assert(EltSize && "Cannot index into a zero-sized array");
07825       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
07826       Offset %= EltSize;
07827       Ty = AT->getElementType();
07828     } else {
07829       // Otherwise, we can't index into the middle of this atomic type, bail.
07830       return 0;
07831     }
07832   }
07833   
07834   return Ty;
07835 }
07836 
07837 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
07838 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
07839   Value *Src = CI.getOperand(0);
07840   
07841   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
07842     // If casting the result of a getelementptr instruction with no offset, turn
07843     // this into a cast of the original pointer!
07844     if (GEP->hasAllZeroIndices()) {
07845       // Changing the cast operand is usually not a good idea but it is safe
07846       // here because the pointer operand is being replaced with another 
07847       // pointer operand so the opcode doesn't need to change.
07848       AddToWorkList(GEP);
07849       CI.setOperand(0, GEP->getOperand(0));
07850       return &CI;
07851     }
07852     
07853     // If the GEP has a single use, and the base pointer is a bitcast, and the
07854     // GEP computes a constant offset, see if we can convert these three
07855     // instructions into fewer.  This typically happens with unions and other
07856     // non-type-safe code.
07857     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
07858       if (GEP->hasAllConstantIndices()) {
07859         // We are guaranteed to get a constant from EmitGEPOffset.
07860         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
07861         int64_t Offset = OffsetV->getSExtValue();
07862         
07863         // Get the base pointer input of the bitcast, and the type it points to.
07864         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
07865         const Type *GEPIdxTy =
07866           cast<PointerType>(OrigBase->getType())->getElementType();
07867         SmallVector<Value*, 8> NewIndices;
07868         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
07869           // If we were able to index down into an element, create the GEP
07870           // and bitcast the result.  This eliminates one bitcast, potentially
07871           // two.
07872           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
07873                                                         NewIndices.begin(),
07874                                                         NewIndices.end(), "");
07875           InsertNewInstBefore(NGEP, CI);
07876           NGEP->takeName(GEP);
07877           
07878           if (isa<BitCastInst>(CI))
07879             return new BitCastInst(NGEP, CI.getType());
07880           assert(isa<PtrToIntInst>(CI));
07881           return new PtrToIntInst(NGEP, CI.getType());
07882         }
07883       }      
07884     }
07885   }
07886     
07887   return commonCastTransforms(CI);
07888 }
07889 
07890 
07891 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
07892 /// integer types. This function implements the common transforms for all those
07893 /// cases.
07894 /// @brief Implement the transforms common to CastInst with integer operands
07895 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
07896   if (Instruction *Result = commonCastTransforms(CI))
07897     return Result;
07898 
07899   Value *Src = CI.getOperand(0);
07900   const Type *SrcTy = Src->getType();
07901   const Type *DestTy = CI.getType();
07902   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
07903   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
07904 
07905   // See if we can simplify any instructions used by the LHS whose sole 
07906   // purpose is to compute bits we don't care about.
07907   if (SimplifyDemandedInstructionBits(CI))
07908     return &CI;
07909 
07910   // If the source isn't an instruction or has more than one use then we
07911   // can't do anything more. 
07912   Instruction *SrcI = dyn_cast<Instruction>(Src);
07913   if (!SrcI || !Src->hasOneUse())
07914     return 0;
07915 
07916   // Attempt to propagate the cast into the instruction for int->int casts.
07917   int NumCastsRemoved = 0;
07918   if (!isa<BitCastInst>(CI) &&
07919       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
07920                                  CI.getOpcode(), NumCastsRemoved)) {
07921     // If this cast is a truncate, evaluting in a different type always
07922     // eliminates the cast, so it is always a win.  If this is a zero-extension,
07923     // we need to do an AND to maintain the clear top-part of the computation,
07924     // so we require that the input have eliminated at least one cast.  If this
07925     // is a sign extension, we insert two new casts (to do the extension) so we
07926     // require that two casts have been eliminated.
07927     bool DoXForm = false;
07928     bool JustReplace = false;
07929     switch (CI.getOpcode()) {
07930     default:
07931       // All the others use floating point so we shouldn't actually 
07932       // get here because of the check above.
07933       assert(0 && "Unknown cast type");
07934     case Instruction::Trunc:
07935       DoXForm = true;
07936       break;
07937     case Instruction::ZExt: {
07938       DoXForm = NumCastsRemoved >= 1;
07939       if (!DoXForm && 0) {
07940         // If it's unnecessary to issue an AND to clear the high bits, it's
07941         // always profitable to do this xform.
07942         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
07943         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
07944         if (MaskedValueIsZero(TryRes, Mask))
07945           return ReplaceInstUsesWith(CI, TryRes);
07946         
07947         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
07948           if (TryI->use_empty())
07949             EraseInstFromFunction(*TryI);
07950       }
07951       break;
07952     }
07953     case Instruction::SExt: {
07954       DoXForm = NumCastsRemoved >= 2;
07955       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
07956         // If we do not have to emit the truncate + sext pair, then it's always
07957         // profitable to do this xform.
07958         //
07959         // It's not safe to eliminate the trunc + sext pair if one of the
07960         // eliminated cast is a truncate. e.g.
07961         // t2 = trunc i32 t1 to i16
07962         // t3 = sext i16 t2 to i32
07963         // !=
07964         // i32 t1
07965         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
07966         unsigned NumSignBits = ComputeNumSignBits(TryRes);
07967         if (NumSignBits > (DestBitSize - SrcBitSize))
07968           return ReplaceInstUsesWith(CI, TryRes);
07969         
07970         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
07971           if (TryI->use_empty())
07972             EraseInstFromFunction(*TryI);
07973       }
07974       break;
07975     }
07976     }
07977     
07978     if (DoXForm) {
07979       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
07980            << " cast: " << CI;
07981       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
07982                                            CI.getOpcode() == Instruction::SExt);
07983       if (JustReplace)
07984         // Just replace this cast with the result.
07985         return ReplaceInstUsesWith(CI, Res);
07986 
07987       assert(Res->getType() == DestTy);
07988       switch (CI.getOpcode()) {
07989       default: assert(0 && "Unknown cast type!");
07990       case Instruction::Trunc:
07991       case Instruction::BitCast:
07992         // Just replace this cast with the result.
07993         return ReplaceInstUsesWith(CI, Res);
07994       case Instruction::ZExt: {
07995         assert(SrcBitSize < DestBitSize && "Not a zext?");
07996 
07997         // If the high bits are already zero, just replace this cast with the
07998         // result.
07999         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
08000         if (MaskedValueIsZero(Res, Mask))
08001           return ReplaceInstUsesWith(CI, Res);
08002 
08003         // We need to emit an AND to clear the high bits.
08004         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
08005                                                             SrcBitSize));
08006         return BinaryOperator::CreateAnd(Res, C);
08007       }
08008       case Instruction::SExt: {
08009         // If the high bits are already filled with sign bit, just replace this
08010         // cast with the result.
08011         unsigned NumSignBits = ComputeNumSignBits(Res);
08012         if (NumSignBits > (DestBitSize - SrcBitSize))
08013           return ReplaceInstUsesWith(CI, Res);
08014 
08015         // We need to emit a cast to truncate, then a cast to sext.
08016         return CastInst::Create(Instruction::SExt,
08017             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
08018                              CI), DestTy);
08019       }
08020       }
08021     }
08022   }
08023   
08024   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
08025   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
08026 
08027   switch (SrcI->getOpcode()) {
08028   case Instruction::Add:
08029   case Instruction::Mul:
08030   case Instruction::And:
08031   case Instruction::Or:
08032   case Instruction::Xor:
08033     // If we are discarding information, rewrite.
08034     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
08035       // Don't insert two casts if they cannot be eliminated.  We allow 
08036       // two casts to be inserted if the sizes are the same.  This could 
08037       // only be converting signedness, which is a noop.
08038       if (DestBitSize == SrcBitSize || 
08039           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
08040           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
08041         Instruction::CastOps opcode = CI.getOpcode();
08042         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
08043         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
08044         return BinaryOperator::Create(
08045             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
08046       }
08047     }
08048 
08049     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
08050     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
08051         SrcI->getOpcode() == Instruction::Xor &&
08052         Op1 == ConstantInt::getTrue() &&
08053         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
08054       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
08055       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
08056     }
08057     break;
08058   case Instruction::SDiv:
08059   case Instruction::UDiv:
08060   case Instruction::SRem:
08061   case Instruction::URem:
08062     // If we are just changing the sign, rewrite.
08063     if (DestBitSize == SrcBitSize) {
08064       // Don't insert two casts if they cannot be eliminated.  We allow 
08065       // two casts to be inserted if the sizes are the same.  This could 
08066       // only be converting signedness, which is a noop.
08067       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
08068           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
08069         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
08070                                        Op0, DestTy, *SrcI);
08071         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
08072                                        Op1, DestTy, *SrcI);
08073         return BinaryOperator::Create(
08074           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
08075       }
08076     }
08077     break;
08078 
08079   case Instruction::Shl:
08080     // Allow changing the sign of the source operand.  Do not allow 
08081     // changing the size of the shift, UNLESS the shift amount is a 
08082     // constant.  We must not change variable sized shifts to a smaller 
08083     // size, because it is undefined to shift more bits out than exist 
08084     // in the value.
08085     if (DestBitSize == SrcBitSize ||
08086         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
08087       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
08088           Instruction::BitCast : Instruction::Trunc);
08089       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
08090       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
08091       return BinaryOperator::CreateShl(Op0c, Op1c);
08092     }
08093     break;
08094   case Instruction::AShr:
08095     // If this is a signed shr, and if all bits shifted in are about to be
08096     // truncated off, turn it into an unsigned shr to allow greater
08097     // simplifications.
08098     if (DestBitSize < SrcBitSize &&
08099         isa<ConstantInt>(Op1)) {
08100       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
08101       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
08102         // Insert the new logical shift right.
08103         return BinaryOperator::CreateLShr(Op0, Op1);
08104       }
08105     }
08106     break;
08107   }
08108   return 0;
08109 }
08110 
08111 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
08112   if (Instruction *Result = commonIntCastTransforms(CI))
08113     return Result;
08114   
08115   Value *Src = CI.getOperand(0);
08116   const Type *Ty = CI.getType();
08117   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
08118   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
08119   
08120   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
08121     switch (SrcI->getOpcode()) {
08122     default: break;
08123     case Instruction::LShr:
08124       // We can shrink lshr to something smaller if we know the bits shifted in
08125       // are already zeros.
08126       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
08127         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
08128         
08129         // Get a mask for the bits shifting in.
08130         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
08131         Value* SrcIOp0 = SrcI->getOperand(0);
08132         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
08133           if (ShAmt >= DestBitWidth)        // All zeros.
08134             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
08135 
08136           // Okay, we can shrink this.  Truncate the input, then return a new
08137           // shift.
08138           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
08139           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
08140                                        Ty, CI);
08141           return BinaryOperator::CreateLShr(V1, V2);
08142         }
08143       } else {     // This is a variable shr.
08144         
08145         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
08146         // more LLVM instructions, but allows '1 << Y' to be hoisted if
08147         // loop-invariant and CSE'd.
08148         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
08149           Value *One = ConstantInt::get(SrcI->getType(), 1);
08150 
08151           Value *V = InsertNewInstBefore(
08152               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
08153                                      "tmp"), CI);
08154           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
08155                                                             SrcI->getOperand(0),
08156                                                             "tmp"), CI);
08157           Value *Zero = Constant::getNullValue(V->getType());
08158           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
08159         }
08160       }
08161       break;
08162     }
08163   }
08164   
08165   return 0;
08166 }
08167 
08168 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
08169 /// in order to eliminate the icmp.
08170 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
08171                                              bool DoXform) {
08172   // If we are just checking for a icmp eq of a single bit and zext'ing it
08173   // to an integer, then shift the bit to the appropriate place and then
08174   // cast to integer to avoid the comparison.
08175   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
08176     const APInt &Op1CV = Op1C->getValue();
08177       
08178     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
08179     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
08180     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
08181         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
08182       if (!DoXform) return ICI;
08183 
08184       Value *In = ICI->getOperand(0);
08185       Value *Sh = ConstantInt::get(In->getType(),
08186                                    In->getType()->getPrimitiveSizeInBits()-1);
08187       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
08188                                                         In->getName()+".lobit"),
08189                                CI);
08190       if (In->getType() != CI.getType())
08191         In = CastInst::CreateIntegerCast(In, CI.getType(),
08192                                          false/*ZExt*/, "tmp", &CI);
08193 
08194       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
08195         Constant *One = ConstantInt::get(In->getType(), 1);
08196         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
08197                                                          In->getName()+".not"),
08198                                  CI);
08199       }
08200 
08201       return ReplaceInstUsesWith(CI, In);
08202     }
08203       
08204       
08205       
08206     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
08207     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
08208     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
08209     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
08210     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
08211     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
08212     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
08213     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
08214     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
08215         // This only works for EQ and NE
08216         ICI->isEquality()) {
08217       // If Op1C some other power of two, convert:
08218       uint32_t BitWidth = Op1C->getType()->getBitWidth();
08219       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
08220       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
08221       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
08222         
08223       APInt KnownZeroMask(~KnownZero);
08224       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
08225         if (!DoXform) return ICI;
08226 
08227         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
08228         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
08229           // (X&4) == 2 --> false
08230           // (X&4) != 2 --> true
08231           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
08232           Res = ConstantExpr::getZExt(Res, CI.getType());
08233           return ReplaceInstUsesWith(CI, Res);
08234         }
08235           
08236         uint32_t ShiftAmt = KnownZeroMask.logBase2();
08237         Value *In = ICI->getOperand(0);
08238         if (ShiftAmt) {
08239           // Perform a logical shr by shiftamt.
08240           // Insert the shift to put the result in the low bit.
08241           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
08242                                   ConstantInt::get(In->getType(), ShiftAmt),
08243                                                    In->getName()+".lobit"), CI);
08244         }
08245           
08246         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
08247           Constant *One = ConstantInt::get(In->getType(), 1);
08248           In = BinaryOperator::CreateXor(In, One, "tmp");
08249           InsertNewInstBefore(cast<Instruction>(In), CI);
08250         }
08251           
08252         if (CI.getType() == In->getType())
08253           return ReplaceInstUsesWith(CI, In);
08254         else
08255           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
08256       }
08257     }
08258   }
08259 
08260   return 0;
08261 }
08262 
08263 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
08264   // If one of the common conversion will work ..
08265   if (Instruction *Result = commonIntCastTransforms(CI))
08266     return Result;
08267 
08268   Value *Src = CI.getOperand(0);
08269 
08270   // If this is a cast of a cast
08271   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
08272     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
08273     // types and if the sizes are just right we can convert this into a logical
08274     // 'and' which will be much cheaper than the pair of casts.
08275     if (isa<TruncInst>(CSrc)) {
08276       // Get the sizes of the types involved
08277       Value *A = CSrc->getOperand(0);
08278       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
08279       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
08280       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
08281       // If we're actually extending zero bits and the trunc is a no-op
08282       if (MidSize < DstSize && SrcSize == DstSize) {
08283         // Replace both of the casts with an And of the type mask.
08284         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
08285         Constant *AndConst = ConstantInt::get(AndValue);
08286         Instruction *And = 
08287           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
08288         // Unfortunately, if the type changed, we need to cast it back.
08289         if (And->getType() != CI.getType()) {
08290           And->setName(CSrc->getName()+".mask");
08291           InsertNewInstBefore(And, CI);
08292           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
08293         }
08294         return And;
08295       }
08296     }
08297   }
08298 
08299   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
08300     return transformZExtICmp(ICI, CI);
08301 
08302   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
08303   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
08304     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
08305     // of the (zext icmp) will be transformed.
08306     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
08307     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
08308     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
08309         (transformZExtICmp(LHS, CI, false) ||
08310          transformZExtICmp(RHS, CI, false))) {
08311       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
08312       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
08313       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
08314     }
08315   }
08316 
08317   return 0;
08318 }
08319 
08320 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
08321   if (Instruction *I = commonIntCastTransforms(CI))
08322     return I;
08323   
08324   Value *Src = CI.getOperand(0);
08325   
08326   // Canonicalize sign-extend from i1 to a select.
08327   if (Src->getType() == Type::Int1Ty)
08328     return SelectInst::Create(Src,
08329                               ConstantInt::getAllOnesValue(CI.getType()),
08330                               Constant::getNullValue(CI.getType()));
08331 
08332   // See if the value being truncated is already sign extended.  If so, just
08333   // eliminate the trunc/sext pair.
08334   if (getOpcode(Src) == Instruction::Trunc) {
08335     Value *Op = cast<User>(Src)->getOperand(0);
08336     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
08337     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
08338     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
08339     unsigned NumSignBits = ComputeNumSignBits(Op);
08340 
08341     if (OpBits == DestBits) {
08342       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
08343       // bits, it is already ready.
08344       if (NumSignBits > DestBits-MidBits)
08345         return ReplaceInstUsesWith(CI, Op);
08346     } else if (OpBits < DestBits) {
08347       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
08348       // bits, just sext from i32.
08349       if (NumSignBits > OpBits-MidBits)
08350         return new SExtInst(Op, CI.getType(), "tmp");
08351     } else {
08352       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
08353       // bits, just truncate to i32.
08354       if (NumSignBits > OpBits-MidBits)
08355         return new TruncInst(Op, CI.getType(), "tmp");
08356     }
08357   }
08358 
08359   // If the input is a shl/ashr pair of a same constant, then this is a sign
08360   // extension from a smaller value.  If we could trust arbitrary bitwidth
08361   // integers, we could turn this into a truncate to the smaller bit and then
08362   // use a sext for the whole extension.  Since we don't, look deeper and check
08363   // for a truncate.  If the source and dest are the same type, eliminate the
08364   // trunc and extend and just do shifts.  For example, turn:
08365   //   %a = trunc i32 %i to i8
08366   //   %b = shl i8 %a, 6
08367   //   %c = ashr i8 %b, 6
08368   //   %d = sext i8 %c to i32
08369   // into:
08370   //   %a = shl i32 %i, 30
08371   //   %d = ashr i32 %a, 30
08372   Value *A = 0;
08373   ConstantInt *BA = 0, *CA = 0;
08374   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
08375                         m_ConstantInt(CA))) &&
08376       BA == CA && isa<TruncInst>(A)) {
08377     Value *I = cast<TruncInst>(A)->getOperand(0);
08378     if (I->getType() == CI.getType()) {
08379       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
08380       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
08381       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
08382       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
08383       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
08384                                                         CI.getName()), CI);
08385       return BinaryOperator::CreateAShr(I, ShAmtV);
08386     }
08387   }
08388   
08389   return 0;
08390 }
08391 
08392 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
08393 /// in the specified FP type without changing its value.
08394 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
08395   bool losesInfo;
08396   APFloat F = CFP->getValueAPF();
08397   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
08398   if (!losesInfo)
08399     return ConstantFP::get(F);
08400   return 0;
08401 }
08402 
08403 /// LookThroughFPExtensions - If this is an fp extension instruction, look
08404 /// through it until we get the source value.
08405 static Value *LookThroughFPExtensions(Value *V) {
08406   if (Instruction *I = dyn_cast<Instruction>(V))
08407     if (I->getOpcode() == Instruction::FPExt)
08408       return LookThroughFPExtensions(I->getOperand(0));
08409   
08410   // If this value is a constant, return the constant in the smallest FP type
08411   // that can accurately represent it.  This allows us to turn
08412   // (float)((double)X+2.0) into x+2.0f.
08413   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
08414     if (CFP->getType() == Type::PPC_FP128Ty)
08415       return V;  // No constant folding of this.
08416     // See if the value can be truncated to float and then reextended.
08417     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
08418       return V;
08419     if (CFP->getType() == Type::DoubleTy)
08420       return V;  // Won't shrink.
08421     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
08422       return V;
08423     // Don't try to shrink to various long double types.
08424   }
08425   
08426   return V;
08427 }
08428 
08429 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
08430   if (Instruction *I = commonCastTransforms(CI))
08431     return I;
08432   
08433   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
08434   // smaller than the destination type, we can eliminate the truncate by doing
08435   // the add as the smaller type.  This applies to add/sub/mul/div as well as
08436   // many builtins (sqrt, etc).
08437   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
08438   if (OpI && OpI->hasOneUse()) {
08439     switch (OpI->getOpcode()) {
08440     default: break;
08441     case Instruction::Add:
08442     case Instruction::Sub:
08443     case Instruction::Mul:
08444     case Instruction::FDiv:
08445     case Instruction::FRem:
08446       const Type *SrcTy = OpI->getType();
08447       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
08448       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
08449       if (LHSTrunc->getType() != SrcTy && 
08450           RHSTrunc->getType() != SrcTy) {
08451         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
08452         // If the source types were both smaller than the destination type of
08453         // the cast, do this xform.
08454         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
08455             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
08456           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
08457                                       CI.getType(), CI);
08458           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
08459                                       CI.getType(), CI);
08460           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
08461         }
08462       }
08463       break;  
08464     }
08465   }
08466   return 0;
08467 }
08468 
08469 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
08470   return commonCastTransforms(CI);
08471 }
08472 
08473 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
08474   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
08475   if (OpI == 0)
08476     return commonCastTransforms(FI);
08477 
08478   // fptoui(uitofp(X)) --> X
08479   // fptoui(sitofp(X)) --> X
08480   // This is safe if the intermediate type has enough bits in its mantissa to
08481   // accurately represent all values of X.  For example, do not do this with
08482   // i64->float->i64.  This is also safe for sitofp case, because any negative
08483   // 'X' value would cause an undefined result for the fptoui. 
08484   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
08485       OpI->getOperand(0)->getType() == FI.getType() &&
08486       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
08487                     OpI->getType()->getFPMantissaWidth())
08488     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
08489 
08490   return commonCastTransforms(FI);
08491 }
08492 
08493 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
08494   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
08495   if (OpI == 0)
08496     return commonCastTransforms(FI);
08497   
08498   // fptosi(sitofp(X)) --> X
08499   // fptosi(uitofp(X)) --> X
08500   // This is safe if the intermediate type has enough bits in its mantissa to
08501   // accurately represent all values of X.  For example, do not do this with
08502   // i64->float->i64.  This is also safe for sitofp case, because any negative
08503   // 'X' value would cause an undefined result for the fptoui. 
08504   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
08505       OpI->getOperand(0)->getType() == FI.getType() &&
08506       (int)FI.getType()->getPrimitiveSizeInBits() <= 
08507                     OpI->getType()->getFPMantissaWidth())
08508     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
08509   
08510   return commonCastTransforms(FI);
08511 }
08512 
08513 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
08514   return commonCastTransforms(CI);
08515 }
08516 
08517 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
08518   return commonCastTransforms(CI);
08519 }
08520 
08521 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
08522   return commonPointerCastTransforms(CI);
08523 }
08524 
08525 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
08526   if (Instruction *I = commonCastTransforms(CI))
08527     return I;
08528   
08529   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
08530   if (!DestPointee->isSized()) return 0;
08531 
08532   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
08533   ConstantInt *Cst;
08534   Value *X;
08535   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
08536                                     m_ConstantInt(Cst)))) {
08537     // If the source and destination operands have the same type, see if this
08538     // is a single-index GEP.
08539     if (X->getType() == CI.getType()) {
08540       // Get the size of the pointee type.
08541       uint64_t Size = TD->getTypePaddedSize(DestPointee);
08542 
08543       // Convert the constant to intptr type.
08544       APInt Offset = Cst->getValue();
08545       Offset.sextOrTrunc(TD->getPointerSizeInBits());
08546 
08547       // If Offset is evenly divisible by Size, we can do this xform.
08548       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
08549         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
08550         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
08551       }
08552     }
08553     // TODO: Could handle other cases, e.g. where add is indexing into field of
08554     // struct etc.
08555   } else if (CI.getOperand(0)->hasOneUse() &&
08556              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
08557     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
08558     // "inttoptr+GEP" instead of "add+intptr".
08559     
08560     // Get the size of the pointee type.
08561     uint64_t Size = TD->getTypePaddedSize(DestPointee);
08562     
08563     // Convert the constant to intptr type.
08564     APInt Offset = Cst->getValue();
08565     Offset.sextOrTrunc(TD->getPointerSizeInBits());
08566     
08567     // If Offset is evenly divisible by Size, we can do this xform.
08568     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
08569       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
08570       
08571       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
08572                                                             "tmp"), CI);
08573       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
08574     }
08575   }
08576   return 0;
08577 }
08578 
08579 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
08580   // If the operands are integer typed then apply the integer transforms,
08581   // otherwise just apply the common ones.
08582   Value *Src = CI.getOperand(0);
08583   const Type *SrcTy = Src->getType();
08584   const Type *DestTy = CI.getType();
08585 
08586   if (SrcTy->isInteger() && DestTy->isInteger()) {
08587     if (Instruction *Result = commonIntCastTransforms(CI))
08588       return Result;
08589   } else if (isa<PointerType>(SrcTy)) {
08590     if (Instruction *I = commonPointerCastTransforms(CI))
08591       return I;
08592   } else {
08593     if (Instruction *Result = commonCastTransforms(CI))
08594       return Result;
08595   }
08596 
08597 
08598   // Get rid of casts from one type to the same type. These are useless and can
08599   // be replaced by the operand.
08600   if (DestTy == Src->getType())
08601     return ReplaceInstUsesWith(CI, Src);
08602 
08603   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
08604     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
08605     const Type *DstElTy = DstPTy->getElementType();
08606     const Type *SrcElTy = SrcPTy->getElementType();
08607     
08608     // If the address spaces don't match, don't eliminate the bitcast, which is
08609     // required for changing types.
08610     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
08611       return 0;
08612     
08613     // If we are casting a malloc or alloca to a pointer to a type of the same
08614     // size, rewrite the allocation instruction to allocate the "right" type.
08615     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
08616       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
08617         return V;
08618     
08619     // If the source and destination are pointers, and this cast is equivalent
08620     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
08621     // This can enhance SROA and other transforms that want type-safe pointers.
08622     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
08623     unsigned NumZeros = 0;
08624     while (SrcElTy != DstElTy && 
08625            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
08626            SrcElTy->getNumContainedTypes() /* not "{}" */) {
08627       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
08628       ++NumZeros;
08629     }
08630 
08631     // If we found a path from the src to dest, create the getelementptr now.
08632     if (SrcElTy == DstElTy) {
08633       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
08634       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
08635                                        ((Instruction*) NULL));
08636     }
08637   }
08638 
08639   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
08640     if (SVI->hasOneUse()) {
08641       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
08642       // a bitconvert to a vector with the same # elts.
08643       if (isa<VectorType>(DestTy) && 
08644           cast<VectorType>(DestTy)->getNumElements() ==
08645                 SVI->getType()->getNumElements() &&
08646           SVI->getType()->getNumElements() ==
08647             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
08648         CastInst *Tmp;
08649         // If either of the operands is a cast from CI.getType(), then
08650         // evaluating the shuffle in the casted destination's type will allow
08651         // us to eliminate at least one cast.
08652         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
08653              Tmp->getOperand(0)->getType() == DestTy) ||
08654             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
08655              Tmp->getOperand(0)->getType() == DestTy)) {
08656           Value *LHS = InsertCastBefore(Instruction::BitCast,
08657                                         SVI->getOperand(0), DestTy, CI);
08658           Value *RHS = InsertCastBefore(Instruction::BitCast,
08659                                         SVI->getOperand(1), DestTy, CI);
08660           // Return a new shuffle vector.  Use the same element ID's, as we
08661           // know the vector types match #elts.
08662           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
08663         }
08664       }
08665     }
08666   }
08667   return 0;
08668 }
08669 
08670 /// GetSelectFoldableOperands - We want to turn code that looks like this:
08671 ///   %C = or %A, %B
08672 ///   %D = select %cond, %C, %A
08673 /// into:
08674 ///   %C = select %cond, %B, 0
08675 ///   %D = or %A, %C
08676 ///
08677 /// Assuming that the specified instruction is an operand to the select, return
08678 /// a bitmask indicating which operands of this instruction are foldable if they
08679 /// equal the other incoming value of the select.
08680 ///
08681 static unsigned GetSelectFoldableOperands(Instruction *I) {
08682   switch (I->getOpcode()) {
08683   case Instruction::Add:
08684   case Instruction::Mul:
08685   case Instruction::And:
08686   case Instruction::Or:
08687   case Instruction::Xor:
08688     return 3;              // Can fold through either operand.
08689   case Instruction::Sub:   // Can only fold on the amount subtracted.
08690   case Instruction::Shl:   // Can only fold on the shift amount.
08691   case Instruction::LShr:
08692   case Instruction::AShr:
08693     return 1;
08694   default:
08695     return 0;              // Cannot fold
08696   }
08697 }
08698 
08699 /// GetSelectFoldableConstant - For the same transformation as the previous
08700 /// function, return the identity constant that goes into the select.
08701 static Constant *GetSelectFoldableConstant(Instruction *I) {
08702   switch (I->getOpcode()) {
08703   default: assert(0 && "This cannot happen!"); abort();
08704   case Instruction::Add:
08705   case Instruction::Sub:
08706   case Instruction::Or:
08707   case Instruction::Xor:
08708   case Instruction::Shl:
08709   case Instruction::LShr:
08710   case Instruction::AShr:
08711     return Constant::getNullValue(I->getType());
08712   case Instruction::And:
08713     return Constant::getAllOnesValue(I->getType());
08714   case Instruction::Mul:
08715     return ConstantInt::get(I->getType(), 1);
08716   }
08717 }
08718 
08719 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
08720 /// have the same opcode and only one use each.  Try to simplify this.
08721 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
08722                                           Instruction *FI) {
08723   if (TI->getNumOperands() == 1) {
08724     // If this is a non-volatile load or a cast from the same type,
08725     // merge.
08726     if (TI->isCast()) {
08727       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
08728         return 0;
08729     } else {
08730       return 0;  // unknown unary op.
08731     }
08732 
08733     // Fold this by inserting a select from the input values.
08734     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
08735                                            FI->getOperand(0), SI.getName()+".v");
08736     InsertNewInstBefore(NewSI, SI);
08737     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
08738                             TI->getType());
08739   }
08740 
08741   // Only handle binary operators here.
08742   if (!isa<BinaryOperator>(TI))
08743     return 0;
08744 
08745   // Figure out if the operations have any operands in common.
08746   Value *MatchOp, *OtherOpT, *OtherOpF;
08747   bool MatchIsOpZero;
08748   if (TI->getOperand(0) == FI->getOperand(0)) {
08749     MatchOp  = TI->getOperand(0);
08750     OtherOpT = TI->getOperand(1);
08751     OtherOpF = FI->getOperand(1);
08752     MatchIsOpZero = true;
08753   } else if (TI->getOperand(1) == FI->getOperand(1)) {
08754     MatchOp  = TI->getOperand(1);
08755     OtherOpT = TI->getOperand(0);
08756     OtherOpF = FI->getOperand(0);
08757     MatchIsOpZero = false;
08758   } else if (!TI->isCommutative()) {
08759     return 0;
08760   } else if (TI->getOperand(0) == FI->getOperand(1)) {
08761     MatchOp  = TI->getOperand(0);
08762     OtherOpT = TI->getOperand(1);
08763     OtherOpF = FI->getOperand(0);
08764     MatchIsOpZero = true;
08765   } else if (TI->getOperand(1) == FI->getOperand(0)) {
08766     MatchOp  = TI->getOperand(1);
08767     OtherOpT = TI->getOperand(0);
08768     OtherOpF = FI->getOperand(1);
08769     MatchIsOpZero = true;
08770   } else {
08771     return 0;
08772   }
08773 
08774   // If we reach here, they do have operations in common.
08775   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
08776                                          OtherOpF, SI.getName()+".v");
08777   InsertNewInstBefore(NewSI, SI);
08778 
08779   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
08780     if (MatchIsOpZero)
08781       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
08782     else
08783       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
08784   }
08785   assert(0 && "Shouldn't get here");
08786   return 0;
08787 }
08788 
08789 /// visitSelectInstWithICmp - Visit a SelectInst that has an
08790 /// ICmpInst as its first operand.
08791 ///
08792 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
08793                                                    ICmpInst *ICI) {
08794   bool Changed = false;
08795   ICmpInst::Predicate Pred = ICI->getPredicate();
08796   Value *CmpLHS = ICI->getOperand(0);
08797   Value *CmpRHS = ICI->getOperand(1);
08798   Value *TrueVal = SI.getTrueValue();
08799   Value *FalseVal = SI.getFalseValue();
08800 
08801   // Check cases where the comparison is with a constant that
08802   // can be adjusted to fit the min/max idiom. We may edit ICI in
08803   // place here, so make sure the select is the only user.
08804   if (ICI->hasOneUse())
08805     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
08806       switch (Pred) {
08807       default: break;
08808       case ICmpInst::ICMP_ULT:
08809       case ICmpInst::ICMP_SLT: {
08810         // X < MIN ? T : F  -->  F
08811         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
08812           return ReplaceInstUsesWith(SI, FalseVal);
08813         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
08814         Constant *AdjustedRHS = SubOne(CI);
08815         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
08816             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
08817           Pred = ICmpInst::getSwappedPredicate(Pred);
08818           CmpRHS = AdjustedRHS;
08819           std::swap(FalseVal, TrueVal);
08820           ICI->setPredicate(Pred);
08821           ICI->setOperand(1, CmpRHS);
08822           SI.setOperand(1, TrueVal);
08823           SI.setOperand(2, FalseVal);
08824           Changed = true;
08825         }
08826         break;
08827       }
08828       case ICmpInst::ICMP_UGT:
08829       case ICmpInst::ICMP_SGT: {
08830         // X > MAX ? T : F  -->  F
08831         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
08832           return ReplaceInstUsesWith(SI, FalseVal);
08833         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
08834         Constant *AdjustedRHS = AddOne(CI);
08835         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
08836             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
08837           Pred = ICmpInst::getSwappedPredicate(Pred);
08838           CmpRHS = AdjustedRHS;
08839           std::swap(FalseVal, TrueVal);
08840           ICI->setPredicate(Pred);
08841           ICI->setOperand(1, CmpRHS);
08842           SI.setOperand(1, TrueVal);
08843           SI.setOperand(2, FalseVal);
08844           Changed = true;
08845         }
08846         break;
08847       }
08848       }
08849 
08850       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
08851       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
08852       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
08853       if (match(TrueVal, m_ConstantInt<-1>()) &&
08854           match(FalseVal, m_ConstantInt<0>()))
08855         Pred = ICI->getPredicate();
08856       else if (match(TrueVal, m_ConstantInt<0>()) &&
08857                match(FalseVal, m_ConstantInt<-1>()))
08858         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
08859       
08860       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
08861         // If we are just checking for a icmp eq of a single bit and zext'ing it
08862         // to an integer, then shift the bit to the appropriate place and then
08863         // cast to integer to avoid the comparison.
08864         const APInt &Op1CV = CI->getValue();
08865     
08866         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
08867         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
08868         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
08869             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
08870           Value *In = ICI->getOperand(0);
08871           Value *Sh = ConstantInt::get(In->getType(),
08872                                        In->getType()->getPrimitiveSizeInBits()-1);
08873           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
08874                                                           In->getName()+".lobit"),
08875                                    *ICI);
08876           if (In->getType() != SI.getType())
08877             In = CastInst::CreateIntegerCast(In, SI.getType(),
08878                                              true/*SExt*/, "tmp", ICI);
08879     
08880           if (Pred == ICmpInst::ICMP_SGT)
08881             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
08882                                        In->getName()+".not"), *ICI);
08883     
08884           return ReplaceInstUsesWith(SI, In);
08885         }
08886       }
08887     }
08888 
08889   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
08890     // Transform (X == Y) ? X : Y  -> Y
08891     if (Pred == ICmpInst::ICMP_EQ)
08892       return ReplaceInstUsesWith(SI, FalseVal);
08893     // Transform (X != Y) ? X : Y  -> X
08894     if (Pred == ICmpInst::ICMP_NE)
08895       return ReplaceInstUsesWith(SI, TrueVal);
08896     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
08897 
08898   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
08899     // Transform (X == Y) ? Y : X  -> X
08900     if (Pred == ICmpInst::ICMP_EQ)
08901       return ReplaceInstUsesWith(SI, FalseVal);
08902     // Transform (X != Y) ? Y : X  -> Y
08903     if (Pred == ICmpInst::ICMP_NE)
08904       return ReplaceInstUsesWith(SI, TrueVal);
08905     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
08906   }
08907 
08908   /// NOTE: if we wanted to, this is where to detect integer ABS
08909 
08910   return Changed ? &SI : 0;
08911 }
08912 
08913 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
08914   Value *CondVal = SI.getCondition();
08915   Value *TrueVal = SI.getTrueValue();
08916   Value *FalseVal = SI.getFalseValue();
08917 
08918   // select true, X, Y  -> X
08919   // select false, X, Y -> Y
08920   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
08921     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
08922 
08923   // select C, X, X -> X
08924   if (TrueVal == FalseVal)
08925     return ReplaceInstUsesWith(SI, TrueVal);
08926 
08927   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
08928     return ReplaceInstUsesWith(SI, FalseVal);
08929   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
08930     return ReplaceInstUsesWith(SI, TrueVal);
08931   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
08932     if (isa<Constant>(TrueVal))
08933       return ReplaceInstUsesWith(SI, TrueVal);
08934     else
08935       return ReplaceInstUsesWith(SI, FalseVal);
08936   }
08937 
08938   if (SI.getType() == Type::Int1Ty) {
08939     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
08940       if (C->getZExtValue()) {
08941         // Change: A = select B, true, C --> A = or B, C
08942         return BinaryOperator::CreateOr(CondVal, FalseVal);
08943       } else {
08944         // Change: A = select B, false, C --> A = and !B, C
08945         Value *NotCond =
08946           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
08947                                              "not."+CondVal->getName()), SI);
08948         return BinaryOperator::CreateAnd(NotCond, FalseVal);
08949       }
08950     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
08951       if (C->getZExtValue() == false) {
08952         // Change: A = select B, C, false --> A = and B, C
08953         return BinaryOperator::CreateAnd(CondVal, TrueVal);
08954       } else {
08955         // Change: A = select B, C, true --> A = or !B, C
08956         Value *NotCond =
08957           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
08958                                              "not."+CondVal->getName()), SI);
08959         return BinaryOperator::CreateOr(NotCond, TrueVal);
08960       }
08961     }
08962     
08963     // select a, b, a  -> a&b
08964     // select a, a, b  -> a|b
08965     if (CondVal == TrueVal)
08966       return BinaryOperator::CreateOr(CondVal, FalseVal);
08967     else if (CondVal == FalseVal)
08968       return BinaryOperator::CreateAnd(CondVal, TrueVal);
08969   }
08970 
08971   // Selecting between two integer constants?
08972   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
08973     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
08974       // select C, 1, 0 -> zext C to int
08975       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
08976         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
08977       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
08978         // select C, 0, 1 -> zext !C to int
08979         Value *NotCond =
08980           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
08981                                                "not."+CondVal->getName()), SI);
08982         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
08983       }
08984 
08985       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
08986 
08987         // (x <s 0) ? -1 : 0 -> ashr x, 31
08988         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
08989           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
08990             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
08991               // The comparison constant and the result are not neccessarily the
08992               // same width. Make an all-ones value by inserting a AShr.
08993               Value *X = IC->getOperand(0);
08994               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
08995               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
08996               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
08997                                                         ShAmt, "ones");
08998               InsertNewInstBefore(SRA, SI);
08999 
09000               // Then cast to the appropriate width.
09001               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
09002             }
09003           }
09004 
09005 
09006         // If one of the constants is zero (we know they can't both be) and we
09007         // have an icmp instruction with zero, and we have an 'and' with the
09008         // non-constant value, eliminate this whole mess.  This corresponds to
09009         // cases like this: ((X & 27) ? 27 : 0)
09010         if (TrueValC->isZero() || FalseValC->isZero())
09011           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
09012               cast<Constant>(IC->getOperand(1))->isNullValue())
09013             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
09014               if (ICA->getOpcode() == Instruction::And &&
09015                   isa<ConstantInt>(ICA->getOperand(1)) &&
09016                   (ICA->getOperand(1) == TrueValC ||
09017                    ICA->getOperand(1) == FalseValC) &&
09018                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
09019                 // Okay, now we know that everything is set up, we just don't
09020                 // know whether we have a icmp_ne or icmp_eq and whether the 
09021                 // true or false val is the zero.
09022                 bool ShouldNotVal = !TrueValC->isZero();
09023                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
09024                 Value *V = ICA;
09025                 if (ShouldNotVal)
09026                   V = InsertNewInstBefore(BinaryOperator::Create(
09027                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
09028                 return ReplaceInstUsesWith(SI, V);
09029               }
09030       }
09031     }
09032 
09033   // See if we are selecting two values based on a comparison of the two values.
09034   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
09035     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
09036       // Transform (X == Y) ? X : Y  -> Y
09037       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
09038         // This is not safe in general for floating point:  
09039         // consider X== -0, Y== +0.
09040         // It becomes safe if either operand is a nonzero constant.
09041         ConstantFP *CFPt, *CFPf;
09042         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
09043               !CFPt->getValueAPF().isZero()) ||
09044             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
09045              !CFPf->getValueAPF().isZero()))
09046         return ReplaceInstUsesWith(SI, FalseVal);
09047       }
09048       // Transform (X != Y) ? X : Y  -> X
09049       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
09050         return ReplaceInstUsesWith(SI, TrueVal);
09051       // NOTE: if we wanted to, this is where to detect MIN/MAX
09052 
09053     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
09054       // Transform (X == Y) ? Y : X  -> X
09055       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
09056         // This is not safe in general for floating point:  
09057         // consider X== -0, Y== +0.
09058         // It becomes safe if either operand is a nonzero constant.
09059         ConstantFP *CFPt, *CFPf;
09060         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
09061               !CFPt->getValueAPF().isZero()) ||
09062             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
09063              !CFPf->getValueAPF().isZero()))
09064           return ReplaceInstUsesWith(SI, FalseVal);
09065       }
09066       // Transform (X != Y) ? Y : X  -> Y
09067       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
09068         return ReplaceInstUsesWith(SI, TrueVal);
09069       // NOTE: if we wanted to, this is where to detect MIN/MAX
09070     }
09071     // NOTE: if we wanted to, this is where to detect ABS
09072   }
09073 
09074   // See if we are selecting two values based on a comparison of the two values.
09075   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
09076     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
09077       return Result;
09078 
09079   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
09080     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
09081       if (TI->hasOneUse() && FI->hasOneUse()) {
09082         Instruction *AddOp = 0, *SubOp = 0;
09083 
09084         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
09085         if (TI->getOpcode() == FI->getOpcode())
09086           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
09087             return IV;
09088 
09089         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
09090         // even legal for FP.
09091         if (TI->getOpcode() == Instruction::Sub &&
09092             FI->getOpcode() == Instruction::Add) {
09093           AddOp = FI; SubOp = TI;
09094         } else if (FI->getOpcode() == Instruction::Sub &&
09095                    TI->getOpcode() == Instruction::Add) {
09096           AddOp = TI; SubOp = FI;
09097         }
09098 
09099         if (AddOp) {
09100           Value *OtherAddOp = 0;
09101           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
09102             OtherAddOp = AddOp->getOperand(1);
09103           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
09104             OtherAddOp = AddOp->getOperand(0);
09105           }
09106 
09107           if (OtherAddOp) {
09108             // So at this point we know we have (Y -> OtherAddOp):
09109             //        select C, (add X, Y), (sub X, Z)
09110             Value *NegVal;  // Compute -Z
09111             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
09112               NegVal = ConstantExpr::getNeg(C);
09113             } else {
09114               NegVal = InsertNewInstBefore(
09115                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
09116             }
09117 
09118             Value *NewTrueOp = OtherAddOp;
09119             Value *NewFalseOp = NegVal;
09120             if (AddOp != TI)
09121               std::swap(NewTrueOp, NewFalseOp);
09122             Instruction *NewSel =
09123               SelectInst::Create(CondVal, NewTrueOp,
09124                                  NewFalseOp, SI.getName() + ".p");
09125 
09126             NewSel = InsertNewInstBefore(NewSel, SI);
09127             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
09128           }
09129         }
09130       }
09131 
09132   // See if we can fold the select into one of our operands.
09133   if (SI.getType()->isInteger()) {
09134     // See the comment above GetSelectFoldableOperands for a description of the
09135     // transformation we are doing here.
09136     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
09137       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
09138           !isa<Constant>(FalseVal))
09139         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
09140           unsigned OpToFold = 0;
09141           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
09142             OpToFold = 1;
09143           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
09144             OpToFold = 2;
09145           }
09146 
09147           if (OpToFold) {
09148             Constant *C = GetSelectFoldableConstant(TVI);
09149             Instruction *NewSel =
09150               SelectInst::Create(SI.getCondition(),
09151                                  TVI->getOperand(2-OpToFold), C);
09152             InsertNewInstBefore(NewSel, SI);
09153             NewSel->takeName(TVI);
09154             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
09155               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
09156             else {
09157               assert(0 && "Unknown instruction!!");
09158             }
09159           }
09160         }
09161 
09162     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
09163       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
09164           !isa<Constant>(TrueVal))
09165         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
09166           unsigned OpToFold = 0;
09167           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
09168             OpToFold = 1;
09169           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
09170             OpToFold = 2;
09171           }
09172 
09173           if (OpToFold) {
09174             Constant *C = GetSelectFoldableConstant(FVI);
09175             Instruction *NewSel =
09176               SelectInst::Create(SI.getCondition(), C,
09177                                  FVI->getOperand(2-OpToFold));
09178             InsertNewInstBefore(NewSel, SI);
09179             NewSel->takeName(FVI);
09180             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
09181               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
09182             else
09183               assert(0 && "Unknown instruction!!");
09184           }
09185         }
09186   }
09187 
09188   if (BinaryOperator::isNot(CondVal)) {
09189     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
09190     SI.setOperand(1, FalseVal);
09191     SI.setOperand(2, TrueVal);
09192     return &SI;
09193   }
09194 
09195   return 0;
09196 }
09197 
09198 /// EnforceKnownAlignment - If the specified pointer points to an object that
09199 /// we control, modify the object's alignment to PrefAlign. This isn't
09200 /// often possible though. If alignment is important, a more reliable approach
09201 /// is to simply align all global variables and allocation instructions to
09202 /// their preferred alignment from the beginning.
09203 ///
09204 static unsigned EnforceKnownAlignment(Value *V,
09205                                       unsigned Align, unsigned PrefAlign) {
09206 
09207   User *U = dyn_cast<User>(V);
09208   if (!U) return Align;
09209 
09210   switch (getOpcode(U)) {
09211   default: break;
09212   case Instruction::BitCast:
09213     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
09214   case Instruction::GetElementPtr: {
09215     // If all indexes are zero, it is just the alignment of the base pointer.
09216     bool AllZeroOperands = true;
09217     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
09218       if (!isa<Constant>(*i) ||
09219           !cast<Constant>(*i)->isNullValue()) {
09220         AllZeroOperands = false;
09221         break;
09222       }
09223 
09224     if (AllZeroOperands) {
09225       // Treat this like a bitcast.
09226       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
09227     }
09228     break;
09229   }
09230   }
09231 
09232   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
09233     // If there is a large requested alignment and we can, bump up the alignment
09234     // of the global.
09235     if (!GV->isDeclaration()) {
09236       GV->setAlignment(PrefAlign);
09237       Align = PrefAlign;
09238     }
09239   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
09240     // If there is a requested alignment and if this is an alloca, round up.  We
09241     // don't do this for malloc, because some systems can't respect the request.
09242     if (isa<AllocaInst>(AI)) {
09243       AI->setAlignment(PrefAlign);
09244       Align = PrefAlign;
09245     }
09246   }
09247 
09248   return Align;
09249 }
09250 
09251 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
09252 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
09253 /// and it is more than the alignment of the ultimate object, see if we can
09254 /// increase the alignment of the ultimate object, making this check succeed.
09255 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
09256                                                   unsigned PrefAlign) {
09257   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
09258                       sizeof(PrefAlign) * CHAR_BIT;
09259   APInt Mask = APInt::getAllOnesValue(BitWidth);
09260   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
09261   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
09262   unsigned TrailZ = KnownZero.countTrailingOnes();
09263   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
09264 
09265   if (PrefAlign > Align)
09266     Align = EnforceKnownAlignment(V, Align, PrefAlign);
09267   
09268     // We don't need to make any adjustment.
09269   return Align;
09270 }
09271 
09272 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
09273   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
09274   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
09275   unsigned MinAlign = std::min(DstAlign, SrcAlign);
09276   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
09277 
09278   if (CopyAlign < MinAlign) {
09279     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
09280     return MI;
09281   }
09282   
09283   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
09284   // load/store.
09285   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
09286   if (MemOpLength == 0) return 0;
09287   
09288   // Source and destination pointer types are always "i8*" for intrinsic.  See
09289   // if the size is something we can handle with a single primitive load/store.
09290   // A single load+store correctly handles overlapping memory in the memmove
09291   // case.
09292   unsigned Size = MemOpLength->getZExtValue();
09293   if (Size == 0) return MI;  // Delete this mem transfer.
09294   
09295   if (Size > 8 || (Size&(Size-1)))
09296     return 0;  // If not 1/2/4/8 bytes, exit.
09297   
09298   // Use an integer load+store unless we can find something better.
09299   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
09300   
09301   // Memcpy forces the use of i8* for the source and destination.  That means
09302   // that if you're using memcpy to move one double around, you'll get a cast
09303   // from double* to i8*.  We'd much rather use a double load+store rather than
09304   // an i64 load+store, here because this improves the odds that the source or
09305   // dest address will be promotable.  See if we can find a better type than the
09306   // integer datatype.
09307   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
09308     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
09309     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
09310       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
09311       // down through these levels if so.
09312       while (!SrcETy->isSingleValueType()) {
09313         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
09314           if (STy->getNumElements() == 1)
09315             SrcETy = STy->getElementType(0);
09316           else
09317             break;
09318         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
09319           if (ATy->getNumElements() == 1)
09320             SrcETy = ATy->getElementType();
09321           else
09322             break;
09323         } else
09324           break;
09325       }
09326       
09327       if (SrcETy->isSingleValueType())
09328         NewPtrTy = PointerType::getUnqual(SrcETy);
09329     }
09330   }
09331   
09332   
09333   // If the memcpy/memmove provides better alignment info than we can
09334   // infer, use it.
09335   SrcAlign = std::max(SrcAlign, CopyAlign);
09336   DstAlign = std::max(DstAlign, CopyAlign);
09337   
09338   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
09339   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
09340   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
09341   InsertNewInstBefore(L, *MI);
09342   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
09343 
09344   // Set the size of the copy to 0, it will be deleted on the next iteration.
09345   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
09346   return MI;
09347 }
09348 
09349 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
09350   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
09351   if (MI->getAlignment()->getZExtValue() < Alignment) {
09352     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
09353     return MI;
09354   }
09355   
09356   // Extract the length and alignment and fill if they are constant.
09357   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
09358   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
09359   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
09360     return 0;
09361   uint64_t Len = LenC->getZExtValue();
09362   Alignment = MI->getAlignment()->getZExtValue();
09363   
09364   // If the length is zero, this is a no-op
09365   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
09366   
09367   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
09368   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
09369     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
09370     
09371     Value *Dest = MI->getDest();
09372     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
09373 
09374     // Alignment 0 is identity for alignment 1 for memset, but not store.
09375     if (Alignment == 0) Alignment = 1;
09376     
09377     // Extract the fill value and store.
09378     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
09379     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
09380                                       Alignment), *MI);
09381     
09382     // Set the size of the copy to 0, it will be deleted on the next iteration.
09383     MI->setLength(Constant::getNullValue(LenC->getType()));
09384     return MI;
09385   }
09386 
09387   return 0;
09388 }
09389 
09390 
09391 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
09392 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
09393 /// the heavy lifting.
09394 ///
09395 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
09396   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
09397   if (!II) return visitCallSite(&CI);
09398   
09399   // Intrinsics cannot occur in an invoke, so handle them here instead of in
09400   // visitCallSite.
09401   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
09402     bool Changed = false;
09403 
09404     // memmove/cpy/set of zero bytes is a noop.
09405     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
09406       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
09407 
09408       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
09409         if (CI->getZExtValue() == 1) {
09410           // Replace the instruction with just byte operations.  We would
09411           // transform other cases to loads/stores, but we don't know if
09412           // alignment is sufficient.
09413         }
09414     }
09415 
09416     // If we have a memmove and the source operation is a constant global,
09417     // then the source and dest pointers can't alias, so we can change this
09418     // into a call to memcpy.
09419     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
09420       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
09421         if (GVSrc->isConstant()) {
09422           Module *M = CI.getParent()->getParent()->getParent();
09423           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
09424           const Type *Tys[1];
09425           Tys[0] = CI.getOperand(3)->getType();
09426           CI.setOperand(0, 
09427                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
09428           Changed = true;
09429         }
09430 
09431       // memmove(x,x,size) -> noop.
09432       if (MMI->getSource() == MMI->getDest())
09433         return EraseInstFromFunction(CI);
09434     }
09435 
09436     // If we can determine a pointer alignment that is bigger than currently
09437     // set, update the alignment.
09438     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
09439       if (Instruction *I = SimplifyMemTransfer(MI))
09440         return I;
09441     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
09442       if (Instruction *I = SimplifyMemSet(MSI))
09443         return I;
09444     }
09445           
09446     if (Changed) return II;
09447   }
09448   
09449   switch (II->getIntrinsicID()) {
09450   default: break;
09451   case Intrinsic::bswap:
09452     // bswap(bswap(x)) -> x
09453     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
09454       if (Operand->getIntrinsicID() == Intrinsic::bswap)
09455         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
09456     break;
09457   case Intrinsic::ppc_altivec_lvx:
09458   case Intrinsic::ppc_altivec_lvxl:
09459   case Intrinsic::x86_sse_loadu_ps:
09460   case Intrinsic::x86_sse2_loadu_pd:
09461   case Intrinsic::x86_sse2_loadu_dq:
09462     // Turn PPC lvx     -> load if the pointer is known aligned.
09463     // Turn X86 loadups -> load if the pointer is known aligned.
09464     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
09465       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
09466                                        PointerType::getUnqual(II->getType()),
09467                                        CI);
09468       return new LoadInst(Ptr);
09469     }
09470     break;
09471   case Intrinsic::ppc_altivec_stvx:
09472   case Intrinsic::ppc_altivec_stvxl:
09473     // Turn stvx -> store if the pointer is known aligned.
09474     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
09475       const Type *OpPtrTy = 
09476         PointerType::getUnqual(II->getOperand(1)->getType());
09477       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
09478       return new StoreInst(II->getOperand(1), Ptr);
09479     }
09480     break;
09481   case Intrinsic::x86_sse_storeu_ps:
09482   case Intrinsic::x86_sse2_storeu_pd:
09483   case Intrinsic::x86_sse2_storeu_dq:
09484     // Turn X86 storeu -> store if the pointer is known aligned.
09485     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
09486       const Type *OpPtrTy = 
09487         PointerType::getUnqual(II->getOperand(2)->getType());
09488       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
09489       return new StoreInst(II->getOperand(2), Ptr);
09490     }
09491     break;
09492     
09493   case Intrinsic::x86_sse_cvttss2si: {
09494     // These intrinsics only demands the 0th element of its input vector.  If
09495     // we can simplify the input based on that, do so now.
09496     uint64_t UndefElts;
09497     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
09498                                               UndefElts)) {
09499       II->setOperand(1, V);
09500       return II;
09501     }
09502     break;
09503   }
09504     
09505   case Intrinsic::ppc_altivec_vperm:
09506     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
09507     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
09508       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
09509       
09510       // Check that all of the elements are integer constants or undefs.
09511       bool AllEltsOk = true;
09512       for (unsigned i = 0; i != 16; ++i) {
09513         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
09514             !isa<UndefValue>(Mask->getOperand(i))) {
09515           AllEltsOk = false;
09516           break;
09517         }
09518       }
09519       
09520       if (AllEltsOk) {
09521         // Cast the input vectors to byte vectors.
09522         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
09523         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
09524         Value *Result = UndefValue::get(Op0->getType());
09525         
09526         // Only extract each element once.
09527         Value *ExtractedElts[32];
09528         memset(ExtractedElts, 0, sizeof(ExtractedElts));
09529         
09530         for (unsigned i = 0; i != 16; ++i) {
09531           if (isa<UndefValue>(Mask->getOperand(i)))
09532             continue;
09533           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
09534           Idx &= 31;  // Match the hardware behavior.
09535           
09536           if (ExtractedElts[Idx] == 0) {
09537             Instruction *Elt = 
09538               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
09539             InsertNewInstBefore(Elt, CI);
09540             ExtractedElts[Idx] = Elt;
09541           }
09542         
09543           // Insert this value into the result vector.
09544           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
09545                                              i, "tmp");
09546           InsertNewInstBefore(cast<Instruction>(Result), CI);
09547         }
09548         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
09549       }
09550     }
09551     break;
09552 
09553   case Intrinsic::stackrestore: {
09554     // If the save is right next to the restore, remove the restore.  This can
09555     // happen when variable allocas are DCE'd.
09556     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
09557       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
09558         BasicBlock::iterator BI = SS;
09559         if (&*++BI == II)
09560           return EraseInstFromFunction(CI);
09561       }
09562     }
09563     
09564     // Scan down this block to see if there is another stack restore in the
09565     // same block without an intervening call/alloca.
09566     BasicBlock::iterator BI = II;
09567     TerminatorInst *TI = II->getParent()->getTerminator();
09568     bool CannotRemove = false;
09569     for (++BI; &*BI != TI; ++BI) {
09570       if (isa<AllocaInst>(BI)) {
09571         CannotRemove = true;
09572         break;
09573       }
09574       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
09575         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
09576           // If there is a stackrestore below this one, remove this one.
09577           if (II->getIntrinsicID() == Intrinsic::stackrestore)
09578             return EraseInstFromFunction(CI);
09579           // Otherwise, ignore the intrinsic.
09580         } else {
09581           // If we found a non-intrinsic call, we can't remove the stack
09582           // restore.
09583           CannotRemove = true;
09584           break;
09585         }
09586       }
09587     }
09588     
09589     // If the stack restore is in a return/unwind block and if there are no
09590     // allocas or calls between the restore and the return, nuke the restore.
09591     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
09592       return EraseInstFromFunction(CI);
09593     break;
09594   }
09595   }
09596 
09597   return visitCallSite(II);
09598 }
09599 
09600 // InvokeInst simplification
09601 //
09602 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
09603   return visitCallSite(&II);
09604 }
09605 
09606 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
09607 /// passed through the varargs area, we can eliminate the use of the cast.
09608 static bool isSafeToEliminateVarargsCast(const CallSite CS,
09609                                          const CastInst * const CI,
09610                                          const TargetData * const TD,
09611                                          const int ix) {
09612   if (!CI->isLosslessCast())
09613     return false;
09614 
09615   // The size of ByVal arguments is derived from the type, so we
09616   // can't change to a type with a different size.  If the size were
09617   // passed explicitly we could avoid this check.
09618   if (!CS.paramHasAttr(ix, Attribute::ByVal))
09619     return true;
09620 
09621   const Type* SrcTy = 
09622             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
09623   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
09624   if (!SrcTy->isSized() || !DstTy->isSized())
09625     return false;
09626   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
09627     return false;
09628   return true;
09629 }
09630 
09631 // visitCallSite - Improvements for call and invoke instructions.
09632 //
09633 Instruction *InstCombiner::visitCallSite(CallSite CS) {
09634   bool Changed = false;
09635 
09636   // If the callee is a constexpr cast of a function, attempt to move the cast
09637   // to the arguments of the call/invoke.
09638   if (transformConstExprCastCall(CS)) return 0;
09639 
09640   Value *Callee = CS.getCalledValue();
09641 
09642   if (Function *CalleeF = dyn_cast<Function>(Callee))
09643     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
09644       Instruction *OldCall = CS.getInstruction();
09645       // If the call and callee calling conventions don't match, this call must
09646       // be unreachable, as the call is undefined.
09647       new StoreInst(ConstantInt::getTrue(),
09648                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
09649                                     OldCall);
09650       if (!OldCall->use_empty())
09651         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
09652       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
09653         return EraseInstFromFunction(*OldCall);
09654       return 0;
09655     }
09656 
09657   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
09658     // This instruction is not reachable, just remove it.  We insert a store to
09659     // undef so that we know that this code is not reachable, despite the fact
09660     // that we can't modify the CFG here.
09661     new StoreInst(ConstantInt::getTrue(),
09662                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
09663                   CS.getInstruction());
09664 
09665     if (!CS.getInstruction()->use_empty())
09666       CS.getInstruction()->
09667         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
09668 
09669     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
09670       // Don't break the CFG, insert a dummy cond branch.
09671       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
09672                          ConstantInt::getTrue(), II);
09673     }
09674     return EraseInstFromFunction(*CS.getInstruction());
09675   }
09676 
09677   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
09678     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
09679       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
09680         return transformCallThroughTrampoline(CS);
09681 
09682   const PointerType *PTy = cast<PointerType>(Callee->getType());
09683   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
09684   if (FTy->isVarArg()) {
09685     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
09686     // See if we can optimize any arguments passed through the varargs area of
09687     // the call.
09688     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
09689            E = CS.arg_end(); I != E; ++I, ++ix) {
09690       CastInst *CI = dyn_cast<CastInst>(*I);
09691       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
09692         *I = CI->getOperand(0);
09693         Changed = true;
09694       }
09695     }
09696   }
09697 
09698   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
09699     // Inline asm calls cannot throw - mark them 'nounwind'.
09700     CS.setDoesNotThrow();
09701     Changed = true;
09702   }
09703 
09704   return Changed ? CS.getInstruction() : 0;
09705 }
09706 
09707 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
09708 // attempt to move the cast to the arguments of the call/invoke.
09709 //
09710 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
09711   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
09712   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
09713   if (CE->getOpcode() != Instruction::BitCast || 
09714       !isa<Function>(CE->getOperand(0)))
09715     return false;
09716   Function *Callee = cast<Function>(CE->getOperand(0));
09717   Instruction *Caller = CS.getInstruction();
09718   const AttrListPtr &CallerPAL = CS.getAttributes();
09719 
09720   // Okay, this is a cast from a function to a different type.  Unless doing so
09721   // would cause a type conversion of one of our arguments, change this call to
09722   // be a direct call with arguments casted to the appropriate types.
09723   //
09724   const FunctionType *FT = Callee->getFunctionType();
09725   const Type *OldRetTy = Caller->getType();
09726   const Type *NewRetTy = FT->getReturnType();
09727 
09728   if (isa<StructType>(NewRetTy))
09729     return false; // TODO: Handle multiple return values.
09730 
09731   // Check to see if we are changing the return type...
09732   if (OldRetTy != NewRetTy) {
09733     if (Callee->isDeclaration() &&
09734         // Conversion is ok if changing from one pointer type to another or from
09735         // a pointer to an integer of the same size.
09736         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
09737           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
09738       return false;   // Cannot transform this return value.
09739 
09740     if (!Caller->use_empty() &&
09741         // void -> non-void is handled specially
09742         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
09743       return false;   // Cannot transform this return value.
09744 
09745     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
09746       Attributes RAttrs = CallerPAL.getRetAttributes();
09747       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
09748         return false;   // Attribute not compatible with transformed value.
09749     }
09750 
09751     // If the callsite is an invoke instruction, and the return value is used by
09752     // a PHI node in a successor, we cannot change the return type of the call
09753     // because there is no place to put the cast instruction (without breaking
09754     // the critical edge).  Bail out in this case.
09755     if (!Caller->use_empty())
09756       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
09757         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
09758              UI != E; ++UI)
09759           if (PHINode *PN = dyn_cast<PHINode>(*UI))
09760             if (PN->getParent() == II->getNormalDest() ||
09761                 PN->getParent() == II->getUnwindDest())
09762               return false;
09763   }
09764 
09765   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
09766   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
09767 
09768   CallSite::arg_iterator AI = CS.arg_begin();
09769   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
09770     const Type *ParamTy = FT->getParamType(i);
09771     const Type *ActTy = (*AI)->getType();
09772 
09773     if (!CastInst::isCastable(ActTy, ParamTy))
09774       return false;   // Cannot transform this parameter value.
09775 
09776     if (CallerPAL.getParamAttributes(i + 1) 
09777         & Attribute::typeIncompatible(ParamTy))
09778       return false;   // Attribute not compatible with transformed value.
09779 
09780     // Converting from one pointer type to another or between a pointer and an
09781     // integer of the same size is safe even if we do not have a body.
09782     bool isConvertible = ActTy == ParamTy ||
09783       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
09784        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
09785     if (Callee->isDeclaration() && !isConvertible) return false;
09786   }
09787 
09788   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
09789       Callee->isDeclaration())
09790     return false;   // Do not delete arguments unless we have a function body.
09791 
09792   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
09793       !CallerPAL.isEmpty())
09794     // In this case we have more arguments than the new function type, but we
09795     // won't be dropping them.  Check that these extra arguments have attributes
09796     // that are compatible with being a vararg call argument.
09797     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
09798       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
09799         break;
09800       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
09801       if (PAttrs & Attribute::VarArgsIncompatible)
09802         return false;
09803     }
09804 
09805   // Okay, we decided that this is a safe thing to do: go ahead and start
09806   // inserting cast instructions as necessary...
09807   std::vector<Value*> Args;
09808   Args.reserve(NumActualArgs);
09809   SmallVector<AttributeWithIndex, 8> attrVec;
09810   attrVec.reserve(NumCommonArgs);
09811 
09812   // Get any return attributes.
09813   Attributes RAttrs = CallerPAL.getRetAttributes();
09814 
09815   // If the return value is not being used, the type may not be compatible
09816   // with the existing attributes.  Wipe out any problematic attributes.
09817   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
09818 
09819   // Add the new return attributes.
09820   if (RAttrs)
09821     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
09822 
09823   AI = CS.arg_begin();
09824   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
09825     const Type *ParamTy = FT->getParamType(i);
09826     if ((*AI)->getType() == ParamTy) {
09827       Args.push_back(*AI);
09828     } else {
09829       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
09830           false, ParamTy, false);
09831       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
09832       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
09833     }
09834 
09835     // Add any parameter attributes.
09836     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
09837       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
09838   }
09839 
09840   // If the function takes more arguments than the call was taking, add them
09841   // now...
09842   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
09843     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
09844 
09845   // If we are removing arguments to the function, emit an obnoxious warning...
09846   if (FT->getNumParams() < NumActualArgs) {
09847     if (!FT->isVarArg()) {
09848       cerr << "WARNING: While resolving call to function '"
09849            << Callee->getName() << "' arguments were dropped!\n";
09850     } else {
09851       // Add all of the arguments in their promoted form to the arg list...
09852       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
09853         const Type *PTy = getPromotedType((*AI)->getType());
09854         if (PTy != (*AI)->getType()) {
09855           // Must promote to pass through va_arg area!
09856           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
09857                                                                 PTy, false);
09858           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
09859           InsertNewInstBefore(Cast, *Caller);
09860           Args.push_back(Cast);
09861         } else {
09862           Args.push_back(*AI);
09863         }
09864 
09865         // Add any parameter attributes.
09866         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
09867           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
09868       }
09869     }
09870   }
09871 
09872   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
09873     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
09874 
09875   if (NewRetTy == Type::VoidTy)
09876     Caller->setName("");   // Void type should not have a name.
09877 
09878   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
09879 
09880   Instruction *NC;
09881   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
09882     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
09883                             Args.begin(), Args.end(),
09884                             Caller->getName(), Caller);
09885     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
09886     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
09887   } else {
09888     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
09889                           Caller->getName(), Caller);
09890     CallInst *CI = cast<CallInst>(Caller);
09891     if (CI->isTailCall())
09892       cast<CallInst>(NC)->setTailCall();
09893     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
09894     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
09895   }
09896 
09897   // Insert a cast of the return type as necessary.
09898   Value *NV = NC;
09899   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
09900     if (NV->getType() != Type::VoidTy) {
09901       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
09902                                                             OldRetTy, false);
09903       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
09904 
09905       // If this is an invoke instruction, we should insert it after the first
09906       // non-phi, instruction in the normal successor block.
09907       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
09908         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
09909         InsertNewInstBefore(NC, *I);
09910       } else {
09911         // Otherwise, it's a call, just insert cast right after the call instr
09912         InsertNewInstBefore(NC, *Caller);
09913       }
09914       AddUsersToWorkList(*Caller);
09915     } else {
09916       NV = UndefValue::get(Caller->getType());
09917     }
09918   }
09919 
09920   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
09921     Caller->replaceAllUsesWith(NV);
09922   Caller->eraseFromParent();
09923   RemoveFromWorkList(Caller);
09924   return true;
09925 }
09926 
09927 // transformCallThroughTrampoline - Turn a call to a function created by the
09928 // init_trampoline intrinsic into a direct call to the underlying function.
09929 //
09930 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
09931   Value *Callee = CS.getCalledValue();
09932   const PointerType *PTy = cast<PointerType>(Callee->getType());
09933   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
09934   const AttrListPtr &Attrs = CS.getAttributes();
09935 
09936   // If the call already has the 'nest' attribute somewhere then give up -
09937   // otherwise 'nest' would occur twice after splicing in the chain.
09938   if (Attrs.hasAttrSomewhere(Attribute::Nest))
09939     return 0;
09940 
09941   IntrinsicInst *Tramp =
09942     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
09943 
09944   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
09945   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
09946   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
09947 
09948   const AttrListPtr &NestAttrs = NestF->getAttributes();
09949   if (!NestAttrs.isEmpty()) {
09950     unsigned NestIdx = 1;
09951     const Type *NestTy = 0;
09952     Attributes NestAttr = Attribute::None;
09953 
09954     // Look for a parameter marked with the 'nest' attribute.
09955     for (FunctionType::param_iterator I = NestFTy->param_begin(),
09956          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
09957       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
09958         // Record the parameter type and any other attributes.
09959         NestTy = *I;
09960         NestAttr = NestAttrs.getParamAttributes(NestIdx);
09961         break;
09962       }
09963 
09964     if (NestTy) {
09965       Instruction *Caller = CS.getInstruction();
09966       std::vector<Value*> NewArgs;
09967       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
09968 
09969       SmallVector<AttributeWithIndex, 8> NewAttrs;
09970       NewAttrs.reserve(Attrs.getNumSlots() + 1);
09971 
09972       // Insert the nest argument into the call argument list, which may
09973       // mean appending it.  Likewise for attributes.
09974 
09975       // Add any result attributes.
09976       if (Attributes Attr = Attrs.getRetAttributes())
09977         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
09978 
09979       {
09980         unsigned Idx = 1;
09981         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
09982         do {
09983           if (Idx == NestIdx) {
09984             // Add the chain argument and attributes.
09985             Value *NestVal = Tramp->getOperand(3);
09986             if (NestVal->getType() != NestTy)
09987               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
09988             NewArgs.push_back(NestVal);
09989             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
09990           }
09991 
09992           if (I == E)
09993             break;
09994 
09995           // Add the original argument and attributes.
09996           NewArgs.push_back(*I);
09997           if (Attributes Attr = Attrs.getParamAttributes(Idx))
09998             NewAttrs.push_back
09999               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10000 
10001           ++Idx, ++I;
10002         } while (1);
10003       }
10004 
10005       // Add any function attributes.
10006       if (Attributes Attr = Attrs.getFnAttributes())
10007         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10008 
10009       // The trampoline may have been bitcast to a bogus type (FTy).
10010       // Handle this by synthesizing a new function type, equal to FTy
10011       // with the chain parameter inserted.
10012 
10013       std::vector<const Type*> NewTypes;
10014       NewTypes.reserve(FTy->getNumParams()+1);
10015 
10016       // Insert the chain's type into the list of parameter types, which may
10017       // mean appending it.
10018       {
10019         unsigned Idx = 1;
10020         FunctionType::param_iterator I = FTy->param_begin(),
10021           E = FTy->param_end();
10022 
10023         do {
10024           if (Idx == NestIdx)
10025             // Add the chain's type.
10026             NewTypes.push_back(NestTy);
10027 
10028           if (I == E)
10029             break;
10030 
10031           // Add the original type.
10032           NewTypes.push_back(*I);
10033 
10034           ++Idx, ++I;
10035         } while (1);
10036       }
10037 
10038       // Replace the trampoline call with a direct call.  Let the generic
10039       // code sort out any function type mismatches.
10040       FunctionType *NewFTy =
10041         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10042       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10043         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10044       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10045 
10046       Instruction *NewCaller;
10047       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10048         NewCaller = InvokeInst::Create(NewCallee,
10049                                        II->getNormalDest(), II->getUnwindDest(),
10050                                        NewArgs.begin(), NewArgs.end(),
10051                                        Caller->getName(), Caller);
10052         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10053         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10054       } else {
10055         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10056                                      Caller->getName(), Caller);
10057         if (cast<CallInst>(Caller)->isTailCall())
10058           cast<CallInst>(NewCaller)->setTailCall();
10059         cast<CallInst>(NewCaller)->
10060           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10061         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10062       }
10063       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10064         Caller->replaceAllUsesWith(NewCaller);
10065       Caller->eraseFromParent();
10066       RemoveFromWorkList(Caller);
10067       return 0;
10068     }
10069   }
10070 
10071   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10072   // parameter, there is no need to adjust the argument list.  Let the generic
10073   // code sort out any function type mismatches.
10074   Constant *NewCallee =
10075     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10076   CS.setCalledFunction(NewCallee);
10077   return CS.getInstruction();
10078 }
10079 
10080 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10081 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10082 /// and a single binop.
10083 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10084   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10085   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10086   unsigned Opc = FirstInst->getOpcode();
10087   Value *LHSVal = FirstInst->getOperand(0);
10088   Value *RHSVal = FirstInst->getOperand(1);
10089     
10090   const Type *LHSType = LHSVal->getType();
10091   const Type *RHSType = RHSVal->getType();
10092   
10093   // Scan to see if all operands are the same opcode, all have one use, and all
10094   // kill their operands (i.e. the operands have one use).
10095   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10096     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10097     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10098         // Verify type of the LHS matches so we don't fold cmp's of different
10099         // types or GEP's with different index types.
10100         I->getOperand(0)->getType() != LHSType ||
10101         I->getOperand(1)->getType() != RHSType)
10102       return 0;
10103 
10104     // If they are CmpInst instructions, check their predicates
10105     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10106       if (cast<CmpInst>(I)->getPredicate() !=
10107           cast<CmpInst>(FirstInst)->getPredicate())
10108         return 0;
10109     
10110     // Keep track of which operand needs a phi node.
10111     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10112     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10113   }
10114   
10115   // Otherwise, this is safe to transform!
10116   
10117   Value *InLHS = FirstInst->getOperand(0);
10118   Value *InRHS = FirstInst->getOperand(1);
10119   PHINode *NewLHS = 0, *NewRHS = 0;
10120   if (LHSVal == 0) {
10121     NewLHS = PHINode::Create(LHSType,
10122                              FirstInst->getOperand(0)->getName() + ".pn");
10123     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10124     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10125     InsertNewInstBefore(NewLHS, PN);
10126     LHSVal = NewLHS;
10127   }
10128   
10129   if (RHSVal == 0) {
10130     NewRHS = PHINode::Create(RHSType,
10131                              FirstInst->getOperand(1)->getName() + ".pn");
10132     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10133     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10134     InsertNewInstBefore(NewRHS, PN);
10135     RHSVal = NewRHS;
10136   }
10137   
10138   // Add all operands to the new PHIs.
10139   if (NewLHS || NewRHS) {
10140     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10141       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10142       if (NewLHS) {
10143         Value *NewInLHS = InInst->getOperand(0);
10144         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10145       }
10146       if (NewRHS) {
10147         Value *NewInRHS = InInst->getOperand(1);
10148         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10149       }
10150     }
10151   }
10152     
10153   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10154     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10155   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10156   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10157                          RHSVal);
10158 }
10159 
10160 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10161   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10162   
10163   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10164                                         FirstInst->op_end());
10165   
10166   // Scan to see if all operands are the same opcode, all have one use, and all
10167   // kill their operands (i.e. the operands have one use).
10168   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10169     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10170     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10171       GEP->getNumOperands() != FirstInst->getNumOperands())
10172       return 0;
10173 
10174     // Compare the operand lists.
10175     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10176       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10177         continue;
10178       
10179       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10180       // if one of the PHIs has a constant for the index.  The index may be
10181       // substantially cheaper to compute for the constants, so making it a
10182       // variable index could pessimize the path.  This also handles the case
10183       // for struct indices, which must always be constant.
10184       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10185           isa<ConstantInt>(GEP->getOperand(op)))
10186         return 0;
10187       
10188       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10189         return 0;
10190       FixedOperands[op] = 0;  // Needs a PHI.
10191     }
10192   }
10193   
10194   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10195   // that is variable.
10196   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10197   
10198   bool HasAnyPHIs = false;
10199   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10200     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10201     Value *FirstOp = FirstInst->getOperand(i);
10202     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10203                                      FirstOp->getName()+".pn");
10204     InsertNewInstBefore(NewPN, PN);
10205     
10206     NewPN->reserveOperandSpace(e);
10207     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10208     OperandPhis[i] = NewPN;
10209     FixedOperands[i] = NewPN;
10210     HasAnyPHIs = true;
10211   }
10212 
10213   
10214   // Add all operands to the new PHIs.
10215   if (HasAnyPHIs) {
10216     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10217       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10218       BasicBlock *InBB = PN.getIncomingBlock(i);
10219       
10220       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10221         if (PHINode *OpPhi = OperandPhis[op])
10222           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10223     }
10224   }
10225   
10226   Value *Base = FixedOperands[0];
10227   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10228                                    FixedOperands.end());
10229 }
10230 
10231 
10232 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10233 /// of the block that defines it.  This means that it must be obvious the value
10234 /// of the load is not changed from the point of the load to the end of the
10235 /// block it is in.
10236 ///
10237 /// Finally, it is safe, but not profitable, to sink a load targetting a
10238 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10239 /// to a register.
10240 static bool isSafeToSinkLoad(LoadInst *L) {
10241   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10242   
10243   for (++BBI; BBI != E; ++BBI)
10244     if (BBI->mayWriteToMemory())
10245       return false;
10246   
10247   // Check for non-address taken alloca.  If not address-taken already, it isn't
10248   // profitable to do this xform.
10249   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10250     bool isAddressTaken = false;
10251     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10252          UI != E; ++UI) {
10253       if (isa<LoadInst>(UI)) continue;
10254       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10255         // If storing TO the alloca, then the address isn't taken.
10256         if (SI->getOperand(1) == AI) continue;
10257       }
10258       isAddressTaken = true;
10259       break;
10260     }
10261     
10262     if (!isAddressTaken)
10263       return false;
10264   }
10265   
10266   return true;
10267 }
10268 
10269 
10270 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10271 // operator and they all are only used by the PHI, PHI together their
10272 // inputs, and do the operation once, to the result of the PHI.
10273 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10274   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10275 
10276   // Scan the instruction, looking for input operations that can be folded away.
10277   // If all input operands to the phi are the same instruction (e.g. a cast from
10278   // the same type or "+42") we can pull the operation through the PHI, reducing
10279   // code size and simplifying code.
10280   Constant *ConstantOp = 0;
10281   const Type *CastSrcTy = 0;
10282   bool isVolatile = false;
10283   if (isa<CastInst>(FirstInst)) {
10284     CastSrcTy = FirstInst->getOperand(0)->getType();
10285   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10286     // Can fold binop, compare or shift here if the RHS is a constant, 
10287     // otherwise call FoldPHIArgBinOpIntoPHI.
10288     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10289     if (ConstantOp == 0)
10290       return FoldPHIArgBinOpIntoPHI(PN);
10291   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10292     isVolatile = LI->isVolatile();
10293     // We can't sink the load if the loaded value could be modified between the
10294     // load and the PHI.
10295     if (LI->getParent() != PN.getIncomingBlock(0) ||
10296         !isSafeToSinkLoad(LI))
10297       return 0;
10298     
10299     // If the PHI is of volatile loads and the load block has multiple
10300     // successors, sinking it would remove a load of the volatile value from
10301     // the path through the other successor.
10302     if (isVolatile &&
10303         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10304       return 0;
10305     
10306   } else if (isa<GetElementPtrInst>(FirstInst)) {
10307     return FoldPHIArgGEPIntoPHI(PN);
10308   } else {
10309     return 0;  // Cannot fold this operation.
10310   }
10311 
10312   // Check to see if all arguments are the same operation.
10313   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10314     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10315     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10316     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10317       return 0;
10318     if (CastSrcTy) {
10319       if (I->getOperand(0)->getType() != CastSrcTy)
10320         return 0;  // Cast operation must match.
10321     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10322       // We can't sink the load if the loaded value could be modified between 
10323       // the load and the PHI.
10324       if (LI->isVolatile() != isVolatile ||
10325           LI->getParent() != PN.getIncomingBlock(i) ||
10326           !isSafeToSinkLoad(LI))
10327         return 0;
10328       
10329       // If the PHI is of volatile loads and the load block has multiple
10330       // successors, sinking it would remove a load of the volatile value from
10331       // the path through the other successor.
10332       if (isVolatile &&
10333           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10334         return 0;
10335 
10336       
10337     } else if (I->getOperand(1) != ConstantOp) {
10338       return 0;
10339     }
10340   }
10341 
10342   // Okay, they are all the same operation.  Create a new PHI node of the
10343   // correct type, and PHI together all of the LHS's of the instructions.
10344   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10345                                    PN.getName()+".in");
10346   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10347 
10348   Value *InVal = FirstInst->getOperand(0);
10349   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10350 
10351   // Add all operands to the new PHI.
10352   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10353     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10354     if (NewInVal != InVal)
10355       InVal = 0;
10356     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10357   }
10358 
10359   Value *PhiVal;
10360   if (InVal) {
10361     // The new PHI unions all of the same values together.  This is really
10362     // common, so we handle it intelligently here for compile-time speed.
10363     PhiVal = InVal;
10364     delete NewPN;
10365   } else {
10366     InsertNewInstBefore(NewPN, PN);
10367     PhiVal = NewPN;
10368   }
10369 
10370   // Insert and return the new operation.
10371   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10372     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10373   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10374     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10375   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10376     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10377                            PhiVal, ConstantOp);
10378   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10379   
10380   // If this was a volatile load that we are merging, make sure to loop through
10381   // and mark all the input loads as non-volatile.  If we don't do this, we will
10382   // insert a new volatile load and the old ones will not be deletable.
10383   if (isVolatile)
10384     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10385       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10386   
10387   return new LoadInst(PhiVal, "", isVolatile);
10388 }
10389 
10390 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10391 /// that is dead.
10392 static bool DeadPHICycle(PHINode *PN,
10393                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10394   if (PN->use_empty()) return true;
10395   if (!PN->hasOneUse()) return false;
10396 
10397   // Remember this node, and if we find the cycle, return.
10398   if (!PotentiallyDeadPHIs.insert(PN))
10399     return true;
10400   
10401   // Don't scan crazily complex things.
10402   if (PotentiallyDeadPHIs.size() == 16)
10403     return false;
10404 
10405   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10406     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10407 
10408   return false;
10409 }
10410 
10411 /// PHIsEqualValue - Return true if this phi node is always equal to
10412 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10413 ///   z = some value; x = phi (y, z); y = phi (x, z)
10414 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10415                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10416   // See if we already saw this PHI node.
10417   if (!ValueEqualPHIs.insert(PN))
10418     return true;
10419   
10420   // Don't scan crazily complex things.
10421   if (ValueEqualPHIs.size() == 16)
10422     return false;
10423  
10424   // Scan the operands to see if they are either phi nodes or are equal to
10425   // the value.
10426   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10427     Value *Op = PN->getIncomingValue(i);
10428     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10429       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10430         return false;
10431     } else if (Op != NonPhiInVal)
10432       return false;
10433   }
10434   
10435   return true;
10436 }
10437 
10438 
10439 // PHINode simplification
10440 //
10441 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10442   // If LCSSA is around, don't mess with Phi nodes
10443   if (MustPreserveLCSSA) return 0;
10444   
10445   if (Value *V = PN.hasConstantValue())
10446     return ReplaceInstUsesWith(PN, V);
10447 
10448   // If all PHI operands are the same operation, pull them through the PHI,
10449   // reducing code size.
10450   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10451       isa<Instruction>(PN.getIncomingValue(1)) &&
10452       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10453       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10454       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10455       // than themselves more than once.
10456       PN.getIncomingValue(0)->hasOneUse())
10457     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10458       return Result;
10459 
10460   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10461   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10462   // PHI)... break the cycle.
10463   if (PN.hasOneUse()) {
10464     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10465     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10466       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10467       PotentiallyDeadPHIs.insert(&PN);
10468       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10469         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10470     }
10471    
10472     // If this phi has a single use, and if that use just computes a value for
10473     // the next iteration of a loop, delete the phi.  This occurs with unused
10474     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10475     // common case here is good because the only other things that catch this
10476     // are induction variable analysis (sometimes) and ADCE, which is only run
10477     // late.
10478     if (PHIUser->hasOneUse() &&
10479         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10480         PHIUser->use_back() == &PN) {
10481       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10482     }
10483   }
10484 
10485   // We sometimes end up with phi cycles that non-obviously end up being the
10486   // same value, for example:
10487   //   z = some value; x = phi (y, z); y = phi (x, z)
10488   // where the phi nodes don't necessarily need to be in the same block.  Do a
10489   // quick check to see if the PHI node only contains a single non-phi value, if
10490   // so, scan to see if the phi cycle is actually equal to that value.
10491   {
10492     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10493     // Scan for the first non-phi operand.
10494     while (InValNo != NumOperandVals && 
10495            isa<PHINode>(PN.getIncomingValue(InValNo)))
10496       ++InValNo;
10497 
10498     if (InValNo != NumOperandVals) {
10499       Value *NonPhiInVal = PN.getOperand(InValNo);
10500       
10501       // Scan the rest of the operands to see if there are any conflicts, if so
10502       // there is no need to recursively scan other phis.
10503       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10504         Value *OpVal = PN.getIncomingValue(InValNo);
10505         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10506           break;
10507       }
10508       
10509       // If we scanned over all operands, then we have one unique value plus
10510       // phi values.  Scan PHI nodes to see if they all merge in each other or
10511       // the value.
10512       if (InValNo == NumOperandVals) {
10513         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10514         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10515           return ReplaceInstUsesWith(PN, NonPhiInVal);
10516       }
10517     }
10518   }
10519   return 0;
10520 }
10521 
10522 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10523                                    Instruction *InsertPoint,
10524                                    InstCombiner *IC) {
10525   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10526   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10527   // We must cast correctly to the pointer type. Ensure that we
10528   // sign extend the integer value if it is smaller as this is
10529   // used for address computation.
10530   Instruction::CastOps opcode = 
10531      (VTySize < PtrSize ? Instruction::SExt :
10532       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10533   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10534 }
10535 
10536 
10537 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10538   Value *PtrOp = GEP.getOperand(0);
10539   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10540   // If so, eliminate the noop.
10541   if (GEP.getNumOperands() == 1)
10542     return ReplaceInstUsesWith(GEP, PtrOp);
10543 
10544   if (isa<UndefValue>(GEP.getOperand(0)))
10545     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10546 
10547   bool HasZeroPointerIndex = false;
10548   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10549     HasZeroPointerIndex = C->isNullValue();
10550 
10551   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10552     return ReplaceInstUsesWith(GEP, PtrOp);
10553 
10554   // Eliminate unneeded casts for indices.
10555   bool MadeChange = false;
10556   
10557   gep_type_iterator GTI = gep_type_begin(GEP);
10558   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10559        i != e; ++i, ++GTI) {
10560     if (isa<SequentialType>(*GTI)) {
10561       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10562         if (CI->getOpcode() == Instruction::ZExt ||
10563             CI->getOpcode() == Instruction::SExt) {
10564           const Type *SrcTy = CI->getOperand(0)->getType();
10565           // We can eliminate a cast from i32 to i64 iff the target 
10566           // is a 32-bit pointer target.
10567           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10568             MadeChange = true;
10569             *i = CI->getOperand(0);
10570           }
10571         }
10572       }
10573       // If we are using a wider index than needed for this platform, shrink it
10574       // to what we need.  If narrower, sign-extend it to what we need.
10575       // If the incoming value needs a cast instruction,
10576       // insert it.  This explicit cast can make subsequent optimizations more
10577       // obvious.
10578       Value *Op = *i;
10579       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10580         if (Constant *C = dyn_cast<Constant>(Op)) {
10581           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10582           MadeChange = true;
10583         } else {
10584           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10585                                 GEP);
10586           *i = Op;
10587           MadeChange = true;
10588         }
10589       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10590         if (Constant *C = dyn_cast<Constant>(Op)) {
10591           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10592           MadeChange = true;
10593         } else {
10594           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10595                                 GEP);
10596           *i = Op;
10597           MadeChange = true;
10598         }
10599       }
10600     }
10601   }
10602   if (MadeChange) return &GEP;
10603 
10604   // Combine Indices - If the source pointer to this getelementptr instruction
10605   // is a getelementptr instruction, combine the indices of the two
10606   // getelementptr instructions into a single instruction.
10607   //
10608   SmallVector<Value*, 8> SrcGEPOperands;
10609   if (User *Src = dyn_castGetElementPtr(PtrOp))
10610     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10611 
10612   if (!SrcGEPOperands.empty()) {
10613     // Note that if our source is a gep chain itself that we wait for that
10614     // chain to be resolved before we perform this transformation.  This
10615     // avoids us creating a TON of code in some cases.
10616     //
10617     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10618         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10619       return 0;   // Wait until our source is folded to completion.
10620 
10621     SmallVector<Value*, 8> Indices;
10622 
10623     // Find out whether the last index in the source GEP is a sequential idx.
10624     bool EndsWithSequential = false;
10625     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10626            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10627       EndsWithSequential = !isa<StructType>(*I);
10628 
10629     // Can we combine the two pointer arithmetics offsets?
10630     if (EndsWithSequential) {
10631       // Replace: gep (gep %P, long B), long A, ...
10632       // With:    T = long A+B; gep %P, T, ...
10633       //
10634       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10635       if (SO1 == Constant::getNullValue(SO1->getType())) {
10636         Sum = GO1;
10637       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10638         Sum = SO1;
10639       } else {
10640         // If they aren't the same type, convert both to an integer of the
10641         // target's pointer size.
10642         if (SO1->getType() != GO1->getType()) {
10643           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10644             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10645           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10646             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10647           } else {
10648             unsigned PS = TD->getPointerSizeInBits();
10649             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10650               // Convert GO1 to SO1's type.
10651               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10652 
10653             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10654               // Convert SO1 to GO1's type.
10655               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10656             } else {
10657               const Type *PT = TD->getIntPtrType();
10658               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10659               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10660             }
10661           }
10662         }
10663         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10664           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10665         else {
10666           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10667           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10668         }
10669       }
10670 
10671       // Recycle the GEP we already have if possible.
10672       if (SrcGEPOperands.size() == 2) {
10673         GEP.setOperand(0, SrcGEPOperands[0]);
10674         GEP.setOperand(1, Sum);
10675         return &GEP;
10676       } else {
10677         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10678                        SrcGEPOperands.end()-1);
10679         Indices.push_back(Sum);
10680         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10681       }
10682     } else if (isa<Constant>(*GEP.idx_begin()) &&
10683                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10684                SrcGEPOperands.size() != 1) {
10685       // Otherwise we can do the fold if the first index of the GEP is a zero
10686       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10687                      SrcGEPOperands.end());
10688       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10689     }
10690 
10691     if (!Indices.empty())
10692       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10693                                        Indices.end(), GEP.getName());
10694 
10695   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10696     // GEP of global variable.  If all of the indices for this GEP are
10697     // constants, we can promote this to a constexpr instead of an instruction.
10698 
10699     // Scan for nonconstants...
10700     SmallVector<Constant*, 8> Indices;
10701     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10702     for (; I != E && isa<Constant>(*I); ++I)
10703       Indices.push_back(cast<Constant>(*I));
10704 
10705     if (I == E) {  // If they are all constants...
10706       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10707                                                     &Indices[0],Indices.size());
10708 
10709       // Replace all uses of the GEP with the new constexpr...
10710       return ReplaceInstUsesWith(GEP, CE);
10711     }
10712   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10713     if (!isa<PointerType>(X->getType())) {
10714       // Not interesting.  Source pointer must be a cast from pointer.
10715     } else if (HasZeroPointerIndex) {
10716       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10717       // into     : GEP [10 x i8]* X, i32 0, ...
10718       //
10719       // This occurs when the program declares an array extern like "int X[];"
10720       //
10721       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10722       const PointerType *XTy = cast<PointerType>(X->getType());
10723       if (const ArrayType *XATy =
10724           dyn_cast<ArrayType>(XTy->getElementType()))
10725         if (const ArrayType *CATy =
10726             dyn_cast<ArrayType>(CPTy->getElementType()))
10727           if (CATy->getElementType() == XATy->getElementType()) {
10728             // At this point, we know that the cast source type is a pointer
10729             // to an array of the same type as the destination pointer
10730             // array.  Because the array type is never stepped over (there
10731             // is a leading zero) we can fold the cast into this GEP.
10732             GEP.setOperand(0, X);
10733             return &GEP;
10734           }
10735     } else if (GEP.getNumOperands() == 2) {
10736       // Transform things like:
10737       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10738       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10739       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10740       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10741       if (isa<ArrayType>(SrcElTy) &&
10742           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10743           TD->getTypePaddedSize(ResElTy)) {
10744         Value *Idx[2];
10745         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10746         Idx[1] = GEP.getOperand(1);
10747         Value *V = InsertNewInstBefore(
10748                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10749         // V and GEP are both pointer types --> BitCast
10750         return new BitCastInst(V, GEP.getType());
10751       }
10752       
10753       // Transform things like:
10754       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10755       //   (where tmp = 8*tmp2) into:
10756       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10757       
10758       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10759         uint64_t ArrayEltSize =
10760             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10761         
10762         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10763         // allow either a mul, shift, or constant here.
10764         Value *NewIdx = 0;
10765         ConstantInt *Scale = 0;
10766         if (ArrayEltSize == 1) {
10767           NewIdx = GEP.getOperand(1);
10768           Scale = ConstantInt::get(NewIdx->getType(), 1);
10769         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10770           NewIdx = ConstantInt::get(CI->getType(), 1);
10771           Scale = CI;
10772         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10773           if (Inst->getOpcode() == Instruction::Shl &&
10774               isa<ConstantInt>(Inst->getOperand(1))) {
10775             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10776             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10777             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10778             NewIdx = Inst->getOperand(0);
10779           } else if (Inst->getOpcode() == Instruction::Mul &&
10780                      isa<ConstantInt>(Inst->getOperand(1))) {
10781             Scale = cast<ConstantInt>(Inst->getOperand(1));
10782             NewIdx = Inst->getOperand(0);
10783           }
10784         }
10785         
10786         // If the index will be to exactly the right offset with the scale taken
10787         // out, perform the transformation. Note, we don't know whether Scale is
10788         // signed or not. We'll use unsigned version of division/modulo
10789         // operation after making sure Scale doesn't have the sign bit set.
10790         if (Scale && Scale->getSExtValue() >= 0LL &&
10791             Scale->getZExtValue() % ArrayEltSize == 0) {
10792           Scale = ConstantInt::get(Scale->getType(),
10793                                    Scale->getZExtValue() / ArrayEltSize);
10794           if (Scale->getZExtValue() != 1) {
10795             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10796                                                        false /*ZExt*/);
10797             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10798             NewIdx = InsertNewInstBefore(Sc, GEP);
10799           }
10800 
10801           // Insert the new GEP instruction.
10802           Value *Idx[2];
10803           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10804           Idx[1] = NewIdx;
10805           Instruction *NewGEP =
10806             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10807           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10808           // The NewGEP must be pointer typed, so must the old one -> BitCast
10809           return new BitCastInst(NewGEP, GEP.getType());
10810         }
10811       }
10812     }
10813   }
10814   
10815   /// See if we can simplify:
10816   ///   X = bitcast A to B*
10817   ///   Y = gep X, <...constant indices...>
10818   /// into a gep of the original struct.  This is important for SROA and alias
10819   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10820   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10821     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10822       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10823       // a constant back from EmitGEPOffset.
10824       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10825       int64_t Offset = OffsetV->getSExtValue();
10826       
10827       // If this GEP instruction doesn't move the pointer, just replace the GEP
10828       // with a bitcast of the real input to the dest type.
10829       if (Offset == 0) {
10830         // If the bitcast is of an allocation, and the allocation will be
10831         // converted to match the type of the cast, don't touch this.
10832         if (isa<AllocationInst>(BCI->getOperand(0))) {
10833           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10834           if (Instruction *I = visitBitCast(*BCI)) {
10835             if (I != BCI) {
10836               I->takeName(BCI);
10837               BCI->getParent()->getInstList().insert(BCI, I);
10838               ReplaceInstUsesWith(*BCI, I);
10839             }
10840             return &GEP;
10841           }
10842         }
10843         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10844       }
10845       
10846       // Otherwise, if the offset is non-zero, we need to find out if there is a
10847       // field at Offset in 'A's type.  If so, we can pull the cast through the
10848       // GEP.
10849       SmallVector<Value*, 8> NewIndices;
10850       const Type *InTy =
10851         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10852       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10853         Instruction *NGEP =
10854            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10855                                      NewIndices.end());
10856         if (NGEP->getType() == GEP.getType()) return NGEP;
10857         InsertNewInstBefore(NGEP, GEP);
10858         NGEP->takeName(&GEP);
10859         return new BitCastInst(NGEP, GEP.getType());
10860       }
10861     }
10862   }    
10863     
10864   return 0;
10865 }
10866 
10867 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10868   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10869   if (AI.isArrayAllocation()) {  // Check C != 1
10870     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10871       const Type *NewTy = 
10872         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10873       AllocationInst *New = 0;
10874 
10875       // Create and insert the replacement instruction...
10876       if (isa<MallocInst>(AI))
10877         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10878       else {
10879         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10880         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10881       }
10882 
10883       InsertNewInstBefore(New, AI);
10884 
10885       // Scan to the end of the allocation instructions, to skip over a block of
10886       // allocas if possible...
10887       //
10888       BasicBlock::iterator It = New;
10889       while (isa<AllocationInst>(*It)) ++It;
10890 
10891       // Now that I is pointing to the first non-allocation-inst in the block,
10892       // insert our getelementptr instruction...
10893       //
10894       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10895       Value *Idx[2];
10896       Idx[0] = NullIdx;
10897       Idx[1] = NullIdx;
10898       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10899                                            New->getName()+".sub", It);
10900 
10901       // Now make everything use the getelementptr instead of the original
10902       // allocation.
10903       return ReplaceInstUsesWith(AI, V);
10904     } else if (isa<UndefValue>(AI.getArraySize())) {
10905       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10906     }
10907   }
10908 
10909   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10910     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10911     // Note that we only do this for alloca's, because malloc should allocate and
10912     // return a unique pointer, even for a zero byte allocation.
10913     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10914       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10915 
10916     // If the alignment is 0 (unspecified), assign it the preferred alignment.
10917     if (AI.getAlignment() == 0)
10918       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10919   }
10920 
10921   return 0;
10922 }
10923 
10924 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10925   Value *Op = FI.getOperand(0);
10926 
10927   // free undef -> unreachable.
10928   if (isa<UndefValue>(Op)) {
10929     // Insert a new store to null because we cannot modify the CFG here.
10930     new StoreInst(ConstantInt::getTrue(),
10931                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10932     return EraseInstFromFunction(FI);
10933   }
10934   
10935   // If we have 'free null' delete the instruction.  This can happen in stl code
10936   // when lots of inlining happens.
10937   if (isa<ConstantPointerNull>(Op))
10938     return EraseInstFromFunction(FI);
10939   
10940   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10941   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10942     FI.setOperand(0, CI->getOperand(0));
10943     return &FI;
10944   }
10945   
10946   // Change free (gep X, 0,0,0,0) into free(X)
10947   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10948     if (GEPI->hasAllZeroIndices()) {
10949       AddToWorkList(GEPI);
10950       FI.setOperand(0, GEPI->getOperand(0));
10951       return &FI;
10952     }
10953   }
10954   
10955   // Change free(malloc) into nothing, if the malloc has a single use.
10956   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10957     if (MI->hasOneUse()) {
10958       EraseInstFromFunction(FI);
10959       return EraseInstFromFunction(*MI);
10960     }
10961 
10962   return 0;
10963 }
10964 
10965 
10966 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10967 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10968                                         const TargetData *TD) {
10969   User *CI = cast<User>(LI.getOperand(0));
10970   Value *CastOp = CI->getOperand(0);
10971 
10972   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10973     // Instead of loading constant c string, use corresponding integer value
10974     // directly if string length is small enough.
10975     std::string Str;
10976     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10977       unsigned len = Str.length();
10978       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10979       unsigned numBits = Ty->getPrimitiveSizeInBits();
10980       // Replace LI with immediate integer store.
10981       if ((numBits >> 3) == len + 1) {
10982         APInt StrVal(numBits, 0);
10983         APInt SingleChar(numBits, 0);
10984         if (TD->isLittleEndian()) {
10985           for (signed i = len-1; i >= 0; i--) {
10986             SingleChar = (uint64_t) Str[i];
10987             StrVal = (StrVal << 8) | SingleChar;
10988           }
10989         } else {
10990           for (unsigned i = 0; i < len; i++) {
10991             SingleChar = (uint64_t) Str[i];
10992             StrVal = (StrVal << 8) | SingleChar;
10993           }
10994           // Append NULL at the end.
10995           SingleChar = 0;
10996           StrVal = (StrVal << 8) | SingleChar;
10997         }
10998         Value *NL = ConstantInt::get(StrVal);
10999         return IC.ReplaceInstUsesWith(LI, NL);
11000       }
11001     }
11002   }
11003 
11004   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11005   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11006     const Type *SrcPTy = SrcTy->getElementType();
11007 
11008     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11009          isa<VectorType>(DestPTy)) {
11010       // If the source is an array, the code below will not succeed.  Check to
11011       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11012       // constants.
11013       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11014         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11015           if (ASrcTy->getNumElements() != 0) {
11016             Value *Idxs[2];
11017             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11018             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11019             SrcTy = cast<PointerType>(CastOp->getType());
11020             SrcPTy = SrcTy->getElementType();
11021           }
11022 
11023       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11024             isa<VectorType>(SrcPTy)) &&
11025           // Do not allow turning this into a load of an integer, which is then
11026           // casted to a pointer, this pessimizes pointer analysis a lot.
11027           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11028           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11029                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11030 
11031         // Okay, we are casting from one integer or pointer type to another of
11032         // the same size.  Instead of casting the pointer before the load, cast
11033         // the result of the loaded value.
11034         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11035                                                              CI->getName(),
11036                                                          LI.isVolatile()),LI);
11037         // Now cast the result of the load.
11038         return new BitCastInst(NewLoad, LI.getType());
11039       }
11040     }
11041   }
11042   return 0;
11043 }
11044 
11045 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11046 /// from this value cannot trap.  If it is not obviously safe to load from the
11047 /// specified pointer, we do a quick local scan of the basic block containing
11048 /// ScanFrom, to determine if the address is already accessed.
11049 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11050   // If it is an alloca it is always safe to load from.
11051   if (isa<AllocaInst>(V)) return true;
11052 
11053   // If it is a global variable it is mostly safe to load from.
11054   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11055     // Don't try to evaluate aliases.  External weak GV can be null.
11056     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11057 
11058   // Otherwise, be a little bit agressive by scanning the local block where we
11059   // want to check to see if the pointer is already being loaded or stored
11060   // from/to.  If so, the previous load or store would have already trapped,
11061   // so there is no harm doing an extra load (also, CSE will later eliminate
11062   // the load entirely).
11063   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11064 
11065   while (BBI != E) {
11066     --BBI;
11067 
11068     // If we see a free or a call (which might do a free) the pointer could be
11069     // marked invalid.
11070     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
11071       return false;
11072     
11073     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11074       if (LI->getOperand(0) == V) return true;
11075     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11076       if (SI->getOperand(1) == V) return true;
11077     }
11078 
11079   }
11080   return false;
11081 }
11082 
11083 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11084   Value *Op = LI.getOperand(0);
11085 
11086   // Attempt to improve the alignment.
11087   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11088   if (KnownAlign >
11089       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11090                                 LI.getAlignment()))
11091     LI.setAlignment(KnownAlign);
11092 
11093   // load (cast X) --> cast (load X) iff safe
11094   if (isa<CastInst>(Op))
11095     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11096       return Res;
11097 
11098   // None of the following transforms are legal for volatile loads.
11099   if (LI.isVolatile()) return 0;
11100   
11101   // Do really simple store-to-load forwarding and load CSE, to catch cases
11102   // where there are several consequtive memory accesses to the same location,
11103   // separated by a few arithmetic operations.
11104   BasicBlock::iterator BBI = &LI;
11105   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11106     return ReplaceInstUsesWith(LI, AvailableVal);
11107 
11108   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11109     const Value *GEPI0 = GEPI->getOperand(0);
11110     // TODO: Consider a target hook for valid address spaces for this xform.
11111     if (isa<ConstantPointerNull>(GEPI0) &&
11112         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11113       // Insert a new store to null instruction before the load to indicate
11114       // that this code is not reachable.  We do this instead of inserting
11115       // an unreachable instruction directly because we cannot modify the
11116       // CFG.
11117       new StoreInst(UndefValue::get(LI.getType()),
11118                     Constant::getNullValue(Op->getType()), &LI);
11119       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11120     }
11121   } 
11122 
11123   if (Constant *C = dyn_cast<Constant>(Op)) {
11124     // load null/undef -> undef
11125     // TODO: Consider a target hook for valid address spaces for this xform.
11126     if (isa<UndefValue>(C) || (C->isNullValue() && 
11127         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11128       // Insert a new store to null instruction before the load to indicate that
11129       // this code is not reachable.  We do this instead of inserting an
11130       // unreachable instruction directly because we cannot modify the CFG.
11131       new StoreInst(UndefValue::get(LI.getType()),
11132                     Constant::getNullValue(Op->getType()), &LI);
11133       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11134     }
11135 
11136     // Instcombine load (constant global) into the value loaded.
11137     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11138       if (GV->isConstant() && !GV->isDeclaration())
11139         return ReplaceInstUsesWith(LI, GV->getInitializer());
11140 
11141     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11142     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11143       if (CE->getOpcode() == Instruction::GetElementPtr) {
11144         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11145           if (GV->isConstant() && !GV->isDeclaration())
11146             if (Constant *V = 
11147                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11148               return ReplaceInstUsesWith(LI, V);
11149         if (CE->getOperand(0)->isNullValue()) {
11150           // Insert a new store to null instruction before the load to indicate
11151           // that this code is not reachable.  We do this instead of inserting
11152           // an unreachable instruction directly because we cannot modify the
11153           // CFG.
11154           new StoreInst(UndefValue::get(LI.getType()),
11155                         Constant::getNullValue(Op->getType()), &LI);
11156           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11157         }
11158 
11159       } else if (CE->isCast()) {
11160         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11161           return Res;
11162       }
11163     }
11164   }
11165     
11166   // If this load comes from anywhere in a constant global, and if the global
11167   // is all undef or zero, we know what it loads.
11168   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11169     if (GV->isConstant() && GV->hasInitializer()) {
11170       if (GV->getInitializer()->isNullValue())
11171         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11172       else if (isa<UndefValue>(GV->getInitializer()))
11173         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11174     }
11175   }
11176 
11177   if (Op->hasOneUse()) {
11178     // Change select and PHI nodes to select values instead of addresses: this
11179     // helps alias analysis out a lot, allows many others simplifications, and
11180     // exposes redundancy in the code.
11181     //
11182     // Note that we cannot do the transformation unless we know that the
11183     // introduced loads cannot trap!  Something like this is valid as long as
11184     // the condition is always false: load (select bool %C, int* null, int* %G),
11185     // but it would not be valid if we transformed it to load from null
11186     // unconditionally.
11187     //
11188     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11189       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11190       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11191           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11192         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11193                                      SI->getOperand(1)->getName()+".val"), LI);
11194         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11195                                      SI->getOperand(2)->getName()+".val"), LI);
11196         return SelectInst::Create(SI->getCondition(), V1, V2);
11197       }
11198 
11199       // load (select (cond, null, P)) -> load P
11200       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11201         if (C->isNullValue()) {
11202           LI.setOperand(0, SI->getOperand(2));
11203           return &LI;
11204         }
11205 
11206       // load (select (cond, P, null)) -> load P
11207       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11208         if (C->isNullValue()) {
11209           LI.setOperand(0, SI->getOperand(1));
11210           return &LI;
11211         }
11212     }
11213   }
11214   return 0;
11215 }
11216 
11217 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11218 /// when possible.  This makes it generally easy to do alias analysis and/or
11219 /// SROA/mem2reg of the memory object.
11220 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11221   User *CI = cast<User>(SI.getOperand(1));
11222   Value *CastOp = CI->getOperand(0);
11223 
11224   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11225   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11226   if (SrcTy == 0) return 0;
11227   
11228   const Type *SrcPTy = SrcTy->getElementType();
11229 
11230   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11231     return 0;
11232   
11233   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11234   /// to its first element.  This allows us to handle things like:
11235   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11236   /// on 32-bit hosts.
11237   SmallVector<Value*, 4> NewGEPIndices;
11238   
11239   // If the source is an array, the code below will not succeed.  Check to
11240   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11241   // constants.
11242   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11243     // Index through pointer.
11244     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11245     NewGEPIndices.push_back(Zero);
11246     
11247     while (1) {
11248       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11249         if (!STy->getNumElements()) /* Struct can be empty {} */
11250           break;
11251         NewGEPIndices.push_back(Zero);
11252         SrcPTy = STy->getElementType(0);
11253       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11254         NewGEPIndices.push_back(Zero);
11255         SrcPTy = ATy->getElementType();
11256       } else {
11257         break;
11258       }
11259     }
11260     
11261     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11262   }
11263 
11264   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11265     return 0;
11266   
11267   // If the pointers point into different address spaces or if they point to
11268   // values with different sizes, we can't do the transformation.
11269   if (SrcTy->getAddressSpace() != 
11270         cast<PointerType>(CI->getType())->getAddressSpace() ||
11271       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11272       IC.getTargetData().getTypeSizeInBits(DestPTy))
11273     return 0;
11274 
11275   // Okay, we are casting from one integer or pointer type to another of
11276   // the same size.  Instead of casting the pointer before 
11277   // the store, cast the value to be stored.
11278   Value *NewCast;
11279   Value *SIOp0 = SI.getOperand(0);
11280   Instruction::CastOps opcode = Instruction::BitCast;
11281   const Type* CastSrcTy = SIOp0->getType();
11282   const Type* CastDstTy = SrcPTy;
11283   if (isa<PointerType>(CastDstTy)) {
11284     if (CastSrcTy->isInteger())
11285       opcode = Instruction::IntToPtr;
11286   } else if (isa<IntegerType>(CastDstTy)) {
11287     if (isa<PointerType>(SIOp0->getType()))
11288       opcode = Instruction::PtrToInt;
11289   }
11290   
11291   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11292   // emit a GEP to index into its first field.
11293   if (!NewGEPIndices.empty()) {
11294     if (Constant *C = dyn_cast<Constant>(CastOp))
11295       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11296                                               NewGEPIndices.size());
11297     else
11298       CastOp = IC.InsertNewInstBefore(
11299               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11300                                         NewGEPIndices.end()), SI);
11301   }
11302   
11303   if (Constant *C = dyn_cast<Constant>(SIOp0))
11304     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11305   else
11306     NewCast = IC.InsertNewInstBefore(
11307       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11308       SI);
11309   return new StoreInst(NewCast, CastOp);
11310 }
11311 
11312 /// equivalentAddressValues - Test if A and B will obviously have the same
11313 /// value. This includes recognizing that %t0 and %t1 will have the same
11314 /// value in code like this:
11315 ///   %t0 = getelementptr @a, 0, 3
11316 ///   store i32 0, i32* %t0
11317 ///   %t1 = getelementptr @a, 0, 3
11318 ///   %t2 = load i32* %t1
11319 ///
11320 static bool equivalentAddressValues(Value *A, Value *B) {
11321   // Test if the values are trivially equivalent.
11322   if (A == B) return true;
11323   
11324   // Test if the values come form identical arithmetic instructions.
11325   if (isa<BinaryOperator>(A) ||
11326       isa<CastInst>(A) ||
11327       isa<PHINode>(A) ||
11328       isa<GetElementPtrInst>(A))
11329     if (Instruction *BI = dyn_cast<Instruction>(B))
11330       if (cast<Instruction>(A)->isIdenticalTo(BI))
11331         return true;
11332   
11333   // Otherwise they may not be equivalent.
11334   return false;
11335 }
11336 
11337 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11338   Value *Val = SI.getOperand(0);
11339   Value *Ptr = SI.getOperand(1);
11340 
11341   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11342     EraseInstFromFunction(SI);
11343     ++NumCombined;
11344     return 0;
11345   }
11346   
11347   // If the RHS is an alloca with a single use, zapify the store, making the
11348   // alloca dead.
11349   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11350     if (isa<AllocaInst>(Ptr)) {
11351       EraseInstFromFunction(SI);
11352       ++NumCombined;
11353       return 0;
11354     }
11355     
11356     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11357       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11358           GEP->getOperand(0)->hasOneUse()) {
11359         EraseInstFromFunction(SI);
11360         ++NumCombined;
11361         return 0;
11362       }
11363   }
11364 
11365   // Attempt to improve the alignment.
11366   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11367   if (KnownAlign >
11368       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11369                                 SI.getAlignment()))
11370     SI.setAlignment(KnownAlign);
11371 
11372   // Do really simple DSE, to catch cases where there are several consequtive
11373   // stores to the same location, separated by a few arithmetic operations. This
11374   // situation often occurs with bitfield accesses.
11375   BasicBlock::iterator BBI = &SI;
11376   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11377        --ScanInsts) {
11378     --BBI;
11379     
11380     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11381       // Prev store isn't volatile, and stores to the same location?
11382       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11383                                                           SI.getOperand(1))) {
11384         ++NumDeadStore;
11385         ++BBI;
11386         EraseInstFromFunction(*PrevSI);
11387         continue;
11388       }
11389       break;
11390     }
11391     
11392     // If this is a load, we have to stop.  However, if the loaded value is from
11393     // the pointer we're loading and is producing the pointer we're storing,
11394     // then *this* store is dead (X = load P; store X -> P).
11395     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11396       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11397           !SI.isVolatile()) {
11398         EraseInstFromFunction(SI);
11399         ++NumCombined;
11400         return 0;
11401       }
11402       // Otherwise, this is a load from some other location.  Stores before it
11403       // may not be dead.
11404       break;
11405     }
11406     
11407     // Don't skip over loads or things that can modify memory.
11408     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11409       break;
11410   }
11411   
11412   
11413   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11414 
11415   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11416   if (isa<ConstantPointerNull>(Ptr)) {
11417     if (!isa<UndefValue>(Val)) {
11418       SI.setOperand(0, UndefValue::get(Val->getType()));
11419       if (Instruction *U = dyn_cast<Instruction>(Val))
11420         AddToWorkList(U);  // Dropped a use.
11421       ++NumCombined;
11422     }
11423     return 0;  // Do not modify these!
11424   }
11425 
11426   // store undef, Ptr -> noop
11427   if (isa<UndefValue>(Val)) {
11428     EraseInstFromFunction(SI);
11429     ++NumCombined;
11430     return 0;
11431   }
11432 
11433   // If the pointer destination is a cast, see if we can fold the cast into the
11434   // source instead.
11435   if (isa<CastInst>(Ptr))
11436     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11437       return Res;
11438   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11439     if (CE->isCast())
11440       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11441         return Res;
11442 
11443   
11444   // If this store is the last instruction in the basic block, and if the block
11445   // ends with an unconditional branch, try to move it to the successor block.
11446   BBI = &SI; ++BBI;
11447   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11448     if (BI->isUnconditional())
11449       if (SimplifyStoreAtEndOfBlock(SI))
11450         return 0;  // xform done!
11451   
11452   return 0;
11453 }
11454 
11455 /// SimplifyStoreAtEndOfBlock - Turn things like:
11456 ///   if () { *P = v1; } else { *P = v2 }
11457 /// into a phi node with a store in the successor.
11458 ///
11459 /// Simplify things like:
11460 ///   *P = v1; if () { *P = v2; }
11461 /// into a phi node with a store in the successor.
11462 ///
11463 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11464   BasicBlock *StoreBB = SI.getParent();
11465   
11466   // Check to see if the successor block has exactly two incoming edges.  If
11467   // so, see if the other predecessor contains a store to the same location.
11468   // if so, insert a PHI node (if needed) and move the stores down.
11469   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11470   
11471   // Determine whether Dest has exactly two predecessors and, if so, compute
11472   // the other predecessor.
11473   pred_iterator PI = pred_begin(DestBB);
11474   BasicBlock *OtherBB = 0;
11475   if (*PI != StoreBB)
11476     OtherBB = *PI;
11477   ++PI;
11478   if (PI == pred_end(DestBB))
11479     return false;
11480   
11481   if (*PI != StoreBB) {
11482     if (OtherBB)
11483       return false;
11484     OtherBB = *PI;
11485   }
11486   if (++PI != pred_end(DestBB))
11487     return false;
11488 
11489   // Bail out if all the relevant blocks aren't distinct (this can happen,
11490   // for example, if SI is in an infinite loop)
11491   if (StoreBB == DestBB || OtherBB == DestBB)
11492     return false;
11493 
11494   // Verify that the other block ends in a branch and is not otherwise empty.
11495   BasicBlock::iterator BBI = OtherBB->getTerminator();
11496   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11497   if (!OtherBr || BBI == OtherBB->begin())
11498     return false;
11499   
11500   // If the other block ends in an unconditional branch, check for the 'if then
11501   // else' case.  there is an instruction before the branch.
11502   StoreInst *OtherStore = 0;
11503   if (OtherBr->isUnconditional()) {
11504     // If this isn't a store, or isn't a store to the same location, bail out.
11505     --BBI;
11506     OtherStore = dyn_cast<StoreInst>(BBI);
11507     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11508       return false;
11509   } else {
11510     // Otherwise, the other block ended with a conditional branch. If one of the
11511     // destinations is StoreBB, then we have the if/then case.
11512     if (OtherBr->getSuccessor(0) != StoreBB && 
11513         OtherBr->getSuccessor(1) != StoreBB)
11514       return false;
11515     
11516     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11517     // if/then triangle.  See if there is a store to the same ptr as SI that
11518     // lives in OtherBB.
11519     for (;; --BBI) {
11520       // Check to see if we find the matching store.
11521       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11522         if (OtherStore->getOperand(1) != SI.getOperand(1))
11523           return false;
11524         break;
11525       }
11526       // If we find something that may be using or overwriting the stored
11527       // value, or if we run out of instructions, we can't do the xform.
11528       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11529           BBI == OtherBB->begin())
11530         return false;
11531     }
11532     
11533     // In order to eliminate the store in OtherBr, we have to
11534     // make sure nothing reads or overwrites the stored value in
11535     // StoreBB.
11536     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11537       // FIXME: This should really be AA driven.
11538       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11539         return false;
11540     }
11541   }
11542   
11543   // Insert a PHI node now if we need it.
11544   Value *MergedVal = OtherStore->getOperand(0);
11545   if (MergedVal != SI.getOperand(0)) {
11546     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11547     PN->reserveOperandSpace(2);
11548     PN->addIncoming(SI.getOperand(0), SI.getParent());
11549     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11550     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11551   }
11552   
11553   // Advance to a place where it is safe to insert the new store and
11554   // insert it.
11555   BBI = DestBB->getFirstNonPHI();
11556   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11557                                     OtherStore->isVolatile()), *BBI);
11558   
11559   // Nuke the old stores.
11560   EraseInstFromFunction(SI);
11561   EraseInstFromFunction(*OtherStore);
11562   ++NumCombined;
11563   return true;
11564 }
11565 
11566 
11567 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11568   // Change br (not X), label True, label False to: br X, label False, True
11569   Value *X = 0;
11570   BasicBlock *TrueDest;
11571   BasicBlock *FalseDest;
11572   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11573       !isa<Constant>(X)) {
11574     // Swap Destinations and condition...
11575     BI.setCondition(X);
11576     BI.setSuccessor(0, FalseDest);
11577     BI.setSuccessor(1, TrueDest);
11578     return &BI;
11579   }
11580 
11581   // Cannonicalize fcmp_one -> fcmp_oeq
11582   FCmpInst::Predicate FPred; Value *Y;
11583   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11584                              TrueDest, FalseDest)))
11585     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11586          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11587       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11588       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11589       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11590       NewSCC->takeName(I);
11591       // Swap Destinations and condition...
11592       BI.setCondition(NewSCC);
11593       BI.setSuccessor(0, FalseDest);
11594       BI.setSuccessor(1, TrueDest);
11595       RemoveFromWorkList(I);
11596       I->eraseFromParent();
11597       AddToWorkList(NewSCC);
11598       return &BI;
11599     }
11600 
11601   // Cannonicalize icmp_ne -> icmp_eq
11602   ICmpInst::Predicate IPred;
11603   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11604                       TrueDest, FalseDest)))
11605     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11606          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11607          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11608       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11609       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11610       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11611       NewSCC->takeName(I);
11612       // Swap Destinations and condition...
11613       BI.setCondition(NewSCC);
11614       BI.setSuccessor(0, FalseDest);
11615       BI.setSuccessor(1, TrueDest);
11616       RemoveFromWorkList(I);
11617       I->eraseFromParent();;
11618       AddToWorkList(NewSCC);
11619       return &BI;
11620     }
11621 
11622   return 0;
11623 }
11624 
11625 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11626   Value *Cond = SI.getCondition();
11627   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11628     if (I->getOpcode() == Instruction::Add)
11629       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11630         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11631         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11632           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11633                                                 AddRHS));
11634         SI.setOperand(0, I->getOperand(0));
11635         AddToWorkList(I);
11636         return &SI;
11637       }
11638   }
11639   return 0;
11640 }
11641 
11642 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11643   Value *Agg = EV.getAggregateOperand();
11644 
11645   if (!EV.hasIndices())
11646     return ReplaceInstUsesWith(EV, Agg);
11647 
11648   if (Constant *C = dyn_cast<Constant>(Agg)) {
11649     if (isa<UndefValue>(C))
11650       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11651       
11652     if (isa<ConstantAggregateZero>(C))
11653       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11654 
11655     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11656       // Extract the element indexed by the first index out of the constant
11657       Value *V = C->getOperand(*EV.idx_begin());
11658       if (EV.getNumIndices() > 1)
11659         // Extract the remaining indices out of the constant indexed by the
11660         // first index
11661         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11662       else
11663         return ReplaceInstUsesWith(EV, V);
11664     }
11665     return 0; // Can't handle other constants
11666   } 
11667   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11668     // We're extracting from an insertvalue instruction, compare the indices
11669     const unsigned *exti, *exte, *insi, *inse;
11670     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11671          exte = EV.idx_end(), inse = IV->idx_end();
11672          exti != exte && insi != inse;
11673          ++exti, ++insi) {
11674       if (*insi != *exti)
11675         // The insert and extract both reference distinctly different elements.
11676         // This means the extract is not influenced by the insert, and we can
11677         // replace the aggregate operand of the extract with the aggregate
11678         // operand of the insert. i.e., replace
11679         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11680         // %E = extractvalue { i32, { i32 } } %I, 0
11681         // with
11682         // %E = extractvalue { i32, { i32 } } %A, 0
11683         return ExtractValueInst::Create(IV->getAggregateOperand(),
11684                                         EV.idx_begin(), EV.idx_end());
11685     }
11686     if (exti == exte && insi == inse)
11687       // Both iterators are at the end: Index lists are identical. Replace
11688       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11689       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11690       // with "i32 42"
11691       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11692     if (exti == exte) {
11693       // The extract list is a prefix of the insert list. i.e. replace
11694       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11695       // %E = extractvalue { i32, { i32 } } %I, 1
11696       // with
11697       // %X = extractvalue { i32, { i32 } } %A, 1
11698       // %E = insertvalue { i32 } %X, i32 42, 0
11699       // by switching the order of the insert and extract (though the
11700       // insertvalue should be left in, since it may have other uses).
11701       Value *NewEV = InsertNewInstBefore(
11702         ExtractValueInst::Create(IV->getAggregateOperand(),
11703                                  EV.idx_begin(), EV.idx_end()),
11704         EV);
11705       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11706                                      insi, inse);
11707     }
11708     if (insi == inse)
11709       // The insert list is a prefix of the extract list
11710       // We can simply remove the common indices from the extract and make it
11711       // operate on the inserted value instead of the insertvalue result.
11712       // i.e., replace
11713       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11714       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11715       // with
11716       // %E extractvalue { i32 } { i32 42 }, 0
11717       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11718                                       exti, exte);
11719   }
11720   // Can't simplify extracts from other values. Note that nested extracts are
11721   // already simplified implicitely by the above (extract ( extract (insert) )
11722   // will be translated into extract ( insert ( extract ) ) first and then just
11723   // the value inserted, if appropriate).
11724   return 0;
11725 }
11726 
11727 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11728 /// is to leave as a vector operation.
11729 static bool CheapToScalarize(Value *V, bool isConstant) {
11730   if (isa<ConstantAggregateZero>(V)) 
11731     return true;
11732   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11733     if (isConstant) return true;
11734     // If all elts are the same, we can extract.
11735     Constant *Op0 = C->getOperand(0);
11736     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11737       if (C->getOperand(i) != Op0)
11738         return false;
11739     return true;
11740   }
11741   Instruction *I = dyn_cast<Instruction>(V);
11742   if (!I) return false;
11743   
11744   // Insert element gets simplified to the inserted element or is deleted if
11745   // this is constant idx extract element and its a constant idx insertelt.
11746   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11747       isa<ConstantInt>(I->getOperand(2)))
11748     return true;
11749   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11750     return true;
11751   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11752     if (BO->hasOneUse() &&
11753         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11754          CheapToScalarize(BO->getOperand(1), isConstant)))
11755       return true;
11756   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11757     if (CI->hasOneUse() &&
11758         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11759          CheapToScalarize(CI->getOperand(1), isConstant)))
11760       return true;
11761   
11762   return false;
11763 }
11764 
11765 /// Read and decode a shufflevector mask.
11766 ///
11767 /// It turns undef elements into values that are larger than the number of
11768 /// elements in the input.
11769 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11770   unsigned NElts = SVI->getType()->getNumElements();
11771   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11772     return std::vector<unsigned>(NElts, 0);
11773   if (isa<UndefValue>(SVI->getOperand(2)))
11774     return std::vector<unsigned>(NElts, 2*NElts);
11775 
11776   std::vector<unsigned> Result;
11777   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11778   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11779     if (isa<UndefValue>(*i))
11780       Result.push_back(NElts*2);  // undef -> 8
11781     else
11782       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11783   return Result;
11784 }
11785 
11786 /// FindScalarElement - Given a vector and an element number, see if the scalar
11787 /// value is already around as a register, for example if it were inserted then
11788 /// extracted from the vector.
11789 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11790   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11791   const VectorType *PTy = cast<VectorType>(V->getType());
11792   unsigned Width = PTy->getNumElements();
11793   if (EltNo >= Width)  // Out of range access.
11794     return UndefValue::get(PTy->getElementType());
11795   
11796   if (isa<UndefValue>(V))
11797     return UndefValue::get(PTy->getElementType());
11798   else if (isa<ConstantAggregateZero>(V))
11799     return Constant::getNullValue(PTy->getElementType());
11800   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11801     return CP->getOperand(EltNo);
11802   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11803     // If this is an insert to a variable element, we don't know what it is.
11804     if (!isa<ConstantInt>(III->getOperand(2))) 
11805       return 0;
11806     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11807     
11808     // If this is an insert to the element we are looking for, return the
11809     // inserted value.
11810     if (EltNo == IIElt) 
11811       return III->getOperand(1);
11812     
11813     // Otherwise, the insertelement doesn't modify the value, recurse on its
11814     // vector input.
11815     return FindScalarElement(III->getOperand(0), EltNo);
11816   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11817     unsigned LHSWidth =
11818       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11819     unsigned InEl = getShuffleMask(SVI)[EltNo];
11820     if (InEl < LHSWidth)
11821       return FindScalarElement(SVI->getOperand(0), InEl);
11822     else if (InEl < LHSWidth*2)
11823       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11824     else
11825       return UndefValue::get(PTy->getElementType());
11826   }
11827   
11828   // Otherwise, we don't know.
11829   return 0;
11830 }
11831 
11832 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11833   // If vector val is undef, replace extract with scalar undef.
11834   if (isa<UndefValue>(EI.getOperand(0)))
11835     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11836 
11837   // If vector val is constant 0, replace extract with scalar 0.
11838   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11839     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11840   
11841   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11842     // If vector val is constant with all elements the same, replace EI with
11843     // that element. When the elements are not identical, we cannot replace yet
11844     // (we do that below, but only when the index is constant).
11845     Constant *op0 = C->getOperand(0);
11846     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11847       if (C->getOperand(i) != op0) {
11848         op0 = 0; 
11849         break;
11850       }
11851     if (op0)
11852       return ReplaceInstUsesWith(EI, op0);
11853   }
11854   
11855   // If extracting a specified index from the vector, see if we can recursively
11856   // find a previously computed scalar that was inserted into the vector.
11857   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11858     unsigned IndexVal = IdxC->getZExtValue();
11859     unsigned VectorWidth = 
11860       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11861       
11862     // If this is extracting an invalid index, turn this into undef, to avoid
11863     // crashing the code below.
11864     if (IndexVal >= VectorWidth)
11865       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11866     
11867     // This instruction only demands the single element from the input vector.
11868     // If the input vector has a single use, simplify it based on this use
11869     // property.
11870     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11871       uint64_t UndefElts;
11872       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11873                                                 1 << IndexVal,
11874                                                 UndefElts)) {
11875         EI.setOperand(0, V);
11876         return &EI;
11877       }
11878     }
11879     
11880     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11881       return ReplaceInstUsesWith(EI, Elt);
11882     
11883     // If the this extractelement is directly using a bitcast from a vector of
11884     // the same number of elements, see if we can find the source element from
11885     // it.  In this case, we will end up needing to bitcast the scalars.
11886     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11887       if (const VectorType *VT = 
11888               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11889         if (VT->getNumElements() == VectorWidth)
11890           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11891             return new BitCastInst(Elt, EI.getType());
11892     }
11893   }
11894   
11895   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11896     if (I->hasOneUse()) {
11897       // Push extractelement into predecessor operation if legal and
11898       // profitable to do so
11899       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11900         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11901         if (CheapToScalarize(BO, isConstantElt)) {
11902           ExtractElementInst *newEI0 = 
11903             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11904                                    EI.getName()+".lhs");
11905           ExtractElementInst *newEI1 =
11906             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11907                                    EI.getName()+".rhs");
11908           InsertNewInstBefore(newEI0, EI);
11909           InsertNewInstBefore(newEI1, EI);
11910           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11911         }
11912       } else if (isa<LoadInst>(I)) {
11913         unsigned AS = 
11914           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11915         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11916                                          PointerType::get(EI.getType(), AS),EI);
11917         GetElementPtrInst *GEP =
11918           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11919         InsertNewInstBefore(GEP, EI);
11920         return new LoadInst(GEP);
11921       }
11922     }
11923     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11924       // Extracting the inserted element?
11925       if (IE->getOperand(2) == EI.getOperand(1))
11926         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11927       // If the inserted and extracted elements are constants, they must not
11928       // be the same value, extract from the pre-inserted value instead.
11929       if (isa<Constant>(IE->getOperand(2)) &&
11930           isa<Constant>(EI.getOperand(1))) {
11931         AddUsesToWorkList(EI);
11932         EI.setOperand(0, IE->getOperand(0));
11933         return &EI;
11934       }
11935     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11936       // If this is extracting an element from a shufflevector, figure out where
11937       // it came from and extract from the appropriate input element instead.
11938       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11939         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11940         Value *Src;
11941         unsigned LHSWidth =
11942           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11943 
11944         if (SrcIdx < LHSWidth)
11945           Src = SVI->getOperand(0);
11946         else if (SrcIdx < LHSWidth*2) {
11947           SrcIdx -= LHSWidth;
11948           Src = SVI->getOperand(1);
11949         } else {
11950           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11951         }
11952         return new ExtractElementInst(Src, SrcIdx);
11953       }
11954     }
11955   }
11956   return 0;
11957 }
11958 
11959 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11960 /// elements from either LHS or RHS, return the shuffle mask and true. 
11961 /// Otherwise, return false.
11962 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11963                                          std::vector<Constant*> &Mask) {
11964   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11965          "Invalid CollectSingleShuffleElements");
11966   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11967 
11968   if (isa<UndefValue>(V)) {
11969     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11970     return true;
11971   } else if (V == LHS) {
11972     for (unsigned i = 0; i != NumElts; ++i)
11973       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11974     return true;
11975   } else if (V == RHS) {
11976     for (unsigned i = 0; i != NumElts; ++i)
11977       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11978     return true;
11979   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11980     // If this is an insert of an extract from some other vector, include it.
11981     Value *VecOp    = IEI->getOperand(0);
11982     Value *ScalarOp = IEI->getOperand(1);
11983     Value *IdxOp    = IEI->getOperand(2);
11984     
11985     if (!isa<ConstantInt>(IdxOp))
11986       return false;
11987     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11988     
11989     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11990       // Okay, we can handle this if the vector we are insertinting into is
11991       // transitively ok.
11992       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11993         // If so, update the mask to reflect the inserted undef.
11994         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11995         return true;
11996       }      
11997     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11998       if (isa<ConstantInt>(EI->getOperand(1)) &&
11999           EI->getOperand(0)->getType() == V->getType()) {
12000         unsigned ExtractedIdx =
12001           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12002         
12003         // This must be extracting from either LHS or RHS.
12004         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12005           // Okay, we can handle this if the vector we are insertinting into is
12006           // transitively ok.
12007           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12008             // If so, update the mask to reflect the inserted value.
12009             if (EI->getOperand(0) == LHS) {
12010               Mask[InsertedIdx % NumElts] = 
12011                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12012             } else {
12013               assert(EI->getOperand(0) == RHS);
12014               Mask[InsertedIdx % NumElts] = 
12015                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12016               
12017             }
12018             return true;
12019           }
12020         }
12021       }
12022     }
12023   }
12024   // TODO: Handle shufflevector here!
12025   
12026   return false;
12027 }
12028 
12029 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12030 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12031 /// that computes V and the LHS value of the shuffle.
12032 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12033                                      Value *&RHS) {
12034   assert(isa<VectorType>(V->getType()) && 
12035          (RHS == 0 || V->getType() == RHS->getType()) &&
12036          "Invalid shuffle!");
12037   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12038 
12039   if (isa<UndefValue>(V)) {
12040     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12041     return V;
12042   } else if (isa<ConstantAggregateZero>(V)) {
12043     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12044     return V;
12045   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12046     // If this is an insert of an extract from some other vector, include it.
12047     Value *VecOp    = IEI->getOperand(0);
12048     Value *ScalarOp = IEI->getOperand(1);
12049     Value *IdxOp    = IEI->getOperand(2);
12050     
12051     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12052       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12053           EI->getOperand(0)->getType() == V->getType()) {
12054         unsigned ExtractedIdx =
12055           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12056         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12057         
12058         // Either the extracted from or inserted into vector must be RHSVec,
12059         // otherwise we'd end up with a shuffle of three inputs.
12060         if (EI->getOperand(0) == RHS || RHS == 0) {
12061           RHS = EI->getOperand(0);
12062           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12063           Mask[InsertedIdx % NumElts] = 
12064             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12065           return V;
12066         }
12067         
12068         if (VecOp == RHS) {
12069           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12070           // Everything but the extracted element is replaced with the RHS.
12071           for (unsigned i = 0; i != NumElts; ++i) {
12072             if (i != InsertedIdx)
12073               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12074           }
12075           return V;
12076         }
12077         
12078         // If this insertelement is a chain that comes from exactly these two
12079         // vectors, return the vector and the effective shuffle.
12080         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12081           return EI->getOperand(0);
12082         
12083       }
12084     }
12085   }
12086   // TODO: Handle shufflevector here!
12087   
12088   // Otherwise, can't do anything fancy.  Return an identity vector.
12089   for (unsigned i = 0; i != NumElts; ++i)
12090     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12091   return V;
12092 }
12093 
12094 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12095   Value *VecOp    = IE.getOperand(0);
12096   Value *ScalarOp = IE.getOperand(1);
12097   Value *IdxOp    = IE.getOperand(2);
12098   
12099   // Inserting an undef or into an undefined place, remove this.
12100   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12101     ReplaceInstUsesWith(IE, VecOp);
12102   
12103   // If the inserted element was extracted from some other vector, and if the 
12104   // indexes are constant, try to turn this into a shufflevector operation.
12105   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12106     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12107         EI->getOperand(0)->getType() == IE.getType()) {
12108       unsigned NumVectorElts = IE.getType()->getNumElements();
12109       unsigned ExtractedIdx =
12110         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12111       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12112       
12113       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12114         return ReplaceInstUsesWith(IE, VecOp);
12115       
12116       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12117         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12118       
12119       // If we are extracting a value from a vector, then inserting it right
12120       // back into the same place, just use the input vector.
12121       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12122         return ReplaceInstUsesWith(IE, VecOp);      
12123       
12124       // We could theoretically do this for ANY input.  However, doing so could
12125       // turn chains of insertelement instructions into a chain of shufflevector
12126       // instructions, and right now we do not merge shufflevectors.  As such,
12127       // only do this in a situation where it is clear that there is benefit.
12128       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12129         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12130         // the values of VecOp, except then one read from EIOp0.
12131         // Build a new shuffle mask.
12132         std::vector<Constant*> Mask;
12133         if (isa<UndefValue>(VecOp))
12134           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12135         else {
12136           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12137           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12138                                                        NumVectorElts));
12139         } 
12140         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12141         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12142                                      ConstantVector::get(Mask));
12143       }
12144       
12145       // If this insertelement isn't used by some other insertelement, turn it
12146       // (and any insertelements it points to), into one big shuffle.
12147       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12148         std::vector<Constant*> Mask;
12149         Value *RHS = 0;
12150         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12151         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12152         // We now have a shuffle of LHS, RHS, Mask.
12153         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12154       }
12155     }
12156   }
12157 
12158   return 0;
12159 }
12160 
12161 
12162 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12163   Value *LHS = SVI.getOperand(0);
12164   Value *RHS = SVI.getOperand(1);
12165   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12166 
12167   bool MadeChange = false;
12168 
12169   // Undefined shuffle mask -> undefined value.
12170   if (isa<UndefValue>(SVI.getOperand(2)))
12171     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12172 
12173   uint64_t UndefElts;
12174   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12175 
12176   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12177     return 0;
12178 
12179   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12180   if (VWidth <= 64 &&
12181       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12182     LHS = SVI.getOperand(0);
12183     RHS = SVI.getOperand(1);
12184     MadeChange = true;
12185   }
12186   
12187   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12188   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12189   if (LHS == RHS || isa<UndefValue>(LHS)) {
12190     if (isa<UndefValue>(LHS) && LHS == RHS) {
12191       // shuffle(undef,undef,mask) -> undef.
12192       return ReplaceInstUsesWith(SVI, LHS);
12193     }
12194     
12195     // Remap any references to RHS to use LHS.
12196     std::vector<Constant*> Elts;
12197     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12198       if (Mask[i] >= 2*e)
12199         Elts.push_back(UndefValue::get(Type::Int32Ty));
12200       else {
12201         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12202             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12203           Mask[i] = 2*e;     // Turn into undef.
12204           Elts.push_back(UndefValue::get(Type::Int32Ty));
12205         } else {
12206           Mask[i] = Mask[i] % e;  // Force to LHS.
12207           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12208         }
12209       }
12210     }
12211     SVI.setOperand(0, SVI.getOperand(1));
12212     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12213     SVI.setOperand(2, ConstantVector::get(Elts));
12214     LHS = SVI.getOperand(0);
12215     RHS = SVI.getOperand(1);
12216     MadeChange = true;
12217   }
12218   
12219   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12220   bool isLHSID = true, isRHSID = true;
12221     
12222   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12223     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12224     // Is this an identity shuffle of the LHS value?
12225     isLHSID &= (Mask[i] == i);
12226       
12227     // Is this an identity shuffle of the RHS value?
12228     isRHSID &= (Mask[i]-e == i);
12229   }
12230 
12231   // Eliminate identity shuffles.
12232   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12233   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12234   
12235   // If the LHS is a shufflevector itself, see if we can combine it with this
12236   // one without producing an unusual shuffle.  Here we are really conservative:
12237   // we are absolutely afraid of producing a shuffle mask not in the input
12238   // program, because the code gen may not be smart enough to turn a merged
12239   // shuffle into two specific shuffles: it may produce worse code.  As such,
12240   // we only merge two shuffles if the result is one of the two input shuffle
12241   // masks.  In this case, merging the shuffles just removes one instruction,
12242   // which we know is safe.  This is good for things like turning:
12243   // (splat(splat)) -> splat.
12244   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12245     if (isa<UndefValue>(RHS)) {
12246       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12247 
12248       std::vector<unsigned> NewMask;
12249       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12250         if (Mask[i] >= 2*e)
12251           NewMask.push_back(2*e);
12252         else
12253           NewMask.push_back(LHSMask[Mask[i]]);
12254       
12255       // If the result mask is equal to the src shuffle or this shuffle mask, do
12256       // the replacement.
12257       if (NewMask == LHSMask || NewMask == Mask) {
12258         unsigned LHSInNElts =
12259           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12260         std::vector<Constant*> Elts;
12261         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12262           if (NewMask[i] >= LHSInNElts*2) {
12263             Elts.push_back(UndefValue::get(Type::Int32Ty));
12264           } else {
12265             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12266           }
12267         }
12268         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12269                                      LHSSVI->getOperand(1),
12270                                      ConstantVector::get(Elts));
12271       }
12272     }
12273   }
12274 
12275   return MadeChange ? &SVI : 0;
12276 }
12277 
12278 
12279 
12280 
12281 /// TryToSinkInstruction - Try to move the specified instruction from its
12282 /// current block into the beginning of DestBlock, which can only happen if it's
12283 /// safe to move the instruction past all of the instructions between it and the
12284 /// end of its block.
12285 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12286   assert(I->hasOneUse() && "Invariants didn't hold!");
12287 
12288   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12289   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12290     return false;
12291 
12292   // Do not sink alloca instructions out of the entry block.
12293   if (isa<AllocaInst>(I) && I->getParent() ==
12294         &DestBlock->getParent()->getEntryBlock())
12295     return false;
12296 
12297   // We can only sink load instructions if there is nothing between the load and
12298   // the end of block that could change the value.
12299   if (I->mayReadFromMemory()) {
12300     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12301          Scan != E; ++Scan)
12302       if (Scan->mayWriteToMemory())
12303         return false;
12304   }
12305 
12306   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12307 
12308   I->moveBefore(InsertPos);
12309   ++NumSunkInst;
12310   return true;
12311 }
12312 
12313 
12314 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12315 /// all reachable code to the worklist.
12316 ///
12317 /// This has a couple of tricks to make the code faster and more powerful.  In
12318 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12319 /// them to the worklist (this significantly speeds up instcombine on code where
12320 /// many instructions are dead or constant).  Additionally, if we find a branch
12321 /// whose condition is a known constant, we only visit the reachable successors.
12322 ///
12323 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12324                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12325                                        InstCombiner &IC,
12326                                        const TargetData *TD) {
12327   SmallVector<BasicBlock*, 256> Worklist;
12328   Worklist.push_back(BB);
12329 
12330   while (!Worklist.empty()) {
12331     BB = Worklist.back();
12332     Worklist.pop_back();
12333     
12334     // We have now visited this block!  If we've already been here, ignore it.
12335     if (!Visited.insert(BB)) continue;
12336 
12337     DbgInfoIntrinsic *DBI_Prev = NULL;
12338     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12339       Instruction *Inst = BBI++;
12340       
12341       // DCE instruction if trivially dead.
12342       if (isInstructionTriviallyDead(Inst)) {
12343         ++NumDeadInst;
12344         DOUT << "IC: DCE: " << *Inst;
12345         Inst->eraseFromParent();
12346         continue;
12347       }
12348       
12349       // ConstantProp instruction if trivially constant.
12350       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12351         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12352         Inst->replaceAllUsesWith(C);
12353         ++NumConstProp;
12354         Inst->eraseFromParent();
12355         continue;
12356       }
12357      
12358       // If there are two consecutive llvm.dbg.stoppoint calls then
12359       // it is likely that the optimizer deleted code in between these
12360       // two intrinsics. 
12361       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12362       if (DBI_Next) {
12363         if (DBI_Prev
12364             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12365             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12366           IC.RemoveFromWorkList(DBI_Prev);
12367           DBI_Prev->eraseFromParent();
12368         }
12369         DBI_Prev = DBI_Next;
12370       }
12371 
12372       IC.AddToWorkList(Inst);
12373     }
12374 
12375     // Recursively visit successors.  If this is a branch or switch on a
12376     // constant, only visit the reachable successor.
12377     TerminatorInst *TI = BB->getTerminator();
12378     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12379       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12380         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12381         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12382         Worklist.push_back(ReachableBB);
12383         continue;
12384       }
12385     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12386       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12387         // See if this is an explicit destination.
12388         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12389           if (SI->getCaseValue(i) == Cond) {
12390             BasicBlock *ReachableBB = SI->getSuccessor(i);
12391             Worklist.push_back(ReachableBB);
12392             continue;
12393           }
12394         
12395         // Otherwise it is the default destination.
12396         Worklist.push_back(SI->getSuccessor(0));
12397         continue;
12398       }
12399     }
12400     
12401     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12402       Worklist.push_back(TI->getSuccessor(i));
12403   }
12404 }
12405 
12406 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12407   bool Changed = false;
12408   TD = &getAnalysis<TargetData>();
12409   
12410   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12411              << F.getNameStr() << "\n");
12412 
12413   {
12414     // Do a depth-first traversal of the function, populate the worklist with
12415     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12416     // track of which blocks we visit.
12417     SmallPtrSet<BasicBlock*, 64> Visited;
12418     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12419 
12420     // Do a quick scan over the function.  If we find any blocks that are
12421     // unreachable, remove any instructions inside of them.  This prevents
12422     // the instcombine code from having to deal with some bad special cases.
12423     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12424       if (!Visited.count(BB)) {
12425         Instruction *Term = BB->getTerminator();
12426         while (Term != BB->begin()) {   // Remove instrs bottom-up
12427           BasicBlock::iterator I = Term; --I;
12428 
12429           DOUT << "IC: DCE: " << *I;
12430           ++NumDeadInst;
12431 
12432           if (!I->use_empty())
12433             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12434           I->eraseFromParent();
12435           Changed = true;
12436         }
12437       }
12438   }
12439 
12440   while (!Worklist.empty()) {
12441     Instruction *I = RemoveOneFromWorkList();
12442     if (I == 0) continue;  // skip null values.
12443 
12444     // Check to see if we can DCE the instruction.
12445     if (isInstructionTriviallyDead(I)) {
12446       // Add operands to the worklist.
12447       if (I->getNumOperands() < 4)
12448         AddUsesToWorkList(*I);
12449       ++NumDeadInst;
12450 
12451       DOUT << "IC: DCE: " << *I;
12452 
12453       I->eraseFromParent();
12454       RemoveFromWorkList(I);
12455       Changed = true;
12456       continue;
12457     }
12458 
12459     // Instruction isn't dead, see if we can constant propagate it.
12460     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12461       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12462 
12463       // Add operands to the worklist.
12464       AddUsesToWorkList(*I);
12465       ReplaceInstUsesWith(*I, C);
12466 
12467       ++NumConstProp;
12468       I->eraseFromParent();
12469       RemoveFromWorkList(I);
12470       Changed = true;
12471       continue;
12472     }
12473 
12474     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12475       // See if we can constant fold its operands.
12476       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12477         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12478           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12479             if (NewC != CE) {
12480               i->set(NewC);
12481               Changed = true;
12482             }
12483     }
12484 
12485     // See if we can trivially sink this instruction to a successor basic block.
12486     if (I->hasOneUse()) {
12487       BasicBlock *BB = I->getParent();
12488       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12489       if (UserParent != BB) {
12490         bool UserIsSuccessor = false;
12491         // See if the user is one of our successors.
12492         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12493           if (*SI == UserParent) {
12494             UserIsSuccessor = true;
12495             break;
12496           }
12497 
12498         // If the user is one of our immediate successors, and if that successor
12499         // only has us as a predecessors (we'd have to split the critical edge
12500         // otherwise), we can keep going.
12501         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12502             next(pred_begin(UserParent)) == pred_end(UserParent))
12503           // Okay, the CFG is simple enough, try to sink this instruction.
12504           Changed |= TryToSinkInstruction(I, UserParent);
12505       }
12506     }
12507 
12508     // Now that we have an instruction, try combining it to simplify it...
12509 #ifndef NDEBUG
12510     std::string OrigI;
12511 #endif
12512     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12513     if (Instruction *Result = visit(*I)) {
12514       ++NumCombined;
12515       // Should we replace the old instruction with a new one?
12516       if (Result != I) {
12517         DOUT << "IC: Old = " << *I
12518              << "    New = " << *Result;
12519 
12520         // Everything uses the new instruction now.
12521         I->replaceAllUsesWith(Result);
12522 
12523         // Push the new instruction and any users onto the worklist.
12524         AddToWorkList(Result);
12525         AddUsersToWorkList(*Result);
12526 
12527         // Move the name to the new instruction first.
12528         Result->takeName(I);
12529 
12530         // Insert the new instruction into the basic block...
12531         BasicBlock *InstParent = I->getParent();
12532         BasicBlock::iterator InsertPos = I;
12533 
12534         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12535           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12536             ++InsertPos;
12537 
12538         InstParent->getInstList().insert(InsertPos, Result);
12539 
12540         // Make sure that we reprocess all operands now that we reduced their
12541         // use counts.
12542         AddUsesToWorkList(*I);
12543 
12544         // Instructions can end up on the worklist more than once.  Make sure
12545         // we do not process an instruction that has been deleted.
12546         RemoveFromWorkList(I);
12547 
12548         // Erase the old instruction.
12549         InstParent->getInstList().erase(I);
12550       } else {
12551 #ifndef NDEBUG
12552         DOUT << "IC: Mod = " << OrigI
12553              << "    New = " << *I;
12554 #endif
12555 
12556         // If the instruction was modified, it's possible that it is now dead.
12557         // if so, remove it.
12558         if (isInstructionTriviallyDead(I)) {
12559           // Make sure we process all operands now that we are reducing their
12560           // use counts.
12561           AddUsesToWorkList(*I);
12562 
12563           // Instructions may end up in the worklist more than once.  Erase all
12564           // occurrences of this instruction.
12565           RemoveFromWorkList(I);
12566           I->eraseFromParent();
12567         } else {
12568           AddToWorkList(I);
12569           AddUsersToWorkList(*I);
12570         }
12571       }
12572       Changed = true;
12573     }
12574   }
12575 
12576   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12577     
12578   // Do an explicit clear, this shrinks the map if needed.
12579   WorklistMap.clear();
12580   return Changed;
12581 }
12582 
12583 
12584 bool InstCombiner::runOnFunction(Function &F) {
12585   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12586   
12587   bool EverMadeChange = false;
12588 
12589   // Iterate while there is work to do.
12590   unsigned Iteration = 0;
12591   while (DoOneIteration(F, Iteration++))
12592     EverMadeChange = true;
12593   return EverMadeChange;
12594 }
12595 
12596 FunctionPass *llvm::createInstructionCombiningPass() {
12597   return new InstCombiner();
12598 }