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