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