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