LLVM API Documentation

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