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