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