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