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