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 "InstCombine.h"
00039 #include "llvm-c/Initialization.h"
00040 #include "llvm/ADT/SmallPtrSet.h"
00041 #include "llvm/ADT/Statistic.h"
00042 #include "llvm/ADT/StringSwitch.h"
00043 #include "llvm/Analysis/ConstantFolding.h"
00044 #include "llvm/Analysis/InstructionSimplify.h"
00045 #include "llvm/Analysis/MemoryBuiltins.h"
00046 #include "llvm/IR/CFG.h"
00047 #include "llvm/IR/DataLayout.h"
00048 #include "llvm/IR/GetElementPtrTypeIterator.h"
00049 #include "llvm/IR/IntrinsicInst.h"
00050 #include "llvm/IR/PatternMatch.h"
00051 #include "llvm/IR/ValueHandle.h"
00052 #include "llvm/Support/CommandLine.h"
00053 #include "llvm/Support/Debug.h"
00054 #include "llvm/Target/TargetLibraryInfo.h"
00055 #include "llvm/Transforms/Utils/Local.h"
00056 #include <algorithm>
00057 #include <climits>
00058 using namespace llvm;
00059 using namespace llvm::PatternMatch;
00060 
00061 STATISTIC(NumCombined , "Number of insts combined");
00062 STATISTIC(NumConstProp, "Number of constant folds");
00063 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
00064 STATISTIC(NumSunkInst , "Number of instructions sunk");
00065 STATISTIC(NumExpand,    "Number of expansions");
00066 STATISTIC(NumFactor   , "Number of factorizations");
00067 STATISTIC(NumReassoc  , "Number of reassociations");
00068 
00069 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
00070                                    cl::init(false),
00071                                    cl::desc("Enable unsafe double to float "
00072                                             "shrinking for math lib calls"));
00073 
00074 // Initialization Routines
00075 void llvm::initializeInstCombine(PassRegistry &Registry) {
00076   initializeInstCombinerPass(Registry);
00077 }
00078 
00079 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
00080   initializeInstCombine(*unwrap(R));
00081 }
00082 
00083 char InstCombiner::ID = 0;
00084 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
00085                 "Combine redundant instructions", false, false)
00086 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00087 INITIALIZE_PASS_END(InstCombiner, "instcombine",
00088                 "Combine redundant instructions", false, false)
00089 
00090 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
00091   AU.setPreservesCFG();
00092   AU.addRequired<TargetLibraryInfo>();
00093 }
00094 
00095 
00096 Value *InstCombiner::EmitGEPOffset(User *GEP) {
00097   return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
00098 }
00099 
00100 /// ShouldChangeType - Return true if it is desirable to convert a computation
00101 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
00102 /// type for example, or from a smaller to a larger illegal type.
00103 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
00104   assert(From->isIntegerTy() && To->isIntegerTy());
00105 
00106   // If we don't have DL, we don't know if the source/dest are legal.
00107   if (!DL) return false;
00108 
00109   unsigned FromWidth = From->getPrimitiveSizeInBits();
00110   unsigned ToWidth = To->getPrimitiveSizeInBits();
00111   bool FromLegal = DL->isLegalInteger(FromWidth);
00112   bool ToLegal = DL->isLegalInteger(ToWidth);
00113 
00114   // If this is a legal integer from type, and the result would be an illegal
00115   // type, don't do the transformation.
00116   if (FromLegal && !ToLegal)
00117     return false;
00118 
00119   // Otherwise, if both are illegal, do not increase the size of the result. We
00120   // do allow things like i160 -> i64, but not i64 -> i160.
00121   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
00122     return false;
00123 
00124   return true;
00125 }
00126 
00127 // Return true, if No Signed Wrap should be maintained for I.
00128 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
00129 // where both B and C should be ConstantInts, results in a constant that does
00130 // not overflow. This function only handles the Add and Sub opcodes. For
00131 // all other opcodes, the function conservatively returns false.
00132 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
00133   OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
00134   if (!OBO || !OBO->hasNoSignedWrap()) {
00135     return false;
00136   }
00137 
00138   // We reason about Add and Sub Only.
00139   Instruction::BinaryOps Opcode = I.getOpcode();
00140   if (Opcode != Instruction::Add &&
00141       Opcode != Instruction::Sub) {
00142     return false;
00143   }
00144 
00145   ConstantInt *CB = dyn_cast<ConstantInt>(B);
00146   ConstantInt *CC = dyn_cast<ConstantInt>(C);
00147 
00148   if (!CB || !CC) {
00149     return false;
00150   }
00151 
00152   const APInt &BVal = CB->getValue();
00153   const APInt &CVal = CC->getValue();
00154   bool Overflow = false;
00155 
00156   if (Opcode == Instruction::Add) {
00157     BVal.sadd_ov(CVal, Overflow);
00158   } else {
00159     BVal.ssub_ov(CVal, Overflow);
00160   }
00161 
00162   return !Overflow;
00163 }
00164 
00165 /// Conservatively clears subclassOptionalData after a reassociation or
00166 /// commutation. We preserve fast-math flags when applicable as they can be
00167 /// preserved.
00168 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
00169   FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
00170   if (!FPMO) {
00171     I.clearSubclassOptionalData();
00172     return;
00173   }
00174 
00175   FastMathFlags FMF = I.getFastMathFlags();
00176   I.clearSubclassOptionalData();
00177   I.setFastMathFlags(FMF);
00178 }
00179 
00180 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
00181 /// operators which are associative or commutative:
00182 //
00183 //  Commutative operators:
00184 //
00185 //  1. Order operands such that they are listed from right (least complex) to
00186 //     left (most complex).  This puts constants before unary operators before
00187 //     binary operators.
00188 //
00189 //  Associative operators:
00190 //
00191 //  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
00192 //  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
00193 //
00194 //  Associative and commutative operators:
00195 //
00196 //  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
00197 //  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
00198 //  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
00199 //     if C1 and C2 are constants.
00200 //
00201 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
00202   Instruction::BinaryOps Opcode = I.getOpcode();
00203   bool Changed = false;
00204 
00205   do {
00206     // Order operands such that they are listed from right (least complex) to
00207     // left (most complex).  This puts constants before unary operators before
00208     // binary operators.
00209     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
00210         getComplexity(I.getOperand(1)))
00211       Changed = !I.swapOperands();
00212 
00213     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
00214     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
00215 
00216     if (I.isAssociative()) {
00217       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
00218       if (Op0 && Op0->getOpcode() == Opcode) {
00219         Value *A = Op0->getOperand(0);
00220         Value *B = Op0->getOperand(1);
00221         Value *C = I.getOperand(1);
00222 
00223         // Does "B op C" simplify?
00224         if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
00225           // It simplifies to V.  Form "A op V".
00226           I.setOperand(0, A);
00227           I.setOperand(1, V);
00228           // Conservatively clear the optional flags, since they may not be
00229           // preserved by the reassociation.
00230           if (MaintainNoSignedWrap(I, B, C) &&
00231               (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
00232             // Note: this is only valid because SimplifyBinOp doesn't look at
00233             // the operands to Op0.
00234             I.clearSubclassOptionalData();
00235             I.setHasNoSignedWrap(true);
00236           } else {
00237             ClearSubclassDataAfterReassociation(I);
00238           }
00239 
00240           Changed = true;
00241           ++NumReassoc;
00242           continue;
00243         }
00244       }
00245 
00246       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
00247       if (Op1 && Op1->getOpcode() == Opcode) {
00248         Value *A = I.getOperand(0);
00249         Value *B = Op1->getOperand(0);
00250         Value *C = Op1->getOperand(1);
00251 
00252         // Does "A op B" simplify?
00253         if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
00254           // It simplifies to V.  Form "V op C".
00255           I.setOperand(0, V);
00256           I.setOperand(1, C);
00257           // Conservatively clear the optional flags, since they may not be
00258           // preserved by the reassociation.
00259           ClearSubclassDataAfterReassociation(I);
00260           Changed = true;
00261           ++NumReassoc;
00262           continue;
00263         }
00264       }
00265     }
00266 
00267     if (I.isAssociative() && I.isCommutative()) {
00268       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
00269       if (Op0 && Op0->getOpcode() == Opcode) {
00270         Value *A = Op0->getOperand(0);
00271         Value *B = Op0->getOperand(1);
00272         Value *C = I.getOperand(1);
00273 
00274         // Does "C op A" simplify?
00275         if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
00276           // It simplifies to V.  Form "V op B".
00277           I.setOperand(0, V);
00278           I.setOperand(1, B);
00279           // Conservatively clear the optional flags, since they may not be
00280           // preserved by the reassociation.
00281           ClearSubclassDataAfterReassociation(I);
00282           Changed = true;
00283           ++NumReassoc;
00284           continue;
00285         }
00286       }
00287 
00288       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
00289       if (Op1 && Op1->getOpcode() == Opcode) {
00290         Value *A = I.getOperand(0);
00291         Value *B = Op1->getOperand(0);
00292         Value *C = Op1->getOperand(1);
00293 
00294         // Does "C op A" simplify?
00295         if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
00296           // It simplifies to V.  Form "B op V".
00297           I.setOperand(0, B);
00298           I.setOperand(1, V);
00299           // Conservatively clear the optional flags, since they may not be
00300           // preserved by the reassociation.
00301           ClearSubclassDataAfterReassociation(I);
00302           Changed = true;
00303           ++NumReassoc;
00304           continue;
00305         }
00306       }
00307 
00308       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
00309       // if C1 and C2 are constants.
00310       if (Op0 && Op1 &&
00311           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
00312           isa<Constant>(Op0->getOperand(1)) &&
00313           isa<Constant>(Op1->getOperand(1)) &&
00314           Op0->hasOneUse() && Op1->hasOneUse()) {
00315         Value *A = Op0->getOperand(0);
00316         Constant *C1 = cast<Constant>(Op0->getOperand(1));
00317         Value *B = Op1->getOperand(0);
00318         Constant *C2 = cast<Constant>(Op1->getOperand(1));
00319 
00320         Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
00321         BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
00322         if (isa<FPMathOperator>(New)) {
00323           FastMathFlags Flags = I.getFastMathFlags();
00324           Flags &= Op0->getFastMathFlags();
00325           Flags &= Op1->getFastMathFlags();
00326           New->setFastMathFlags(Flags);
00327         }
00328         InsertNewInstWith(New, I);
00329         New->takeName(Op1);
00330         I.setOperand(0, New);
00331         I.setOperand(1, Folded);
00332         // Conservatively clear the optional flags, since they may not be
00333         // preserved by the reassociation.
00334         ClearSubclassDataAfterReassociation(I);
00335 
00336         Changed = true;
00337         continue;
00338       }
00339     }
00340 
00341     // No further simplifications.
00342     return Changed;
00343   } while (1);
00344 }
00345 
00346 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
00347 /// "(X LOp Y) ROp (X LOp Z)".
00348 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
00349                                      Instruction::BinaryOps ROp) {
00350   switch (LOp) {
00351   default:
00352     return false;
00353 
00354   case Instruction::And:
00355     // And distributes over Or and Xor.
00356     switch (ROp) {
00357     default:
00358       return false;
00359     case Instruction::Or:
00360     case Instruction::Xor:
00361       return true;
00362     }
00363 
00364   case Instruction::Mul:
00365     // Multiplication distributes over addition and subtraction.
00366     switch (ROp) {
00367     default:
00368       return false;
00369     case Instruction::Add:
00370     case Instruction::Sub:
00371       return true;
00372     }
00373 
00374   case Instruction::Or:
00375     // Or distributes over And.
00376     switch (ROp) {
00377     default:
00378       return false;
00379     case Instruction::And:
00380       return true;
00381     }
00382   }
00383 }
00384 
00385 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
00386 /// "(X ROp Z) LOp (Y ROp Z)".
00387 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
00388                                      Instruction::BinaryOps ROp) {
00389   if (Instruction::isCommutative(ROp))
00390     return LeftDistributesOverRight(ROp, LOp);
00391   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
00392   // but this requires knowing that the addition does not overflow and other
00393   // such subtleties.
00394   return false;
00395 }
00396 
00397 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
00398 /// which some other binary operation distributes over either by factorizing
00399 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
00400 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
00401 /// a win).  Returns the simplified value, or null if it didn't simplify.
00402 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
00403   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00404   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
00405   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
00406   Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
00407 
00408   // Factorization.
00409   if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
00410     // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
00411     // a common term.
00412     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
00413     Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
00414     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
00415 
00416     // Does "X op' Y" always equal "Y op' X"?
00417     bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
00418 
00419     // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
00420     if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
00421       // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
00422       // commutative case, "(A op' B) op (C op' A)"?
00423       if (A == C || (InnerCommutative && A == D)) {
00424         if (A != C)
00425           std::swap(C, D);
00426         // Consider forming "A op' (B op D)".
00427         // If "B op D" simplifies then it can be formed with no cost.
00428         Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
00429         // If "B op D" doesn't simplify then only go on if both of the existing
00430         // operations "A op' B" and "C op' D" will be zapped as no longer used.
00431         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
00432           V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
00433         if (V) {
00434           ++NumFactor;
00435           V = Builder->CreateBinOp(InnerOpcode, A, V);
00436           V->takeName(&I);
00437           return V;
00438         }
00439       }
00440 
00441     // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
00442     if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
00443       // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
00444       // commutative case, "(A op' B) op (B op' D)"?
00445       if (B == D || (InnerCommutative && B == C)) {
00446         if (B != D)
00447           std::swap(C, D);
00448         // Consider forming "(A op C) op' B".
00449         // If "A op C" simplifies then it can be formed with no cost.
00450         Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
00451         // If "A op C" doesn't simplify then only go on if both of the existing
00452         // operations "A op' B" and "C op' D" will be zapped as no longer used.
00453         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
00454           V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
00455         if (V) {
00456           ++NumFactor;
00457           V = Builder->CreateBinOp(InnerOpcode, V, B);
00458           V->takeName(&I);
00459           return V;
00460         }
00461       }
00462   }
00463 
00464   // Expansion.
00465   if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
00466     // The instruction has the form "(A op' B) op C".  See if expanding it out
00467     // to "(A op C) op' (B op C)" results in simplifications.
00468     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
00469     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
00470 
00471     // Do "A op C" and "B op C" both simplify?
00472     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
00473       if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
00474         // They do! Return "L op' R".
00475         ++NumExpand;
00476         // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
00477         if ((L == A && R == B) ||
00478             (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
00479           return Op0;
00480         // Otherwise return "L op' R" if it simplifies.
00481         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
00482           return V;
00483         // Otherwise, create a new instruction.
00484         C = Builder->CreateBinOp(InnerOpcode, L, R);
00485         C->takeName(&I);
00486         return C;
00487       }
00488   }
00489 
00490   if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
00491     // The instruction has the form "A op (B op' C)".  See if expanding it out
00492     // to "(A op B) op' (A op C)" results in simplifications.
00493     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
00494     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
00495 
00496     // Do "A op B" and "A op C" both simplify?
00497     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
00498       if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
00499         // They do! Return "L op' R".
00500         ++NumExpand;
00501         // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
00502         if ((L == B && R == C) ||
00503             (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
00504           return Op1;
00505         // Otherwise return "L op' R" if it simplifies.
00506         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
00507           return V;
00508         // Otherwise, create a new instruction.
00509         A = Builder->CreateBinOp(InnerOpcode, L, R);
00510         A->takeName(&I);
00511         return A;
00512       }
00513   }
00514 
00515   return 0;
00516 }
00517 
00518 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
00519 // if the LHS is a constant zero (which is the 'negate' form).
00520 //
00521 Value *InstCombiner::dyn_castNegVal(Value *V) const {
00522   if (BinaryOperator::isNeg(V))
00523     return BinaryOperator::getNegArgument(V);
00524 
00525   // Constants can be considered to be negated values if they can be folded.
00526   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
00527     return ConstantExpr::getNeg(C);
00528 
00529   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
00530     if (C->getType()->getElementType()->isIntegerTy())
00531       return ConstantExpr::getNeg(C);
00532 
00533   return 0;
00534 }
00535 
00536 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
00537 // instruction if the LHS is a constant negative zero (which is the 'negate'
00538 // form).
00539 //
00540 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
00541   if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
00542     return BinaryOperator::getFNegArgument(V);
00543 
00544   // Constants can be considered to be negated values if they can be folded.
00545   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
00546     return ConstantExpr::getFNeg(C);
00547 
00548   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
00549     if (C->getType()->getElementType()->isFloatingPointTy())
00550       return ConstantExpr::getFNeg(C);
00551 
00552   return 0;
00553 }
00554 
00555 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
00556                                              InstCombiner *IC) {
00557   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
00558     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
00559   }
00560 
00561   // Figure out if the constant is the left or the right argument.
00562   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
00563   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
00564 
00565   if (Constant *SOC = dyn_cast<Constant>(SO)) {
00566     if (ConstIsRHS)
00567       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
00568     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
00569   }
00570 
00571   Value *Op0 = SO, *Op1 = ConstOperand;
00572   if (!ConstIsRHS)
00573     std::swap(Op0, Op1);
00574 
00575   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
00576     Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
00577                                     SO->getName()+".op");
00578     Instruction *FPInst = dyn_cast<Instruction>(RI);
00579     if (FPInst && isa<FPMathOperator>(FPInst))
00580       FPInst->copyFastMathFlags(BO);
00581     return RI;
00582   }
00583   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
00584     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
00585                                    SO->getName()+".cmp");
00586   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
00587     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
00588                                    SO->getName()+".cmp");
00589   llvm_unreachable("Unknown binary instruction type!");
00590 }
00591 
00592 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
00593 // constant as the other operand, try to fold the binary operator into the
00594 // select arguments.  This also works for Cast instructions, which obviously do
00595 // not have a second operand.
00596 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
00597   // Don't modify shared select instructions
00598   if (!SI->hasOneUse()) return 0;
00599   Value *TV = SI->getOperand(1);
00600   Value *FV = SI->getOperand(2);
00601 
00602   if (isa<Constant>(TV) || isa<Constant>(FV)) {
00603     // Bool selects with constant operands can be folded to logical ops.
00604     if (SI->getType()->isIntegerTy(1)) return 0;
00605 
00606     // If it's a bitcast involving vectors, make sure it has the same number of
00607     // elements on both sides.
00608     if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
00609       VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
00610       VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
00611 
00612       // Verify that either both or neither are vectors.
00613       if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
00614       // If vectors, verify that they have the same number of elements.
00615       if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
00616         return 0;
00617     }
00618 
00619     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
00620     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
00621 
00622     return SelectInst::Create(SI->getCondition(),
00623                               SelectTrueVal, SelectFalseVal);
00624   }
00625   return 0;
00626 }
00627 
00628 
00629 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
00630 /// has a PHI node as operand #0, see if we can fold the instruction into the
00631 /// PHI (which is only possible if all operands to the PHI are constants).
00632 ///
00633 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
00634   PHINode *PN = cast<PHINode>(I.getOperand(0));
00635   unsigned NumPHIValues = PN->getNumIncomingValues();
00636   if (NumPHIValues == 0)
00637     return 0;
00638 
00639   // We normally only transform phis with a single use.  However, if a PHI has
00640   // multiple uses and they are all the same operation, we can fold *all* of the
00641   // uses into the PHI.
00642   if (!PN->hasOneUse()) {
00643     // Walk the use list for the instruction, comparing them to I.
00644     for (User *U : PN->users()) {
00645       Instruction *UI = cast<Instruction>(U);
00646       if (UI != &I && !I.isIdenticalTo(UI))
00647         return 0;
00648     }
00649     // Otherwise, we can replace *all* users with the new PHI we form.
00650   }
00651 
00652   // Check to see if all of the operands of the PHI are simple constants
00653   // (constantint/constantfp/undef).  If there is one non-constant value,
00654   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
00655   // bail out.  We don't do arbitrary constant expressions here because moving
00656   // their computation can be expensive without a cost model.
00657   BasicBlock *NonConstBB = 0;
00658   for (unsigned i = 0; i != NumPHIValues; ++i) {
00659     Value *InVal = PN->getIncomingValue(i);
00660     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
00661       continue;
00662 
00663     if (isa<PHINode>(InVal)) return 0;  // Itself a phi.
00664     if (NonConstBB) return 0;  // More than one non-const value.
00665 
00666     NonConstBB = PN->getIncomingBlock(i);
00667 
00668     // If the InVal is an invoke at the end of the pred block, then we can't
00669     // insert a computation after it without breaking the edge.
00670     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
00671       if (II->getParent() == NonConstBB)
00672         return 0;
00673 
00674     // If the incoming non-constant value is in I's block, we will remove one
00675     // instruction, but insert another equivalent one, leading to infinite
00676     // instcombine.
00677     if (NonConstBB == I.getParent())
00678       return 0;
00679   }
00680 
00681   // If there is exactly one non-constant value, we can insert a copy of the
00682   // operation in that block.  However, if this is a critical edge, we would be
00683   // inserting the computation one some other paths (e.g. inside a loop).  Only
00684   // do this if the pred block is unconditionally branching into the phi block.
00685   if (NonConstBB != 0) {
00686     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
00687     if (!BI || !BI->isUnconditional()) return 0;
00688   }
00689 
00690   // Okay, we can do the transformation: create the new PHI node.
00691   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
00692   InsertNewInstBefore(NewPN, *PN);
00693   NewPN->takeName(PN);
00694 
00695   // If we are going to have to insert a new computation, do so right before the
00696   // predecessors terminator.
00697   if (NonConstBB)
00698     Builder->SetInsertPoint(NonConstBB->getTerminator());
00699 
00700   // Next, add all of the operands to the PHI.
00701   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
00702     // We only currently try to fold the condition of a select when it is a phi,
00703     // not the true/false values.
00704     Value *TrueV = SI->getTrueValue();
00705     Value *FalseV = SI->getFalseValue();
00706     BasicBlock *PhiTransBB = PN->getParent();
00707     for (unsigned i = 0; i != NumPHIValues; ++i) {
00708       BasicBlock *ThisBB = PN->getIncomingBlock(i);
00709       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
00710       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
00711       Value *InV = 0;
00712       // Beware of ConstantExpr:  it may eventually evaluate to getNullValue,
00713       // even if currently isNullValue gives false.
00714       Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
00715       if (InC && !isa<ConstantExpr>(InC))
00716         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
00717       else
00718         InV = Builder->CreateSelect(PN->getIncomingValue(i),
00719                                     TrueVInPred, FalseVInPred, "phitmp");
00720       NewPN->addIncoming(InV, ThisBB);
00721     }
00722   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
00723     Constant *C = cast<Constant>(I.getOperand(1));
00724     for (unsigned i = 0; i != NumPHIValues; ++i) {
00725       Value *InV = 0;
00726       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00727         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
00728       else if (isa<ICmpInst>(CI))
00729         InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
00730                                   C, "phitmp");
00731       else
00732         InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
00733                                   C, "phitmp");
00734       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00735     }
00736   } else if (I.getNumOperands() == 2) {
00737     Constant *C = cast<Constant>(I.getOperand(1));
00738     for (unsigned i = 0; i != NumPHIValues; ++i) {
00739       Value *InV = 0;
00740       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00741         InV = ConstantExpr::get(I.getOpcode(), InC, C);
00742       else
00743         InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
00744                                    PN->getIncomingValue(i), C, "phitmp");
00745       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00746     }
00747   } else {
00748     CastInst *CI = cast<CastInst>(&I);
00749     Type *RetTy = CI->getType();
00750     for (unsigned i = 0; i != NumPHIValues; ++i) {
00751       Value *InV;
00752       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00753         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
00754       else
00755         InV = Builder->CreateCast(CI->getOpcode(),
00756                                 PN->getIncomingValue(i), I.getType(), "phitmp");
00757       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00758     }
00759   }
00760 
00761   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
00762     Instruction *User = cast<Instruction>(*UI++);
00763     if (User == &I) continue;
00764     ReplaceInstUsesWith(*User, NewPN);
00765     EraseInstFromFunction(*User);
00766   }
00767   return ReplaceInstUsesWith(I, NewPN);
00768 }
00769 
00770 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
00771 /// whether or not there is a sequence of GEP indices into the pointed type that
00772 /// will land us at the specified offset.  If so, fill them into NewIndices and
00773 /// return the resultant element type, otherwise return null.
00774 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
00775                                         SmallVectorImpl<Value*> &NewIndices) {
00776   assert(PtrTy->isPtrOrPtrVectorTy());
00777 
00778   if (!DL)
00779     return 0;
00780 
00781   Type *Ty = PtrTy->getPointerElementType();
00782   if (!Ty->isSized())
00783     return 0;
00784 
00785   // Start with the index over the outer type.  Note that the type size
00786   // might be zero (even if the offset isn't zero) if the indexed type
00787   // is something like [0 x {int, int}]
00788   Type *IntPtrTy = DL->getIntPtrType(PtrTy);
00789   int64_t FirstIdx = 0;
00790   if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
00791     FirstIdx = Offset/TySize;
00792     Offset -= FirstIdx*TySize;
00793 
00794     // Handle hosts where % returns negative instead of values [0..TySize).
00795     if (Offset < 0) {
00796       --FirstIdx;
00797       Offset += TySize;
00798       assert(Offset >= 0);
00799     }
00800     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
00801   }
00802 
00803   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
00804 
00805   // Index into the types.  If we fail, set OrigBase to null.
00806   while (Offset) {
00807     // Indexing into tail padding between struct/array elements.
00808     if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
00809       return 0;
00810 
00811     if (StructType *STy = dyn_cast<StructType>(Ty)) {
00812       const StructLayout *SL = DL->getStructLayout(STy);
00813       assert(Offset < (int64_t)SL->getSizeInBytes() &&
00814              "Offset must stay within the indexed type");
00815 
00816       unsigned Elt = SL->getElementContainingOffset(Offset);
00817       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
00818                                             Elt));
00819 
00820       Offset -= SL->getElementOffset(Elt);
00821       Ty = STy->getElementType(Elt);
00822     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
00823       uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
00824       assert(EltSize && "Cannot index into a zero-sized array");
00825       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
00826       Offset %= EltSize;
00827       Ty = AT->getElementType();
00828     } else {
00829       // Otherwise, we can't index into the middle of this atomic type, bail.
00830       return 0;
00831     }
00832   }
00833 
00834   return Ty;
00835 }
00836 
00837 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
00838   // If this GEP has only 0 indices, it is the same pointer as
00839   // Src. If Src is not a trivial GEP too, don't combine
00840   // the indices.
00841   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
00842       !Src.hasOneUse())
00843     return false;
00844   return true;
00845 }
00846 
00847 /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
00848 /// the multiplication is known not to overflow then NoSignedWrap is set.
00849 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
00850   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
00851   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
00852          Scale.getBitWidth() && "Scale not compatible with value!");
00853 
00854   // If Val is zero or Scale is one then Val = Val * Scale.
00855   if (match(Val, m_Zero()) || Scale == 1) {
00856     NoSignedWrap = true;
00857     return Val;
00858   }
00859 
00860   // If Scale is zero then it does not divide Val.
00861   if (Scale.isMinValue())
00862     return 0;
00863 
00864   // Look through chains of multiplications, searching for a constant that is
00865   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
00866   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
00867   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
00868   // down from Val:
00869   //
00870   //     Val = M1 * X          ||   Analysis starts here and works down
00871   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
00872   //      M2 =  Z * 4          \/   than one use
00873   //
00874   // Then to modify a term at the bottom:
00875   //
00876   //     Val = M1 * X
00877   //      M1 =  Z * Y          ||   Replaced M2 with Z
00878   //
00879   // Then to work back up correcting nsw flags.
00880 
00881   // Op - the term we are currently analyzing.  Starts at Val then drills down.
00882   // Replaced with its descaled value before exiting from the drill down loop.
00883   Value *Op = Val;
00884 
00885   // Parent - initially null, but after drilling down notes where Op came from.
00886   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
00887   // 0'th operand of Val.
00888   std::pair<Instruction*, unsigned> Parent;
00889 
00890   // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
00891   // levels that doesn't overflow.
00892   bool RequireNoSignedWrap = false;
00893 
00894   // logScale - log base 2 of the scale.  Negative if not a power of 2.
00895   int32_t logScale = Scale.exactLogBase2();
00896 
00897   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
00898 
00899     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
00900       // If Op is a constant divisible by Scale then descale to the quotient.
00901       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
00902       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
00903       if (!Remainder.isMinValue())
00904         // Not divisible by Scale.
00905         return 0;
00906       // Replace with the quotient in the parent.
00907       Op = ConstantInt::get(CI->getType(), Quotient);
00908       NoSignedWrap = true;
00909       break;
00910     }
00911 
00912     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
00913 
00914       if (BO->getOpcode() == Instruction::Mul) {
00915         // Multiplication.
00916         NoSignedWrap = BO->hasNoSignedWrap();
00917         if (RequireNoSignedWrap && !NoSignedWrap)
00918           return 0;
00919 
00920         // There are three cases for multiplication: multiplication by exactly
00921         // the scale, multiplication by a constant different to the scale, and
00922         // multiplication by something else.
00923         Value *LHS = BO->getOperand(0);
00924         Value *RHS = BO->getOperand(1);
00925 
00926         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
00927           // Multiplication by a constant.
00928           if (CI->getValue() == Scale) {
00929             // Multiplication by exactly the scale, replace the multiplication
00930             // by its left-hand side in the parent.
00931             Op = LHS;
00932             break;
00933           }
00934 
00935           // Otherwise drill down into the constant.
00936           if (!Op->hasOneUse())
00937             return 0;
00938 
00939           Parent = std::make_pair(BO, 1);
00940           continue;
00941         }
00942 
00943         // Multiplication by something else. Drill down into the left-hand side
00944         // since that's where the reassociate pass puts the good stuff.
00945         if (!Op->hasOneUse())
00946           return 0;
00947 
00948         Parent = std::make_pair(BO, 0);
00949         continue;
00950       }
00951 
00952       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
00953           isa<ConstantInt>(BO->getOperand(1))) {
00954         // Multiplication by a power of 2.
00955         NoSignedWrap = BO->hasNoSignedWrap();
00956         if (RequireNoSignedWrap && !NoSignedWrap)
00957           return 0;
00958 
00959         Value *LHS = BO->getOperand(0);
00960         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
00961           getLimitedValue(Scale.getBitWidth());
00962         // Op = LHS << Amt.
00963 
00964         if (Amt == logScale) {
00965           // Multiplication by exactly the scale, replace the multiplication
00966           // by its left-hand side in the parent.
00967           Op = LHS;
00968           break;
00969         }
00970         if (Amt < logScale || !Op->hasOneUse())
00971           return 0;
00972 
00973         // Multiplication by more than the scale.  Reduce the multiplying amount
00974         // by the scale in the parent.
00975         Parent = std::make_pair(BO, 1);
00976         Op = ConstantInt::get(BO->getType(), Amt - logScale);
00977         break;
00978       }
00979     }
00980 
00981     if (!Op->hasOneUse())
00982       return 0;
00983 
00984     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
00985       if (Cast->getOpcode() == Instruction::SExt) {
00986         // Op is sign-extended from a smaller type, descale in the smaller type.
00987         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
00988         APInt SmallScale = Scale.trunc(SmallSize);
00989         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
00990         // descale Op as (sext Y) * Scale.  In order to have
00991         //   sext (Y * SmallScale) = (sext Y) * Scale
00992         // some conditions need to hold however: SmallScale must sign-extend to
00993         // Scale and the multiplication Y * SmallScale should not overflow.
00994         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
00995           // SmallScale does not sign-extend to Scale.
00996           return 0;
00997         assert(SmallScale.exactLogBase2() == logScale);
00998         // Require that Y * SmallScale must not overflow.
00999         RequireNoSignedWrap = true;
01000 
01001         // Drill down through the cast.
01002         Parent = std::make_pair(Cast, 0);
01003         Scale = SmallScale;
01004         continue;
01005       }
01006 
01007       if (Cast->getOpcode() == Instruction::Trunc) {
01008         // Op is truncated from a larger type, descale in the larger type.
01009         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
01010         //   trunc (Y * sext Scale) = (trunc Y) * Scale
01011         // always holds.  However (trunc Y) * Scale may overflow even if
01012         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
01013         // from this point up in the expression (see later).
01014         if (RequireNoSignedWrap)
01015           return 0;
01016 
01017         // Drill down through the cast.
01018         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
01019         Parent = std::make_pair(Cast, 0);
01020         Scale = Scale.sext(LargeSize);
01021         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
01022           logScale = -1;
01023         assert(Scale.exactLogBase2() == logScale);
01024         continue;
01025       }
01026     }
01027 
01028     // Unsupported expression, bail out.
01029     return 0;
01030   }
01031 
01032   // We know that we can successfully descale, so from here on we can safely
01033   // modify the IR.  Op holds the descaled version of the deepest term in the
01034   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
01035   // not to overflow.
01036 
01037   if (!Parent.first)
01038     // The expression only had one term.
01039     return Op;
01040 
01041   // Rewrite the parent using the descaled version of its operand.
01042   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
01043   assert(Op != Parent.first->getOperand(Parent.second) &&
01044          "Descaling was a no-op?");
01045   Parent.first->setOperand(Parent.second, Op);
01046   Worklist.Add(Parent.first);
01047 
01048   // Now work back up the expression correcting nsw flags.  The logic is based
01049   // on the following observation: if X * Y is known not to overflow as a signed
01050   // multiplication, and Y is replaced by a value Z with smaller absolute value,
01051   // then X * Z will not overflow as a signed multiplication either.  As we work
01052   // our way up, having NoSignedWrap 'true' means that the descaled value at the
01053   // current level has strictly smaller absolute value than the original.
01054   Instruction *Ancestor = Parent.first;
01055   do {
01056     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
01057       // If the multiplication wasn't nsw then we can't say anything about the
01058       // value of the descaled multiplication, and we have to clear nsw flags
01059       // from this point on up.
01060       bool OpNoSignedWrap = BO->hasNoSignedWrap();
01061       NoSignedWrap &= OpNoSignedWrap;
01062       if (NoSignedWrap != OpNoSignedWrap) {
01063         BO->setHasNoSignedWrap(NoSignedWrap);
01064         Worklist.Add(Ancestor);
01065       }
01066     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
01067       // The fact that the descaled input to the trunc has smaller absolute
01068       // value than the original input doesn't tell us anything useful about
01069       // the absolute values of the truncations.
01070       NoSignedWrap = false;
01071     }
01072     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
01073            "Failed to keep proper track of nsw flags while drilling down?");
01074 
01075     if (Ancestor == Val)
01076       // Got to the top, all done!
01077       return Val;
01078 
01079     // Move up one level in the expression.
01080     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
01081     Ancestor = Ancestor->user_back();
01082   } while (1);
01083 }
01084 
01085 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
01086   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
01087 
01088   if (Value *V = SimplifyGEPInst(Ops, DL))
01089     return ReplaceInstUsesWith(GEP, V);
01090 
01091   Value *PtrOp = GEP.getOperand(0);
01092 
01093   // Eliminate unneeded casts for indices, and replace indices which displace
01094   // by multiples of a zero size type with zero.
01095   if (DL) {
01096     bool MadeChange = false;
01097     Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
01098 
01099     gep_type_iterator GTI = gep_type_begin(GEP);
01100     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
01101          I != E; ++I, ++GTI) {
01102       // Skip indices into struct types.
01103       SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
01104       if (!SeqTy) continue;
01105 
01106       // If the element type has zero size then any index over it is equivalent
01107       // to an index of zero, so replace it with zero if it is not zero already.
01108       if (SeqTy->getElementType()->isSized() &&
01109           DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
01110         if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
01111           *I = Constant::getNullValue(IntPtrTy);
01112           MadeChange = true;
01113         }
01114 
01115       Type *IndexTy = (*I)->getType();
01116       if (IndexTy != IntPtrTy) {
01117         // If we are using a wider index than needed for this platform, shrink
01118         // it to what we need.  If narrower, sign-extend it to what we need.
01119         // This explicit cast can make subsequent optimizations more obvious.
01120         *I = Builder->CreateIntCast(*I, IntPtrTy, true);
01121         MadeChange = true;
01122       }
01123     }
01124     if (MadeChange) return &GEP;
01125   }
01126 
01127   // Combine Indices - If the source pointer to this getelementptr instruction
01128   // is a getelementptr instruction, combine the indices of the two
01129   // getelementptr instructions into a single instruction.
01130   //
01131   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
01132     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
01133       return 0;
01134 
01135     // Note that if our source is a gep chain itself then we wait for that
01136     // chain to be resolved before we perform this transformation.  This
01137     // avoids us creating a TON of code in some cases.
01138     if (GEPOperator *SrcGEP =
01139           dyn_cast<GEPOperator>(Src->getOperand(0)))
01140       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
01141         return 0;   // Wait until our source is folded to completion.
01142 
01143     SmallVector<Value*, 8> Indices;
01144 
01145     // Find out whether the last index in the source GEP is a sequential idx.
01146     bool EndsWithSequential = false;
01147     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
01148          I != E; ++I)
01149       EndsWithSequential = !(*I)->isStructTy();
01150 
01151     // Can we combine the two pointer arithmetics offsets?
01152     if (EndsWithSequential) {
01153       // Replace: gep (gep %P, long B), long A, ...
01154       // With:    T = long A+B; gep %P, T, ...
01155       //
01156       Value *Sum;
01157       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
01158       Value *GO1 = GEP.getOperand(1);
01159       if (SO1 == Constant::getNullValue(SO1->getType())) {
01160         Sum = GO1;
01161       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
01162         Sum = SO1;
01163       } else {
01164         // If they aren't the same type, then the input hasn't been processed
01165         // by the loop above yet (which canonicalizes sequential index types to
01166         // intptr_t).  Just avoid transforming this until the input has been
01167         // normalized.
01168         if (SO1->getType() != GO1->getType())
01169           return 0;
01170         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
01171       }
01172 
01173       // Update the GEP in place if possible.
01174       if (Src->getNumOperands() == 2) {
01175         GEP.setOperand(0, Src->getOperand(0));
01176         GEP.setOperand(1, Sum);
01177         return &GEP;
01178       }
01179       Indices.append(Src->op_begin()+1, Src->op_end()-1);
01180       Indices.push_back(Sum);
01181       Indices.append(GEP.op_begin()+2, GEP.op_end());
01182     } else if (isa<Constant>(*GEP.idx_begin()) &&
01183                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
01184                Src->getNumOperands() != 1) {
01185       // Otherwise we can do the fold if the first index of the GEP is a zero
01186       Indices.append(Src->op_begin()+1, Src->op_end());
01187       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
01188     }
01189 
01190     if (!Indices.empty())
01191       return (GEP.isInBounds() && Src->isInBounds()) ?
01192         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
01193                                           GEP.getName()) :
01194         GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
01195   }
01196 
01197   // Canonicalize (gep i8* X, -(ptrtoint Y)) to (sub (ptrtoint X), (ptrtoint Y))
01198   // The GEP pattern is emitted by the SCEV expander for certain kinds of
01199   // pointer arithmetic.
01200   if (DL && GEP.getNumIndices() == 1 &&
01201       match(GEP.getOperand(1), m_Neg(m_PtrToInt(m_Value())))) {
01202     unsigned AS = GEP.getPointerAddressSpace();
01203     if (GEP.getType() == Builder->getInt8PtrTy(AS) &&
01204         GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
01205         DL->getPointerSizeInBits(AS)) {
01206       Operator *Index = cast<Operator>(GEP.getOperand(1));
01207       Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
01208       Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
01209       return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
01210     }
01211   }
01212 
01213   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
01214   Value *StrippedPtr = PtrOp->stripPointerCasts();
01215   PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
01216 
01217   // We do not handle pointer-vector geps here.
01218   if (!StrippedPtrTy)
01219     return 0;
01220 
01221   if (StrippedPtr != PtrOp) {
01222     bool HasZeroPointerIndex = false;
01223     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
01224       HasZeroPointerIndex = C->isZero();
01225 
01226     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
01227     // into     : GEP [10 x i8]* X, i32 0, ...
01228     //
01229     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
01230     //           into     : GEP i8* X, ...
01231     //
01232     // This occurs when the program declares an array extern like "int X[];"
01233     if (HasZeroPointerIndex) {
01234       PointerType *CPTy = cast<PointerType>(PtrOp->getType());
01235       if (ArrayType *CATy =
01236           dyn_cast<ArrayType>(CPTy->getElementType())) {
01237         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
01238         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
01239           // -> GEP i8* X, ...
01240           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
01241           GetElementPtrInst *Res =
01242             GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
01243           Res->setIsInBounds(GEP.isInBounds());
01244           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
01245             return Res;
01246           // Insert Res, and create an addrspacecast.
01247           // e.g.,
01248           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
01249           // ->
01250           // %0 = GEP i8 addrspace(1)* X, ...
01251           // addrspacecast i8 addrspace(1)* %0 to i8*
01252           return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
01253         }
01254 
01255         if (ArrayType *XATy =
01256               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
01257           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
01258           if (CATy->getElementType() == XATy->getElementType()) {
01259             // -> GEP [10 x i8]* X, i32 0, ...
01260             // At this point, we know that the cast source type is a pointer
01261             // to an array of the same type as the destination pointer
01262             // array.  Because the array type is never stepped over (there
01263             // is a leading zero) we can fold the cast into this GEP.
01264             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
01265               GEP.setOperand(0, StrippedPtr);
01266               return &GEP;
01267             }
01268             // Cannot replace the base pointer directly because StrippedPtr's
01269             // address space is different. Instead, create a new GEP followed by
01270             // an addrspacecast.
01271             // e.g.,
01272             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
01273             //   i32 0, ...
01274             // ->
01275             // %0 = GEP [10 x i8] addrspace(1)* X, ...
01276             // addrspacecast i8 addrspace(1)* %0 to i8*
01277             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
01278             Value *NewGEP = GEP.isInBounds() ?
01279               Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
01280               Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
01281             return new AddrSpaceCastInst(NewGEP, GEP.getType());
01282           }
01283         }
01284       }
01285     } else if (GEP.getNumOperands() == 2) {
01286       // Transform things like:
01287       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
01288       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
01289       Type *SrcElTy = StrippedPtrTy->getElementType();
01290       Type *ResElTy = PtrOp->getType()->getPointerElementType();
01291       if (DL && SrcElTy->isArrayTy() &&
01292           DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
01293           DL->getTypeAllocSize(ResElTy)) {
01294         Type *IdxType = DL->getIntPtrType(GEP.getType());
01295         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
01296         Value *NewGEP = GEP.isInBounds() ?
01297           Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
01298           Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
01299 
01300         // V and GEP are both pointer types --> BitCast
01301         if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
01302           return new BitCastInst(NewGEP, GEP.getType());
01303         return new AddrSpaceCastInst(NewGEP, GEP.getType());
01304       }
01305 
01306       // Transform things like:
01307       // %V = mul i64 %N, 4
01308       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
01309       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
01310       if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
01311         // Check that changing the type amounts to dividing the index by a scale
01312         // factor.
01313         uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
01314         uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
01315         if (ResSize && SrcSize % ResSize == 0) {
01316           Value *Idx = GEP.getOperand(1);
01317           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
01318           uint64_t Scale = SrcSize / ResSize;
01319 
01320           // Earlier transforms ensure that the index has type IntPtrType, which
01321           // considerably simplifies the logic by eliminating implicit casts.
01322           assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
01323                  "Index not cast to pointer width?");
01324 
01325           bool NSW;
01326           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
01327             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
01328             // If the multiplication NewIdx * Scale may overflow then the new
01329             // GEP may not be "inbounds".
01330             Value *NewGEP = GEP.isInBounds() && NSW ?
01331               Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
01332               Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
01333 
01334             // The NewGEP must be pointer typed, so must the old one -> BitCast
01335             if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
01336               return new BitCastInst(NewGEP, GEP.getType());
01337             return new AddrSpaceCastInst(NewGEP, GEP.getType());
01338           }
01339         }
01340       }
01341 
01342       // Similarly, transform things like:
01343       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
01344       //   (where tmp = 8*tmp2) into:
01345       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
01346       if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
01347           SrcElTy->isArrayTy()) {
01348         // Check that changing to the array element type amounts to dividing the
01349         // index by a scale factor.
01350         uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
01351         uint64_t ArrayEltSize
01352           = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
01353         if (ResSize && ArrayEltSize % ResSize == 0) {
01354           Value *Idx = GEP.getOperand(1);
01355           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
01356           uint64_t Scale = ArrayEltSize / ResSize;
01357 
01358           // Earlier transforms ensure that the index has type IntPtrType, which
01359           // considerably simplifies the logic by eliminating implicit casts.
01360           assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
01361                  "Index not cast to pointer width?");
01362 
01363           bool NSW;
01364           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
01365             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
01366             // If the multiplication NewIdx * Scale may overflow then the new
01367             // GEP may not be "inbounds".
01368             Value *Off[2] = {
01369               Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
01370               NewIdx
01371             };
01372 
01373             Value *NewGEP = GEP.isInBounds() && NSW ?
01374               Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
01375               Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
01376             // The NewGEP must be pointer typed, so must the old one -> BitCast
01377             if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
01378               return new BitCastInst(NewGEP, GEP.getType());
01379             return new AddrSpaceCastInst(NewGEP, GEP.getType());
01380           }
01381         }
01382       }
01383     }
01384   }
01385 
01386   if (!DL)
01387     return 0;
01388 
01389   /// See if we can simplify:
01390   ///   X = bitcast A* to B*
01391   ///   Y = gep X, <...constant indices...>
01392   /// into a gep of the original struct.  This is important for SROA and alias
01393   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
01394   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
01395     Value *Operand = BCI->getOperand(0);
01396     PointerType *OpType = cast<PointerType>(Operand->getType());
01397     unsigned OffsetBits = DL->getPointerTypeSizeInBits(OpType);
01398     APInt Offset(OffsetBits, 0);
01399     if (!isa<BitCastInst>(Operand) &&
01400         GEP.accumulateConstantOffset(*DL, Offset) &&
01401         StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
01402 
01403       // If this GEP instruction doesn't move the pointer, just replace the GEP
01404       // with a bitcast of the real input to the dest type.
01405       if (!Offset) {
01406         // If the bitcast is of an allocation, and the allocation will be
01407         // converted to match the type of the cast, don't touch this.
01408         if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
01409           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
01410           if (Instruction *I = visitBitCast(*BCI)) {
01411             if (I != BCI) {
01412               I->takeName(BCI);
01413               BCI->getParent()->getInstList().insert(BCI, I);
01414               ReplaceInstUsesWith(*BCI, I);
01415             }
01416             return &GEP;
01417           }
01418         }
01419         return new BitCastInst(Operand, GEP.getType());
01420       }
01421 
01422       // Otherwise, if the offset is non-zero, we need to find out if there is a
01423       // field at Offset in 'A's type.  If so, we can pull the cast through the
01424       // GEP.
01425       SmallVector<Value*, 8> NewIndices;
01426       if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
01427         Value *NGEP = GEP.isInBounds() ?
01428           Builder->CreateInBoundsGEP(Operand, NewIndices) :
01429           Builder->CreateGEP(Operand, NewIndices);
01430 
01431         if (NGEP->getType() == GEP.getType())
01432           return ReplaceInstUsesWith(GEP, NGEP);
01433         NGEP->takeName(&GEP);
01434         return new BitCastInst(NGEP, GEP.getType());
01435       }
01436     }
01437   }
01438 
01439   return 0;
01440 }
01441 
01442 static bool
01443 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
01444                      const TargetLibraryInfo *TLI) {
01445   SmallVector<Instruction*, 4> Worklist;
01446   Worklist.push_back(AI);
01447 
01448   do {
01449     Instruction *PI = Worklist.pop_back_val();
01450     for (User *U : PI->users()) {
01451       Instruction *I = cast<Instruction>(U);
01452       switch (I->getOpcode()) {
01453       default:
01454         // Give up the moment we see something we can't handle.
01455         return false;
01456 
01457       case Instruction::BitCast:
01458       case Instruction::GetElementPtr:
01459         Users.push_back(I);
01460         Worklist.push_back(I);
01461         continue;
01462 
01463       case Instruction::ICmp: {
01464         ICmpInst *ICI = cast<ICmpInst>(I);
01465         // We can fold eq/ne comparisons with null to false/true, respectively.
01466         if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
01467           return false;
01468         Users.push_back(I);
01469         continue;
01470       }
01471 
01472       case Instruction::Call:
01473         // Ignore no-op and store intrinsics.
01474         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01475           switch (II->getIntrinsicID()) {
01476           default:
01477             return false;
01478 
01479           case Intrinsic::memmove:
01480           case Intrinsic::memcpy:
01481           case Intrinsic::memset: {
01482             MemIntrinsic *MI = cast<MemIntrinsic>(II);
01483             if (MI->isVolatile() || MI->getRawDest() != PI)
01484               return false;
01485           }
01486           // fall through
01487           case Intrinsic::dbg_declare:
01488           case Intrinsic::dbg_value:
01489           case Intrinsic::invariant_start:
01490           case Intrinsic::invariant_end:
01491           case Intrinsic::lifetime_start:
01492           case Intrinsic::lifetime_end:
01493           case Intrinsic::objectsize:
01494             Users.push_back(I);
01495             continue;
01496           }
01497         }
01498 
01499         if (isFreeCall(I, TLI)) {
01500           Users.push_back(I);
01501           continue;
01502         }
01503         return false;
01504 
01505       case Instruction::Store: {
01506         StoreInst *SI = cast<StoreInst>(I);
01507         if (SI->isVolatile() || SI->getPointerOperand() != PI)
01508           return false;
01509         Users.push_back(I);
01510         continue;
01511       }
01512       }
01513       llvm_unreachable("missing a return?");
01514     }
01515   } while (!Worklist.empty());
01516   return true;
01517 }
01518 
01519 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
01520   // If we have a malloc call which is only used in any amount of comparisons
01521   // to null and free calls, delete the calls and replace the comparisons with
01522   // true or false as appropriate.
01523   SmallVector<WeakVH, 64> Users;
01524   if (isAllocSiteRemovable(&MI, Users, TLI)) {
01525     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
01526       Instruction *I = cast_or_null<Instruction>(&*Users[i]);
01527       if (!I) continue;
01528 
01529       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
01530         ReplaceInstUsesWith(*C,
01531                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
01532                                              C->isFalseWhenEqual()));
01533       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
01534         ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
01535       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01536         if (II->getIntrinsicID() == Intrinsic::objectsize) {
01537           ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
01538           uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
01539           ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
01540         }
01541       }
01542       EraseInstFromFunction(*I);
01543     }
01544 
01545     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
01546       // Replace invoke with a NOP intrinsic to maintain the original CFG
01547       Module *M = II->getParent()->getParent()->getParent();
01548       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
01549       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
01550                          None, "", II->getParent());
01551     }
01552     return EraseInstFromFunction(MI);
01553   }
01554   return 0;
01555 }
01556 
01557 /// \brief Move the call to free before a NULL test.
01558 ///
01559 /// Check if this free is accessed after its argument has been test
01560 /// against NULL (property 0).
01561 /// If yes, it is legal to move this call in its predecessor block.
01562 ///
01563 /// The move is performed only if the block containing the call to free
01564 /// will be removed, i.e.:
01565 /// 1. it has only one predecessor P, and P has two successors
01566 /// 2. it contains the call and an unconditional branch
01567 /// 3. its successor is the same as its predecessor's successor
01568 ///
01569 /// The profitability is out-of concern here and this function should
01570 /// be called only if the caller knows this transformation would be
01571 /// profitable (e.g., for code size).
01572 static Instruction *
01573 tryToMoveFreeBeforeNullTest(CallInst &FI) {
01574   Value *Op = FI.getArgOperand(0);
01575   BasicBlock *FreeInstrBB = FI.getParent();
01576   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
01577 
01578   // Validate part of constraint #1: Only one predecessor
01579   // FIXME: We can extend the number of predecessor, but in that case, we
01580   //        would duplicate the call to free in each predecessor and it may
01581   //        not be profitable even for code size.
01582   if (!PredBB)
01583     return 0;
01584 
01585   // Validate constraint #2: Does this block contains only the call to
01586   //                         free and an unconditional branch?
01587   // FIXME: We could check if we can speculate everything in the
01588   //        predecessor block
01589   if (FreeInstrBB->size() != 2)
01590     return 0;
01591   BasicBlock *SuccBB;
01592   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
01593     return 0;
01594 
01595   // Validate the rest of constraint #1 by matching on the pred branch.
01596   TerminatorInst *TI = PredBB->getTerminator();
01597   BasicBlock *TrueBB, *FalseBB;
01598   ICmpInst::Predicate Pred;
01599   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
01600     return 0;
01601   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
01602     return 0;
01603 
01604   // Validate constraint #3: Ensure the null case just falls through.
01605   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
01606     return 0;
01607   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
01608          "Broken CFG: missing edge from predecessor to successor");
01609 
01610   FI.moveBefore(TI);
01611   return &FI;
01612 }
01613 
01614 
01615 Instruction *InstCombiner::visitFree(CallInst &FI) {
01616   Value *Op = FI.getArgOperand(0);
01617 
01618   // free undef -> unreachable.
01619   if (isa<UndefValue>(Op)) {
01620     // Insert a new store to null because we cannot modify the CFG here.
01621     Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
01622                          UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
01623     return EraseInstFromFunction(FI);
01624   }
01625 
01626   // If we have 'free null' delete the instruction.  This can happen in stl code
01627   // when lots of inlining happens.
01628   if (isa<ConstantPointerNull>(Op))
01629     return EraseInstFromFunction(FI);
01630 
01631   // If we optimize for code size, try to move the call to free before the null
01632   // test so that simplify cfg can remove the empty block and dead code
01633   // elimination the branch. I.e., helps to turn something like:
01634   // if (foo) free(foo);
01635   // into
01636   // free(foo);
01637   if (MinimizeSize)
01638     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
01639       return I;
01640 
01641   return 0;
01642 }
01643 
01644 
01645 
01646 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
01647   // Change br (not X), label True, label False to: br X, label False, True
01648   Value *X = 0;
01649   BasicBlock *TrueDest;
01650   BasicBlock *FalseDest;
01651   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
01652       !isa<Constant>(X)) {
01653     // Swap Destinations and condition...
01654     BI.setCondition(X);
01655     BI.swapSuccessors();
01656     return &BI;
01657   }
01658 
01659   // Canonicalize fcmp_one -> fcmp_oeq
01660   FCmpInst::Predicate FPred; Value *Y;
01661   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
01662                              TrueDest, FalseDest)) &&
01663       BI.getCondition()->hasOneUse())
01664     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
01665         FPred == FCmpInst::FCMP_OGE) {
01666       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
01667       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
01668 
01669       // Swap Destinations and condition.
01670       BI.swapSuccessors();
01671       Worklist.Add(Cond);
01672       return &BI;
01673     }
01674 
01675   // Canonicalize icmp_ne -> icmp_eq
01676   ICmpInst::Predicate IPred;
01677   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
01678                       TrueDest, FalseDest)) &&
01679       BI.getCondition()->hasOneUse())
01680     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
01681         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
01682         IPred == ICmpInst::ICMP_SGE) {
01683       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
01684       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
01685       // Swap Destinations and condition.
01686       BI.swapSuccessors();
01687       Worklist.Add(Cond);
01688       return &BI;
01689     }
01690 
01691   return 0;
01692 }
01693 
01694 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
01695   Value *Cond = SI.getCondition();
01696   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
01697     if (I->getOpcode() == Instruction::Add)
01698       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
01699         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
01700         // Skip the first item since that's the default case.
01701         for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
01702              i != e; ++i) {
01703           ConstantInt* CaseVal = i.getCaseValue();
01704           Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
01705                                                       AddRHS);
01706           assert(isa<ConstantInt>(NewCaseVal) &&
01707                  "Result of expression should be constant");
01708           i.setValue(cast<ConstantInt>(NewCaseVal));
01709         }
01710         SI.setCondition(I->getOperand(0));
01711         Worklist.Add(I);
01712         return &SI;
01713       }
01714   }
01715   return 0;
01716 }
01717 
01718 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
01719   Value *Agg = EV.getAggregateOperand();
01720 
01721   if (!EV.hasIndices())
01722     return ReplaceInstUsesWith(EV, Agg);
01723 
01724   if (Constant *C = dyn_cast<Constant>(Agg)) {
01725     if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
01726       if (EV.getNumIndices() == 0)
01727         return ReplaceInstUsesWith(EV, C2);
01728       // Extract the remaining indices out of the constant indexed by the
01729       // first index
01730       return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
01731     }
01732     return 0; // Can't handle other constants
01733   }
01734 
01735   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
01736     // We're extracting from an insertvalue instruction, compare the indices
01737     const unsigned *exti, *exte, *insi, *inse;
01738     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
01739          exte = EV.idx_end(), inse = IV->idx_end();
01740          exti != exte && insi != inse;
01741          ++exti, ++insi) {
01742       if (*insi != *exti)
01743         // The insert and extract both reference distinctly different elements.
01744         // This means the extract is not influenced by the insert, and we can
01745         // replace the aggregate operand of the extract with the aggregate
01746         // operand of the insert. i.e., replace
01747         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
01748         // %E = extractvalue { i32, { i32 } } %I, 0
01749         // with
01750         // %E = extractvalue { i32, { i32 } } %A, 0
01751         return ExtractValueInst::Create(IV->getAggregateOperand(),
01752                                         EV.getIndices());
01753     }
01754     if (exti == exte && insi == inse)
01755       // Both iterators are at the end: Index lists are identical. Replace
01756       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
01757       // %C = extractvalue { i32, { i32 } } %B, 1, 0
01758       // with "i32 42"
01759       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
01760     if (exti == exte) {
01761       // The extract list is a prefix of the insert list. i.e. replace
01762       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
01763       // %E = extractvalue { i32, { i32 } } %I, 1
01764       // with
01765       // %X = extractvalue { i32, { i32 } } %A, 1
01766       // %E = insertvalue { i32 } %X, i32 42, 0
01767       // by switching the order of the insert and extract (though the
01768       // insertvalue should be left in, since it may have other uses).
01769       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
01770                                                  EV.getIndices());
01771       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
01772                                      makeArrayRef(insi, inse));
01773     }
01774     if (insi == inse)
01775       // The insert list is a prefix of the extract list
01776       // We can simply remove the common indices from the extract and make it
01777       // operate on the inserted value instead of the insertvalue result.
01778       // i.e., replace
01779       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
01780       // %E = extractvalue { i32, { i32 } } %I, 1, 0
01781       // with
01782       // %E extractvalue { i32 } { i32 42 }, 0
01783       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
01784                                       makeArrayRef(exti, exte));
01785   }
01786   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
01787     // We're extracting from an intrinsic, see if we're the only user, which
01788     // allows us to simplify multiple result intrinsics to simpler things that
01789     // just get one value.
01790     if (II->hasOneUse()) {
01791       // Check if we're grabbing the overflow bit or the result of a 'with
01792       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
01793       // and replace it with a traditional binary instruction.
01794       switch (II->getIntrinsicID()) {
01795       case Intrinsic::uadd_with_overflow:
01796       case Intrinsic::sadd_with_overflow:
01797         if (*EV.idx_begin() == 0) {  // Normal result.
01798           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
01799           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
01800           EraseInstFromFunction(*II);
01801           return BinaryOperator::CreateAdd(LHS, RHS);
01802         }
01803 
01804         // If the normal result of the add is dead, and the RHS is a constant,
01805         // we can transform this into a range comparison.
01806         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
01807         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
01808           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
01809             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
01810                                 ConstantExpr::getNot(CI));
01811         break;
01812       case Intrinsic::usub_with_overflow:
01813       case Intrinsic::ssub_with_overflow:
01814         if (*EV.idx_begin() == 0) {  // Normal result.
01815           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
01816           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
01817           EraseInstFromFunction(*II);
01818           return BinaryOperator::CreateSub(LHS, RHS);
01819         }
01820         break;
01821       case Intrinsic::umul_with_overflow:
01822       case Intrinsic::smul_with_overflow:
01823         if (*EV.idx_begin() == 0) {  // Normal result.
01824           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
01825           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
01826           EraseInstFromFunction(*II);
01827           return BinaryOperator::CreateMul(LHS, RHS);
01828         }
01829         break;
01830       default:
01831         break;
01832       }
01833     }
01834   }
01835   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
01836     // If the (non-volatile) load only has one use, we can rewrite this to a
01837     // load from a GEP. This reduces the size of the load.
01838     // FIXME: If a load is used only by extractvalue instructions then this
01839     //        could be done regardless of having multiple uses.
01840     if (L->isSimple() && L->hasOneUse()) {
01841       // extractvalue has integer indices, getelementptr has Value*s. Convert.
01842       SmallVector<Value*, 4> Indices;
01843       // Prefix an i32 0 since we need the first element.
01844       Indices.push_back(Builder->getInt32(0));
01845       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
01846             I != E; ++I)
01847         Indices.push_back(Builder->getInt32(*I));
01848 
01849       // We need to insert these at the location of the old load, not at that of
01850       // the extractvalue.
01851       Builder->SetInsertPoint(L->getParent(), L);
01852       Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
01853       // Returning the load directly will cause the main loop to insert it in
01854       // the wrong spot, so use ReplaceInstUsesWith().
01855       return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
01856     }
01857   // We could simplify extracts from other values. Note that nested extracts may
01858   // already be simplified implicitly by the above: extract (extract (insert) )
01859   // will be translated into extract ( insert ( extract ) ) first and then just
01860   // the value inserted, if appropriate. Similarly for extracts from single-use
01861   // loads: extract (extract (load)) will be translated to extract (load (gep))
01862   // and if again single-use then via load (gep (gep)) to load (gep).
01863   // However, double extracts from e.g. function arguments or return values
01864   // aren't handled yet.
01865   return 0;
01866 }
01867 
01868 enum Personality_Type {
01869   Unknown_Personality,
01870   GNU_Ada_Personality,
01871   GNU_CXX_Personality,
01872   GNU_ObjC_Personality
01873 };
01874 
01875 /// RecognizePersonality - See if the given exception handling personality
01876 /// function is one that we understand.  If so, return a description of it;
01877 /// otherwise return Unknown_Personality.
01878 static Personality_Type RecognizePersonality(Value *Pers) {
01879   Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
01880   if (!F)
01881     return Unknown_Personality;
01882   return StringSwitch<Personality_Type>(F->getName())
01883     .Case("__gnat_eh_personality", GNU_Ada_Personality)
01884     .Case("__gxx_personality_v0",  GNU_CXX_Personality)
01885     .Case("__objc_personality_v0", GNU_ObjC_Personality)
01886     .Default(Unknown_Personality);
01887 }
01888 
01889 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
01890 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
01891   switch (Personality) {
01892   case Unknown_Personality:
01893     return false;
01894   case GNU_Ada_Personality:
01895     // While __gnat_all_others_value will match any Ada exception, it doesn't
01896     // match foreign exceptions (or didn't, before gcc-4.7).
01897     return false;
01898   case GNU_CXX_Personality:
01899   case GNU_ObjC_Personality:
01900     return TypeInfo->isNullValue();
01901   }
01902   llvm_unreachable("Unknown personality!");
01903 }
01904 
01905 static bool shorter_filter(const Value *LHS, const Value *RHS) {
01906   return
01907     cast<ArrayType>(LHS->getType())->getNumElements()
01908   <
01909     cast<ArrayType>(RHS->getType())->getNumElements();
01910 }
01911 
01912 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
01913   // The logic here should be correct for any real-world personality function.
01914   // However if that turns out not to be true, the offending logic can always
01915   // be conditioned on the personality function, like the catch-all logic is.
01916   Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
01917 
01918   // Simplify the list of clauses, eg by removing repeated catch clauses
01919   // (these are often created by inlining).
01920   bool MakeNewInstruction = false; // If true, recreate using the following:
01921   SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
01922   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
01923 
01924   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
01925   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
01926     bool isLastClause = i + 1 == e;
01927     if (LI.isCatch(i)) {
01928       // A catch clause.
01929       Value *CatchClause = LI.getClause(i);
01930       Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
01931 
01932       // If we already saw this clause, there is no point in having a second
01933       // copy of it.
01934       if (AlreadyCaught.insert(TypeInfo)) {
01935         // This catch clause was not already seen.
01936         NewClauses.push_back(CatchClause);
01937       } else {
01938         // Repeated catch clause - drop the redundant copy.
01939         MakeNewInstruction = true;
01940       }
01941 
01942       // If this is a catch-all then there is no point in keeping any following
01943       // clauses or marking the landingpad as having a cleanup.
01944       if (isCatchAll(Personality, TypeInfo)) {
01945         if (!isLastClause)
01946           MakeNewInstruction = true;
01947         CleanupFlag = false;
01948         break;
01949       }
01950     } else {
01951       // A filter clause.  If any of the filter elements were already caught
01952       // then they can be dropped from the filter.  It is tempting to try to
01953       // exploit the filter further by saying that any typeinfo that does not
01954       // occur in the filter can't be caught later (and thus can be dropped).
01955       // However this would be wrong, since typeinfos can match without being
01956       // equal (for example if one represents a C++ class, and the other some
01957       // class derived from it).
01958       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
01959       Value *FilterClause = LI.getClause(i);
01960       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
01961       unsigned NumTypeInfos = FilterType->getNumElements();
01962 
01963       // An empty filter catches everything, so there is no point in keeping any
01964       // following clauses or marking the landingpad as having a cleanup.  By
01965       // dealing with this case here the following code is made a bit simpler.
01966       if (!NumTypeInfos) {
01967         NewClauses.push_back(FilterClause);
01968         if (!isLastClause)
01969           MakeNewInstruction = true;
01970         CleanupFlag = false;
01971         break;
01972       }
01973 
01974       bool MakeNewFilter = false; // If true, make a new filter.
01975       SmallVector<Constant *, 16> NewFilterElts; // New elements.
01976       if (isa<ConstantAggregateZero>(FilterClause)) {
01977         // Not an empty filter - it contains at least one null typeinfo.
01978         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
01979         Constant *TypeInfo =
01980           Constant::getNullValue(FilterType->getElementType());
01981         // If this typeinfo is a catch-all then the filter can never match.
01982         if (isCatchAll(Personality, TypeInfo)) {
01983           // Throw the filter away.
01984           MakeNewInstruction = true;
01985           continue;
01986         }
01987 
01988         // There is no point in having multiple copies of this typeinfo, so
01989         // discard all but the first copy if there is more than one.
01990         NewFilterElts.push_back(TypeInfo);
01991         if (NumTypeInfos > 1)
01992           MakeNewFilter = true;
01993       } else {
01994         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
01995         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
01996         NewFilterElts.reserve(NumTypeInfos);
01997 
01998         // Remove any filter elements that were already caught or that already
01999         // occurred in the filter.  While there, see if any of the elements are
02000         // catch-alls.  If so, the filter can be discarded.
02001         bool SawCatchAll = false;
02002         for (unsigned j = 0; j != NumTypeInfos; ++j) {
02003           Value *Elt = Filter->getOperand(j);
02004           Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
02005           if (isCatchAll(Personality, TypeInfo)) {
02006             // This element is a catch-all.  Bail out, noting this fact.
02007             SawCatchAll = true;
02008             break;
02009           }
02010           if (AlreadyCaught.count(TypeInfo))
02011             // Already caught by an earlier clause, so having it in the filter
02012             // is pointless.
02013             continue;
02014           // There is no point in having multiple copies of the same typeinfo in
02015           // a filter, so only add it if we didn't already.
02016           if (SeenInFilter.insert(TypeInfo))
02017             NewFilterElts.push_back(cast<Constant>(Elt));
02018         }
02019         // A filter containing a catch-all cannot match anything by definition.
02020         if (SawCatchAll) {
02021           // Throw the filter away.
02022           MakeNewInstruction = true;
02023           continue;
02024         }
02025 
02026         // If we dropped something from the filter, make a new one.
02027         if (NewFilterElts.size() < NumTypeInfos)
02028           MakeNewFilter = true;
02029       }
02030       if (MakeNewFilter) {
02031         FilterType = ArrayType::get(FilterType->getElementType(),
02032                                     NewFilterElts.size());
02033         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
02034         MakeNewInstruction = true;
02035       }
02036 
02037       NewClauses.push_back(FilterClause);
02038 
02039       // If the new filter is empty then it will catch everything so there is
02040       // no point in keeping any following clauses or marking the landingpad
02041       // as having a cleanup.  The case of the original filter being empty was
02042       // already handled above.
02043       if (MakeNewFilter && !NewFilterElts.size()) {
02044         assert(MakeNewInstruction && "New filter but not a new instruction!");
02045         CleanupFlag = false;
02046         break;
02047       }
02048     }
02049   }
02050 
02051   // If several filters occur in a row then reorder them so that the shortest
02052   // filters come first (those with the smallest number of elements).  This is
02053   // advantageous because shorter filters are more likely to match, speeding up
02054   // unwinding, but mostly because it increases the effectiveness of the other
02055   // filter optimizations below.
02056   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
02057     unsigned j;
02058     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
02059     for (j = i; j != e; ++j)
02060       if (!isa<ArrayType>(NewClauses[j]->getType()))
02061         break;
02062 
02063     // Check whether the filters are already sorted by length.  We need to know
02064     // if sorting them is actually going to do anything so that we only make a
02065     // new landingpad instruction if it does.
02066     for (unsigned k = i; k + 1 < j; ++k)
02067       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
02068         // Not sorted, so sort the filters now.  Doing an unstable sort would be
02069         // correct too but reordering filters pointlessly might confuse users.
02070         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
02071                          shorter_filter);
02072         MakeNewInstruction = true;
02073         break;
02074       }
02075 
02076     // Look for the next batch of filters.
02077     i = j + 1;
02078   }
02079 
02080   // If typeinfos matched if and only if equal, then the elements of a filter L
02081   // that occurs later than a filter F could be replaced by the intersection of
02082   // the elements of F and L.  In reality two typeinfos can match without being
02083   // equal (for example if one represents a C++ class, and the other some class
02084   // derived from it) so it would be wrong to perform this transform in general.
02085   // However the transform is correct and useful if F is a subset of L.  In that
02086   // case L can be replaced by F, and thus removed altogether since repeating a
02087   // filter is pointless.  So here we look at all pairs of filters F and L where
02088   // L follows F in the list of clauses, and remove L if every element of F is
02089   // an element of L.  This can occur when inlining C++ functions with exception
02090   // specifications.
02091   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
02092     // Examine each filter in turn.
02093     Value *Filter = NewClauses[i];
02094     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
02095     if (!FTy)
02096       // Not a filter - skip it.
02097       continue;
02098     unsigned FElts = FTy->getNumElements();
02099     // Examine each filter following this one.  Doing this backwards means that
02100     // we don't have to worry about filters disappearing under us when removed.
02101     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
02102       Value *LFilter = NewClauses[j];
02103       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
02104       if (!LTy)
02105         // Not a filter - skip it.
02106         continue;
02107       // If Filter is a subset of LFilter, i.e. every element of Filter is also
02108       // an element of LFilter, then discard LFilter.
02109       SmallVectorImpl<Value *>::iterator J = NewClauses.begin() + j;
02110       // If Filter is empty then it is a subset of LFilter.
02111       if (!FElts) {
02112         // Discard LFilter.
02113         NewClauses.erase(J);
02114         MakeNewInstruction = true;
02115         // Move on to the next filter.
02116         continue;
02117       }
02118       unsigned LElts = LTy->getNumElements();
02119       // If Filter is longer than LFilter then it cannot be a subset of it.
02120       if (FElts > LElts)
02121         // Move on to the next filter.
02122         continue;
02123       // At this point we know that LFilter has at least one element.
02124       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
02125         // Filter is a subset of LFilter iff Filter contains only zeros (as we
02126         // already know that Filter is not longer than LFilter).
02127         if (isa<ConstantAggregateZero>(Filter)) {
02128           assert(FElts <= LElts && "Should have handled this case earlier!");
02129           // Discard LFilter.
02130           NewClauses.erase(J);
02131           MakeNewInstruction = true;
02132         }
02133         // Move on to the next filter.
02134         continue;
02135       }
02136       ConstantArray *LArray = cast<ConstantArray>(LFilter);
02137       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
02138         // Since Filter is non-empty and contains only zeros, it is a subset of
02139         // LFilter iff LFilter contains a zero.
02140         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
02141         for (unsigned l = 0; l != LElts; ++l)
02142           if (LArray->getOperand(l)->isNullValue()) {
02143             // LFilter contains a zero - discard it.
02144             NewClauses.erase(J);
02145             MakeNewInstruction = true;
02146             break;
02147           }
02148         // Move on to the next filter.
02149         continue;
02150       }
02151       // At this point we know that both filters are ConstantArrays.  Loop over
02152       // operands to see whether every element of Filter is also an element of
02153       // LFilter.  Since filters tend to be short this is probably faster than
02154       // using a method that scales nicely.
02155       ConstantArray *FArray = cast<ConstantArray>(Filter);
02156       bool AllFound = true;
02157       for (unsigned f = 0; f != FElts; ++f) {
02158         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
02159         AllFound = false;
02160         for (unsigned l = 0; l != LElts; ++l) {
02161           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
02162           if (LTypeInfo == FTypeInfo) {
02163             AllFound = true;
02164             break;
02165           }
02166         }
02167         if (!AllFound)
02168           break;
02169       }
02170       if (AllFound) {
02171         // Discard LFilter.
02172         NewClauses.erase(J);
02173         MakeNewInstruction = true;
02174       }
02175       // Move on to the next filter.
02176     }
02177   }
02178 
02179   // If we changed any of the clauses, replace the old landingpad instruction
02180   // with a new one.
02181   if (MakeNewInstruction) {
02182     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
02183                                                  LI.getPersonalityFn(),
02184                                                  NewClauses.size());
02185     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
02186       NLI->addClause(NewClauses[i]);
02187     // A landing pad with no clauses must have the cleanup flag set.  It is
02188     // theoretically possible, though highly unlikely, that we eliminated all
02189     // clauses.  If so, force the cleanup flag to true.
02190     if (NewClauses.empty())
02191       CleanupFlag = true;
02192     NLI->setCleanup(CleanupFlag);
02193     return NLI;
02194   }
02195 
02196   // Even if none of the clauses changed, we may nonetheless have understood
02197   // that the cleanup flag is pointless.  Clear it if so.
02198   if (LI.isCleanup() != CleanupFlag) {
02199     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
02200     LI.setCleanup(CleanupFlag);
02201     return &LI;
02202   }
02203 
02204   return 0;
02205 }
02206 
02207 
02208 
02209 
02210 /// TryToSinkInstruction - Try to move the specified instruction from its
02211 /// current block into the beginning of DestBlock, which can only happen if it's
02212 /// safe to move the instruction past all of the instructions between it and the
02213 /// end of its block.
02214 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
02215   assert(I->hasOneUse() && "Invariants didn't hold!");
02216 
02217   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
02218   if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
02219       isa<TerminatorInst>(I))
02220     return false;
02221 
02222   // Do not sink alloca instructions out of the entry block.
02223   if (isa<AllocaInst>(I) && I->getParent() ==
02224         &DestBlock->getParent()->getEntryBlock())
02225     return false;
02226 
02227   // We can only sink load instructions if there is nothing between the load and
02228   // the end of block that could change the value.
02229   if (I->mayReadFromMemory()) {
02230     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
02231          Scan != E; ++Scan)
02232       if (Scan->mayWriteToMemory())
02233         return false;
02234   }
02235 
02236   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
02237   I->moveBefore(InsertPos);
02238   ++NumSunkInst;
02239   return true;
02240 }
02241 
02242 
02243 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
02244 /// all reachable code to the worklist.
02245 ///
02246 /// This has a couple of tricks to make the code faster and more powerful.  In
02247 /// particular, we constant fold and DCE instructions as we go, to avoid adding
02248 /// them to the worklist (this significantly speeds up instcombine on code where
02249 /// many instructions are dead or constant).  Additionally, if we find a branch
02250 /// whose condition is a known constant, we only visit the reachable successors.
02251 ///
02252 static bool AddReachableCodeToWorklist(BasicBlock *BB,
02253                                        SmallPtrSet<BasicBlock*, 64> &Visited,
02254                                        InstCombiner &IC,
02255                                        const DataLayout *DL,
02256                                        const TargetLibraryInfo *TLI) {
02257   bool MadeIRChange = false;
02258   SmallVector<BasicBlock*, 256> Worklist;
02259   Worklist.push_back(BB);
02260 
02261   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
02262   DenseMap<ConstantExpr*, Constant*> FoldedConstants;
02263 
02264   do {
02265     BB = Worklist.pop_back_val();
02266 
02267     // We have now visited this block!  If we've already been here, ignore it.
02268     if (!Visited.insert(BB)) continue;
02269 
02270     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
02271       Instruction *Inst = BBI++;
02272 
02273       // DCE instruction if trivially dead.
02274       if (isInstructionTriviallyDead(Inst, TLI)) {
02275         ++NumDeadInst;
02276         DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
02277         Inst->eraseFromParent();
02278         continue;
02279       }
02280 
02281       // ConstantProp instruction if trivially constant.
02282       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
02283         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
02284           DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
02285                        << *Inst << '\n');
02286           Inst->replaceAllUsesWith(C);
02287           ++NumConstProp;
02288           Inst->eraseFromParent();
02289           continue;
02290         }
02291 
02292       if (DL) {
02293         // See if we can constant fold its operands.
02294         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
02295              i != e; ++i) {
02296           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
02297           if (CE == 0) continue;
02298 
02299           Constant*& FoldRes = FoldedConstants[CE];
02300           if (!FoldRes)
02301             FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
02302           if (!FoldRes)
02303             FoldRes = CE;
02304 
02305           if (FoldRes != CE) {
02306             *i = FoldRes;
02307             MadeIRChange = true;
02308           }
02309         }
02310       }
02311 
02312       InstrsForInstCombineWorklist.push_back(Inst);
02313     }
02314 
02315     // Recursively visit successors.  If this is a branch or switch on a
02316     // constant, only visit the reachable successor.
02317     TerminatorInst *TI = BB->getTerminator();
02318     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
02319       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
02320         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
02321         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
02322         Worklist.push_back(ReachableBB);
02323         continue;
02324       }
02325     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
02326       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
02327         // See if this is an explicit destination.
02328         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
02329              i != e; ++i)
02330           if (i.getCaseValue() == Cond) {
02331             BasicBlock *ReachableBB = i.getCaseSuccessor();
02332             Worklist.push_back(ReachableBB);
02333             continue;
02334           }
02335 
02336         // Otherwise it is the default destination.
02337         Worklist.push_back(SI->getDefaultDest());
02338         continue;
02339       }
02340     }
02341 
02342     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
02343       Worklist.push_back(TI->getSuccessor(i));
02344   } while (!Worklist.empty());
02345 
02346   // Once we've found all of the instructions to add to instcombine's worklist,
02347   // add them in reverse order.  This way instcombine will visit from the top
02348   // of the function down.  This jives well with the way that it adds all uses
02349   // of instructions to the worklist after doing a transformation, thus avoiding
02350   // some N^2 behavior in pathological cases.
02351   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
02352                               InstrsForInstCombineWorklist.size());
02353 
02354   return MadeIRChange;
02355 }
02356 
02357 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
02358   MadeIRChange = false;
02359 
02360   DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
02361                << F.getName() << "\n");
02362 
02363   {
02364     // Do a depth-first traversal of the function, populate the worklist with
02365     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
02366     // track of which blocks we visit.
02367     SmallPtrSet<BasicBlock*, 64> Visited;
02368     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
02369                                                TLI);
02370 
02371     // Do a quick scan over the function.  If we find any blocks that are
02372     // unreachable, remove any instructions inside of them.  This prevents
02373     // the instcombine code from having to deal with some bad special cases.
02374     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
02375       if (Visited.count(BB)) continue;
02376 
02377       // Delete the instructions backwards, as it has a reduced likelihood of
02378       // having to update as many def-use and use-def chains.
02379       Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
02380       while (EndInst != BB->begin()) {
02381         // Delete the next to last instruction.
02382         BasicBlock::iterator I = EndInst;
02383         Instruction *Inst = --I;
02384         if (!Inst->use_empty())
02385           Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
02386         if (isa<LandingPadInst>(Inst)) {
02387           EndInst = Inst;
02388           continue;
02389         }
02390         if (!isa<DbgInfoIntrinsic>(Inst)) {
02391           ++NumDeadInst;
02392           MadeIRChange = true;
02393         }
02394         Inst->eraseFromParent();
02395       }
02396     }
02397   }
02398 
02399   while (!Worklist.isEmpty()) {
02400     Instruction *I = Worklist.RemoveOne();
02401     if (I == 0) continue;  // skip null values.
02402 
02403     // Check to see if we can DCE the instruction.
02404     if (isInstructionTriviallyDead(I, TLI)) {
02405       DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
02406       EraseInstFromFunction(*I);
02407       ++NumDeadInst;
02408       MadeIRChange = true;
02409       continue;
02410     }
02411 
02412     // Instruction isn't dead, see if we can constant propagate it.
02413     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
02414       if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
02415         DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
02416 
02417         // Add operands to the worklist.
02418         ReplaceInstUsesWith(*I, C);
02419         ++NumConstProp;
02420         EraseInstFromFunction(*I);
02421         MadeIRChange = true;
02422         continue;
02423       }
02424 
02425     // See if we can trivially sink this instruction to a successor basic block.
02426     if (I->hasOneUse()) {
02427       BasicBlock *BB = I->getParent();
02428       Instruction *UserInst = cast<Instruction>(*I->user_begin());
02429       BasicBlock *UserParent;
02430 
02431       // Get the block the use occurs in.
02432       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
02433         UserParent = PN->getIncomingBlock(*I->use_begin());
02434       else
02435         UserParent = UserInst->getParent();
02436 
02437       if (UserParent != BB) {
02438         bool UserIsSuccessor = false;
02439         // See if the user is one of our successors.
02440         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
02441           if (*SI == UserParent) {
02442             UserIsSuccessor = true;
02443             break;
02444           }
02445 
02446         // If the user is one of our immediate successors, and if that successor
02447         // only has us as a predecessors (we'd have to split the critical edge
02448         // otherwise), we can keep going.
02449         if (UserIsSuccessor && UserParent->getSinglePredecessor())
02450           // Okay, the CFG is simple enough, try to sink this instruction.
02451           MadeIRChange |= TryToSinkInstruction(I, UserParent);
02452       }
02453     }
02454 
02455     // Now that we have an instruction, try combining it to simplify it.
02456     Builder->SetInsertPoint(I->getParent(), I);
02457     Builder->SetCurrentDebugLocation(I->getDebugLoc());
02458 
02459 #ifndef NDEBUG
02460     std::string OrigI;
02461 #endif
02462     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
02463     DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
02464 
02465     if (Instruction *Result = visit(*I)) {
02466       ++NumCombined;
02467       // Should we replace the old instruction with a new one?
02468       if (Result != I) {
02469         DEBUG(dbgs() << "IC: Old = " << *I << '\n'
02470                      << "    New = " << *Result << '\n');
02471 
02472         if (!I->getDebugLoc().isUnknown())
02473           Result->setDebugLoc(I->getDebugLoc());
02474         // Everything uses the new instruction now.
02475         I->replaceAllUsesWith(Result);
02476 
02477         // Move the name to the new instruction first.
02478         Result->takeName(I);
02479 
02480         // Push the new instruction and any users onto the worklist.
02481         Worklist.Add(Result);
02482         Worklist.AddUsersToWorkList(*Result);
02483 
02484         // Insert the new instruction into the basic block...
02485         BasicBlock *InstParent = I->getParent();
02486         BasicBlock::iterator InsertPos = I;
02487 
02488         // If we replace a PHI with something that isn't a PHI, fix up the
02489         // insertion point.
02490         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
02491           InsertPos = InstParent->getFirstInsertionPt();
02492 
02493         InstParent->getInstList().insert(InsertPos, Result);
02494 
02495         EraseInstFromFunction(*I);
02496       } else {
02497 #ifndef NDEBUG
02498         DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
02499                      << "    New = " << *I << '\n');
02500 #endif
02501 
02502         // If the instruction was modified, it's possible that it is now dead.
02503         // if so, remove it.
02504         if (isInstructionTriviallyDead(I, TLI)) {
02505           EraseInstFromFunction(*I);
02506         } else {
02507           Worklist.Add(I);
02508           Worklist.AddUsersToWorkList(*I);
02509         }
02510       }
02511       MadeIRChange = true;
02512     }
02513   }
02514 
02515   Worklist.Zap();
02516   return MadeIRChange;
02517 }
02518 
02519 namespace {
02520 class InstCombinerLibCallSimplifier : public LibCallSimplifier {
02521   InstCombiner *IC;
02522 public:
02523   InstCombinerLibCallSimplifier(const DataLayout *DL,
02524                                 const TargetLibraryInfo *TLI,
02525                                 InstCombiner *IC)
02526     : LibCallSimplifier(DL, TLI, UnsafeFPShrink) {
02527     this->IC = IC;
02528   }
02529 
02530   /// replaceAllUsesWith - override so that instruction replacement
02531   /// can be defined in terms of the instruction combiner framework.
02532   void replaceAllUsesWith(Instruction *I, Value *With) const override {
02533     IC->ReplaceInstUsesWith(*I, With);
02534   }
02535 };
02536 }
02537 
02538 bool InstCombiner::runOnFunction(Function &F) {
02539   if (skipOptnoneFunction(F))
02540     return false;
02541 
02542   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
02543   DL = DLP ? &DLP->getDataLayout() : 0;
02544   TLI = &getAnalysis<TargetLibraryInfo>();
02545   // Minimizing size?
02546   MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
02547                                                 Attribute::MinSize);
02548 
02549   /// Builder - This is an IRBuilder that automatically inserts new
02550   /// instructions into the worklist when they are created.
02551   IRBuilder<true, TargetFolder, InstCombineIRInserter>
02552     TheBuilder(F.getContext(), TargetFolder(DL),
02553                InstCombineIRInserter(Worklist));
02554   Builder = &TheBuilder;
02555 
02556   InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
02557   Simplifier = &TheSimplifier;
02558 
02559   bool EverMadeChange = false;
02560 
02561   // Lower dbg.declare intrinsics otherwise their value may be clobbered
02562   // by instcombiner.
02563   EverMadeChange = LowerDbgDeclare(F);
02564 
02565   // Iterate while there is work to do.
02566   unsigned Iteration = 0;
02567   while (DoOneIteration(F, Iteration++))
02568     EverMadeChange = true;
02569 
02570   Builder = 0;
02571   return EverMadeChange;
02572 }
02573 
02574 FunctionPass *llvm::createInstructionCombiningPass() {
02575   return new InstCombiner();
02576 }