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