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