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