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