blob: 75fec3e79d36b0e243ce34b8e45abc04c9b02bf2 [file] [log] [blame]
Chandler Carrutha9174582015-01-22 05:25:13 +00001//===- InstCombineInternal.h - InstCombine pass internals -------*- C++ -*-===//
Chris Lattner35522b72010-01-04 07:12:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00009//
Chandler Carrutha9174582015-01-22 05:25:13 +000010/// \file
11///
12/// This file provides internal interfaces used to implement the InstCombine.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000013//
Chandler Carrutha9174582015-01-22 05:25:13 +000014//===----------------------------------------------------------------------===//
Chris Lattner35522b72010-01-04 07:12:23 +000015
Chandler Carrutha9174582015-01-22 05:25:13 +000016#ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
17#define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
Chris Lattner35522b72010-01-04 07:12:23 +000018
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/ArrayRef.h"
Bjorn Steinbrink83505342015-07-10 06:55:49 +000020#include "llvm/Analysis/AliasAnalysis.h"
Daniel Berlin2c75c632017-04-26 20:56:07 +000021#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth452a0072014-03-04 11:59:06 +000022#include "llvm/Analysis/TargetFolder.h"
David Blaikie31b98d22018-06-04 21:23:21 +000023#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth802d7552012-12-04 07:12:27 +000024#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000025#include "llvm/IR/Argument.h"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/Constant.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DerivedTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000031#include "llvm/IR/InstVisitor.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000032#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000035#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Use.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Support/Casting.h"
39#include "llvm/Support/Compiler.h"
40#include "llvm/Support/Debug.h"
Craig Topper1a36b7d2017-05-15 06:39:41 +000041#include "llvm/Support/KnownBits.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000043#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000044#include <cassert>
45#include <cstdint>
Chris Lattner35522b72010-01-04 07:12:23 +000046
Chandler Carruth964daaa2014-04-22 02:55:47 +000047#define DEBUG_TYPE "instcombine"
48
Chris Lattner35522b72010-01-04 07:12:23 +000049namespace llvm {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000050
51class APInt;
52class AssumptionCache;
Chandler Carruthd70cc602014-05-07 17:36:59 +000053class CallSite;
54class DataLayout;
Hal Finkel60db0582014-09-07 18:57:58 +000055class DominatorTree;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000056class GEPOperator;
57class GlobalVariable;
58class LoopInfo;
Adam Nemetea06e6e2017-07-26 19:03:18 +000059class OptimizationRemarkEmitter;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000060class TargetLibraryInfo;
61class User;
Jakub Staszak190db2f2013-01-14 23:16:36 +000062
Sanjay Patel73fc8dd2017-02-03 21:43:34 +000063/// Assign a complexity or rank value to LLVM Values. This is used to reduce
64/// the amount of pattern matching needed for compares and commutative
65/// instructions. For example, if we have:
66/// icmp ugt X, Constant
67/// or
68/// xor (add X, Constant), cast Z
69///
70/// We do not have to consider the commuted variants of these patterns because
71/// canonicalization based on complexity guarantees the above ordering.
Chandler Carruth3a622162015-01-20 19:27:58 +000072///
73/// This routine maps IR values to various complexity ranks:
74/// 0 -> undef
75/// 1 -> Constants
76/// 2 -> Other non-instructions
77/// 3 -> Arguments
Sanjay Patel73fc8dd2017-02-03 21:43:34 +000078/// 4 -> Cast and (f)neg/not instructions
79/// 5 -> Other instructions
Chris Lattner2188e402010-01-04 07:37:31 +000080static inline unsigned getComplexity(Value *V) {
81 if (isa<Instruction>(V)) {
Sanjay Patel73fc8dd2017-02-03 21:43:34 +000082 if (isa<CastInst>(V) || BinaryOperator::isNeg(V) ||
83 BinaryOperator::isFNeg(V) || BinaryOperator::isNot(V))
84 return 4;
85 return 5;
Chris Lattner2188e402010-01-04 07:37:31 +000086 }
Chandler Carruthd70cc602014-05-07 17:36:59 +000087 if (isa<Argument>(V))
88 return 3;
Chris Lattner2188e402010-01-04 07:37:31 +000089 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
90}
Chris Lattner35522b72010-01-04 07:12:23 +000091
Sanjay Patelb2e70032017-05-17 14:21:19 +000092/// Predicate canonicalization reduces the number of patterns that need to be
93/// matched by other transforms. For example, we may swap the operands of a
94/// conditional branch or select to create a compare with a canonical (inverted)
95/// predicate which is then more likely to be matched with other values.
96static inline bool isCanonicalPredicate(CmpInst::Predicate Pred) {
97 switch (Pred) {
98 case CmpInst::ICMP_NE:
99 case CmpInst::ICMP_ULE:
100 case CmpInst::ICMP_SLE:
101 case CmpInst::ICMP_UGE:
102 case CmpInst::ICMP_SGE:
103 // TODO: There are 16 FCMP predicates. Should others be (not) canonical?
104 case CmpInst::FCMP_ONE:
105 case CmpInst::FCMP_OLE:
106 case CmpInst::FCMP_OGE:
107 return false;
108 default:
109 return true;
110 }
111}
112
Sanjay Patele800df8e2017-06-22 15:28:01 +0000113/// Return the source operand of a potentially bitcasted value while optionally
114/// checking if it has one use. If there is no bitcast or the one use check is
115/// not met, return the input value itself.
116static inline Value *peekThroughBitcast(Value *V, bool OneUseOnly = false) {
117 if (auto *BitCast = dyn_cast<BitCastInst>(V))
118 if (!OneUseOnly || BitCast->hasOneUse())
119 return BitCast->getOperand(0);
120
121 // V is not a bitcast or V has more than one use and OneUseOnly is true.
122 return V;
123}
124
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000125/// Add one to a Constant
Benjamin Kramer970f4952014-01-19 16:56:10 +0000126static inline Constant *AddOne(Constant *C) {
127 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
128}
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000129
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000130/// Subtract one from a Constant
Benjamin Kramer970f4952014-01-19 16:56:10 +0000131static inline Constant *SubOne(Constant *C) {
132 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
133}
134
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000135/// Return true if the specified value is free to invert (apply ~ to).
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000136/// This happens in cases where the ~ can be eliminated. If WillInvertAllUses
137/// is true, work under the assumption that the caller intends to remove all
138/// uses of V and only keep uses of ~V.
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000139static inline bool IsFreeToInvert(Value *V, bool WillInvertAllUses) {
140 // ~(~(X)) -> X.
141 if (BinaryOperator::isNot(V))
142 return true;
143
144 // Constants can be considered to be not'ed values.
145 if (isa<ConstantInt>(V))
146 return true;
147
Sanjay Patel611f9f92016-10-27 17:30:50 +0000148 // A vector of constant integers can be inverted easily.
Craig Topperbcf511c2017-06-30 21:09:34 +0000149 if (V->getType()->isVectorTy() && isa<Constant>(V)) {
Sanjay Patel611f9f92016-10-27 17:30:50 +0000150 unsigned NumElts = V->getType()->getVectorNumElements();
151 for (unsigned i = 0; i != NumElts; ++i) {
Craig Topperbcf511c2017-06-30 21:09:34 +0000152 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
Sanjay Patel611f9f92016-10-27 17:30:50 +0000153 if (!Elt)
154 return false;
155
156 if (isa<UndefValue>(Elt))
157 continue;
158
159 if (!isa<ConstantInt>(Elt))
160 return false;
161 }
162 return true;
163 }
164
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000165 // Compares can be inverted if all of their uses are being modified to use the
166 // ~V.
167 if (isa<CmpInst>(V))
168 return WillInvertAllUses;
169
170 // If `V` is of the form `A + Constant` then `-1 - V` can be folded into `(-1
171 // - Constant) - A` if we are willing to invert all of the uses.
172 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
173 if (BO->getOpcode() == Instruction::Add ||
174 BO->getOpcode() == Instruction::Sub)
175 if (isa<Constant>(BO->getOperand(0)) || isa<Constant>(BO->getOperand(1)))
176 return WillInvertAllUses;
177
178 return false;
179}
180
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000181/// Specific patterns of overflow check idioms that we match.
Sanjoy Dasb0984472015-04-08 04:27:22 +0000182enum OverflowCheckFlavor {
183 OCF_UNSIGNED_ADD,
184 OCF_SIGNED_ADD,
185 OCF_UNSIGNED_SUB,
186 OCF_SIGNED_SUB,
187 OCF_UNSIGNED_MUL,
188 OCF_SIGNED_MUL,
189
190 OCF_INVALID
191};
192
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000193/// Returns the OverflowCheckFlavor corresponding to a overflow_with_op
Sanjoy Dasb0984472015-04-08 04:27:22 +0000194/// intrinsic.
195static inline OverflowCheckFlavor
196IntrinsicIDToOverflowCheckFlavor(unsigned ID) {
197 switch (ID) {
198 default:
199 return OCF_INVALID;
200 case Intrinsic::uadd_with_overflow:
201 return OCF_UNSIGNED_ADD;
202 case Intrinsic::sadd_with_overflow:
203 return OCF_SIGNED_ADD;
204 case Intrinsic::usub_with_overflow:
205 return OCF_UNSIGNED_SUB;
206 case Intrinsic::ssub_with_overflow:
207 return OCF_SIGNED_SUB;
208 case Intrinsic::umul_with_overflow:
209 return OCF_UNSIGNED_MUL;
210 case Intrinsic::smul_with_overflow:
211 return OCF_SIGNED_MUL;
212 }
213}
214
Sanjay Patel3e5c0512018-06-21 14:59:35 +0000215/// Integer division/remainder require special handling to avoid undefined
216/// behavior. If a constant vector has undef elements, replace those undefs with
217/// '1' because that's always safe to execute.
218static inline Constant *getSafeVectorConstantForIntDivRem(Constant *In) {
219 assert(In->getType()->isVectorTy() && "Not expecting scalars here");
220 assert(In->getType()->getVectorElementType()->isIntegerTy() &&
221 "Not expecting FP opcodes/operands/constants here");
222
223 unsigned NumElts = In->getType()->getVectorNumElements();
224 SmallVector<Constant *, 16> Out(NumElts);
225 for (unsigned i = 0; i != NumElts; ++i) {
226 Constant *C = In->getAggregateElement(i);
227 Out[i] = isa<UndefValue>(C) ? ConstantInt::get(C->getType(), 1) : C;
228 }
229 return ConstantVector::get(Out);
230}
231
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000232/// The core instruction combiner logic.
Chandler Carruth3a622162015-01-20 19:27:58 +0000233///
234/// This class provides both the logic to recursively visit instructions and
Craig Topper28ec3462016-12-28 03:12:42 +0000235/// combine them.
Duncan Sands6c5e4352010-05-11 20:16:09 +0000236class LLVM_LIBRARY_VISIBILITY InstCombiner
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000237 : public InstVisitor<InstCombiner, Instruction *> {
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000238 // FIXME: These members shouldn't be public.
Chris Lattner35522b72010-01-04 07:12:23 +0000239public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000240 /// A worklist of the instructions that need to be simplified.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000241 InstCombineWorklist &Worklist;
Chris Lattner35522b72010-01-04 07:12:23 +0000242
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000243 /// An IRBuilder that automatically inserts new instructions into the
Chandler Carruth3a622162015-01-20 19:27:58 +0000244 /// worklist.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000245 using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
Craig Topperbb4069e2017-07-07 23:16:26 +0000246 BuilderTy &Builder;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000247
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000248private:
249 // Mode in which we are running the combiner.
250 const bool MinimizeSize;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000251
Matthias Braunc31032d2016-03-09 18:47:11 +0000252 /// Enable combines that trigger rarely but are costly in compiletime.
253 const bool ExpensiveCombines;
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000254
Bjorn Steinbrink83505342015-07-10 06:55:49 +0000255 AliasAnalysis *AA;
256
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000257 // Required analyses.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000258 AssumptionCache &AC;
Justin Bogner99798402016-08-05 01:06:44 +0000259 TargetLibraryInfo &TLI;
260 DominatorTree &DT;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000261 const DataLayout &DL;
Daniel Berlin2c75c632017-04-26 20:56:07 +0000262 const SimplifyQuery SQ;
Adam Nemetea06e6e2017-07-26 19:03:18 +0000263 OptimizationRemarkEmitter &ORE;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000264
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000265 // Optional analyses. When non-null, these can both be used to do better
266 // combining and will be updated to reflect any changes.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000267 LoopInfo *LI;
268
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000269 bool MadeIRChange = false;
Chris Lattner35522b72010-01-04 07:12:23 +0000270
271public:
Craig Topperbb4069e2017-07-07 23:16:26 +0000272 InstCombiner(InstCombineWorklist &Worklist, BuilderTy &Builder,
Matthias Braunc31032d2016-03-09 18:47:11 +0000273 bool MinimizeSize, bool ExpensiveCombines, AliasAnalysis *AA,
Daniel Berlin2c75c632017-04-26 20:56:07 +0000274 AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
Adam Nemetea06e6e2017-07-26 19:03:18 +0000275 OptimizationRemarkEmitter &ORE, const DataLayout &DL,
276 LoopInfo *LI)
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000277 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000278 ExpensiveCombines(ExpensiveCombines), AA(AA), AC(AC), TLI(TLI), DT(DT),
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000279 DL(DL), SQ(DL, &TLI, &DT, &AC), ORE(ORE), LI(LI) {}
Jakub Staszak190db2f2013-01-14 23:16:36 +0000280
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000281 /// Run the combiner over the entire worklist until it is empty.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000282 ///
283 /// \returns true if the IR is changed.
284 bool run();
Chris Lattner35522b72010-01-04 07:12:23 +0000285
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000286 AssumptionCache &getAssumptionCache() const { return AC; }
287
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288 const DataLayout &getDataLayout() const { return DL; }
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000289
Justin Bogner99798402016-08-05 01:06:44 +0000290 DominatorTree &getDominatorTree() const { return DT; }
Chris Lattner35522b72010-01-04 07:12:23 +0000291
Chandler Carruth5175b9a2015-01-20 08:35:24 +0000292 LoopInfo *getLoopInfo() const { return LI; }
293
Justin Bogner99798402016-08-05 01:06:44 +0000294 TargetLibraryInfo &getTargetLibraryInfo() const { return TLI; }
Chad Rosier43a33062011-12-02 01:26:24 +0000295
Chris Lattner35522b72010-01-04 07:12:23 +0000296 // Visitation implementation - Implement instruction combining for different
297 // instruction types. The semantics are as follows:
298 // Return Value:
299 // null - No change was made
300 // I - Change was made, I is still valid, I may be dead though
301 // otherwise - Change was made, replace I with returned instruction
302 //
303 Instruction *visitAdd(BinaryOperator &I);
304 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner229907c2011-07-18 04:54:35 +0000305 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
Chris Lattner35522b72010-01-04 07:12:23 +0000306 Instruction *visitSub(BinaryOperator &I);
307 Instruction *visitFSub(BinaryOperator &I);
308 Instruction *visitMul(BinaryOperator &I);
309 Instruction *visitFMul(BinaryOperator &I);
310 Instruction *visitURem(BinaryOperator &I);
311 Instruction *visitSRem(BinaryOperator &I);
312 Instruction *visitFRem(BinaryOperator &I);
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000313 bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000314 Instruction *commonRemTransforms(BinaryOperator &I);
315 Instruction *commonIRemTransforms(BinaryOperator &I);
316 Instruction *commonDivTransforms(BinaryOperator &I);
317 Instruction *commonIDivTransforms(BinaryOperator &I);
318 Instruction *visitUDiv(BinaryOperator &I);
319 Instruction *visitSDiv(BinaryOperator &I);
Frits van Bommel2a559512011-01-29 17:50:27 +0000320 Instruction *visitFDiv(BinaryOperator &I);
Erik Ecksteind1817522014-12-03 10:39:15 +0000321 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
Chris Lattner35522b72010-01-04 07:12:23 +0000322 Instruction *visitAnd(BinaryOperator &I);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000323 Instruction *visitOr(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000324 Instruction *visitXor(BinaryOperator &I);
325 Instruction *visitShl(BinaryOperator &I);
326 Instruction *visitAShr(BinaryOperator &I);
327 Instruction *visitLShr(BinaryOperator &I);
328 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000329 Instruction *visitFCmpInst(FCmpInst &I);
330 Instruction *visitICmpInst(ICmpInst &I);
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000331 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
Chris Lattner35522b72010-01-04 07:12:23 +0000332 BinaryOperator &I);
333 Instruction *commonCastTransforms(CastInst &CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000334 Instruction *commonPointerCastTransforms(CastInst &CI);
335 Instruction *visitTrunc(TruncInst &CI);
336 Instruction *visitZExt(ZExtInst &CI);
337 Instruction *visitSExt(SExtInst &CI);
338 Instruction *visitFPTrunc(FPTruncInst &CI);
339 Instruction *visitFPExt(CastInst &CI);
340 Instruction *visitFPToUI(FPToUIInst &FI);
341 Instruction *visitFPToSI(FPToSIInst &FI);
342 Instruction *visitUIToFP(CastInst &CI);
343 Instruction *visitSIToFP(CastInst &CI);
344 Instruction *visitPtrToInt(PtrToIntInst &CI);
345 Instruction *visitIntToPtr(IntToPtrInst &CI);
346 Instruction *visitBitCast(BitCastInst &CI);
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +0000347 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
Mehdi Aminib9a0fa42015-02-16 21:47:54 +0000348 Instruction *FoldItoFPtoI(Instruction &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000349 Instruction *visitSelectInst(SelectInst &SI);
Chris Lattner35522b72010-01-04 07:12:23 +0000350 Instruction *visitCallInst(CallInst &CI);
351 Instruction *visitInvokeInst(InvokeInst &II);
352
353 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
354 Instruction *visitPHINode(PHINode &PN);
355 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
356 Instruction *visitAllocaInst(AllocaInst &AI);
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000357 Instruction *visitAllocSite(Instruction &FI);
Gabor Greif75f69432010-06-24 12:21:15 +0000358 Instruction *visitFree(CallInst &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000359 Instruction *visitLoadInst(LoadInst &LI);
360 Instruction *visitStoreInst(StoreInst &SI);
361 Instruction *visitBranchInst(BranchInst &BI);
Davide Italianoaec46172017-01-31 18:09:05 +0000362 Instruction *visitFenceInst(FenceInst &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000363 Instruction *visitSwitchInst(SwitchInst &SI);
Hal Finkel93873cc12014-09-07 21:28:34 +0000364 Instruction *visitReturnInst(ReturnInst &RI);
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000365 Instruction *visitInsertValueInst(InsertValueInst &IV);
Chris Lattner35522b72010-01-04 07:12:23 +0000366 Instruction *visitInsertElementInst(InsertElementInst &IE);
367 Instruction *visitExtractElementInst(ExtractElementInst &EI);
368 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
369 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Duncan Sands5c055792011-09-30 13:12:16 +0000370 Instruction *visitLandingPadInst(LandingPadInst &LI);
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +0000371 Instruction *visitVAStartInst(VAStartInst &I);
372 Instruction *visitVACopyInst(VACopyInst &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000373
Sanjay Patel53523312016-09-12 14:25:46 +0000374 /// Specify what to return for unhandled instructions.
Craig Toppere73658d2014-04-28 04:05:08 +0000375 Instruction *visitInstruction(Instruction &I) { return nullptr; }
Chris Lattner35522b72010-01-04 07:12:23 +0000376
Sanjay Patel53523312016-09-12 14:25:46 +0000377 /// True when DB dominates all uses of DI except UI.
378 /// UI must be in the same block as DI.
379 /// The routine checks that the DI parent and DB are different.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +0000380 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
381 const BasicBlock *DB) const;
382
Sanjay Patel53523312016-09-12 14:25:46 +0000383 /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +0000384 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
385 const unsigned SIOpd);
386
Yaxun Liuba01ed02017-02-10 21:46:07 +0000387 /// Try to replace instruction \p I with value \p V which are pointers
388 /// in different address space.
389 /// \return true if successful.
390 bool replacePointer(Instruction &I, Value *V);
391
Chris Lattner35522b72010-01-04 07:12:23 +0000392private:
Sanjay Patel2217f752017-01-31 17:25:42 +0000393 bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
394 bool shouldChangeType(Type *From, Type *To) const;
Chris Lattner2188e402010-01-04 07:37:31 +0000395 Value *dyn_castNegVal(Value *V) const;
David Blaikie87ca1b62015-03-27 20:56:11 +0000396 Type *FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Chandler Carruthd70cc602014-05-07 17:36:59 +0000397 SmallVectorImpl<Value *> &NewIndices);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000398
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000399 /// Classify whether a cast is worth optimizing.
Chandler Carruth3a622162015-01-20 19:27:58 +0000400 ///
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000401 /// This is a helper to decide whether the simplification of
402 /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
403 ///
404 /// \param CI The cast we are interested in.
405 ///
406 /// \return true if this cast actually results in any code being generated and
407 /// if it cannot already be eliminated by some other transformation.
408 bool shouldOptimizeCast(CastInst *CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000409
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000410 /// Try to optimize a sequence of instructions checking if an operation
Sanjoy Dasb0984472015-04-08 04:27:22 +0000411 /// on LHS and RHS overflows.
412 ///
Sanjoy Das6f5dca72015-08-28 19:09:31 +0000413 /// If this overflow check is done via one of the overflow check intrinsics,
414 /// then CtxI has to be the call instruction calling that intrinsic. If this
415 /// overflow check is done by arithmetic followed by a compare, then CtxI has
416 /// to be the arithmetic instruction.
417 ///
Sanjoy Dasb0984472015-04-08 04:27:22 +0000418 /// If a simplification is possible, stores the simplified result of the
419 /// operation in OperationResult and result of the overflow check in
420 /// OverflowResult, and return true. If no simplification is possible,
421 /// returns false.
422 bool OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, Value *RHS,
423 Instruction &CtxI, Value *&OperationResult,
424 Constant *&OverflowResult);
425
Chris Lattner35522b72010-01-04 07:12:23 +0000426 Instruction *visitCallSite(CallSite CS);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000427 Instruction *tryOptimizeCall(CallInst *CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000428 bool transformConstExprCastCall(CallSite CS);
Duncan Sandsa0984362011-09-06 13:37:06 +0000429 Instruction *transformCallThroughTrampoline(CallSite CS,
430 IntrinsicInst *Tramp);
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000431
432 /// Transform (zext icmp) to bitwise / integer operations in order to
433 /// eliminate it.
434 ///
435 /// \param ICI The icmp of the (zext icmp) pair we are interested in.
436 /// \parem CI The zext of the (zext icmp) pair we are interested in.
437 /// \param DoTransform Pass false to just test whether the given (zext icmp)
438 /// would be transformed. Pass true to actually perform the transformation.
439 ///
440 /// \return null if the transformation cannot be performed. If the
441 /// transformation can be performed the new instruction that replaces the
442 /// (zext icmp) pair will be returned (if \p DoTransform is false the
443 /// unmodified \p ICI will be returned in this case).
444 Instruction *transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
445 bool DoTransform = true);
446
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000447 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000448
Craig Topper2b1fc322017-05-22 06:25:31 +0000449 bool willNotOverflowSignedAdd(const Value *LHS, const Value *RHS,
450 const Instruction &CxtI) const {
Craig Topperbb973722017-05-15 02:44:08 +0000451 return computeOverflowForSignedAdd(LHS, RHS, &CxtI) ==
452 OverflowResult::NeverOverflows;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000453 }
454
Craig Topper2b1fc322017-05-22 06:25:31 +0000455 bool willNotOverflowUnsignedAdd(const Value *LHS, const Value *RHS,
456 const Instruction &CxtI) const {
Craig Topperbb973722017-05-15 02:44:08 +0000457 return computeOverflowForUnsignedAdd(LHS, RHS, &CxtI) ==
458 OverflowResult::NeverOverflows;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000459 }
460
Craig Topper2b1fc322017-05-22 06:25:31 +0000461 bool willNotOverflowSignedSub(const Value *LHS, const Value *RHS,
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000462 const Instruction &CxtI) const {
463 return computeOverflowForSignedSub(LHS, RHS, &CxtI) ==
464 OverflowResult::NeverOverflows;
465 }
466
Craig Topper2b1fc322017-05-22 06:25:31 +0000467 bool willNotOverflowUnsignedSub(const Value *LHS, const Value *RHS,
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000468 const Instruction &CxtI) const {
469 return computeOverflowForUnsignedSub(LHS, RHS, &CxtI) ==
470 OverflowResult::NeverOverflows;
471 }
472
Craig Topper2b1fc322017-05-22 06:25:31 +0000473 bool willNotOverflowSignedMul(const Value *LHS, const Value *RHS,
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000474 const Instruction &CxtI) const {
475 return computeOverflowForSignedMul(LHS, RHS, &CxtI) ==
476 OverflowResult::NeverOverflows;
477 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000478
Craig Topper2b1fc322017-05-22 06:25:31 +0000479 bool willNotOverflowUnsignedMul(const Value *LHS, const Value *RHS,
480 const Instruction &CxtI) const {
Craig Topperbb973722017-05-15 02:44:08 +0000481 return computeOverflowForUnsignedMul(LHS, RHS, &CxtI) ==
482 OverflowResult::NeverOverflows;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000483 }
484
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000485 Value *EmitGEPOffset(User *GEP);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000486 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000487 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
Sanjay Patel40e7ba02016-02-23 16:36:07 +0000488 Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
Sanjay Patel94da1de2017-08-05 15:19:18 +0000489 Instruction *narrowBinOp(TruncInst &Trunc);
Sanjay Patel1d681122018-01-25 16:34:36 +0000490 Instruction *narrowMaskedBinOp(BinaryOperator &And);
Sanjay Patelc50e55d2017-08-09 18:37:41 +0000491 Instruction *narrowRotate(TruncInst &Trunc);
Guozhi Weiae541f62016-10-25 20:43:42 +0000492 Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000493
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000494 /// Determine if a pair of casts can be replaced by a single cast.
495 ///
496 /// \param CI1 The first of a pair of casts.
497 /// \param CI2 The second of a pair of casts.
498 ///
499 /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
500 /// Instruction::CastOps value for a cast that can replace the pair, casting
501 /// CI1->getSrcTy() to CI2->getDstTy().
502 ///
503 /// \see CastInst::isEliminableCastPair
504 Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
505 const CastInst *CI2);
506
Craig Topperda6ea0d2017-06-16 05:10:37 +0000507 Value *foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction &CxtI);
Craig Topperf2d3e6d2017-06-15 19:09:51 +0000508 Value *foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction &CxtI);
Sanjay Patel5e456b92017-05-18 20:53:16 +0000509 Value *foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS);
510
Sanjay Patel64fc5da2017-09-02 17:53:33 +0000511 /// Optimize (fcmp)&(fcmp) or (fcmp)|(fcmp).
512 /// NOTE: Unlike most of instcombine, this returns a Value which should
513 /// already be inserted into the function.
514 Value *foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd);
515
Craig Topperda6ea0d2017-06-16 05:10:37 +0000516 Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
517 bool JoinedByAnd, Instruction &CxtI);
Chris Lattner35522b72010-01-04 07:12:23 +0000518public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000519 /// Inserts an instruction \p New before instruction \p Old
Chandler Carruth3a622162015-01-20 19:27:58 +0000520 ///
521 /// Also adds the new instruction to the worklist and returns \p New so that
522 /// it is suitable for use as the return from the visitation patterns.
Chris Lattner35522b72010-01-04 07:12:23 +0000523 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Craig Toppere73658d2014-04-28 04:05:08 +0000524 assert(New && !New->getParent() &&
Chris Lattner35522b72010-01-04 07:12:23 +0000525 "New instruction already inserted into a basic block!");
526 BasicBlock *BB = Old.getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000527 BB->getInstList().insert(Old.getIterator(), New); // Insert inst
Chris Lattner35522b72010-01-04 07:12:23 +0000528 Worklist.Add(New);
529 return New;
530 }
Eli Friedman6efb64e2011-05-19 01:20:42 +0000531
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000532 /// Same as InsertNewInstBefore, but also sets the debug loc.
Eli Friedman6efb64e2011-05-19 01:20:42 +0000533 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
534 New->setDebugLoc(Old.getDebugLoc());
535 return InsertNewInstBefore(New, Old);
536 }
537
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000538 /// A combiner-aware RAUW-like routine.
Chandler Carruth3a622162015-01-20 19:27:58 +0000539 ///
540 /// This method is to be used when an instruction is found to be dead,
Sanjay Patelf2ea8a22016-01-06 00:23:12 +0000541 /// replaceable with another preexisting expression. Here we add all uses of
Chandler Carruth3a622162015-01-20 19:27:58 +0000542 /// I to the worklist, replace all uses of I with the new value, then return
543 /// I, so that the inst combiner will know that I was modified.
Sanjay Patel4b198802016-02-01 22:23:39 +0000544 Instruction *replaceInstUsesWith(Instruction &I, Value *V) {
Owen Anderson51b75b8c2015-03-10 05:13:47 +0000545 // If there are no uses to replace, then we return nullptr to indicate that
546 // no changes were made to the program.
547 if (I.use_empty()) return nullptr;
548
Chandler Carruthd70cc602014-05-07 17:36:59 +0000549 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000550
Chris Lattner35522b72010-01-04 07:12:23 +0000551 // If we are replacing the instruction with itself, this must be in a
552 // segment of unreachable code, so just clobber the instruction.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000553 if (&I == V)
Chris Lattner35522b72010-01-04 07:12:23 +0000554 V = UndefValue::get(I.getType());
Frits van Bommeld14d9912011-03-27 23:32:31 +0000555
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000556 LLVM_DEBUG(dbgs() << "IC: Replacing " << I << "\n"
557 << " with " << *V << '\n');
Frits van Bommeld14d9912011-03-27 23:32:31 +0000558
Chris Lattner35522b72010-01-04 07:12:23 +0000559 I.replaceAllUsesWith(V);
560 return &I;
561 }
562
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000563 /// Creates a result tuple for an overflow intrinsic \p II with a given
Sanjoy Dasb0984472015-04-08 04:27:22 +0000564 /// \p Result and a constant \p Overflow value.
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000565 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
Sanjoy Dasb0984472015-04-08 04:27:22 +0000566 Constant *Overflow) {
567 Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000568 StructType *ST = cast<StructType>(II->getType());
569 Constant *Struct = ConstantStruct::get(ST, V);
570 return InsertValueInst::Create(Struct, Result, 0);
571 }
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000572
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000573 /// Combiner aware instruction erasure.
Chandler Carruth3a622162015-01-20 19:27:58 +0000574 ///
575 /// When dealing with an instruction that has side effects or produces a void
576 /// value, we can't rely on DCE to delete the instruction. Instead, visit
577 /// methods should return the value returned by this function.
Sanjay Patel4b198802016-02-01 22:23:39 +0000578 Instruction *eraseInstFromFunction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000579 LLVM_DEBUG(dbgs() << "IC: ERASE " << I << '\n');
Adrian Prantlfa9e84e2017-03-16 20:11:54 +0000580 assert(I.use_empty() && "Cannot erase instruction that is used!");
Adrian Prantl47ea6472017-03-16 21:14:09 +0000581 salvageDebugInfo(I);
582
Chris Lattner35522b72010-01-04 07:12:23 +0000583 // Make sure that we reprocess all operands now that we reduced their
584 // use counts.
585 if (I.getNumOperands() < 8) {
Sanjay Patel8af7fbc32016-01-31 16:34:48 +0000586 for (Use &Operand : I.operands())
587 if (auto *Inst = dyn_cast<Instruction>(Operand))
588 Worklist.Add(Inst);
Chris Lattner35522b72010-01-04 07:12:23 +0000589 }
590 Worklist.Remove(&I);
591 I.eraseFromParent();
592 MadeIRChange = true;
Chandler Carruthd70cc602014-05-07 17:36:59 +0000593 return nullptr; // Don't do anything with FI
Chris Lattner35522b72010-01-04 07:12:23 +0000594 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000595
Craig Topper2b1fc322017-05-22 06:25:31 +0000596 void computeKnownBits(const Value *V, KnownBits &Known,
597 unsigned Depth, const Instruction *CxtI) const {
Craig Topper26c41592017-05-15 02:30:27 +0000598 llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000599 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000600
Craig Topper2b1fc322017-05-22 06:25:31 +0000601 KnownBits computeKnownBits(const Value *V, unsigned Depth,
602 const Instruction *CxtI) const {
Craig Topper1a36b7d2017-05-15 06:39:41 +0000603 return llvm::computeKnownBits(V, DL, Depth, &AC, CxtI, &DT);
604 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000605
Craig Topperd4039f72017-05-25 21:51:12 +0000606 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero = false,
607 unsigned Depth = 0,
608 const Instruction *CxtI = nullptr) {
609 return llvm::isKnownToBeAPowerOfTwo(V, DL, OrZero, Depth, &AC, CxtI, &DT);
610 }
611
Craig Topper2b1fc322017-05-22 06:25:31 +0000612 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth = 0,
613 const Instruction *CxtI = nullptr) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000614 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, &AC, CxtI, &DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000615 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000616
Craig Topper2b1fc322017-05-22 06:25:31 +0000617 unsigned ComputeNumSignBits(const Value *Op, unsigned Depth = 0,
618 const Instruction *CxtI = nullptr) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000619 return llvm::ComputeNumSignBits(Op, DL, Depth, &AC, CxtI, &DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000620 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000621
Craig Topper2b1fc322017-05-22 06:25:31 +0000622 OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
623 const Value *RHS,
624 const Instruction *CxtI) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000625 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
David Majnemer491331a2015-01-02 07:29:43 +0000626 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000627
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000628 OverflowResult computeOverflowForSignedMul(const Value *LHS,
629 const Value *RHS,
630 const Instruction *CxtI) const {
631 return llvm::computeOverflowForSignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
632 }
633
Craig Topper2b1fc322017-05-22 06:25:31 +0000634 OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
635 const Value *RHS,
636 const Instruction *CxtI) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000637 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
David Majnemer5310c1e2015-01-07 00:39:50 +0000638 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000639
Craig Topperbb973722017-05-15 02:44:08 +0000640 OverflowResult computeOverflowForSignedAdd(const Value *LHS,
641 const Value *RHS,
642 const Instruction *CxtI) const {
643 return llvm::computeOverflowForSignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
644 }
Chris Lattner35522b72010-01-04 07:12:23 +0000645
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000646 OverflowResult computeOverflowForUnsignedSub(const Value *LHS,
647 const Value *RHS,
648 const Instruction *CxtI) const {
649 return llvm::computeOverflowForUnsignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
650 }
651
652 OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
653 const Instruction *CxtI) const {
654 return llvm::computeOverflowForSignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
655 }
656
Davide Italiano2133bf52017-02-07 17:56:50 +0000657 /// Maximum size of array considered when transforming.
David Blaikie4c01af22017-02-07 18:58:17 +0000658 uint64_t MaxArraySizeForCombine;
Davide Italiano2133bf52017-02-07 17:56:50 +0000659
Chris Lattner35522b72010-01-04 07:12:23 +0000660private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000661 /// Performs a few simplifications for operators which are associative
Chandler Carruth3a622162015-01-20 19:27:58 +0000662 /// or commutative.
Duncan Sands641baf12010-11-13 15:10:37 +0000663 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000664
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000665 /// Tries to simplify binary operations which some other binary
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000666 /// operation distributes over.
Chandler Carruth3a622162015-01-20 19:27:58 +0000667 ///
668 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
669 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
670 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
671 /// value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000672 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000673
Sanjoy Das6f1937b2018-04-26 20:52:28 +0000674 /// Tries to simplify add operations using the definition of remainder.
675 ///
676 /// The definition of remainder is X % C = X - (X / C ) * C. The add
677 /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
678 /// X % (C0 * C1)
679 Value *SimplifyAddWithRemainder(BinaryOperator &I);
680
Quentin Colombetaa103b32017-09-20 17:32:16 +0000681 // Binary Op helper for select operations where the expression can be
682 // efficiently reorganized.
683 Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
684 Value *RHS);
685
Daniel Berlin2c75c632017-04-26 20:56:07 +0000686 /// This tries to simplify binary operations by factorizing out common terms
687 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
Craig Topper47c8f662017-07-06 18:35:52 +0000688 Value *tryFactorization(BinaryOperator &, Instruction::BinaryOps, Value *,
689 Value *, Value *, Value *);
Daniel Berlin2c75c632017-04-26 20:56:07 +0000690
Anna Thomasd67165c2017-06-23 13:41:45 +0000691 /// Match a select chain which produces one of three values based on whether
692 /// the LHS is less than, equal to, or greater than RHS respectively.
693 /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
694 /// Equal and Greater values are saved in the matching process and returned to
695 /// the caller.
696 bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
697 ConstantInt *&Less, ConstantInt *&Equal,
698 ConstantInt *&Greater);
699
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000700 /// Attempts to replace V with a simpler value based on the demanded
Chandler Carruth3a622162015-01-20 19:27:58 +0000701 /// bits.
Craig Topperb45eabc2017-04-26 16:39:58 +0000702 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, KnownBits &Known,
703 unsigned Depth, Instruction *CxtI);
Craig Topper47596dd2017-03-25 06:52:52 +0000704 bool SimplifyDemandedBits(Instruction *I, unsigned Op,
Craig Topperb45eabc2017-04-26 16:39:58 +0000705 const APInt &DemandedMask, KnownBits &Known,
706 unsigned Depth = 0);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000707
Craig Topperb0076fe2017-04-12 18:05:21 +0000708 /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
709 /// bits. It also tries to handle simplifications that can be done based on
710 /// DemandedMask, but without modifying the Instruction.
711 Value *SimplifyMultipleUseDemandedBits(Instruction *I,
712 const APInt &DemandedMask,
Craig Topperb45eabc2017-04-26 16:39:58 +0000713 KnownBits &Known,
Craig Topperb0076fe2017-04-12 18:05:21 +0000714 unsigned Depth, Instruction *CxtI);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000715
Shuxin Yang63e999e2012-12-04 00:04:54 +0000716 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
717 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
Sanjay Patelcc663b82017-04-20 22:37:01 +0000718 Value *simplifyShrShlDemandedBits(
Sanjay Patelc9485ca2017-04-20 22:33:54 +0000719 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
Craig Topperb45eabc2017-04-26 16:39:58 +0000720 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000721
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000722 /// Tries to simplify operands to an integer instruction based on its
Chandler Carruth3a622162015-01-20 19:27:58 +0000723 /// demanded bits.
Chris Lattner35522b72010-01-04 07:12:23 +0000724 bool SimplifyDemandedInstructionBits(Instruction &Inst);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000725
Nicolai Haehnleb29ee702018-06-21 13:37:31 +0000726 Value *simplifyAMDGCNMemoryIntrinsicDemanded(IntrinsicInst *II,
727 APInt DemandedElts,
728 int DmaskIdx = -1);
729
Chris Lattner35522b72010-01-04 07:12:23 +0000730 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
Chandler Carruthd70cc602014-05-07 17:36:59 +0000731 APInt &UndefElts, unsigned Depth = 0);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000732
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000733 /// Canonicalize the position of binops relative to shufflevector.
734 Instruction *foldShuffledBinop(BinaryOperator &Inst);
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000735
736 /// Given a binary operator, cast instruction, or select which has a PHI node
737 /// as operand #0, see if we can fold the instruction into the PHI (which is
738 /// only possible if all operands to the PHI are constants).
Craig Topperfb71b7d2017-04-14 19:20:12 +0000739 Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000740
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000741 /// Given an instruction with a select as one operand and a constant as the
742 /// other operand, try to fold the binary operator into the select arguments.
743 /// This also works for Cast instructions, which obviously do not have a
744 /// second operand.
745 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
746
747 /// This is a convenience wrapper function for the above two functions.
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000748 Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000749
Sanjay Patel8d810fe2017-10-13 16:43:58 +0000750 Instruction *foldAddWithConstant(BinaryOperator &Add);
751
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000752 /// Try to rotate an operation below a PHI node, using PHI nodes for
Chandler Carruth3a622162015-01-20 19:27:58 +0000753 /// its operands.
Chris Lattner35522b72010-01-04 07:12:23 +0000754 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
755 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
756 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
757 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Sanjay Patel95334072015-09-27 20:34:31 +0000758 Instruction *FoldPHIArgZextsIntoPHI(PHINode &PN);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000759
Xinliang David Li4cdc9da2017-10-10 05:07:54 +0000760 /// If an integer typed PHI has only one use which is an IntToPtr operation,
761 /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
762 /// insert a new pointer typed PHI and replace the original one.
763 Instruction *FoldIntegerTypedPHI(PHINode &PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000764
Dehao Chenf4646272017-10-02 18:13:14 +0000765 /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
Robert Lougher2428a402016-12-14 17:49:19 +0000766 /// folded operation.
Dehao Chenf4646272017-10-02 18:13:14 +0000767 void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
Robert Lougher2428a402016-12-14 17:49:19 +0000768
Sanjay Patel43395062016-07-21 18:07:40 +0000769 Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
770 ICmpInst::Predicate Cond, Instruction &I);
Pete Cooper980a9352016-08-12 17:13:28 +0000771 Instruction *foldAllocaCmp(ICmpInst &ICI, const AllocaInst *Alloca,
772 const Value *Other);
Sanjay Patel43395062016-07-21 18:07:40 +0000773 Instruction *foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
774 GlobalVariable *GV, CmpInst &ICI,
775 ConstantInt *AndCst = nullptr);
776 Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
777 Constant *RHSC);
Craig Toppera85f8622017-08-23 05:46:09 +0000778 Instruction *foldICmpAddOpConst(Value *X, ConstantInt *CI,
Sanjay Patel43395062016-07-21 18:07:40 +0000779 ICmpInst::Predicate Pred);
780 Instruction *foldICmpWithCastAndCast(ICmpInst &ICI);
Sanjay Patelf58f68c2016-09-10 15:03:44 +0000781
Sanjay Patel3151dec2016-09-12 15:24:31 +0000782 Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
Sanjay Patel06b127a2016-09-15 14:37:50 +0000783 Instruction *foldICmpWithConstant(ICmpInst &Cmp);
Sanjay Patelf58f68c2016-09-10 15:03:44 +0000784 Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
Sanjay Patel10494b22016-09-16 16:10:22 +0000785 Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
786 Instruction *foldICmpBinOp(ICmpInst &Cmp);
787 Instruction *foldICmpEquality(ICmpInst &Cmp);
Nikolai Bozhenov0e7ebbc2017-10-16 09:19:21 +0000788 Instruction *foldICmpWithZero(ICmpInst &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +0000789
Craig Topper524c44f2017-08-23 05:46:07 +0000790 Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
Anna Thomasd67165c2017-06-23 13:41:45 +0000791 ConstantInt *C);
Daniel Neilson901acfa2018-04-03 17:26:20 +0000792 Instruction *foldICmpBitCastConstant(ICmpInst &Cmp, BitCastInst *Bitcast,
793 const APInt &C);
Craig Topper524c44f2017-08-23 05:46:07 +0000794 Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000795 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000796 Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000797 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000798 Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000799 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000800 Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000801 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000802 Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000803 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000804 Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000805 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000806 Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000807 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000808 Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000809 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000810 Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000811 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000812 Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000813 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000814 Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000815 const APInt &C);
Sanjay Pateld3c7bb282016-08-26 16:42:33 +0000816 Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000817 const APInt &C1);
Sanjay Patel14e0e182016-08-26 18:28:46 +0000818 Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000819 const APInt &C1, const APInt &C2);
Sanjay Patel8da42cc2016-09-15 22:26:31 +0000820 Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
821 const APInt &C2);
822 Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
823 const APInt &C2);
Sanjay Patela3f4f082016-08-16 17:54:36 +0000824
Sanjay Patelf58f68c2016-09-10 15:03:44 +0000825 Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
826 BinaryOperator *BO,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000827 const APInt &C);
828 Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, const APInt &C);
Sanjay Patel43395062016-07-21 18:07:40 +0000829
Sanjay Patel453ceff2016-09-29 22:18:30 +0000830 // Helpers of visitSelectInst().
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000831 Instruction *foldSelectExtConst(SelectInst &Sel);
Sanjay Patel453ceff2016-09-29 22:18:30 +0000832 Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
833 Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
834 Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
835 Value *A, Value *B, Instruction &Outer,
836 SelectPatternFlavor SPF2, Value *C);
837 Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
838
Craig Topper70e4f432017-04-02 17:57:30 +0000839 Instruction *OptAndOp(BinaryOperator *Op, ConstantInt *OpRHS,
Chris Lattner35522b72010-01-04 07:12:23 +0000840 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000841
Sanjay Patel85d79742016-08-31 19:49:56 +0000842 Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
843 bool isSigned, bool Inside);
Chris Lattner35522b72010-01-04 07:12:23 +0000844 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chad Rosiera00df492016-05-25 16:22:14 +0000845 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000846 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Igor Laevsky900ffa32017-02-08 14:32:04 +0000847
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000848 Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000849 Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
Chris Lattner35522b72010-01-04 07:12:23 +0000850
Chris Lattner229907c2011-07-18 04:54:35 +0000851 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
Duncan Sands533c8ae2012-10-23 08:28:26 +0000852
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000853 /// Returns a value X such that Val = X * Scale, or null if none.
Chandler Carruth3a622162015-01-20 19:27:58 +0000854 ///
855 /// If the multiplication is known not to overflow then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +0000856 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
Chris Lattner35522b72010-01-04 07:12:23 +0000857};
858
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000859} // end namespace llvm
Chris Lattner35522b72010-01-04 07:12:23 +0000860
Chandler Carruth964daaa2014-04-22 02:55:47 +0000861#undef DEBUG_TYPE
862
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000863#endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H