1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // InstructionCombining - Combine instructions to form fewer, simple
10 // instructions.  This pass does not modify the CFG.  This pass is where
11 // algebraic simplification happens.
12 //
13 // This pass combines things like:
14 //    %Y = add i32 %X, 1
15 //    %Z = add i32 %Y, 1
16 // into:
17 //    %Z = add i32 %X, 2
18 //
19 // This is a simple worklist driven algorithm.
20 //
21 // This pass guarantees that the following canonicalizations are performed on
22 // the program:
23 //    1. If a binary operator has a constant operand, it is moved to the RHS
24 //    2. Bitwise operators with constant operands are always grouped so that
25 //       shifts are performed first, then or's, then and's, then xor's.
26 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
27 //    4. All cmp instructions on boolean values are replaced with logical ops
28 //    5. add X, X is represented as (X*2) => (X << 1)
29 //    6. Multiplies with a power-of-two constant argument are transformed into
30 //       shifts.
31 //   ... etc.
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "InstCombineInternal.h"
36 #include "llvm-c/Initialization.h"
37 #include "llvm-c/Transforms/InstCombine.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/None.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/TinyPtrVector.h"
46 #include "llvm/Analysis/AliasAnalysis.h"
47 #include "llvm/Analysis/AssumptionCache.h"
48 #include "llvm/Analysis/BasicAliasAnalysis.h"
49 #include "llvm/Analysis/BlockFrequencyInfo.h"
50 #include "llvm/Analysis/CFG.h"
51 #include "llvm/Analysis/ConstantFolding.h"
52 #include "llvm/Analysis/EHPersonalities.h"
53 #include "llvm/Analysis/GlobalsModRef.h"
54 #include "llvm/Analysis/InstructionSimplify.h"
55 #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
56 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/Analysis/MemoryBuiltins.h"
58 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
59 #include "llvm/Analysis/ProfileSummaryInfo.h"
60 #include "llvm/Analysis/TargetFolder.h"
61 #include "llvm/Analysis/TargetLibraryInfo.h"
62 #include "llvm/Analysis/ValueTracking.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DIBuilder.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Dominators.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GetElementPtrTypeIterator.h"
73 #include "llvm/IR/IRBuilder.h"
74 #include "llvm/IR/InstrTypes.h"
75 #include "llvm/IR/Instruction.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/LegacyPassManager.h"
80 #include "llvm/IR/Metadata.h"
81 #include "llvm/IR/Operator.h"
82 #include "llvm/IR/PassManager.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/Use.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/IR/ValueHandle.h"
89 #include "llvm/Pass.h"
90 #include "llvm/Support/CBindingWrapping.h"
91 #include "llvm/Support/Casting.h"
92 #include "llvm/Support/CommandLine.h"
93 #include "llvm/Support/Compiler.h"
94 #include "llvm/Support/Debug.h"
95 #include "llvm/Support/DebugCounter.h"
96 #include "llvm/Support/ErrorHandling.h"
97 #include "llvm/Support/KnownBits.h"
98 #include "llvm/Support/raw_ostream.h"
99 #include "llvm/Transforms/InstCombine/InstCombine.h"
100 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
101 #include "llvm/Transforms/Utils/Local.h"
102 #include <algorithm>
103 #include <cassert>
104 #include <cstdint>
105 #include <memory>
106 #include <string>
107 #include <utility>
108 
109 using namespace llvm;
110 using namespace llvm::PatternMatch;
111 
112 #define DEBUG_TYPE "instcombine"
113 
114 STATISTIC(NumCombined , "Number of insts combined");
115 STATISTIC(NumConstProp, "Number of constant folds");
116 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
117 STATISTIC(NumSunkInst , "Number of instructions sunk");
118 STATISTIC(NumExpand,    "Number of expansions");
119 STATISTIC(NumFactor   , "Number of factorizations");
120 STATISTIC(NumReassoc  , "Number of reassociations");
121 DEBUG_COUNTER(VisitCounter, "instcombine-visit",
122               "Controls which instructions are visited");
123 
124 static cl::opt<bool>
125 EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"),
126                                               cl::init(true));
127 
128 static cl::opt<bool>
129 EnableExpensiveCombines("expensive-combines",
130                         cl::desc("Enable expensive instruction combines"));
131 
132 static cl::opt<unsigned>
133 MaxArraySize("instcombine-maxarray-size", cl::init(1024),
134              cl::desc("Maximum array size considered when doing a combine"));
135 
136 // FIXME: Remove this flag when it is no longer necessary to convert
137 // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false
138 // increases variable availability at the cost of accuracy. Variables that
139 // cannot be promoted by mem2reg or SROA will be described as living in memory
140 // for their entire lifetime. However, passes like DSE and instcombine can
141 // delete stores to the alloca, leading to misleading and inaccurate debug
142 // information. This flag can be removed when those passes are fixed.
143 static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
144                                                cl::Hidden, cl::init(true));
145 
146 Value *InstCombiner::EmitGEPOffset(User *GEP) {
147   return llvm::EmitGEPOffset(&Builder, DL, GEP);
148 }
149 
150 /// Return true if it is desirable to convert an integer computation from a
151 /// given bit width to a new bit width.
152 /// We don't want to convert from a legal to an illegal type or from a smaller
153 /// to a larger illegal type. A width of '1' is always treated as a legal type
154 /// because i1 is a fundamental type in IR, and there are many specialized
155 /// optimizations for i1 types. Widths of 8, 16 or 32 are equally treated as
156 /// legal to convert to, in order to open up more combining opportunities.
157 /// NOTE: this treats i8, i16 and i32 specially, due to them being so common
158 /// from frontend languages.
159 bool InstCombiner::shouldChangeType(unsigned FromWidth,
160                                     unsigned ToWidth) const {
161   bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
162   bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
163 
164   // Convert to widths of 8, 16 or 32 even if they are not legal types. Only
165   // shrink types, to prevent infinite loops.
166   if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32))
167     return true;
168 
169   // If this is a legal integer from type, and the result would be an illegal
170   // type, don't do the transformation.
171   if (FromLegal && !ToLegal)
172     return false;
173 
174   // Otherwise, if both are illegal, do not increase the size of the result. We
175   // do allow things like i160 -> i64, but not i64 -> i160.
176   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
177     return false;
178 
179   return true;
180 }
181 
182 /// Return true if it is desirable to convert a computation from 'From' to 'To'.
183 /// We don't want to convert from a legal to an illegal type or from a smaller
184 /// to a larger illegal type. i1 is always treated as a legal type because it is
185 /// a fundamental type in IR, and there are many specialized optimizations for
186 /// i1 types.
187 bool InstCombiner::shouldChangeType(Type *From, Type *To) const {
188   // TODO: This could be extended to allow vectors. Datalayout changes might be
189   // needed to properly support that.
190   if (!From->isIntegerTy() || !To->isIntegerTy())
191     return false;
192 
193   unsigned FromWidth = From->getPrimitiveSizeInBits();
194   unsigned ToWidth = To->getPrimitiveSizeInBits();
195   return shouldChangeType(FromWidth, ToWidth);
196 }
197 
198 // Return true, if No Signed Wrap should be maintained for I.
199 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
200 // where both B and C should be ConstantInts, results in a constant that does
201 // not overflow. This function only handles the Add and Sub opcodes. For
202 // all other opcodes, the function conservatively returns false.
203 static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
204   auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
205   if (!OBO || !OBO->hasNoSignedWrap())
206     return false;
207 
208   // We reason about Add and Sub Only.
209   Instruction::BinaryOps Opcode = I.getOpcode();
210   if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
211     return false;
212 
213   const APInt *BVal, *CVal;
214   if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
215     return false;
216 
217   bool Overflow = false;
218   if (Opcode == Instruction::Add)
219     (void)BVal->sadd_ov(*CVal, Overflow);
220   else
221     (void)BVal->ssub_ov(*CVal, Overflow);
222 
223   return !Overflow;
224 }
225 
226 static bool hasNoUnsignedWrap(BinaryOperator &I) {
227   auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
228   return OBO && OBO->hasNoUnsignedWrap();
229 }
230 
231 static bool hasNoSignedWrap(BinaryOperator &I) {
232   auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
233   return OBO && OBO->hasNoSignedWrap();
234 }
235 
236 /// Conservatively clears subclassOptionalData after a reassociation or
237 /// commutation. We preserve fast-math flags when applicable as they can be
238 /// preserved.
239 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
240   FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
241   if (!FPMO) {
242     I.clearSubclassOptionalData();
243     return;
244   }
245 
246   FastMathFlags FMF = I.getFastMathFlags();
247   I.clearSubclassOptionalData();
248   I.setFastMathFlags(FMF);
249 }
250 
251 /// Combine constant operands of associative operations either before or after a
252 /// cast to eliminate one of the associative operations:
253 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
254 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
255 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) {
256   auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
257   if (!Cast || !Cast->hasOneUse())
258     return false;
259 
260   // TODO: Enhance logic for other casts and remove this check.
261   auto CastOpcode = Cast->getOpcode();
262   if (CastOpcode != Instruction::ZExt)
263     return false;
264 
265   // TODO: Enhance logic for other BinOps and remove this check.
266   if (!BinOp1->isBitwiseLogicOp())
267     return false;
268 
269   auto AssocOpcode = BinOp1->getOpcode();
270   auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
271   if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
272     return false;
273 
274   Constant *C1, *C2;
275   if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
276       !match(BinOp2->getOperand(1), m_Constant(C2)))
277     return false;
278 
279   // TODO: This assumes a zext cast.
280   // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
281   // to the destination type might lose bits.
282 
283   // Fold the constants together in the destination type:
284   // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
285   Type *DestTy = C1->getType();
286   Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
287   Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
288   Cast->setOperand(0, BinOp2->getOperand(0));
289   BinOp1->setOperand(1, FoldedC);
290   return true;
291 }
292 
293 /// This performs a few simplifications for operators that are associative or
294 /// commutative:
295 ///
296 ///  Commutative operators:
297 ///
298 ///  1. Order operands such that they are listed from right (least complex) to
299 ///     left (most complex).  This puts constants before unary operators before
300 ///     binary operators.
301 ///
302 ///  Associative operators:
303 ///
304 ///  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
305 ///  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
306 ///
307 ///  Associative and commutative operators:
308 ///
309 ///  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
310 ///  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
311 ///  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
312 ///     if C1 and C2 are constants.
313 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
314   Instruction::BinaryOps Opcode = I.getOpcode();
315   bool Changed = false;
316 
317   do {
318     // Order operands such that they are listed from right (least complex) to
319     // left (most complex).  This puts constants before unary operators before
320     // binary operators.
321     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
322         getComplexity(I.getOperand(1)))
323       Changed = !I.swapOperands();
324 
325     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
326     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
327 
328     if (I.isAssociative()) {
329       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
330       if (Op0 && Op0->getOpcode() == Opcode) {
331         Value *A = Op0->getOperand(0);
332         Value *B = Op0->getOperand(1);
333         Value *C = I.getOperand(1);
334 
335         // Does "B op C" simplify?
336         if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
337           // It simplifies to V.  Form "A op V".
338           I.setOperand(0, A);
339           I.setOperand(1, V);
340           bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0);
341           bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0);
342 
343           // Conservatively clear all optional flags since they may not be
344           // preserved by the reassociation. Reset nsw/nuw based on the above
345           // analysis.
346           ClearSubclassDataAfterReassociation(I);
347 
348           // Note: this is only valid because SimplifyBinOp doesn't look at
349           // the operands to Op0.
350           if (IsNUW)
351             I.setHasNoUnsignedWrap(true);
352 
353           if (IsNSW)
354             I.setHasNoSignedWrap(true);
355 
356           Changed = true;
357           ++NumReassoc;
358           continue;
359         }
360       }
361 
362       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
363       if (Op1 && Op1->getOpcode() == Opcode) {
364         Value *A = I.getOperand(0);
365         Value *B = Op1->getOperand(0);
366         Value *C = Op1->getOperand(1);
367 
368         // Does "A op B" simplify?
369         if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
370           // It simplifies to V.  Form "V op C".
371           I.setOperand(0, V);
372           I.setOperand(1, C);
373           // Conservatively clear the optional flags, since they may not be
374           // preserved by the reassociation.
375           ClearSubclassDataAfterReassociation(I);
376           Changed = true;
377           ++NumReassoc;
378           continue;
379         }
380       }
381     }
382 
383     if (I.isAssociative() && I.isCommutative()) {
384       if (simplifyAssocCastAssoc(&I)) {
385         Changed = true;
386         ++NumReassoc;
387         continue;
388       }
389 
390       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
391       if (Op0 && Op0->getOpcode() == Opcode) {
392         Value *A = Op0->getOperand(0);
393         Value *B = Op0->getOperand(1);
394         Value *C = I.getOperand(1);
395 
396         // Does "C op A" simplify?
397         if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
398           // It simplifies to V.  Form "V op B".
399           I.setOperand(0, V);
400           I.setOperand(1, B);
401           // Conservatively clear the optional flags, since they may not be
402           // preserved by the reassociation.
403           ClearSubclassDataAfterReassociation(I);
404           Changed = true;
405           ++NumReassoc;
406           continue;
407         }
408       }
409 
410       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
411       if (Op1 && Op1->getOpcode() == Opcode) {
412         Value *A = I.getOperand(0);
413         Value *B = Op1->getOperand(0);
414         Value *C = Op1->getOperand(1);
415 
416         // Does "C op A" simplify?
417         if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
418           // It simplifies to V.  Form "B op V".
419           I.setOperand(0, B);
420           I.setOperand(1, V);
421           // Conservatively clear the optional flags, since they may not be
422           // preserved by the reassociation.
423           ClearSubclassDataAfterReassociation(I);
424           Changed = true;
425           ++NumReassoc;
426           continue;
427         }
428       }
429 
430       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
431       // if C1 and C2 are constants.
432       Value *A, *B;
433       Constant *C1, *C2;
434       if (Op0 && Op1 &&
435           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
436           match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&
437           match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2))))) {
438         bool IsNUW = hasNoUnsignedWrap(I) &&
439            hasNoUnsignedWrap(*Op0) &&
440            hasNoUnsignedWrap(*Op1);
441          BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?
442            BinaryOperator::CreateNUW(Opcode, A, B) :
443            BinaryOperator::Create(Opcode, A, B);
444 
445          if (isa<FPMathOperator>(NewBO)) {
446           FastMathFlags Flags = I.getFastMathFlags();
447           Flags &= Op0->getFastMathFlags();
448           Flags &= Op1->getFastMathFlags();
449           NewBO->setFastMathFlags(Flags);
450         }
451         InsertNewInstWith(NewBO, I);
452         NewBO->takeName(Op1);
453         I.setOperand(0, NewBO);
454         I.setOperand(1, ConstantExpr::get(Opcode, C1, C2));
455         // Conservatively clear the optional flags, since they may not be
456         // preserved by the reassociation.
457         ClearSubclassDataAfterReassociation(I);
458         if (IsNUW)
459           I.setHasNoUnsignedWrap(true);
460 
461         Changed = true;
462         continue;
463       }
464     }
465 
466     // No further simplifications.
467     return Changed;
468   } while (true);
469 }
470 
471 /// Return whether "X LOp (Y ROp Z)" is always equal to
472 /// "(X LOp Y) ROp (X LOp Z)".
473 static bool leftDistributesOverRight(Instruction::BinaryOps LOp,
474                                      Instruction::BinaryOps ROp) {
475   // X & (Y | Z) <--> (X & Y) | (X & Z)
476   // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
477   if (LOp == Instruction::And)
478     return ROp == Instruction::Or || ROp == Instruction::Xor;
479 
480   // X | (Y & Z) <--> (X | Y) & (X | Z)
481   if (LOp == Instruction::Or)
482     return ROp == Instruction::And;
483 
484   // X * (Y + Z) <--> (X * Y) + (X * Z)
485   // X * (Y - Z) <--> (X * Y) - (X * Z)
486   if (LOp == Instruction::Mul)
487     return ROp == Instruction::Add || ROp == Instruction::Sub;
488 
489   return false;
490 }
491 
492 /// Return whether "(X LOp Y) ROp Z" is always equal to
493 /// "(X ROp Z) LOp (Y ROp Z)".
494 static bool rightDistributesOverLeft(Instruction::BinaryOps LOp,
495                                      Instruction::BinaryOps ROp) {
496   if (Instruction::isCommutative(ROp))
497     return leftDistributesOverRight(ROp, LOp);
498 
499   // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
500   return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp);
501 
502   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
503   // but this requires knowing that the addition does not overflow and other
504   // such subtleties.
505 }
506 
507 /// This function returns identity value for given opcode, which can be used to
508 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
509 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
510   if (isa<Constant>(V))
511     return nullptr;
512 
513   return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
514 }
515 
516 /// This function predicates factorization using distributive laws. By default,
517 /// it just returns the 'Op' inputs. But for special-cases like
518 /// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
519 /// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
520 /// allow more factorization opportunities.
521 static Instruction::BinaryOps
522 getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op,
523                           Value *&LHS, Value *&RHS) {
524   assert(Op && "Expected a binary operator");
525   LHS = Op->getOperand(0);
526   RHS = Op->getOperand(1);
527   if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
528     Constant *C;
529     if (match(Op, m_Shl(m_Value(), m_Constant(C)))) {
530       // X << C --> X * (1 << C)
531       RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C);
532       return Instruction::Mul;
533     }
534     // TODO: We can add other conversions e.g. shr => div etc.
535   }
536   return Op->getOpcode();
537 }
538 
539 /// This tries to simplify binary operations by factorizing out common terms
540 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
541 Value *InstCombiner::tryFactorization(BinaryOperator &I,
542                                       Instruction::BinaryOps InnerOpcode,
543                                       Value *A, Value *B, Value *C, Value *D) {
544   assert(A && B && C && D && "All values must be provided");
545 
546   Value *V = nullptr;
547   Value *SimplifiedInst = nullptr;
548   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
549   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
550 
551   // Does "X op' Y" always equal "Y op' X"?
552   bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
553 
554   // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
555   if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode))
556     // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
557     // commutative case, "(A op' B) op (C op' A)"?
558     if (A == C || (InnerCommutative && A == D)) {
559       if (A != C)
560         std::swap(C, D);
561       // Consider forming "A op' (B op D)".
562       // If "B op D" simplifies then it can be formed with no cost.
563       V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
564       // If "B op D" doesn't simplify then only go on if both of the existing
565       // operations "A op' B" and "C op' D" will be zapped as no longer used.
566       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
567         V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
568       if (V) {
569         SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V);
570       }
571     }
572 
573   // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
574   if (!SimplifiedInst && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
575     // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
576     // commutative case, "(A op' B) op (B op' D)"?
577     if (B == D || (InnerCommutative && B == C)) {
578       if (B != D)
579         std::swap(C, D);
580       // Consider forming "(A op C) op' B".
581       // If "A op C" simplifies then it can be formed with no cost.
582       V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
583 
584       // If "A op C" doesn't simplify then only go on if both of the existing
585       // operations "A op' B" and "C op' D" will be zapped as no longer used.
586       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
587         V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
588       if (V) {
589         SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B);
590       }
591     }
592 
593   if (SimplifiedInst) {
594     ++NumFactor;
595     SimplifiedInst->takeName(&I);
596 
597     // Check if we can add NSW/NUW flags to SimplifiedInst. If so, set them.
598     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
599       if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
600         bool HasNSW = false;
601         bool HasNUW = false;
602         if (isa<OverflowingBinaryOperator>(&I)) {
603           HasNSW = I.hasNoSignedWrap();
604           HasNUW = I.hasNoUnsignedWrap();
605         }
606 
607         if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {
608           HasNSW &= LOBO->hasNoSignedWrap();
609           HasNUW &= LOBO->hasNoUnsignedWrap();
610         }
611 
612         if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {
613           HasNSW &= ROBO->hasNoSignedWrap();
614           HasNUW &= ROBO->hasNoUnsignedWrap();
615         }
616 
617         if (TopLevelOpcode == Instruction::Add &&
618             InnerOpcode == Instruction::Mul) {
619           // We can propagate 'nsw' if we know that
620           //  %Y = mul nsw i16 %X, C
621           //  %Z = add nsw i16 %Y, %X
622           // =>
623           //  %Z = mul nsw i16 %X, C+1
624           //
625           // iff C+1 isn't INT_MIN
626           const APInt *CInt;
627           if (match(V, m_APInt(CInt))) {
628             if (!CInt->isMinSignedValue())
629               BO->setHasNoSignedWrap(HasNSW);
630           }
631 
632           // nuw can be propagated with any constant or nuw value.
633           BO->setHasNoUnsignedWrap(HasNUW);
634         }
635       }
636     }
637   }
638   return SimplifiedInst;
639 }
640 
641 /// This tries to simplify binary operations which some other binary operation
642 /// distributes over either by factorizing out common terms
643 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
644 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
645 /// Returns the simplified value, or null if it didn't simplify.
646 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
647   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
648   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
649   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
650   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
651 
652   {
653     // Factorization.
654     Value *A, *B, *C, *D;
655     Instruction::BinaryOps LHSOpcode, RHSOpcode;
656     if (Op0)
657       LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
658     if (Op1)
659       RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
660 
661     // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
662     // a common term.
663     if (Op0 && Op1 && LHSOpcode == RHSOpcode)
664       if (Value *V = tryFactorization(I, LHSOpcode, A, B, C, D))
665         return V;
666 
667     // The instruction has the form "(A op' B) op (C)".  Try to factorize common
668     // term.
669     if (Op0)
670       if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
671         if (Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident))
672           return V;
673 
674     // The instruction has the form "(B) op (C op' D)".  Try to factorize common
675     // term.
676     if (Op1)
677       if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
678         if (Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D))
679           return V;
680   }
681 
682   // Expansion.
683   if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
684     // The instruction has the form "(A op' B) op C".  See if expanding it out
685     // to "(A op C) op' (B op C)" results in simplifications.
686     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
687     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
688 
689     Value *L = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
690     Value *R = SimplifyBinOp(TopLevelOpcode, B, C, SQ.getWithInstruction(&I));
691 
692     // Do "A op C" and "B op C" both simplify?
693     if (L && R) {
694       // They do! Return "L op' R".
695       ++NumExpand;
696       C = Builder.CreateBinOp(InnerOpcode, L, R);
697       C->takeName(&I);
698       return C;
699     }
700 
701     // Does "A op C" simplify to the identity value for the inner opcode?
702     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
703       // They do! Return "B op C".
704       ++NumExpand;
705       C = Builder.CreateBinOp(TopLevelOpcode, B, C);
706       C->takeName(&I);
707       return C;
708     }
709 
710     // Does "B op C" simplify to the identity value for the inner opcode?
711     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
712       // They do! Return "A op C".
713       ++NumExpand;
714       C = Builder.CreateBinOp(TopLevelOpcode, A, C);
715       C->takeName(&I);
716       return C;
717     }
718   }
719 
720   if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
721     // The instruction has the form "A op (B op' C)".  See if expanding it out
722     // to "(A op B) op' (A op C)" results in simplifications.
723     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
724     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
725 
726     Value *L = SimplifyBinOp(TopLevelOpcode, A, B, SQ.getWithInstruction(&I));
727     Value *R = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
728 
729     // Do "A op B" and "A op C" both simplify?
730     if (L && R) {
731       // They do! Return "L op' R".
732       ++NumExpand;
733       A = Builder.CreateBinOp(InnerOpcode, L, R);
734       A->takeName(&I);
735       return A;
736     }
737 
738     // Does "A op B" simplify to the identity value for the inner opcode?
739     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
740       // They do! Return "A op C".
741       ++NumExpand;
742       A = Builder.CreateBinOp(TopLevelOpcode, A, C);
743       A->takeName(&I);
744       return A;
745     }
746 
747     // Does "A op C" simplify to the identity value for the inner opcode?
748     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
749       // They do! Return "A op B".
750       ++NumExpand;
751       A = Builder.CreateBinOp(TopLevelOpcode, A, B);
752       A->takeName(&I);
753       return A;
754     }
755   }
756 
757   return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
758 }
759 
760 Value *InstCombiner::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
761                                                     Value *LHS, Value *RHS) {
762   Instruction::BinaryOps Opcode = I.getOpcode();
763   // (op (select (a, b, c)), (select (a, d, e))) -> (select (a, (op b, d), (op
764   // c, e)))
765   Value *A, *B, *C, *D, *E;
766   Value *SI = nullptr;
767   if (match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C))) &&
768       match(RHS, m_Select(m_Specific(A), m_Value(D), m_Value(E)))) {
769     bool SelectsHaveOneUse = LHS->hasOneUse() && RHS->hasOneUse();
770 
771     FastMathFlags FMF;
772     BuilderTy::FastMathFlagGuard Guard(Builder);
773     if (isa<FPMathOperator>(&I)) {
774       FMF = I.getFastMathFlags();
775       Builder.setFastMathFlags(FMF);
776     }
777 
778     Value *V1 = SimplifyBinOp(Opcode, C, E, FMF, SQ.getWithInstruction(&I));
779     Value *V2 = SimplifyBinOp(Opcode, B, D, FMF, SQ.getWithInstruction(&I));
780     if (V1 && V2)
781       SI = Builder.CreateSelect(A, V2, V1);
782     else if (V2 && SelectsHaveOneUse)
783       SI = Builder.CreateSelect(A, V2, Builder.CreateBinOp(Opcode, C, E));
784     else if (V1 && SelectsHaveOneUse)
785       SI = Builder.CreateSelect(A, Builder.CreateBinOp(Opcode, B, D), V1);
786 
787     if (SI)
788       SI->takeName(&I);
789   }
790 
791   return SI;
792 }
793 
794 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
795 /// constant zero (which is the 'negate' form).
796 Value *InstCombiner::dyn_castNegVal(Value *V) const {
797   Value *NegV;
798   if (match(V, m_Neg(m_Value(NegV))))
799     return NegV;
800 
801   // Constants can be considered to be negated values if they can be folded.
802   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
803     return ConstantExpr::getNeg(C);
804 
805   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
806     if (C->getType()->getElementType()->isIntegerTy())
807       return ConstantExpr::getNeg(C);
808 
809   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
810     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
811       Constant *Elt = CV->getAggregateElement(i);
812       if (!Elt)
813         return nullptr;
814 
815       if (isa<UndefValue>(Elt))
816         continue;
817 
818       if (!isa<ConstantInt>(Elt))
819         return nullptr;
820     }
821     return ConstantExpr::getNeg(CV);
822   }
823 
824   return nullptr;
825 }
826 
827 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
828                                              InstCombiner::BuilderTy &Builder) {
829   if (auto *Cast = dyn_cast<CastInst>(&I))
830     return Builder.CreateCast(Cast->getOpcode(), SO, I.getType());
831 
832   assert(I.isBinaryOp() && "Unexpected opcode for select folding");
833 
834   // Figure out if the constant is the left or the right argument.
835   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
836   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
837 
838   if (auto *SOC = dyn_cast<Constant>(SO)) {
839     if (ConstIsRHS)
840       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
841     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
842   }
843 
844   Value *Op0 = SO, *Op1 = ConstOperand;
845   if (!ConstIsRHS)
846     std::swap(Op0, Op1);
847 
848   auto *BO = cast<BinaryOperator>(&I);
849   Value *RI = Builder.CreateBinOp(BO->getOpcode(), Op0, Op1,
850                                   SO->getName() + ".op");
851   auto *FPInst = dyn_cast<Instruction>(RI);
852   if (FPInst && isa<FPMathOperator>(FPInst))
853     FPInst->copyFastMathFlags(BO);
854   return RI;
855 }
856 
857 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
858   // Don't modify shared select instructions.
859   if (!SI->hasOneUse())
860     return nullptr;
861 
862   Value *TV = SI->getTrueValue();
863   Value *FV = SI->getFalseValue();
864   if (!(isa<Constant>(TV) || isa<Constant>(FV)))
865     return nullptr;
866 
867   // Bool selects with constant operands can be folded to logical ops.
868   if (SI->getType()->isIntOrIntVectorTy(1))
869     return nullptr;
870 
871   // If it's a bitcast involving vectors, make sure it has the same number of
872   // elements on both sides.
873   if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
874     VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
875     VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
876 
877     // Verify that either both or neither are vectors.
878     if ((SrcTy == nullptr) != (DestTy == nullptr))
879       return nullptr;
880 
881     // If vectors, verify that they have the same number of elements.
882     if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
883       return nullptr;
884   }
885 
886   // Test if a CmpInst instruction is used exclusively by a select as
887   // part of a minimum or maximum operation. If so, refrain from doing
888   // any other folding. This helps out other analyses which understand
889   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
890   // and CodeGen. And in this case, at least one of the comparison
891   // operands has at least one user besides the compare (the select),
892   // which would often largely negate the benefit of folding anyway.
893   if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
894     if (CI->hasOneUse()) {
895       Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
896       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
897           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
898         return nullptr;
899     }
900   }
901 
902   Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder);
903   Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder);
904   return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
905 }
906 
907 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
908                                         InstCombiner::BuilderTy &Builder) {
909   bool ConstIsRHS = isa<Constant>(I->getOperand(1));
910   Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
911 
912   if (auto *InC = dyn_cast<Constant>(InV)) {
913     if (ConstIsRHS)
914       return ConstantExpr::get(I->getOpcode(), InC, C);
915     return ConstantExpr::get(I->getOpcode(), C, InC);
916   }
917 
918   Value *Op0 = InV, *Op1 = C;
919   if (!ConstIsRHS)
920     std::swap(Op0, Op1);
921 
922   Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp");
923   auto *FPInst = dyn_cast<Instruction>(RI);
924   if (FPInst && isa<FPMathOperator>(FPInst))
925     FPInst->copyFastMathFlags(I);
926   return RI;
927 }
928 
929 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) {
930   unsigned NumPHIValues = PN->getNumIncomingValues();
931   if (NumPHIValues == 0)
932     return nullptr;
933 
934   // We normally only transform phis with a single use.  However, if a PHI has
935   // multiple uses and they are all the same operation, we can fold *all* of the
936   // uses into the PHI.
937   if (!PN->hasOneUse()) {
938     // Walk the use list for the instruction, comparing them to I.
939     for (User *U : PN->users()) {
940       Instruction *UI = cast<Instruction>(U);
941       if (UI != &I && !I.isIdenticalTo(UI))
942         return nullptr;
943     }
944     // Otherwise, we can replace *all* users with the new PHI we form.
945   }
946 
947   // Check to see if all of the operands of the PHI are simple constants
948   // (constantint/constantfp/undef).  If there is one non-constant value,
949   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
950   // bail out.  We don't do arbitrary constant expressions here because moving
951   // their computation can be expensive without a cost model.
952   BasicBlock *NonConstBB = nullptr;
953   for (unsigned i = 0; i != NumPHIValues; ++i) {
954     Value *InVal = PN->getIncomingValue(i);
955     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
956       continue;
957 
958     if (isa<PHINode>(InVal)) return nullptr;  // Itself a phi.
959     if (NonConstBB) return nullptr;  // More than one non-const value.
960 
961     NonConstBB = PN->getIncomingBlock(i);
962 
963     // If the InVal is an invoke at the end of the pred block, then we can't
964     // insert a computation after it without breaking the edge.
965     if (isa<InvokeInst>(InVal))
966       if (cast<Instruction>(InVal)->getParent() == NonConstBB)
967         return nullptr;
968 
969     // If the incoming non-constant value is in I's block, we will remove one
970     // instruction, but insert another equivalent one, leading to infinite
971     // instcombine.
972     if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
973       return nullptr;
974   }
975 
976   // If there is exactly one non-constant value, we can insert a copy of the
977   // operation in that block.  However, if this is a critical edge, we would be
978   // inserting the computation on some other paths (e.g. inside a loop).  Only
979   // do this if the pred block is unconditionally branching into the phi block.
980   if (NonConstBB != nullptr) {
981     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
982     if (!BI || !BI->isUnconditional()) return nullptr;
983   }
984 
985   // Okay, we can do the transformation: create the new PHI node.
986   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
987   InsertNewInstBefore(NewPN, *PN);
988   NewPN->takeName(PN);
989 
990   // If we are going to have to insert a new computation, do so right before the
991   // predecessor's terminator.
992   if (NonConstBB)
993     Builder.SetInsertPoint(NonConstBB->getTerminator());
994 
995   // Next, add all of the operands to the PHI.
996   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
997     // We only currently try to fold the condition of a select when it is a phi,
998     // not the true/false values.
999     Value *TrueV = SI->getTrueValue();
1000     Value *FalseV = SI->getFalseValue();
1001     BasicBlock *PhiTransBB = PN->getParent();
1002     for (unsigned i = 0; i != NumPHIValues; ++i) {
1003       BasicBlock *ThisBB = PN->getIncomingBlock(i);
1004       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
1005       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
1006       Value *InV = nullptr;
1007       // Beware of ConstantExpr:  it may eventually evaluate to getNullValue,
1008       // even if currently isNullValue gives false.
1009       Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
1010       // For vector constants, we cannot use isNullValue to fold into
1011       // FalseVInPred versus TrueVInPred. When we have individual nonzero
1012       // elements in the vector, we will incorrectly fold InC to
1013       // `TrueVInPred`.
1014       if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
1015         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
1016       else {
1017         // Generate the select in the same block as PN's current incoming block.
1018         // Note: ThisBB need not be the NonConstBB because vector constants
1019         // which are constants by definition are handled here.
1020         // FIXME: This can lead to an increase in IR generation because we might
1021         // generate selects for vector constant phi operand, that could not be
1022         // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For
1023         // non-vector phis, this transformation was always profitable because
1024         // the select would be generated exactly once in the NonConstBB.
1025         Builder.SetInsertPoint(ThisBB->getTerminator());
1026         InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred,
1027                                    FalseVInPred, "phitmp");
1028       }
1029       NewPN->addIncoming(InV, ThisBB);
1030     }
1031   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
1032     Constant *C = cast<Constant>(I.getOperand(1));
1033     for (unsigned i = 0; i != NumPHIValues; ++i) {
1034       Value *InV = nullptr;
1035       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1036         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1037       else if (isa<ICmpInst>(CI))
1038         InV = Builder.CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
1039                                  C, "phitmp");
1040       else
1041         InV = Builder.CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
1042                                  C, "phitmp");
1043       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1044     }
1045   } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
1046     for (unsigned i = 0; i != NumPHIValues; ++i) {
1047       Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i),
1048                                              Builder);
1049       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1050     }
1051   } else {
1052     CastInst *CI = cast<CastInst>(&I);
1053     Type *RetTy = CI->getType();
1054     for (unsigned i = 0; i != NumPHIValues; ++i) {
1055       Value *InV;
1056       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1057         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1058       else
1059         InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i),
1060                                  I.getType(), "phitmp");
1061       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1062     }
1063   }
1064 
1065   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
1066     Instruction *User = cast<Instruction>(*UI++);
1067     if (User == &I) continue;
1068     replaceInstUsesWith(*User, NewPN);
1069     eraseInstFromFunction(*User);
1070   }
1071   return replaceInstUsesWith(I, NewPN);
1072 }
1073 
1074 Instruction *InstCombiner::foldBinOpIntoSelectOrPhi(BinaryOperator &I) {
1075   if (!isa<Constant>(I.getOperand(1)))
1076     return nullptr;
1077 
1078   if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1079     if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1080       return NewSel;
1081   } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1082     if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1083       return NewPhi;
1084   }
1085   return nullptr;
1086 }
1087 
1088 /// Given a pointer type and a constant offset, determine whether or not there
1089 /// is a sequence of GEP indices into the pointed type that will land us at the
1090 /// specified offset. If so, fill them into NewIndices and return the resultant
1091 /// element type, otherwise return null.
1092 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1093                                         SmallVectorImpl<Value *> &NewIndices) {
1094   Type *Ty = PtrTy->getElementType();
1095   if (!Ty->isSized())
1096     return nullptr;
1097 
1098   // Start with the index over the outer type.  Note that the type size
1099   // might be zero (even if the offset isn't zero) if the indexed type
1100   // is something like [0 x {int, int}]
1101   Type *IndexTy = DL.getIndexType(PtrTy);
1102   int64_t FirstIdx = 0;
1103   if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1104     FirstIdx = Offset/TySize;
1105     Offset -= FirstIdx*TySize;
1106 
1107     // Handle hosts where % returns negative instead of values [0..TySize).
1108     if (Offset < 0) {
1109       --FirstIdx;
1110       Offset += TySize;
1111       assert(Offset >= 0);
1112     }
1113     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1114   }
1115 
1116   NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx));
1117 
1118   // Index into the types.  If we fail, set OrigBase to null.
1119   while (Offset) {
1120     // Indexing into tail padding between struct/array elements.
1121     if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1122       return nullptr;
1123 
1124     if (StructType *STy = dyn_cast<StructType>(Ty)) {
1125       const StructLayout *SL = DL.getStructLayout(STy);
1126       assert(Offset < (int64_t)SL->getSizeInBytes() &&
1127              "Offset must stay within the indexed type");
1128 
1129       unsigned Elt = SL->getElementContainingOffset(Offset);
1130       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1131                                             Elt));
1132 
1133       Offset -= SL->getElementOffset(Elt);
1134       Ty = STy->getElementType(Elt);
1135     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1136       uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1137       assert(EltSize && "Cannot index into a zero-sized array");
1138       NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize));
1139       Offset %= EltSize;
1140       Ty = AT->getElementType();
1141     } else {
1142       // Otherwise, we can't index into the middle of this atomic type, bail.
1143       return nullptr;
1144     }
1145   }
1146 
1147   return Ty;
1148 }
1149 
1150 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1151   // If this GEP has only 0 indices, it is the same pointer as
1152   // Src. If Src is not a trivial GEP too, don't combine
1153   // the indices.
1154   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1155       !Src.hasOneUse())
1156     return false;
1157   return true;
1158 }
1159 
1160 /// Return a value X such that Val = X * Scale, or null if none.
1161 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1162 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1163   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1164   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1165          Scale.getBitWidth() && "Scale not compatible with value!");
1166 
1167   // If Val is zero or Scale is one then Val = Val * Scale.
1168   if (match(Val, m_Zero()) || Scale == 1) {
1169     NoSignedWrap = true;
1170     return Val;
1171   }
1172 
1173   // If Scale is zero then it does not divide Val.
1174   if (Scale.isMinValue())
1175     return nullptr;
1176 
1177   // Look through chains of multiplications, searching for a constant that is
1178   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
1179   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
1180   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
1181   // down from Val:
1182   //
1183   //     Val = M1 * X          ||   Analysis starts here and works down
1184   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
1185   //      M2 =  Z * 4          \/   than one use
1186   //
1187   // Then to modify a term at the bottom:
1188   //
1189   //     Val = M1 * X
1190   //      M1 =  Z * Y          ||   Replaced M2 with Z
1191   //
1192   // Then to work back up correcting nsw flags.
1193 
1194   // Op - the term we are currently analyzing.  Starts at Val then drills down.
1195   // Replaced with its descaled value before exiting from the drill down loop.
1196   Value *Op = Val;
1197 
1198   // Parent - initially null, but after drilling down notes where Op came from.
1199   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1200   // 0'th operand of Val.
1201   std::pair<Instruction *, unsigned> Parent;
1202 
1203   // Set if the transform requires a descaling at deeper levels that doesn't
1204   // overflow.
1205   bool RequireNoSignedWrap = false;
1206 
1207   // Log base 2 of the scale. Negative if not a power of 2.
1208   int32_t logScale = Scale.exactLogBase2();
1209 
1210   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1211     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1212       // If Op is a constant divisible by Scale then descale to the quotient.
1213       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1214       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1215       if (!Remainder.isMinValue())
1216         // Not divisible by Scale.
1217         return nullptr;
1218       // Replace with the quotient in the parent.
1219       Op = ConstantInt::get(CI->getType(), Quotient);
1220       NoSignedWrap = true;
1221       break;
1222     }
1223 
1224     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1225       if (BO->getOpcode() == Instruction::Mul) {
1226         // Multiplication.
1227         NoSignedWrap = BO->hasNoSignedWrap();
1228         if (RequireNoSignedWrap && !NoSignedWrap)
1229           return nullptr;
1230 
1231         // There are three cases for multiplication: multiplication by exactly
1232         // the scale, multiplication by a constant different to the scale, and
1233         // multiplication by something else.
1234         Value *LHS = BO->getOperand(0);
1235         Value *RHS = BO->getOperand(1);
1236 
1237         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1238           // Multiplication by a constant.
1239           if (CI->getValue() == Scale) {
1240             // Multiplication by exactly the scale, replace the multiplication
1241             // by its left-hand side in the parent.
1242             Op = LHS;
1243             break;
1244           }
1245 
1246           // Otherwise drill down into the constant.
1247           if (!Op->hasOneUse())
1248             return nullptr;
1249 
1250           Parent = std::make_pair(BO, 1);
1251           continue;
1252         }
1253 
1254         // Multiplication by something else. Drill down into the left-hand side
1255         // since that's where the reassociate pass puts the good stuff.
1256         if (!Op->hasOneUse())
1257           return nullptr;
1258 
1259         Parent = std::make_pair(BO, 0);
1260         continue;
1261       }
1262 
1263       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1264           isa<ConstantInt>(BO->getOperand(1))) {
1265         // Multiplication by a power of 2.
1266         NoSignedWrap = BO->hasNoSignedWrap();
1267         if (RequireNoSignedWrap && !NoSignedWrap)
1268           return nullptr;
1269 
1270         Value *LHS = BO->getOperand(0);
1271         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1272           getLimitedValue(Scale.getBitWidth());
1273         // Op = LHS << Amt.
1274 
1275         if (Amt == logScale) {
1276           // Multiplication by exactly the scale, replace the multiplication
1277           // by its left-hand side in the parent.
1278           Op = LHS;
1279           break;
1280         }
1281         if (Amt < logScale || !Op->hasOneUse())
1282           return nullptr;
1283 
1284         // Multiplication by more than the scale.  Reduce the multiplying amount
1285         // by the scale in the parent.
1286         Parent = std::make_pair(BO, 1);
1287         Op = ConstantInt::get(BO->getType(), Amt - logScale);
1288         break;
1289       }
1290     }
1291 
1292     if (!Op->hasOneUse())
1293       return nullptr;
1294 
1295     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1296       if (Cast->getOpcode() == Instruction::SExt) {
1297         // Op is sign-extended from a smaller type, descale in the smaller type.
1298         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1299         APInt SmallScale = Scale.trunc(SmallSize);
1300         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
1301         // descale Op as (sext Y) * Scale.  In order to have
1302         //   sext (Y * SmallScale) = (sext Y) * Scale
1303         // some conditions need to hold however: SmallScale must sign-extend to
1304         // Scale and the multiplication Y * SmallScale should not overflow.
1305         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1306           // SmallScale does not sign-extend to Scale.
1307           return nullptr;
1308         assert(SmallScale.exactLogBase2() == logScale);
1309         // Require that Y * SmallScale must not overflow.
1310         RequireNoSignedWrap = true;
1311 
1312         // Drill down through the cast.
1313         Parent = std::make_pair(Cast, 0);
1314         Scale = SmallScale;
1315         continue;
1316       }
1317 
1318       if (Cast->getOpcode() == Instruction::Trunc) {
1319         // Op is truncated from a larger type, descale in the larger type.
1320         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
1321         //   trunc (Y * sext Scale) = (trunc Y) * Scale
1322         // always holds.  However (trunc Y) * Scale may overflow even if
1323         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1324         // from this point up in the expression (see later).
1325         if (RequireNoSignedWrap)
1326           return nullptr;
1327 
1328         // Drill down through the cast.
1329         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1330         Parent = std::make_pair(Cast, 0);
1331         Scale = Scale.sext(LargeSize);
1332         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1333           logScale = -1;
1334         assert(Scale.exactLogBase2() == logScale);
1335         continue;
1336       }
1337     }
1338 
1339     // Unsupported expression, bail out.
1340     return nullptr;
1341   }
1342 
1343   // If Op is zero then Val = Op * Scale.
1344   if (match(Op, m_Zero())) {
1345     NoSignedWrap = true;
1346     return Op;
1347   }
1348 
1349   // We know that we can successfully descale, so from here on we can safely
1350   // modify the IR.  Op holds the descaled version of the deepest term in the
1351   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
1352   // not to overflow.
1353 
1354   if (!Parent.first)
1355     // The expression only had one term.
1356     return Op;
1357 
1358   // Rewrite the parent using the descaled version of its operand.
1359   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1360   assert(Op != Parent.first->getOperand(Parent.second) &&
1361          "Descaling was a no-op?");
1362   Parent.first->setOperand(Parent.second, Op);
1363   Worklist.Add(Parent.first);
1364 
1365   // Now work back up the expression correcting nsw flags.  The logic is based
1366   // on the following observation: if X * Y is known not to overflow as a signed
1367   // multiplication, and Y is replaced by a value Z with smaller absolute value,
1368   // then X * Z will not overflow as a signed multiplication either.  As we work
1369   // our way up, having NoSignedWrap 'true' means that the descaled value at the
1370   // current level has strictly smaller absolute value than the original.
1371   Instruction *Ancestor = Parent.first;
1372   do {
1373     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1374       // If the multiplication wasn't nsw then we can't say anything about the
1375       // value of the descaled multiplication, and we have to clear nsw flags
1376       // from this point on up.
1377       bool OpNoSignedWrap = BO->hasNoSignedWrap();
1378       NoSignedWrap &= OpNoSignedWrap;
1379       if (NoSignedWrap != OpNoSignedWrap) {
1380         BO->setHasNoSignedWrap(NoSignedWrap);
1381         Worklist.Add(Ancestor);
1382       }
1383     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1384       // The fact that the descaled input to the trunc has smaller absolute
1385       // value than the original input doesn't tell us anything useful about
1386       // the absolute values of the truncations.
1387       NoSignedWrap = false;
1388     }
1389     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1390            "Failed to keep proper track of nsw flags while drilling down?");
1391 
1392     if (Ancestor == Val)
1393       // Got to the top, all done!
1394       return Val;
1395 
1396     // Move up one level in the expression.
1397     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1398     Ancestor = Ancestor->user_back();
1399   } while (true);
1400 }
1401 
1402 Instruction *InstCombiner::foldVectorBinop(BinaryOperator &Inst) {
1403   if (!Inst.getType()->isVectorTy()) return nullptr;
1404 
1405   BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
1406   unsigned NumElts = cast<VectorType>(Inst.getType())->getNumElements();
1407   Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1408   assert(cast<VectorType>(LHS->getType())->getNumElements() == NumElts);
1409   assert(cast<VectorType>(RHS->getType())->getNumElements() == NumElts);
1410 
1411   // If both operands of the binop are vector concatenations, then perform the
1412   // narrow binop on each pair of the source operands followed by concatenation
1413   // of the results.
1414   Value *L0, *L1, *R0, *R1;
1415   Constant *Mask;
1416   if (match(LHS, m_ShuffleVector(m_Value(L0), m_Value(L1), m_Constant(Mask))) &&
1417       match(RHS, m_ShuffleVector(m_Value(R0), m_Value(R1), m_Specific(Mask))) &&
1418       LHS->hasOneUse() && RHS->hasOneUse() &&
1419       cast<ShuffleVectorInst>(LHS)->isConcat() &&
1420       cast<ShuffleVectorInst>(RHS)->isConcat()) {
1421     // This transform does not have the speculative execution constraint as
1422     // below because the shuffle is a concatenation. The new binops are
1423     // operating on exactly the same elements as the existing binop.
1424     // TODO: We could ease the mask requirement to allow different undef lanes,
1425     //       but that requires an analysis of the binop-with-undef output value.
1426     Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
1427     if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))
1428       BO->copyIRFlags(&Inst);
1429     Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
1430     if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))
1431       BO->copyIRFlags(&Inst);
1432     return new ShuffleVectorInst(NewBO0, NewBO1, Mask);
1433   }
1434 
1435   // It may not be safe to reorder shuffles and things like div, urem, etc.
1436   // because we may trap when executing those ops on unknown vector elements.
1437   // See PR20059.
1438   if (!isSafeToSpeculativelyExecute(&Inst))
1439     return nullptr;
1440 
1441   auto createBinOpShuffle = [&](Value *X, Value *Y, Constant *M) {
1442     Value *XY = Builder.CreateBinOp(Opcode, X, Y);
1443     if (auto *BO = dyn_cast<BinaryOperator>(XY))
1444       BO->copyIRFlags(&Inst);
1445     return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M);
1446   };
1447 
1448   // If both arguments of the binary operation are shuffles that use the same
1449   // mask and shuffle within a single vector, move the shuffle after the binop.
1450   Value *V1, *V2;
1451   if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(Mask))) &&
1452       match(RHS, m_ShuffleVector(m_Value(V2), m_Undef(), m_Specific(Mask))) &&
1453       V1->getType() == V2->getType() &&
1454       (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
1455     // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
1456     return createBinOpShuffle(V1, V2, Mask);
1457   }
1458 
1459   // If both arguments of a commutative binop are select-shuffles that use the
1460   // same mask with commuted operands, the shuffles are unnecessary.
1461   if (Inst.isCommutative() &&
1462       match(LHS, m_ShuffleVector(m_Value(V1), m_Value(V2), m_Constant(Mask))) &&
1463       match(RHS, m_ShuffleVector(m_Specific(V2), m_Specific(V1),
1464                                  m_Specific(Mask)))) {
1465     auto *LShuf = cast<ShuffleVectorInst>(LHS);
1466     auto *RShuf = cast<ShuffleVectorInst>(RHS);
1467     // TODO: Allow shuffles that contain undefs in the mask?
1468     //       That is legal, but it reduces undef knowledge.
1469     // TODO: Allow arbitrary shuffles by shuffling after binop?
1470     //       That might be legal, but we have to deal with poison.
1471     if (LShuf->isSelect() && !LShuf->getMask()->containsUndefElement() &&
1472         RShuf->isSelect() && !RShuf->getMask()->containsUndefElement()) {
1473       // Example:
1474       // LHS = shuffle V1, V2, <0, 5, 6, 3>
1475       // RHS = shuffle V2, V1, <0, 5, 6, 3>
1476       // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
1477       Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
1478       NewBO->copyIRFlags(&Inst);
1479       return NewBO;
1480     }
1481   }
1482 
1483   // If one argument is a shuffle within one vector and the other is a constant,
1484   // try moving the shuffle after the binary operation. This canonicalization
1485   // intends to move shuffles closer to other shuffles and binops closer to
1486   // other binops, so they can be folded. It may also enable demanded elements
1487   // transforms.
1488   Constant *C;
1489   if (match(&Inst, m_c_BinOp(
1490           m_OneUse(m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(Mask))),
1491           m_Constant(C))) &&
1492       V1->getType()->getVectorNumElements() <= NumElts) {
1493     assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() &&
1494            "Shuffle should not change scalar type");
1495 
1496     // Find constant NewC that has property:
1497     //   shuffle(NewC, ShMask) = C
1498     // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)
1499     // reorder is not possible. A 1-to-1 mapping is not required. Example:
1500     // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>
1501     bool ConstOp1 = isa<Constant>(RHS);
1502     SmallVector<int, 16> ShMask;
1503     ShuffleVectorInst::getShuffleMask(Mask, ShMask);
1504     unsigned SrcVecNumElts = V1->getType()->getVectorNumElements();
1505     UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType());
1506     SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar);
1507     bool MayChange = true;
1508     for (unsigned I = 0; I < NumElts; ++I) {
1509       Constant *CElt = C->getAggregateElement(I);
1510       if (ShMask[I] >= 0) {
1511         assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle");
1512         Constant *NewCElt = NewVecC[ShMask[I]];
1513         // Bail out if:
1514         // 1. The constant vector contains a constant expression.
1515         // 2. The shuffle needs an element of the constant vector that can't
1516         //    be mapped to a new constant vector.
1517         // 3. This is a widening shuffle that copies elements of V1 into the
1518         //    extended elements (extending with undef is allowed).
1519         if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) ||
1520             I >= SrcVecNumElts) {
1521           MayChange = false;
1522           break;
1523         }
1524         NewVecC[ShMask[I]] = CElt;
1525       }
1526       // If this is a widening shuffle, we must be able to extend with undef
1527       // elements. If the original binop does not produce an undef in the high
1528       // lanes, then this transform is not safe.
1529       // TODO: We could shuffle those non-undef constant values into the
1530       //       result by using a constant vector (rather than an undef vector)
1531       //       as operand 1 of the new binop, but that might be too aggressive
1532       //       for target-independent shuffle creation.
1533       if (I >= SrcVecNumElts) {
1534         Constant *MaybeUndef =
1535             ConstOp1 ? ConstantExpr::get(Opcode, UndefScalar, CElt)
1536                      : ConstantExpr::get(Opcode, CElt, UndefScalar);
1537         if (!isa<UndefValue>(MaybeUndef)) {
1538           MayChange = false;
1539           break;
1540         }
1541       }
1542     }
1543     if (MayChange) {
1544       Constant *NewC = ConstantVector::get(NewVecC);
1545       // It may not be safe to execute a binop on a vector with undef elements
1546       // because the entire instruction can be folded to undef or create poison
1547       // that did not exist in the original code.
1548       if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))
1549         NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
1550 
1551       // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
1552       // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
1553       Value *NewLHS = ConstOp1 ? V1 : NewC;
1554       Value *NewRHS = ConstOp1 ? NewC : V1;
1555       return createBinOpShuffle(NewLHS, NewRHS, Mask);
1556     }
1557   }
1558 
1559   return nullptr;
1560 }
1561 
1562 /// Try to narrow the width of a binop if at least 1 operand is an extend of
1563 /// of a value. This requires a potentially expensive known bits check to make
1564 /// sure the narrow op does not overflow.
1565 Instruction *InstCombiner::narrowMathIfNoOverflow(BinaryOperator &BO) {
1566   // We need at least one extended operand.
1567   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
1568 
1569   // If this is a sub, we swap the operands since we always want an extension
1570   // on the RHS. The LHS can be an extension or a constant.
1571   if (BO.getOpcode() == Instruction::Sub)
1572     std::swap(Op0, Op1);
1573 
1574   Value *X;
1575   bool IsSext = match(Op0, m_SExt(m_Value(X)));
1576   if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
1577     return nullptr;
1578 
1579   // If both operands are the same extension from the same source type and we
1580   // can eliminate at least one (hasOneUse), this might work.
1581   CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
1582   Value *Y;
1583   if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
1584         cast<Operator>(Op1)->getOpcode() == CastOpc &&
1585         (Op0->hasOneUse() || Op1->hasOneUse()))) {
1586     // If that did not match, see if we have a suitable constant operand.
1587     // Truncating and extending must produce the same constant.
1588     Constant *WideC;
1589     if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
1590       return nullptr;
1591     Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType());
1592     if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC)
1593       return nullptr;
1594     Y = NarrowC;
1595   }
1596 
1597   // Swap back now that we found our operands.
1598   if (BO.getOpcode() == Instruction::Sub)
1599     std::swap(X, Y);
1600 
1601   // Both operands have narrow versions. Last step: the math must not overflow
1602   // in the narrow width.
1603   if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
1604     return nullptr;
1605 
1606   // bo (ext X), (ext Y) --> ext (bo X, Y)
1607   // bo (ext X), C       --> ext (bo X, C')
1608   Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
1609   if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
1610     if (IsSext)
1611       NewBinOp->setHasNoSignedWrap();
1612     else
1613       NewBinOp->setHasNoUnsignedWrap();
1614   }
1615   return CastInst::Create(CastOpc, NarrowBO, BO.getType());
1616 }
1617 
1618 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1619   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1620   Type *GEPType = GEP.getType();
1621   Type *GEPEltType = GEP.getSourceElementType();
1622   if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP)))
1623     return replaceInstUsesWith(GEP, V);
1624 
1625   // For vector geps, use the generic demanded vector support.
1626   if (GEP.getType()->isVectorTy()) {
1627     auto VWidth = GEP.getType()->getVectorNumElements();
1628     APInt UndefElts(VWidth, 0);
1629     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1630     if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
1631                                               UndefElts)) {
1632       if (V != &GEP)
1633         return replaceInstUsesWith(GEP, V);
1634       return &GEP;
1635     }
1636 
1637     // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if
1638     // possible (decide on canonical form for pointer broadcast), 3) exploit
1639     // undef elements to decrease demanded bits
1640   }
1641 
1642   Value *PtrOp = GEP.getOperand(0);
1643 
1644   // Eliminate unneeded casts for indices, and replace indices which displace
1645   // by multiples of a zero size type with zero.
1646   bool MadeChange = false;
1647 
1648   // Index width may not be the same width as pointer width.
1649   // Data layout chooses the right type based on supported integer types.
1650   Type *NewScalarIndexTy =
1651       DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
1652 
1653   gep_type_iterator GTI = gep_type_begin(GEP);
1654   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1655        ++I, ++GTI) {
1656     // Skip indices into struct types.
1657     if (GTI.isStruct())
1658       continue;
1659 
1660     Type *IndexTy = (*I)->getType();
1661     Type *NewIndexType =
1662         IndexTy->isVectorTy()
1663             ? VectorType::get(NewScalarIndexTy, IndexTy->getVectorNumElements())
1664             : NewScalarIndexTy;
1665 
1666     // If the element type has zero size then any index over it is equivalent
1667     // to an index of zero, so replace it with zero if it is not zero already.
1668     Type *EltTy = GTI.getIndexedType();
1669     if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1670       if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
1671         *I = Constant::getNullValue(NewIndexType);
1672         MadeChange = true;
1673       }
1674 
1675     if (IndexTy != NewIndexType) {
1676       // If we are using a wider index than needed for this platform, shrink
1677       // it to what we need.  If narrower, sign-extend it to what we need.
1678       // This explicit cast can make subsequent optimizations more obvious.
1679       *I = Builder.CreateIntCast(*I, NewIndexType, true);
1680       MadeChange = true;
1681     }
1682   }
1683   if (MadeChange)
1684     return &GEP;
1685 
1686   // Check to see if the inputs to the PHI node are getelementptr instructions.
1687   if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
1688     auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1689     if (!Op1)
1690       return nullptr;
1691 
1692     // Don't fold a GEP into itself through a PHI node. This can only happen
1693     // through the back-edge of a loop. Folding a GEP into itself means that
1694     // the value of the previous iteration needs to be stored in the meantime,
1695     // thus requiring an additional register variable to be live, but not
1696     // actually achieving anything (the GEP still needs to be executed once per
1697     // loop iteration).
1698     if (Op1 == &GEP)
1699       return nullptr;
1700 
1701     int DI = -1;
1702 
1703     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1704       auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
1705       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1706         return nullptr;
1707 
1708       // As for Op1 above, don't try to fold a GEP into itself.
1709       if (Op2 == &GEP)
1710         return nullptr;
1711 
1712       // Keep track of the type as we walk the GEP.
1713       Type *CurTy = nullptr;
1714 
1715       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1716         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1717           return nullptr;
1718 
1719         if (Op1->getOperand(J) != Op2->getOperand(J)) {
1720           if (DI == -1) {
1721             // We have not seen any differences yet in the GEPs feeding the
1722             // PHI yet, so we record this one if it is allowed to be a
1723             // variable.
1724 
1725             // The first two arguments can vary for any GEP, the rest have to be
1726             // static for struct slots
1727             if (J > 1) {
1728               assert(CurTy && "No current type?");
1729               if (CurTy->isStructTy())
1730                 return nullptr;
1731             }
1732 
1733             DI = J;
1734           } else {
1735             // The GEP is different by more than one input. While this could be
1736             // extended to support GEPs that vary by more than one variable it
1737             // doesn't make sense since it greatly increases the complexity and
1738             // would result in an R+R+R addressing mode which no backend
1739             // directly supports and would need to be broken into several
1740             // simpler instructions anyway.
1741             return nullptr;
1742           }
1743         }
1744 
1745         // Sink down a layer of the type for the next iteration.
1746         if (J > 0) {
1747           if (J == 1) {
1748             CurTy = Op1->getSourceElementType();
1749           } else if (auto *CT = dyn_cast<CompositeType>(CurTy)) {
1750             CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1751           } else {
1752             CurTy = nullptr;
1753           }
1754         }
1755       }
1756     }
1757 
1758     // If not all GEPs are identical we'll have to create a new PHI node.
1759     // Check that the old PHI node has only one use so that it will get
1760     // removed.
1761     if (DI != -1 && !PN->hasOneUse())
1762       return nullptr;
1763 
1764     auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1765     if (DI == -1) {
1766       // All the GEPs feeding the PHI are identical. Clone one down into our
1767       // BB so that it can be merged with the current GEP.
1768       GEP.getParent()->getInstList().insert(
1769           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1770     } else {
1771       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1772       // into the current block so it can be merged, and create a new PHI to
1773       // set that index.
1774       PHINode *NewPN;
1775       {
1776         IRBuilderBase::InsertPointGuard Guard(Builder);
1777         Builder.SetInsertPoint(PN);
1778         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1779                                   PN->getNumOperands());
1780       }
1781 
1782       for (auto &I : PN->operands())
1783         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1784                            PN->getIncomingBlock(I));
1785 
1786       NewGEP->setOperand(DI, NewPN);
1787       GEP.getParent()->getInstList().insert(
1788           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1789       NewGEP->setOperand(DI, NewPN);
1790     }
1791 
1792     GEP.setOperand(0, NewGEP);
1793     PtrOp = NewGEP;
1794   }
1795 
1796   // Combine Indices - If the source pointer to this getelementptr instruction
1797   // is a getelementptr instruction, combine the indices of the two
1798   // getelementptr instructions into a single instruction.
1799   if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
1800     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1801       return nullptr;
1802 
1803     // Try to reassociate loop invariant GEP chains to enable LICM.
1804     if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 &&
1805         Src->hasOneUse()) {
1806       if (Loop *L = LI->getLoopFor(GEP.getParent())) {
1807         Value *GO1 = GEP.getOperand(1);
1808         Value *SO1 = Src->getOperand(1);
1809         // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is
1810         // invariant: this breaks the dependence between GEPs and allows LICM
1811         // to hoist the invariant part out of the loop.
1812         if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
1813           // We have to be careful here.
1814           // We have something like:
1815           //  %src = getelementptr <ty>, <ty>* %base, <ty> %idx
1816           //  %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2
1817           // If we just swap idx & idx2 then we could inadvertantly
1818           // change %src from a vector to a scalar, or vice versa.
1819           // Cases:
1820           //  1) %base a scalar & idx a scalar & idx2 a vector
1821           //      => Swapping idx & idx2 turns %src into a vector type.
1822           //  2) %base a scalar & idx a vector & idx2 a scalar
1823           //      => Swapping idx & idx2 turns %src in a scalar type
1824           //  3) %base, %idx, and %idx2 are scalars
1825           //      => %src & %gep are scalars
1826           //      => swapping idx & idx2 is safe
1827           //  4) %base a vector
1828           //      => %src is a vector
1829           //      => swapping idx & idx2 is safe.
1830           auto *SO0 = Src->getOperand(0);
1831           auto *SO0Ty = SO0->getType();
1832           if (!isa<VectorType>(GEPType) || // case 3
1833               isa<VectorType>(SO0Ty)) {    // case 4
1834             Src->setOperand(1, GO1);
1835             GEP.setOperand(1, SO1);
1836             return &GEP;
1837           } else {
1838             // Case 1 or 2
1839             // -- have to recreate %src & %gep
1840             // put NewSrc at same location as %src
1841             Builder.SetInsertPoint(cast<Instruction>(PtrOp));
1842             auto *NewSrc = cast<GetElementPtrInst>(
1843                 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName()));
1844             NewSrc->setIsInBounds(Src->isInBounds());
1845             auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1});
1846             NewGEP->setIsInBounds(GEP.isInBounds());
1847             return NewGEP;
1848           }
1849         }
1850       }
1851     }
1852 
1853     // Note that if our source is a gep chain itself then we wait for that
1854     // chain to be resolved before we perform this transformation.  This
1855     // avoids us creating a TON of code in some cases.
1856     if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
1857       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1858         return nullptr;   // Wait until our source is folded to completion.
1859 
1860     SmallVector<Value*, 8> Indices;
1861 
1862     // Find out whether the last index in the source GEP is a sequential idx.
1863     bool EndsWithSequential = false;
1864     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1865          I != E; ++I)
1866       EndsWithSequential = I.isSequential();
1867 
1868     // Can we combine the two pointer arithmetics offsets?
1869     if (EndsWithSequential) {
1870       // Replace: gep (gep %P, long B), long A, ...
1871       // With:    T = long A+B; gep %P, T, ...
1872       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1873       Value *GO1 = GEP.getOperand(1);
1874 
1875       // If they aren't the same type, then the input hasn't been processed
1876       // by the loop above yet (which canonicalizes sequential index types to
1877       // intptr_t).  Just avoid transforming this until the input has been
1878       // normalized.
1879       if (SO1->getType() != GO1->getType())
1880         return nullptr;
1881 
1882       Value *Sum =
1883           SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
1884       // Only do the combine when we are sure the cost after the
1885       // merge is never more than that before the merge.
1886       if (Sum == nullptr)
1887         return nullptr;
1888 
1889       // Update the GEP in place if possible.
1890       if (Src->getNumOperands() == 2) {
1891         GEP.setOperand(0, Src->getOperand(0));
1892         GEP.setOperand(1, Sum);
1893         return &GEP;
1894       }
1895       Indices.append(Src->op_begin()+1, Src->op_end()-1);
1896       Indices.push_back(Sum);
1897       Indices.append(GEP.op_begin()+2, GEP.op_end());
1898     } else if (isa<Constant>(*GEP.idx_begin()) &&
1899                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1900                Src->getNumOperands() != 1) {
1901       // Otherwise we can do the fold if the first index of the GEP is a zero
1902       Indices.append(Src->op_begin()+1, Src->op_end());
1903       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1904     }
1905 
1906     if (!Indices.empty())
1907       return GEP.isInBounds() && Src->isInBounds()
1908                  ? GetElementPtrInst::CreateInBounds(
1909                        Src->getSourceElementType(), Src->getOperand(0), Indices,
1910                        GEP.getName())
1911                  : GetElementPtrInst::Create(Src->getSourceElementType(),
1912                                              Src->getOperand(0), Indices,
1913                                              GEP.getName());
1914   }
1915 
1916   if (GEP.getNumIndices() == 1) {
1917     unsigned AS = GEP.getPointerAddressSpace();
1918     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1919         DL.getIndexSizeInBits(AS)) {
1920       uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType);
1921 
1922       bool Matched = false;
1923       uint64_t C;
1924       Value *V = nullptr;
1925       if (TyAllocSize == 1) {
1926         V = GEP.getOperand(1);
1927         Matched = true;
1928       } else if (match(GEP.getOperand(1),
1929                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
1930         if (TyAllocSize == 1ULL << C)
1931           Matched = true;
1932       } else if (match(GEP.getOperand(1),
1933                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1934         if (TyAllocSize == C)
1935           Matched = true;
1936       }
1937 
1938       if (Matched) {
1939         // Canonicalize (gep i8* X, -(ptrtoint Y))
1940         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1941         // The GEP pattern is emitted by the SCEV expander for certain kinds of
1942         // pointer arithmetic.
1943         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1944           Operator *Index = cast<Operator>(V);
1945           Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType());
1946           Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1));
1947           return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType);
1948         }
1949         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1950         // to (bitcast Y)
1951         Value *Y;
1952         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1953                            m_PtrToInt(m_Specific(GEP.getOperand(0))))))
1954           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType);
1955       }
1956     }
1957   }
1958 
1959   // We do not handle pointer-vector geps here.
1960   if (GEPType->isVectorTy())
1961     return nullptr;
1962 
1963   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1964   Value *StrippedPtr = PtrOp->stripPointerCasts();
1965   PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
1966 
1967   if (StrippedPtr != PtrOp) {
1968     bool HasZeroPointerIndex = false;
1969     Type *StrippedPtrEltTy = StrippedPtrTy->getElementType();
1970 
1971     if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1972       HasZeroPointerIndex = C->isZero();
1973 
1974     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1975     // into     : GEP [10 x i8]* X, i32 0, ...
1976     //
1977     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1978     //           into     : GEP i8* X, ...
1979     //
1980     // This occurs when the program declares an array extern like "int X[];"
1981     if (HasZeroPointerIndex) {
1982       if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
1983         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1984         if (CATy->getElementType() == StrippedPtrEltTy) {
1985           // -> GEP i8* X, ...
1986           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1987           GetElementPtrInst *Res = GetElementPtrInst::Create(
1988               StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName());
1989           Res->setIsInBounds(GEP.isInBounds());
1990           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1991             return Res;
1992           // Insert Res, and create an addrspacecast.
1993           // e.g.,
1994           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1995           // ->
1996           // %0 = GEP i8 addrspace(1)* X, ...
1997           // addrspacecast i8 addrspace(1)* %0 to i8*
1998           return new AddrSpaceCastInst(Builder.Insert(Res), GEPType);
1999         }
2000 
2001         if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) {
2002           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2003           if (CATy->getElementType() == XATy->getElementType()) {
2004             // -> GEP [10 x i8]* X, i32 0, ...
2005             // At this point, we know that the cast source type is a pointer
2006             // to an array of the same type as the destination pointer
2007             // array.  Because the array type is never stepped over (there
2008             // is a leading zero) we can fold the cast into this GEP.
2009             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
2010               GEP.setOperand(0, StrippedPtr);
2011               GEP.setSourceElementType(XATy);
2012               return &GEP;
2013             }
2014             // Cannot replace the base pointer directly because StrippedPtr's
2015             // address space is different. Instead, create a new GEP followed by
2016             // an addrspacecast.
2017             // e.g.,
2018             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
2019             //   i32 0, ...
2020             // ->
2021             // %0 = GEP [10 x i8] addrspace(1)* X, ...
2022             // addrspacecast i8 addrspace(1)* %0 to i8*
2023             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
2024             Value *NewGEP =
2025                 GEP.isInBounds()
2026                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2027                                                 Idx, GEP.getName())
2028                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2029                                         GEP.getName());
2030             return new AddrSpaceCastInst(NewGEP, GEPType);
2031           }
2032         }
2033       }
2034     } else if (GEP.getNumOperands() == 2) {
2035       // Transform things like:
2036       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
2037       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
2038       if (StrippedPtrEltTy->isArrayTy() &&
2039           DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) ==
2040               DL.getTypeAllocSize(GEPEltType)) {
2041         Type *IdxType = DL.getIndexType(GEPType);
2042         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
2043         Value *NewGEP =
2044             GEP.isInBounds()
2045                 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2046                                             GEP.getName())
2047                 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2048                                     GEP.getName());
2049 
2050         // V and GEP are both pointer types --> BitCast
2051         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType);
2052       }
2053 
2054       // Transform things like:
2055       // %V = mul i64 %N, 4
2056       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
2057       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
2058       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) {
2059         // Check that changing the type amounts to dividing the index by a scale
2060         // factor.
2061         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
2062         uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy);
2063         if (ResSize && SrcSize % ResSize == 0) {
2064           Value *Idx = GEP.getOperand(1);
2065           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2066           uint64_t Scale = SrcSize / ResSize;
2067 
2068           // Earlier transforms ensure that the index has the right type
2069           // according to Data Layout, which considerably simplifies the
2070           // logic by eliminating implicit casts.
2071           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2072                  "Index type does not match the Data Layout preferences");
2073 
2074           bool NSW;
2075           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2076             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2077             // If the multiplication NewIdx * Scale may overflow then the new
2078             // GEP may not be "inbounds".
2079             Value *NewGEP =
2080                 GEP.isInBounds() && NSW
2081                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2082                                                 NewIdx, GEP.getName())
2083                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx,
2084                                         GEP.getName());
2085 
2086             // The NewGEP must be pointer typed, so must the old one -> BitCast
2087             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2088                                                                  GEPType);
2089           }
2090         }
2091       }
2092 
2093       // Similarly, transform things like:
2094       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2095       //   (where tmp = 8*tmp2) into:
2096       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2097       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() &&
2098           StrippedPtrEltTy->isArrayTy()) {
2099         // Check that changing to the array element type amounts to dividing the
2100         // index by a scale factor.
2101         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
2102         uint64_t ArrayEltSize =
2103             DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType());
2104         if (ResSize && ArrayEltSize % ResSize == 0) {
2105           Value *Idx = GEP.getOperand(1);
2106           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2107           uint64_t Scale = ArrayEltSize / ResSize;
2108 
2109           // Earlier transforms ensure that the index has the right type
2110           // according to the Data Layout, which considerably simplifies
2111           // the logic by eliminating implicit casts.
2112           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2113                  "Index type does not match the Data Layout preferences");
2114 
2115           bool NSW;
2116           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2117             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2118             // If the multiplication NewIdx * Scale may overflow then the new
2119             // GEP may not be "inbounds".
2120             Type *IndTy = DL.getIndexType(GEPType);
2121             Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
2122 
2123             Value *NewGEP =
2124                 GEP.isInBounds() && NSW
2125                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2126                                                 Off, GEP.getName())
2127                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off,
2128                                         GEP.getName());
2129             // The NewGEP must be pointer typed, so must the old one -> BitCast
2130             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2131                                                                  GEPType);
2132           }
2133         }
2134       }
2135     }
2136   }
2137 
2138   // addrspacecast between types is canonicalized as a bitcast, then an
2139   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2140   // through the addrspacecast.
2141   Value *ASCStrippedPtrOp = PtrOp;
2142   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2143     //   X = bitcast A addrspace(1)* to B addrspace(1)*
2144     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2145     //   Z = gep Y, <...constant indices...>
2146     // Into an addrspacecasted GEP of the struct.
2147     if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2148       ASCStrippedPtrOp = BC;
2149   }
2150 
2151   if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
2152     Value *SrcOp = BCI->getOperand(0);
2153     PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2154     Type *SrcEltType = SrcType->getElementType();
2155 
2156     // GEP directly using the source operand if this GEP is accessing an element
2157     // of a bitcasted pointer to vector or array of the same dimensions:
2158     // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2159     // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2160     auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy) {
2161       return ArrTy->getArrayElementType() == VecTy->getVectorElementType() &&
2162              ArrTy->getArrayNumElements() == VecTy->getVectorNumElements();
2163     };
2164     if (GEP.getNumOperands() == 3 &&
2165         ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() &&
2166           areMatchingArrayAndVecTypes(GEPEltType, SrcEltType)) ||
2167          (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() &&
2168           areMatchingArrayAndVecTypes(SrcEltType, GEPEltType)))) {
2169 
2170       // Create a new GEP here, as using `setOperand()` followed by
2171       // `setSourceElementType()` won't actually update the type of the
2172       // existing GEP Value. Causing issues if this Value is accessed when
2173       // constructing an AddrSpaceCastInst
2174       Value *NGEP =
2175           GEP.isInBounds()
2176               ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]})
2177               : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]});
2178       NGEP->takeName(&GEP);
2179 
2180       // Preserve GEP address space to satisfy users
2181       if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2182         return new AddrSpaceCastInst(NGEP, GEPType);
2183 
2184       return replaceInstUsesWith(GEP, NGEP);
2185     }
2186 
2187     // See if we can simplify:
2188     //   X = bitcast A* to B*
2189     //   Y = gep X, <...constant indices...>
2190     // into a gep of the original struct. This is important for SROA and alias
2191     // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2192     unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
2193     APInt Offset(OffsetBits, 0);
2194     if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) {
2195       // If this GEP instruction doesn't move the pointer, just replace the GEP
2196       // with a bitcast of the real input to the dest type.
2197       if (!Offset) {
2198         // If the bitcast is of an allocation, and the allocation will be
2199         // converted to match the type of the cast, don't touch this.
2200         if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) {
2201           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2202           if (Instruction *I = visitBitCast(*BCI)) {
2203             if (I != BCI) {
2204               I->takeName(BCI);
2205               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
2206               replaceInstUsesWith(*BCI, I);
2207             }
2208             return &GEP;
2209           }
2210         }
2211 
2212         if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
2213           return new AddrSpaceCastInst(SrcOp, GEPType);
2214         return new BitCastInst(SrcOp, GEPType);
2215       }
2216 
2217       // Otherwise, if the offset is non-zero, we need to find out if there is a
2218       // field at Offset in 'A's type.  If so, we can pull the cast through the
2219       // GEP.
2220       SmallVector<Value*, 8> NewIndices;
2221       if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) {
2222         Value *NGEP =
2223             GEP.isInBounds()
2224                 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices)
2225                 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices);
2226 
2227         if (NGEP->getType() == GEPType)
2228           return replaceInstUsesWith(GEP, NGEP);
2229         NGEP->takeName(&GEP);
2230 
2231         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2232           return new AddrSpaceCastInst(NGEP, GEPType);
2233         return new BitCastInst(NGEP, GEPType);
2234       }
2235     }
2236   }
2237 
2238   if (!GEP.isInBounds()) {
2239     unsigned IdxWidth =
2240         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2241     APInt BasePtrOffset(IdxWidth, 0);
2242     Value *UnderlyingPtrOp =
2243             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2244                                                              BasePtrOffset);
2245     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2246       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2247           BasePtrOffset.isNonNegative()) {
2248         APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
2249         if (BasePtrOffset.ule(AllocSize)) {
2250           return GetElementPtrInst::CreateInBounds(
2251               GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1),
2252               GEP.getName());
2253         }
2254       }
2255     }
2256   }
2257 
2258   return nullptr;
2259 }
2260 
2261 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2262                                          Instruction *AI) {
2263   if (isa<ConstantPointerNull>(V))
2264     return true;
2265   if (auto *LI = dyn_cast<LoadInst>(V))
2266     return isa<GlobalVariable>(LI->getPointerOperand());
2267   // Two distinct allocations will never be equal.
2268   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2269   // through bitcasts of V can cause
2270   // the result statement below to be true, even when AI and V (ex:
2271   // i8* ->i32* ->i8* of AI) are the same allocations.
2272   return isAllocLikeFn(V, TLI) && V != AI;
2273 }
2274 
2275 static bool isAllocSiteRemovable(Instruction *AI,
2276                                  SmallVectorImpl<WeakTrackingVH> &Users,
2277                                  const TargetLibraryInfo *TLI) {
2278   SmallVector<Instruction*, 4> Worklist;
2279   Worklist.push_back(AI);
2280 
2281   do {
2282     Instruction *PI = Worklist.pop_back_val();
2283     for (User *U : PI->users()) {
2284       Instruction *I = cast<Instruction>(U);
2285       switch (I->getOpcode()) {
2286       default:
2287         // Give up the moment we see something we can't handle.
2288         return false;
2289 
2290       case Instruction::AddrSpaceCast:
2291       case Instruction::BitCast:
2292       case Instruction::GetElementPtr:
2293         Users.emplace_back(I);
2294         Worklist.push_back(I);
2295         continue;
2296 
2297       case Instruction::ICmp: {
2298         ICmpInst *ICI = cast<ICmpInst>(I);
2299         // We can fold eq/ne comparisons with null to false/true, respectively.
2300         // We also fold comparisons in some conditions provided the alloc has
2301         // not escaped (see isNeverEqualToUnescapedAlloc).
2302         if (!ICI->isEquality())
2303           return false;
2304         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2305         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2306           return false;
2307         Users.emplace_back(I);
2308         continue;
2309       }
2310 
2311       case Instruction::Call:
2312         // Ignore no-op and store intrinsics.
2313         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2314           switch (II->getIntrinsicID()) {
2315           default:
2316             return false;
2317 
2318           case Intrinsic::memmove:
2319           case Intrinsic::memcpy:
2320           case Intrinsic::memset: {
2321             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2322             if (MI->isVolatile() || MI->getRawDest() != PI)
2323               return false;
2324             LLVM_FALLTHROUGH;
2325           }
2326           case Intrinsic::invariant_start:
2327           case Intrinsic::invariant_end:
2328           case Intrinsic::lifetime_start:
2329           case Intrinsic::lifetime_end:
2330           case Intrinsic::objectsize:
2331             Users.emplace_back(I);
2332             continue;
2333           }
2334         }
2335 
2336         if (isFreeCall(I, TLI)) {
2337           Users.emplace_back(I);
2338           continue;
2339         }
2340         return false;
2341 
2342       case Instruction::Store: {
2343         StoreInst *SI = cast<StoreInst>(I);
2344         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2345           return false;
2346         Users.emplace_back(I);
2347         continue;
2348       }
2349       }
2350       llvm_unreachable("missing a return?");
2351     }
2352   } while (!Worklist.empty());
2353   return true;
2354 }
2355 
2356 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2357   // If we have a malloc call which is only used in any amount of comparisons to
2358   // null and free calls, delete the calls and replace the comparisons with true
2359   // or false as appropriate.
2360 
2361   // This is based on the principle that we can substitute our own allocation
2362   // function (which will never return null) rather than knowledge of the
2363   // specific function being called. In some sense this can change the permitted
2364   // outputs of a program (when we convert a malloc to an alloca, the fact that
2365   // the allocation is now on the stack is potentially visible, for example),
2366   // but we believe in a permissible manner.
2367   SmallVector<WeakTrackingVH, 64> Users;
2368 
2369   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2370   // before each store.
2371   TinyPtrVector<DbgVariableIntrinsic *> DIIs;
2372   std::unique_ptr<DIBuilder> DIB;
2373   if (isa<AllocaInst>(MI)) {
2374     DIIs = FindDbgAddrUses(&MI);
2375     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2376   }
2377 
2378   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2379     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2380       // Lowering all @llvm.objectsize calls first because they may
2381       // use a bitcast/GEP of the alloca we are removing.
2382       if (!Users[i])
2383        continue;
2384 
2385       Instruction *I = cast<Instruction>(&*Users[i]);
2386 
2387       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2388         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2389           Value *Result =
2390               lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true);
2391           replaceInstUsesWith(*I, Result);
2392           eraseInstFromFunction(*I);
2393           Users[i] = nullptr; // Skip examining in the next loop.
2394         }
2395       }
2396     }
2397     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2398       if (!Users[i])
2399         continue;
2400 
2401       Instruction *I = cast<Instruction>(&*Users[i]);
2402 
2403       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2404         replaceInstUsesWith(*C,
2405                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2406                                              C->isFalseWhenEqual()));
2407       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2408                  isa<AddrSpaceCastInst>(I)) {
2409         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2410       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2411         for (auto *DII : DIIs)
2412           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2413       }
2414       eraseInstFromFunction(*I);
2415     }
2416 
2417     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2418       // Replace invoke with a NOP intrinsic to maintain the original CFG
2419       Module *M = II->getModule();
2420       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2421       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2422                          None, "", II->getParent());
2423     }
2424 
2425     for (auto *DII : DIIs)
2426       eraseInstFromFunction(*DII);
2427 
2428     return eraseInstFromFunction(MI);
2429   }
2430   return nullptr;
2431 }
2432 
2433 /// Move the call to free before a NULL test.
2434 ///
2435 /// Check if this free is accessed after its argument has been test
2436 /// against NULL (property 0).
2437 /// If yes, it is legal to move this call in its predecessor block.
2438 ///
2439 /// The move is performed only if the block containing the call to free
2440 /// will be removed, i.e.:
2441 /// 1. it has only one predecessor P, and P has two successors
2442 /// 2. it contains the call, noops, and an unconditional branch
2443 /// 3. its successor is the same as its predecessor's successor
2444 ///
2445 /// The profitability is out-of concern here and this function should
2446 /// be called only if the caller knows this transformation would be
2447 /// profitable (e.g., for code size).
2448 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,
2449                                                 const DataLayout &DL) {
2450   Value *Op = FI.getArgOperand(0);
2451   BasicBlock *FreeInstrBB = FI.getParent();
2452   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2453 
2454   // Validate part of constraint #1: Only one predecessor
2455   // FIXME: We can extend the number of predecessor, but in that case, we
2456   //        would duplicate the call to free in each predecessor and it may
2457   //        not be profitable even for code size.
2458   if (!PredBB)
2459     return nullptr;
2460 
2461   // Validate constraint #2: Does this block contains only the call to
2462   //                         free, noops, and an unconditional branch?
2463   BasicBlock *SuccBB;
2464   Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
2465   if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
2466     return nullptr;
2467 
2468   // If there are only 2 instructions in the block, at this point,
2469   // this is the call to free and unconditional.
2470   // If there are more than 2 instructions, check that they are noops
2471   // i.e., they won't hurt the performance of the generated code.
2472   if (FreeInstrBB->size() != 2) {
2473     for (const Instruction &Inst : *FreeInstrBB) {
2474       if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
2475         continue;
2476       auto *Cast = dyn_cast<CastInst>(&Inst);
2477       if (!Cast || !Cast->isNoopCast(DL))
2478         return nullptr;
2479     }
2480   }
2481   // Validate the rest of constraint #1 by matching on the pred branch.
2482   Instruction *TI = PredBB->getTerminator();
2483   BasicBlock *TrueBB, *FalseBB;
2484   ICmpInst::Predicate Pred;
2485   if (!match(TI, m_Br(m_ICmp(Pred,
2486                              m_CombineOr(m_Specific(Op),
2487                                          m_Specific(Op->stripPointerCasts())),
2488                              m_Zero()),
2489                       TrueBB, FalseBB)))
2490     return nullptr;
2491   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2492     return nullptr;
2493 
2494   // Validate constraint #3: Ensure the null case just falls through.
2495   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2496     return nullptr;
2497   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2498          "Broken CFG: missing edge from predecessor to successor");
2499 
2500   // At this point, we know that everything in FreeInstrBB can be moved
2501   // before TI.
2502   for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end();
2503        It != End;) {
2504     Instruction &Instr = *It++;
2505     if (&Instr == FreeInstrBBTerminator)
2506       break;
2507     Instr.moveBefore(TI);
2508   }
2509   assert(FreeInstrBB->size() == 1 &&
2510          "Only the branch instruction should remain");
2511   return &FI;
2512 }
2513 
2514 Instruction *InstCombiner::visitFree(CallInst &FI) {
2515   Value *Op = FI.getArgOperand(0);
2516 
2517   // free undef -> unreachable.
2518   if (isa<UndefValue>(Op)) {
2519     // Leave a marker since we can't modify the CFG here.
2520     CreateNonTerminatorUnreachable(&FI);
2521     return eraseInstFromFunction(FI);
2522   }
2523 
2524   // If we have 'free null' delete the instruction.  This can happen in stl code
2525   // when lots of inlining happens.
2526   if (isa<ConstantPointerNull>(Op))
2527     return eraseInstFromFunction(FI);
2528 
2529   // If we optimize for code size, try to move the call to free before the null
2530   // test so that simplify cfg can remove the empty block and dead code
2531   // elimination the branch. I.e., helps to turn something like:
2532   // if (foo) free(foo);
2533   // into
2534   // free(foo);
2535   if (MinimizeSize)
2536     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))
2537       return I;
2538 
2539   return nullptr;
2540 }
2541 
2542 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2543   if (RI.getNumOperands() == 0) // ret void
2544     return nullptr;
2545 
2546   Value *ResultOp = RI.getOperand(0);
2547   Type *VTy = ResultOp->getType();
2548   if (!VTy->isIntegerTy())
2549     return nullptr;
2550 
2551   // There might be assume intrinsics dominating this return that completely
2552   // determine the value. If so, constant fold it.
2553   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2554   if (Known.isConstant())
2555     RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant()));
2556 
2557   return nullptr;
2558 }
2559 
2560 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2561   // Change br (not X), label True, label False to: br X, label False, True
2562   Value *X = nullptr;
2563   if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) &&
2564       !isa<Constant>(X)) {
2565     // Swap Destinations and condition...
2566     BI.setCondition(X);
2567     BI.swapSuccessors();
2568     return &BI;
2569   }
2570 
2571   // If the condition is irrelevant, remove the use so that other
2572   // transforms on the condition become more effective.
2573   if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) &&
2574       BI.getSuccessor(0) == BI.getSuccessor(1)) {
2575     BI.setCondition(ConstantInt::getFalse(BI.getCondition()->getType()));
2576     return &BI;
2577   }
2578 
2579   // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2580   CmpInst::Predicate Pred;
2581   if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())),
2582                       m_BasicBlock(), m_BasicBlock())) &&
2583       !isCanonicalPredicate(Pred)) {
2584     // Swap destinations and condition.
2585     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2586     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2587     BI.swapSuccessors();
2588     Worklist.Add(Cond);
2589     return &BI;
2590   }
2591 
2592   return nullptr;
2593 }
2594 
2595 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2596   Value *Cond = SI.getCondition();
2597   Value *Op0;
2598   ConstantInt *AddRHS;
2599   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2600     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2601     for (auto Case : SI.cases()) {
2602       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2603       assert(isa<ConstantInt>(NewCase) &&
2604              "Result of expression should be constant");
2605       Case.setValue(cast<ConstantInt>(NewCase));
2606     }
2607     SI.setCondition(Op0);
2608     return &SI;
2609   }
2610 
2611   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2612   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2613   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2614 
2615   // Compute the number of leading bits we can ignore.
2616   // TODO: A better way to determine this would use ComputeNumSignBits().
2617   for (auto &C : SI.cases()) {
2618     LeadingKnownZeros = std::min(
2619         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2620     LeadingKnownOnes = std::min(
2621         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2622   }
2623 
2624   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2625 
2626   // Shrink the condition operand if the new type is smaller than the old type.
2627   // But do not shrink to a non-standard type, because backend can't generate
2628   // good code for that yet.
2629   // TODO: We can make it aggressive again after fixing PR39569.
2630   if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
2631       shouldChangeType(Known.getBitWidth(), NewWidth)) {
2632     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2633     Builder.SetInsertPoint(&SI);
2634     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2635     SI.setCondition(NewCond);
2636 
2637     for (auto Case : SI.cases()) {
2638       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2639       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2640     }
2641     return &SI;
2642   }
2643 
2644   return nullptr;
2645 }
2646 
2647 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2648   Value *Agg = EV.getAggregateOperand();
2649 
2650   if (!EV.hasIndices())
2651     return replaceInstUsesWith(EV, Agg);
2652 
2653   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2654                                           SQ.getWithInstruction(&EV)))
2655     return replaceInstUsesWith(EV, V);
2656 
2657   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2658     // We're extracting from an insertvalue instruction, compare the indices
2659     const unsigned *exti, *exte, *insi, *inse;
2660     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2661          exte = EV.idx_end(), inse = IV->idx_end();
2662          exti != exte && insi != inse;
2663          ++exti, ++insi) {
2664       if (*insi != *exti)
2665         // The insert and extract both reference distinctly different elements.
2666         // This means the extract is not influenced by the insert, and we can
2667         // replace the aggregate operand of the extract with the aggregate
2668         // operand of the insert. i.e., replace
2669         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2670         // %E = extractvalue { i32, { i32 } } %I, 0
2671         // with
2672         // %E = extractvalue { i32, { i32 } } %A, 0
2673         return ExtractValueInst::Create(IV->getAggregateOperand(),
2674                                         EV.getIndices());
2675     }
2676     if (exti == exte && insi == inse)
2677       // Both iterators are at the end: Index lists are identical. Replace
2678       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2679       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2680       // with "i32 42"
2681       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2682     if (exti == exte) {
2683       // The extract list is a prefix of the insert list. i.e. replace
2684       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2685       // %E = extractvalue { i32, { i32 } } %I, 1
2686       // with
2687       // %X = extractvalue { i32, { i32 } } %A, 1
2688       // %E = insertvalue { i32 } %X, i32 42, 0
2689       // by switching the order of the insert and extract (though the
2690       // insertvalue should be left in, since it may have other uses).
2691       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2692                                                 EV.getIndices());
2693       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2694                                      makeArrayRef(insi, inse));
2695     }
2696     if (insi == inse)
2697       // The insert list is a prefix of the extract list
2698       // We can simply remove the common indices from the extract and make it
2699       // operate on the inserted value instead of the insertvalue result.
2700       // i.e., replace
2701       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2702       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2703       // with
2704       // %E extractvalue { i32 } { i32 42 }, 0
2705       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2706                                       makeArrayRef(exti, exte));
2707   }
2708   if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) {
2709     // We're extracting from an overflow intrinsic, see if we're the only user,
2710     // which allows us to simplify multiple result intrinsics to simpler
2711     // things that just get one value.
2712     if (WO->hasOneUse()) {
2713       // Check if we're grabbing only the result of a 'with overflow' intrinsic
2714       // and replace it with a traditional binary instruction.
2715       if (*EV.idx_begin() == 0) {
2716         Instruction::BinaryOps BinOp = WO->getBinaryOp();
2717         Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
2718         replaceInstUsesWith(*WO, UndefValue::get(WO->getType()));
2719         eraseInstFromFunction(*WO);
2720         return BinaryOperator::Create(BinOp, LHS, RHS);
2721       }
2722 
2723       // If the normal result of the add is dead, and the RHS is a constant,
2724       // we can transform this into a range comparison.
2725       // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2726       if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2727         if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS()))
2728           return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(),
2729                               ConstantExpr::getNot(CI));
2730     }
2731   }
2732   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2733     // If the (non-volatile) load only has one use, we can rewrite this to a
2734     // load from a GEP. This reduces the size of the load. If a load is used
2735     // only by extractvalue instructions then this either must have been
2736     // optimized before, or it is a struct with padding, in which case we
2737     // don't want to do the transformation as it loses padding knowledge.
2738     if (L->isSimple() && L->hasOneUse()) {
2739       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2740       SmallVector<Value*, 4> Indices;
2741       // Prefix an i32 0 since we need the first element.
2742       Indices.push_back(Builder.getInt32(0));
2743       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2744             I != E; ++I)
2745         Indices.push_back(Builder.getInt32(*I));
2746 
2747       // We need to insert these at the location of the old load, not at that of
2748       // the extractvalue.
2749       Builder.SetInsertPoint(L);
2750       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
2751                                              L->getPointerOperand(), Indices);
2752       Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
2753       // Whatever aliasing information we had for the orignal load must also
2754       // hold for the smaller load, so propagate the annotations.
2755       AAMDNodes Nodes;
2756       L->getAAMetadata(Nodes);
2757       NL->setAAMetadata(Nodes);
2758       // Returning the load directly will cause the main loop to insert it in
2759       // the wrong spot, so use replaceInstUsesWith().
2760       return replaceInstUsesWith(EV, NL);
2761     }
2762   // We could simplify extracts from other values. Note that nested extracts may
2763   // already be simplified implicitly by the above: extract (extract (insert) )
2764   // will be translated into extract ( insert ( extract ) ) first and then just
2765   // the value inserted, if appropriate. Similarly for extracts from single-use
2766   // loads: extract (extract (load)) will be translated to extract (load (gep))
2767   // and if again single-use then via load (gep (gep)) to load (gep).
2768   // However, double extracts from e.g. function arguments or return values
2769   // aren't handled yet.
2770   return nullptr;
2771 }
2772 
2773 /// Return 'true' if the given typeinfo will match anything.
2774 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2775   switch (Personality) {
2776   case EHPersonality::GNU_C:
2777   case EHPersonality::GNU_C_SjLj:
2778   case EHPersonality::Rust:
2779     // The GCC C EH and Rust personality only exists to support cleanups, so
2780     // it's not clear what the semantics of catch clauses are.
2781     return false;
2782   case EHPersonality::Unknown:
2783     return false;
2784   case EHPersonality::GNU_Ada:
2785     // While __gnat_all_others_value will match any Ada exception, it doesn't
2786     // match foreign exceptions (or didn't, before gcc-4.7).
2787     return false;
2788   case EHPersonality::GNU_CXX:
2789   case EHPersonality::GNU_CXX_SjLj:
2790   case EHPersonality::GNU_ObjC:
2791   case EHPersonality::MSVC_X86SEH:
2792   case EHPersonality::MSVC_Win64SEH:
2793   case EHPersonality::MSVC_CXX:
2794   case EHPersonality::CoreCLR:
2795   case EHPersonality::Wasm_CXX:
2796     return TypeInfo->isNullValue();
2797   }
2798   llvm_unreachable("invalid enum");
2799 }
2800 
2801 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2802   return
2803     cast<ArrayType>(LHS->getType())->getNumElements()
2804   <
2805     cast<ArrayType>(RHS->getType())->getNumElements();
2806 }
2807 
2808 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2809   // The logic here should be correct for any real-world personality function.
2810   // However if that turns out not to be true, the offending logic can always
2811   // be conditioned on the personality function, like the catch-all logic is.
2812   EHPersonality Personality =
2813       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2814 
2815   // Simplify the list of clauses, eg by removing repeated catch clauses
2816   // (these are often created by inlining).
2817   bool MakeNewInstruction = false; // If true, recreate using the following:
2818   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2819   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
2820 
2821   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2822   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2823     bool isLastClause = i + 1 == e;
2824     if (LI.isCatch(i)) {
2825       // A catch clause.
2826       Constant *CatchClause = LI.getClause(i);
2827       Constant *TypeInfo = CatchClause->stripPointerCasts();
2828 
2829       // If we already saw this clause, there is no point in having a second
2830       // copy of it.
2831       if (AlreadyCaught.insert(TypeInfo).second) {
2832         // This catch clause was not already seen.
2833         NewClauses.push_back(CatchClause);
2834       } else {
2835         // Repeated catch clause - drop the redundant copy.
2836         MakeNewInstruction = true;
2837       }
2838 
2839       // If this is a catch-all then there is no point in keeping any following
2840       // clauses or marking the landingpad as having a cleanup.
2841       if (isCatchAll(Personality, TypeInfo)) {
2842         if (!isLastClause)
2843           MakeNewInstruction = true;
2844         CleanupFlag = false;
2845         break;
2846       }
2847     } else {
2848       // A filter clause.  If any of the filter elements were already caught
2849       // then they can be dropped from the filter.  It is tempting to try to
2850       // exploit the filter further by saying that any typeinfo that does not
2851       // occur in the filter can't be caught later (and thus can be dropped).
2852       // However this would be wrong, since typeinfos can match without being
2853       // equal (for example if one represents a C++ class, and the other some
2854       // class derived from it).
2855       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2856       Constant *FilterClause = LI.getClause(i);
2857       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2858       unsigned NumTypeInfos = FilterType->getNumElements();
2859 
2860       // An empty filter catches everything, so there is no point in keeping any
2861       // following clauses or marking the landingpad as having a cleanup.  By
2862       // dealing with this case here the following code is made a bit simpler.
2863       if (!NumTypeInfos) {
2864         NewClauses.push_back(FilterClause);
2865         if (!isLastClause)
2866           MakeNewInstruction = true;
2867         CleanupFlag = false;
2868         break;
2869       }
2870 
2871       bool MakeNewFilter = false; // If true, make a new filter.
2872       SmallVector<Constant *, 16> NewFilterElts; // New elements.
2873       if (isa<ConstantAggregateZero>(FilterClause)) {
2874         // Not an empty filter - it contains at least one null typeinfo.
2875         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2876         Constant *TypeInfo =
2877           Constant::getNullValue(FilterType->getElementType());
2878         // If this typeinfo is a catch-all then the filter can never match.
2879         if (isCatchAll(Personality, TypeInfo)) {
2880           // Throw the filter away.
2881           MakeNewInstruction = true;
2882           continue;
2883         }
2884 
2885         // There is no point in having multiple copies of this typeinfo, so
2886         // discard all but the first copy if there is more than one.
2887         NewFilterElts.push_back(TypeInfo);
2888         if (NumTypeInfos > 1)
2889           MakeNewFilter = true;
2890       } else {
2891         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2892         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2893         NewFilterElts.reserve(NumTypeInfos);
2894 
2895         // Remove any filter elements that were already caught or that already
2896         // occurred in the filter.  While there, see if any of the elements are
2897         // catch-alls.  If so, the filter can be discarded.
2898         bool SawCatchAll = false;
2899         for (unsigned j = 0; j != NumTypeInfos; ++j) {
2900           Constant *Elt = Filter->getOperand(j);
2901           Constant *TypeInfo = Elt->stripPointerCasts();
2902           if (isCatchAll(Personality, TypeInfo)) {
2903             // This element is a catch-all.  Bail out, noting this fact.
2904             SawCatchAll = true;
2905             break;
2906           }
2907 
2908           // Even if we've seen a type in a catch clause, we don't want to
2909           // remove it from the filter.  An unexpected type handler may be
2910           // set up for a call site which throws an exception of the same
2911           // type caught.  In order for the exception thrown by the unexpected
2912           // handler to propagate correctly, the filter must be correctly
2913           // described for the call site.
2914           //
2915           // Example:
2916           //
2917           // void unexpected() { throw 1;}
2918           // void foo() throw (int) {
2919           //   std::set_unexpected(unexpected);
2920           //   try {
2921           //     throw 2.0;
2922           //   } catch (int i) {}
2923           // }
2924 
2925           // There is no point in having multiple copies of the same typeinfo in
2926           // a filter, so only add it if we didn't already.
2927           if (SeenInFilter.insert(TypeInfo).second)
2928             NewFilterElts.push_back(cast<Constant>(Elt));
2929         }
2930         // A filter containing a catch-all cannot match anything by definition.
2931         if (SawCatchAll) {
2932           // Throw the filter away.
2933           MakeNewInstruction = true;
2934           continue;
2935         }
2936 
2937         // If we dropped something from the filter, make a new one.
2938         if (NewFilterElts.size() < NumTypeInfos)
2939           MakeNewFilter = true;
2940       }
2941       if (MakeNewFilter) {
2942         FilterType = ArrayType::get(FilterType->getElementType(),
2943                                     NewFilterElts.size());
2944         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2945         MakeNewInstruction = true;
2946       }
2947 
2948       NewClauses.push_back(FilterClause);
2949 
2950       // If the new filter is empty then it will catch everything so there is
2951       // no point in keeping any following clauses or marking the landingpad
2952       // as having a cleanup.  The case of the original filter being empty was
2953       // already handled above.
2954       if (MakeNewFilter && !NewFilterElts.size()) {
2955         assert(MakeNewInstruction && "New filter but not a new instruction!");
2956         CleanupFlag = false;
2957         break;
2958       }
2959     }
2960   }
2961 
2962   // If several filters occur in a row then reorder them so that the shortest
2963   // filters come first (those with the smallest number of elements).  This is
2964   // advantageous because shorter filters are more likely to match, speeding up
2965   // unwinding, but mostly because it increases the effectiveness of the other
2966   // filter optimizations below.
2967   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2968     unsigned j;
2969     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2970     for (j = i; j != e; ++j)
2971       if (!isa<ArrayType>(NewClauses[j]->getType()))
2972         break;
2973 
2974     // Check whether the filters are already sorted by length.  We need to know
2975     // if sorting them is actually going to do anything so that we only make a
2976     // new landingpad instruction if it does.
2977     for (unsigned k = i; k + 1 < j; ++k)
2978       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2979         // Not sorted, so sort the filters now.  Doing an unstable sort would be
2980         // correct too but reordering filters pointlessly might confuse users.
2981         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2982                          shorter_filter);
2983         MakeNewInstruction = true;
2984         break;
2985       }
2986 
2987     // Look for the next batch of filters.
2988     i = j + 1;
2989   }
2990 
2991   // If typeinfos matched if and only if equal, then the elements of a filter L
2992   // that occurs later than a filter F could be replaced by the intersection of
2993   // the elements of F and L.  In reality two typeinfos can match without being
2994   // equal (for example if one represents a C++ class, and the other some class
2995   // derived from it) so it would be wrong to perform this transform in general.
2996   // However the transform is correct and useful if F is a subset of L.  In that
2997   // case L can be replaced by F, and thus removed altogether since repeating a
2998   // filter is pointless.  So here we look at all pairs of filters F and L where
2999   // L follows F in the list of clauses, and remove L if every element of F is
3000   // an element of L.  This can occur when inlining C++ functions with exception
3001   // specifications.
3002   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
3003     // Examine each filter in turn.
3004     Value *Filter = NewClauses[i];
3005     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
3006     if (!FTy)
3007       // Not a filter - skip it.
3008       continue;
3009     unsigned FElts = FTy->getNumElements();
3010     // Examine each filter following this one.  Doing this backwards means that
3011     // we don't have to worry about filters disappearing under us when removed.
3012     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
3013       Value *LFilter = NewClauses[j];
3014       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
3015       if (!LTy)
3016         // Not a filter - skip it.
3017         continue;
3018       // If Filter is a subset of LFilter, i.e. every element of Filter is also
3019       // an element of LFilter, then discard LFilter.
3020       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
3021       // If Filter is empty then it is a subset of LFilter.
3022       if (!FElts) {
3023         // Discard LFilter.
3024         NewClauses.erase(J);
3025         MakeNewInstruction = true;
3026         // Move on to the next filter.
3027         continue;
3028       }
3029       unsigned LElts = LTy->getNumElements();
3030       // If Filter is longer than LFilter then it cannot be a subset of it.
3031       if (FElts > LElts)
3032         // Move on to the next filter.
3033         continue;
3034       // At this point we know that LFilter has at least one element.
3035       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
3036         // Filter is a subset of LFilter iff Filter contains only zeros (as we
3037         // already know that Filter is not longer than LFilter).
3038         if (isa<ConstantAggregateZero>(Filter)) {
3039           assert(FElts <= LElts && "Should have handled this case earlier!");
3040           // Discard LFilter.
3041           NewClauses.erase(J);
3042           MakeNewInstruction = true;
3043         }
3044         // Move on to the next filter.
3045         continue;
3046       }
3047       ConstantArray *LArray = cast<ConstantArray>(LFilter);
3048       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
3049         // Since Filter is non-empty and contains only zeros, it is a subset of
3050         // LFilter iff LFilter contains a zero.
3051         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
3052         for (unsigned l = 0; l != LElts; ++l)
3053           if (LArray->getOperand(l)->isNullValue()) {
3054             // LFilter contains a zero - discard it.
3055             NewClauses.erase(J);
3056             MakeNewInstruction = true;
3057             break;
3058           }
3059         // Move on to the next filter.
3060         continue;
3061       }
3062       // At this point we know that both filters are ConstantArrays.  Loop over
3063       // operands to see whether every element of Filter is also an element of
3064       // LFilter.  Since filters tend to be short this is probably faster than
3065       // using a method that scales nicely.
3066       ConstantArray *FArray = cast<ConstantArray>(Filter);
3067       bool AllFound = true;
3068       for (unsigned f = 0; f != FElts; ++f) {
3069         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
3070         AllFound = false;
3071         for (unsigned l = 0; l != LElts; ++l) {
3072           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
3073           if (LTypeInfo == FTypeInfo) {
3074             AllFound = true;
3075             break;
3076           }
3077         }
3078         if (!AllFound)
3079           break;
3080       }
3081       if (AllFound) {
3082         // Discard LFilter.
3083         NewClauses.erase(J);
3084         MakeNewInstruction = true;
3085       }
3086       // Move on to the next filter.
3087     }
3088   }
3089 
3090   // If we changed any of the clauses, replace the old landingpad instruction
3091   // with a new one.
3092   if (MakeNewInstruction) {
3093     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
3094                                                  NewClauses.size());
3095     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
3096       NLI->addClause(NewClauses[i]);
3097     // A landing pad with no clauses must have the cleanup flag set.  It is
3098     // theoretically possible, though highly unlikely, that we eliminated all
3099     // clauses.  If so, force the cleanup flag to true.
3100     if (NewClauses.empty())
3101       CleanupFlag = true;
3102     NLI->setCleanup(CleanupFlag);
3103     return NLI;
3104   }
3105 
3106   // Even if none of the clauses changed, we may nonetheless have understood
3107   // that the cleanup flag is pointless.  Clear it if so.
3108   if (LI.isCleanup() != CleanupFlag) {
3109     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
3110     LI.setCleanup(CleanupFlag);
3111     return &LI;
3112   }
3113 
3114   return nullptr;
3115 }
3116 
3117 /// Try to move the specified instruction from its current block into the
3118 /// beginning of DestBlock, which can only happen if it's safe to move the
3119 /// instruction past all of the instructions between it and the end of its
3120 /// block.
3121 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock,
3122                                  InstCombiner::BuilderTy &Builder) {
3123   assert(I->hasOneUse() && "Invariants didn't hold!");
3124   BasicBlock *SrcBlock = I->getParent();
3125 
3126   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3127   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
3128       I->isTerminator())
3129     return false;
3130 
3131   // Do not sink static or dynamic alloca instructions. Static allocas must
3132   // remain in the entry block, and dynamic allocas must not be sunk in between
3133   // a stacksave / stackrestore pair, which would incorrectly shorten its
3134   // lifetime.
3135   if (isa<AllocaInst>(I))
3136     return false;
3137 
3138   // Do not sink into catchswitch blocks.
3139   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
3140     return false;
3141 
3142   // Do not sink convergent call instructions.
3143   if (auto *CI = dyn_cast<CallInst>(I)) {
3144     if (CI->isConvergent())
3145       return false;
3146   }
3147   // We can only sink load instructions if there is nothing between the load and
3148   // the end of block that could change the value.
3149   if (I->mayReadFromMemory()) {
3150     for (BasicBlock::iterator Scan = I->getIterator(),
3151                               E = I->getParent()->end();
3152          Scan != E; ++Scan)
3153       if (Scan->mayWriteToMemory())
3154         return false;
3155   }
3156 
3157   // If this instruction was providing nonnull guarantees insert assumptions for
3158   // nonnull call site arguments.
3159   if (auto CS = dyn_cast<CallBase>(I)) {
3160     for (unsigned Idx = 0; Idx != CS->getNumArgOperands(); Idx++)
3161       if (CS->paramHasAttr(Idx, Attribute::NonNull) ||
3162           (CS->paramHasAttr(Idx, Attribute::Dereferenceable) &&
3163            !llvm::NullPointerIsDefined(CS->getFunction(),
3164                                        CS->getArgOperand(Idx)
3165                                            ->getType()
3166                                            ->getPointerAddressSpace()))) {
3167         Value *V = CS->getArgOperand(Idx);
3168 
3169         Builder.SetInsertPoint(I->getParent(), I->getIterator());
3170         Builder.CreateAssumption(Builder.CreateIsNotNull(V));
3171       }
3172   }
3173 
3174   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
3175   I->moveBefore(&*InsertPos);
3176   ++NumSunkInst;
3177 
3178   // Also sink all related debug uses from the source basic block. Otherwise we
3179   // get debug use before the def. Attempt to salvage debug uses first, to
3180   // maximise the range variables have location for. If we cannot salvage, then
3181   // mark the location undef: we know it was supposed to receive a new location
3182   // here, but that computation has been sunk.
3183   SmallVector<DbgVariableIntrinsic *, 2> DbgUsers;
3184   findDbgUsers(DbgUsers, I);
3185   for (auto *DII : reverse(DbgUsers)) {
3186     if (DII->getParent() == SrcBlock) {
3187       if (isa<DbgDeclareInst>(DII)) {
3188         // A dbg.declare instruction should not be cloned, since there can only be
3189         // one per variable fragment. It should be left in the original place since
3190         // sunk instruction is not an alloca(otherwise we could not be here).
3191         // But we need to update arguments of dbg.declare instruction, so that it
3192         // would not point into sunk instruction.
3193         if (!isa<CastInst>(I))
3194           continue; // dbg.declare points at something it shouldn't
3195 
3196         DII->setOperand(
3197             0, MetadataAsValue::get(I->getContext(),
3198                                     ValueAsMetadata::get(I->getOperand(0))));
3199         continue;
3200       }
3201 
3202       // dbg.value is in the same basic block as the sunk inst, see if we can
3203       // salvage it. Clone a new copy of the instruction: on success we need
3204       // both salvaged and unsalvaged copies.
3205       SmallVector<DbgVariableIntrinsic *, 1> TmpUser{
3206           cast<DbgVariableIntrinsic>(DII->clone())};
3207 
3208       if (!salvageDebugInfoForDbgValues(*I, TmpUser)) {
3209         // We are unable to salvage: sink the cloned dbg.value, and mark the
3210         // original as undef, terminating any earlier variable location.
3211         LLVM_DEBUG(dbgs() << "SINK: " << *DII << '\n');
3212         TmpUser[0]->insertBefore(&*InsertPos);
3213         Value *Undef = UndefValue::get(I->getType());
3214         DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
3215                                                 ValueAsMetadata::get(Undef)));
3216       } else {
3217         // We successfully salvaged: place the salvaged dbg.value in the
3218         // original location, and move the unmodified dbg.value to sink with
3219         // the sunk inst.
3220         TmpUser[0]->insertBefore(DII);
3221         DII->moveBefore(&*InsertPos);
3222       }
3223     }
3224   }
3225   return true;
3226 }
3227 
3228 bool InstCombiner::run() {
3229   while (!Worklist.isEmpty()) {
3230     Instruction *I = Worklist.RemoveOne();
3231     if (I == nullptr) continue;  // skip null values.
3232 
3233     // Check to see if we can DCE the instruction.
3234     if (isInstructionTriviallyDead(I, &TLI)) {
3235       LLVM_DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
3236       eraseInstFromFunction(*I);
3237       ++NumDeadInst;
3238       MadeIRChange = true;
3239       continue;
3240     }
3241 
3242     if (!DebugCounter::shouldExecute(VisitCounter))
3243       continue;
3244 
3245     // Instruction isn't dead, see if we can constant propagate it.
3246     if (!I->use_empty() &&
3247         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
3248       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
3249         LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I
3250                           << '\n');
3251 
3252         // Add operands to the worklist.
3253         replaceInstUsesWith(*I, C);
3254         ++NumConstProp;
3255         if (isInstructionTriviallyDead(I, &TLI))
3256           eraseInstFromFunction(*I);
3257         MadeIRChange = true;
3258         continue;
3259       }
3260     }
3261 
3262     // In general, it is possible for computeKnownBits to determine all bits in
3263     // a value even when the operands are not all constants.
3264     Type *Ty = I->getType();
3265     if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
3266       KnownBits Known = computeKnownBits(I, /*Depth*/0, I);
3267       if (Known.isConstant()) {
3268         Constant *C = ConstantInt::get(Ty, Known.getConstant());
3269         LLVM_DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C
3270                           << " from: " << *I << '\n');
3271 
3272         // Add operands to the worklist.
3273         replaceInstUsesWith(*I, C);
3274         ++NumConstProp;
3275         if (isInstructionTriviallyDead(I, &TLI))
3276           eraseInstFromFunction(*I);
3277         MadeIRChange = true;
3278         continue;
3279       }
3280     }
3281 
3282     // See if we can trivially sink this instruction to a successor basic block.
3283     if (EnableCodeSinking && I->hasOneUse()) {
3284       BasicBlock *BB = I->getParent();
3285       Instruction *UserInst = cast<Instruction>(*I->user_begin());
3286       BasicBlock *UserParent;
3287 
3288       // Get the block the use occurs in.
3289       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3290         UserParent = PN->getIncomingBlock(*I->use_begin());
3291       else
3292         UserParent = UserInst->getParent();
3293 
3294       if (UserParent != BB) {
3295         bool UserIsSuccessor = false;
3296         // See if the user is one of our successors.
3297         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3298           if (*SI == UserParent) {
3299             UserIsSuccessor = true;
3300             break;
3301           }
3302 
3303         // If the user is one of our immediate successors, and if that successor
3304         // only has us as a predecessors (we'd have to split the critical edge
3305         // otherwise), we can keep going.
3306         if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3307           // Okay, the CFG is simple enough, try to sink this instruction.
3308           if (TryToSinkInstruction(I, UserParent, Builder)) {
3309             LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
3310             MadeIRChange = true;
3311             // We'll add uses of the sunk instruction below, but since sinking
3312             // can expose opportunities for it's *operands* add them to the
3313             // worklist
3314             for (Use &U : I->operands())
3315               if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3316                 Worklist.Add(OpI);
3317           }
3318         }
3319       }
3320     }
3321 
3322     // Now that we have an instruction, try combining it to simplify it.
3323     Builder.SetInsertPoint(I);
3324     Builder.SetCurrentDebugLocation(I->getDebugLoc());
3325 
3326 #ifndef NDEBUG
3327     std::string OrigI;
3328 #endif
3329     LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3330     LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3331 
3332     if (Instruction *Result = visit(*I)) {
3333       ++NumCombined;
3334       // Should we replace the old instruction with a new one?
3335       if (Result != I) {
3336         LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3337                           << "    New = " << *Result << '\n');
3338 
3339         if (I->getDebugLoc())
3340           Result->setDebugLoc(I->getDebugLoc());
3341         // Everything uses the new instruction now.
3342         I->replaceAllUsesWith(Result);
3343 
3344         // Move the name to the new instruction first.
3345         Result->takeName(I);
3346 
3347         // Push the new instruction and any users onto the worklist.
3348         Worklist.AddUsersToWorkList(*Result);
3349         Worklist.Add(Result);
3350 
3351         // Insert the new instruction into the basic block...
3352         BasicBlock *InstParent = I->getParent();
3353         BasicBlock::iterator InsertPos = I->getIterator();
3354 
3355         // If we replace a PHI with something that isn't a PHI, fix up the
3356         // insertion point.
3357         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3358           InsertPos = InstParent->getFirstInsertionPt();
3359 
3360         InstParent->getInstList().insert(InsertPos, Result);
3361 
3362         eraseInstFromFunction(*I);
3363       } else {
3364         LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3365                           << "    New = " << *I << '\n');
3366 
3367         // If the instruction was modified, it's possible that it is now dead.
3368         // if so, remove it.
3369         if (isInstructionTriviallyDead(I, &TLI)) {
3370           eraseInstFromFunction(*I);
3371         } else {
3372           Worklist.AddUsersToWorkList(*I);
3373           Worklist.Add(I);
3374         }
3375       }
3376       MadeIRChange = true;
3377     }
3378   }
3379 
3380   Worklist.Zap();
3381   return MadeIRChange;
3382 }
3383 
3384 /// Walk the function in depth-first order, adding all reachable code to the
3385 /// worklist.
3386 ///
3387 /// This has a couple of tricks to make the code faster and more powerful.  In
3388 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3389 /// them to the worklist (this significantly speeds up instcombine on code where
3390 /// many instructions are dead or constant).  Additionally, if we find a branch
3391 /// whose condition is a known constant, we only visit the reachable successors.
3392 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
3393                                        SmallPtrSetImpl<BasicBlock *> &Visited,
3394                                        InstCombineWorklist &ICWorklist,
3395                                        const TargetLibraryInfo *TLI) {
3396   bool MadeIRChange = false;
3397   SmallVector<BasicBlock*, 256> Worklist;
3398   Worklist.push_back(BB);
3399 
3400   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3401   DenseMap<Constant *, Constant *> FoldedConstants;
3402 
3403   do {
3404     BB = Worklist.pop_back_val();
3405 
3406     // We have now visited this block!  If we've already been here, ignore it.
3407     if (!Visited.insert(BB).second)
3408       continue;
3409 
3410     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3411       Instruction *Inst = &*BBI++;
3412 
3413       // DCE instruction if trivially dead.
3414       if (isInstructionTriviallyDead(Inst, TLI)) {
3415         ++NumDeadInst;
3416         LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3417         if (!salvageDebugInfo(*Inst))
3418           replaceDbgUsesWithUndef(Inst);
3419         Inst->eraseFromParent();
3420         MadeIRChange = true;
3421         continue;
3422       }
3423 
3424       // ConstantProp instruction if trivially constant.
3425       if (!Inst->use_empty() &&
3426           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3427         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3428           LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst
3429                             << '\n');
3430           Inst->replaceAllUsesWith(C);
3431           ++NumConstProp;
3432           if (isInstructionTriviallyDead(Inst, TLI))
3433             Inst->eraseFromParent();
3434           MadeIRChange = true;
3435           continue;
3436         }
3437 
3438       // See if we can constant fold its operands.
3439       for (Use &U : Inst->operands()) {
3440         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3441           continue;
3442 
3443         auto *C = cast<Constant>(U);
3444         Constant *&FoldRes = FoldedConstants[C];
3445         if (!FoldRes)
3446           FoldRes = ConstantFoldConstant(C, DL, TLI);
3447         if (!FoldRes)
3448           FoldRes = C;
3449 
3450         if (FoldRes != C) {
3451           LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3452                             << "\n    Old = " << *C
3453                             << "\n    New = " << *FoldRes << '\n');
3454           U = FoldRes;
3455           MadeIRChange = true;
3456         }
3457       }
3458 
3459       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3460       // consumes non-trivial amount of time and provides no value for the optimization.
3461       if (!isa<DbgInfoIntrinsic>(Inst))
3462         InstrsForInstCombineWorklist.push_back(Inst);
3463     }
3464 
3465     // Recursively visit successors.  If this is a branch or switch on a
3466     // constant, only visit the reachable successor.
3467     Instruction *TI = BB->getTerminator();
3468     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3469       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3470         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3471         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3472         Worklist.push_back(ReachableBB);
3473         continue;
3474       }
3475     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3476       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3477         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3478         continue;
3479       }
3480     }
3481 
3482     for (BasicBlock *SuccBB : successors(TI))
3483       Worklist.push_back(SuccBB);
3484   } while (!Worklist.empty());
3485 
3486   // Once we've found all of the instructions to add to instcombine's worklist,
3487   // add them in reverse order.  This way instcombine will visit from the top
3488   // of the function down.  This jives well with the way that it adds all uses
3489   // of instructions to the worklist after doing a transformation, thus avoiding
3490   // some N^2 behavior in pathological cases.
3491   ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3492 
3493   return MadeIRChange;
3494 }
3495 
3496 /// Populate the IC worklist from a function, and prune any dead basic
3497 /// blocks discovered in the process.
3498 ///
3499 /// This also does basic constant propagation and other forward fixing to make
3500 /// the combiner itself run much faster.
3501 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3502                                           TargetLibraryInfo *TLI,
3503                                           InstCombineWorklist &ICWorklist) {
3504   bool MadeIRChange = false;
3505 
3506   // Do a depth-first traversal of the function, populate the worklist with
3507   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3508   // track of which blocks we visit.
3509   SmallPtrSet<BasicBlock *, 32> Visited;
3510   MadeIRChange |=
3511       AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3512 
3513   // Do a quick scan over the function.  If we find any blocks that are
3514   // unreachable, remove any instructions inside of them.  This prevents
3515   // the instcombine code from having to deal with some bad special cases.
3516   for (BasicBlock &BB : F) {
3517     if (Visited.count(&BB))
3518       continue;
3519 
3520     unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3521     MadeIRChange |= NumDeadInstInBB > 0;
3522     NumDeadInst += NumDeadInstInBB;
3523   }
3524 
3525   return MadeIRChange;
3526 }
3527 
3528 static bool combineInstructionsOverFunction(
3529     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3530     AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
3531     OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
3532     ProfileSummaryInfo *PSI, bool ExpensiveCombines = true,
3533     LoopInfo *LI = nullptr) {
3534   auto &DL = F.getParent()->getDataLayout();
3535   ExpensiveCombines |= EnableExpensiveCombines;
3536 
3537   /// Builder - This is an IRBuilder that automatically inserts new
3538   /// instructions into the worklist when they are created.
3539   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3540       F.getContext(), TargetFolder(DL),
3541       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3542         Worklist.Add(I);
3543         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3544           AC.registerAssumption(cast<CallInst>(I));
3545       }));
3546 
3547   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3548   // by instcombiner.
3549   bool MadeIRChange = false;
3550   if (ShouldLowerDbgDeclare)
3551     MadeIRChange = LowerDbgDeclare(F);
3552 
3553   // Iterate while there is work to do.
3554   int Iteration = 0;
3555   while (true) {
3556     ++Iteration;
3557     LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3558                       << F.getName() << "\n");
3559 
3560     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3561 
3562     InstCombiner IC(Worklist, Builder, F.hasMinSize(), ExpensiveCombines, AA,
3563                     AC, TLI, DT, ORE, BFI, PSI, DL, LI);
3564     IC.MaxArraySizeForCombine = MaxArraySize;
3565 
3566     if (!IC.run())
3567       break;
3568   }
3569 
3570   return MadeIRChange || Iteration > 1;
3571 }
3572 
3573 PreservedAnalyses InstCombinePass::run(Function &F,
3574                                        FunctionAnalysisManager &AM) {
3575   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3576   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3577   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3578   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3579 
3580   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3581 
3582   auto *AA = &AM.getResult<AAManager>(F);
3583   const ModuleAnalysisManager &MAM =
3584       AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
3585   ProfileSummaryInfo *PSI =
3586       MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3587   auto *BFI = (PSI && PSI->hasProfileSummary()) ?
3588       &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
3589 
3590   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3591                                        BFI, PSI, ExpensiveCombines, LI))
3592     // No changes, all analyses are preserved.
3593     return PreservedAnalyses::all();
3594 
3595   // Mark all the analyses that instcombine updates as preserved.
3596   PreservedAnalyses PA;
3597   PA.preserveSet<CFGAnalyses>();
3598   PA.preserve<AAManager>();
3599   PA.preserve<BasicAA>();
3600   PA.preserve<GlobalsAA>();
3601   return PA;
3602 }
3603 
3604 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3605   AU.setPreservesCFG();
3606   AU.addRequired<AAResultsWrapperPass>();
3607   AU.addRequired<AssumptionCacheTracker>();
3608   AU.addRequired<TargetLibraryInfoWrapperPass>();
3609   AU.addRequired<DominatorTreeWrapperPass>();
3610   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3611   AU.addPreserved<DominatorTreeWrapperPass>();
3612   AU.addPreserved<AAResultsWrapperPass>();
3613   AU.addPreserved<BasicAAWrapperPass>();
3614   AU.addPreserved<GlobalsAAWrapperPass>();
3615   AU.addRequired<ProfileSummaryInfoWrapperPass>();
3616   LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
3617 }
3618 
3619 bool InstructionCombiningPass::runOnFunction(Function &F) {
3620   if (skipFunction(F))
3621     return false;
3622 
3623   // Required analyses.
3624   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3625   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3626   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
3627   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3628   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3629 
3630   // Optional analyses.
3631   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3632   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3633   ProfileSummaryInfo *PSI =
3634       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3635   BlockFrequencyInfo *BFI =
3636       (PSI && PSI->hasProfileSummary()) ?
3637       &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
3638       nullptr;
3639 
3640   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3641                                          BFI, PSI, ExpensiveCombines, LI);
3642 }
3643 
3644 char InstructionCombiningPass::ID = 0;
3645 
3646 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3647                       "Combine redundant instructions", false, false)
3648 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3649 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3650 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3651 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3652 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3653 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3654 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
3655 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
3656 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3657                     "Combine redundant instructions", false, false)
3658 
3659 // Initialization Routines
3660 void llvm::initializeInstCombine(PassRegistry &Registry) {
3661   initializeInstructionCombiningPassPass(Registry);
3662 }
3663 
3664 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3665   initializeInstructionCombiningPassPass(*unwrap(R));
3666 }
3667 
3668 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3669   return new InstructionCombiningPass(ExpensiveCombines);
3670 }
3671 
3672 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) {
3673   unwrap(PM)->add(createInstructionCombiningPass());
3674 }
3675