blob: 6cba8e37509bc925226f7c9bf2af1d56afa616cc [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohmand78c4002008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattner35522b72010-01-04 07:12:23 +000037#include "InstCombine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm-c/Initialization.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/StringSwitch.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc1f19072009-11-09 23:28:39 +000043#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000044#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000045#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000047#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000049#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000050#include "llvm/IR/ValueHandle.h"
Meador Inge193e0352012-11-13 04:16:17 +000051#include "llvm/Support/CommandLine.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000053#include "llvm/Target/TargetLibraryInfo.h"
54#include "llvm/Transforms/Utils/Local.h"
Chris Lattner053c0932002-05-14 15:24:07 +000055#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000056#include <climits>
Chris Lattner8427bff2003-12-07 01:24:23 +000057using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000058using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000059
Chandler Carruth964daaa2014-04-22 02:55:47 +000060#define DEBUG_TYPE "instcombine"
61
Chris Lattner79a42ac2006-12-19 21:40:18 +000062STATISTIC(NumCombined , "Number of insts combined");
63STATISTIC(NumConstProp, "Number of constant folds");
64STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner79a42ac2006-12-19 21:40:18 +000065STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sandsfbb9ac32010-12-22 13:36:08 +000066STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000067STATISTIC(NumFactor , "Number of factorizations");
68STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000069
Meador Inge193e0352012-11-13 04:16:17 +000070static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
71 cl::init(false),
72 cl::desc("Enable unsafe double to float "
73 "shrinking for math lib calls"));
74
Owen Andersonf7ef5df2010-10-07 20:04:55 +000075// Initialization Routines
76void llvm::initializeInstCombine(PassRegistry &Registry) {
77 initializeInstCombinerPass(Registry);
78}
79
80void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
81 initializeInstCombine(*unwrap(R));
82}
Chris Lattner260ab202002-04-18 17:39:14 +000083
Dan Gohmand78c4002008-05-13 00:00:25 +000084char InstCombiner::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +000085INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
86 "Combine redundant instructions", false, false)
87INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
88INITIALIZE_PASS_END(InstCombiner, "instcombine",
Owen Andersondf7a4f22010-10-07 22:25:06 +000089 "Combine redundant instructions", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000090
Chris Lattner7e044912010-01-04 07:17:19 +000091void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner7e044912010-01-04 07:17:19 +000092 AU.setPreservesCFG();
Chad Rosier82e1bd82011-11-29 23:57:10 +000093 AU.addRequired<TargetLibraryInfo>();
Chris Lattner7e044912010-01-04 07:17:19 +000094}
95
96
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000097Value *InstCombiner::EmitGEPOffset(User *GEP) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +000098 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000099}
100
Chris Lattner1559bed2009-11-10 07:23:37 +0000101/// ShouldChangeType - Return true if it is desirable to convert a computation
102/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
103/// type for example, or from a smaller to a larger illegal type.
Chris Lattner229907c2011-07-18 04:54:35 +0000104bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
Duncan Sands19d0b472010-02-16 11:11:14 +0000105 assert(From->isIntegerTy() && To->isIntegerTy());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000106
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000107 // If we don't have DL, we don't know if the source/dest are legal.
108 if (!DL) return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000109
Chris Lattner1559bed2009-11-10 07:23:37 +0000110 unsigned FromWidth = From->getPrimitiveSizeInBits();
111 unsigned ToWidth = To->getPrimitiveSizeInBits();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000112 bool FromLegal = DL->isLegalInteger(FromWidth);
113 bool ToLegal = DL->isLegalInteger(ToWidth);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000114
Chris Lattner1559bed2009-11-10 07:23:37 +0000115 // If this is a legal integer from type, and the result would be an illegal
116 // type, don't do the transformation.
117 if (FromLegal && !ToLegal)
118 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000119
Chris Lattner1559bed2009-11-10 07:23:37 +0000120 // Otherwise, if both are illegal, do not increase the size of the result. We
121 // do allow things like i160 -> i64, but not i64 -> i160.
122 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
123 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000124
Chris Lattner1559bed2009-11-10 07:23:37 +0000125 return true;
126}
127
Nick Lewyckyde492782011-08-14 01:45:19 +0000128// Return true, if No Signed Wrap should be maintained for I.
129// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
130// where both B and C should be ConstantInts, results in a constant that does
131// not overflow. This function only handles the Add and Sub opcodes. For
132// all other opcodes, the function conservatively returns false.
133static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
134 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
135 if (!OBO || !OBO->hasNoSignedWrap()) {
136 return false;
137 }
138
139 // We reason about Add and Sub Only.
140 Instruction::BinaryOps Opcode = I.getOpcode();
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000141 if (Opcode != Instruction::Add &&
Nick Lewyckyde492782011-08-14 01:45:19 +0000142 Opcode != Instruction::Sub) {
143 return false;
144 }
145
146 ConstantInt *CB = dyn_cast<ConstantInt>(B);
147 ConstantInt *CC = dyn_cast<ConstantInt>(C);
148
149 if (!CB || !CC) {
150 return false;
151 }
152
153 const APInt &BVal = CB->getValue();
154 const APInt &CVal = CC->getValue();
155 bool Overflow = false;
156
157 if (Opcode == Instruction::Add) {
158 BVal.sadd_ov(CVal, Overflow);
159 } else {
160 BVal.ssub_ov(CVal, Overflow);
161 }
162
163 return !Overflow;
164}
165
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000166/// Conservatively clears subclassOptionalData after a reassociation or
167/// commutation. We preserve fast-math flags when applicable as they can be
168/// preserved.
169static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
170 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
171 if (!FPMO) {
172 I.clearSubclassOptionalData();
173 return;
174 }
175
176 FastMathFlags FMF = I.getFastMathFlags();
177 I.clearSubclassOptionalData();
178 I.setFastMathFlags(FMF);
179}
180
Duncan Sands641baf12010-11-13 15:10:37 +0000181/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
182/// operators which are associative or commutative:
183//
184// Commutative operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000185//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000186// 1. Order operands such that they are listed from right (least complex) to
187// left (most complex). This puts constants before unary operators before
188// binary operators.
189//
Duncan Sands641baf12010-11-13 15:10:37 +0000190// Associative operators:
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000191//
Duncan Sands641baf12010-11-13 15:10:37 +0000192// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
193// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
194//
195// Associative and commutative operators:
196//
197// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
198// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
199// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
200// if C1 and C2 are constants.
201//
202bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000203 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands641baf12010-11-13 15:10:37 +0000204 bool Changed = false;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000205
Duncan Sands641baf12010-11-13 15:10:37 +0000206 do {
207 // Order operands such that they are listed from right (least complex) to
208 // left (most complex). This puts constants before unary operators before
209 // binary operators.
210 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
211 getComplexity(I.getOperand(1)))
212 Changed = !I.swapOperands();
213
214 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
215 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
216
217 if (I.isAssociative()) {
218 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
219 if (Op0 && Op0->getOpcode() == Opcode) {
220 Value *A = Op0->getOperand(0);
221 Value *B = Op0->getOperand(1);
222 Value *C = I.getOperand(1);
223
224 // Does "B op C" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000225 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000226 // It simplifies to V. Form "A op V".
227 I.setOperand(0, A);
228 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000229 // Conservatively clear the optional flags, since they may not be
230 // preserved by the reassociation.
Nick Lewyckyae13df62011-08-14 03:41:33 +0000231 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendlingea6397f2012-07-19 00:11:40 +0000232 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewyckyae13df62011-08-14 03:41:33 +0000233 // Note: this is only valid because SimplifyBinOp doesn't look at
234 // the operands to Op0.
Nick Lewyckyde492782011-08-14 01:45:19 +0000235 I.clearSubclassOptionalData();
236 I.setHasNoSignedWrap(true);
237 } else {
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000238 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000239 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000240
Duncan Sands641baf12010-11-13 15:10:37 +0000241 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000242 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000243 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000244 }
Duncan Sands641baf12010-11-13 15:10:37 +0000245 }
246
247 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
248 if (Op1 && Op1->getOpcode() == Opcode) {
249 Value *A = I.getOperand(0);
250 Value *B = Op1->getOperand(0);
251 Value *C = Op1->getOperand(1);
252
253 // Does "A op B" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000254 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000255 // It simplifies to V. Form "V op C".
256 I.setOperand(0, V);
257 I.setOperand(1, C);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000258 // Conservatively clear the optional flags, since they may not be
259 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000260 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000261 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000262 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000263 continue;
264 }
265 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266 }
Duncan Sands641baf12010-11-13 15:10:37 +0000267
268 if (I.isAssociative() && I.isCommutative()) {
269 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
270 if (Op0 && Op0->getOpcode() == Opcode) {
271 Value *A = Op0->getOperand(0);
272 Value *B = Op0->getOperand(1);
273 Value *C = I.getOperand(1);
274
275 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000276 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000277 // It simplifies to V. Form "V op B".
278 I.setOperand(0, V);
279 I.setOperand(1, B);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000280 // Conservatively clear the optional flags, since they may not be
281 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000282 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000283 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000284 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000285 continue;
286 }
287 }
288
289 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
290 if (Op1 && Op1->getOpcode() == Opcode) {
291 Value *A = I.getOperand(0);
292 Value *B = Op1->getOperand(0);
293 Value *C = Op1->getOperand(1);
294
295 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000296 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000297 // It simplifies to V. Form "B op V".
298 I.setOperand(0, B);
299 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000300 // Conservatively clear the optional flags, since they may not be
301 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000302 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000303 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000304 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000305 continue;
306 }
307 }
308
309 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
310 // if C1 and C2 are constants.
311 if (Op0 && Op1 &&
312 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
313 isa<Constant>(Op0->getOperand(1)) &&
314 isa<Constant>(Op1->getOperand(1)) &&
315 Op0->hasOneUse() && Op1->hasOneUse()) {
316 Value *A = Op0->getOperand(0);
317 Constant *C1 = cast<Constant>(Op0->getOperand(1));
318 Value *B = Op1->getOperand(0);
319 Constant *C2 = cast<Constant>(Op1->getOperand(1));
320
321 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckyde492782011-08-14 01:45:19 +0000322 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Owen Anderson1664dc82014-01-20 07:44:53 +0000323 if (isa<FPMathOperator>(New)) {
324 FastMathFlags Flags = I.getFastMathFlags();
325 Flags &= Op0->getFastMathFlags();
326 Flags &= Op1->getFastMathFlags();
327 New->setFastMathFlags(Flags);
328 }
Eli Friedman35211c62011-05-27 00:19:40 +0000329 InsertNewInstWith(New, I);
Eli Friedman41e509a2011-05-18 23:58:37 +0000330 New->takeName(Op1);
Duncan Sands641baf12010-11-13 15:10:37 +0000331 I.setOperand(0, New);
332 I.setOperand(1, Folded);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000333 // Conservatively clear the optional flags, since they may not be
334 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000335 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000336
Duncan Sands641baf12010-11-13 15:10:37 +0000337 Changed = true;
338 continue;
339 }
340 }
341
342 // No further simplifications.
343 return Changed;
344 } while (1);
Chris Lattner260ab202002-04-18 17:39:14 +0000345}
Chris Lattnerca081252001-12-14 16:52:21 +0000346
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000347/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sands22df7412010-11-23 15:25:34 +0000348/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000349static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
350 Instruction::BinaryOps ROp) {
351 switch (LOp) {
352 default:
353 return false;
354
355 case Instruction::And:
356 // And distributes over Or and Xor.
357 switch (ROp) {
358 default:
359 return false;
360 case Instruction::Or:
361 case Instruction::Xor:
362 return true;
363 }
364
365 case Instruction::Mul:
366 // Multiplication distributes over addition and subtraction.
367 switch (ROp) {
368 default:
369 return false;
370 case Instruction::Add:
371 case Instruction::Sub:
372 return true;
373 }
374
375 case Instruction::Or:
376 // Or distributes over And.
377 switch (ROp) {
378 default:
379 return false;
380 case Instruction::And:
381 return true;
382 }
383 }
384}
385
386/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
387/// "(X ROp Z) LOp (Y ROp Z)".
388static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
389 Instruction::BinaryOps ROp) {
390 if (Instruction::isCommutative(ROp))
391 return LeftDistributesOverRight(ROp, LOp);
392 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
393 // but this requires knowing that the addition does not overflow and other
394 // such subtleties.
395 return false;
396}
397
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000398/// This function returns identity value for given opcode, which can be used to
399/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
400static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
401 if (isa<Constant>(V))
402 return nullptr;
403
404 if (OpCode == Instruction::Mul)
405 return ConstantInt::get(V->getType(), 1);
406
407 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
408
409 return nullptr;
410}
411
412/// This function factors binary ops which can be combined using distributive
413/// laws. This also factor SHL as MUL e.g. SHL(X, 2) ==> MUL(X, 4).
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000414static Instruction::BinaryOps
415getBinOpsForFactorization(BinaryOperator *Op, Value *&LHS, Value *&RHS) {
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000416 if (!Op)
417 return Instruction::BinaryOpsEnd;
418
419 if (Op->getOpcode() == Instruction::Shl) {
420 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
421 // The multiplier is really 1 << CST.
422 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
423 LHS = Op->getOperand(0);
424 return Instruction::Mul;
425 }
426 }
427
428 // TODO: We can add other conversions e.g. shr => div etc.
429
430 LHS = Op->getOperand(0);
431 RHS = Op->getOperand(1);
432 return Op->getOpcode();
433}
434
435/// This tries to simplify binary operations by factorizing out common terms
436/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
437static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
438 const DataLayout *DL, BinaryOperator &I,
439 Instruction::BinaryOps InnerOpcode, Value *A,
440 Value *B, Value *C, Value *D) {
441
442 // If any of A, B, C, D are null, we can not factor I, return early.
443 // Checking A and C should be enough.
444 if (!A || !C || !B || !D)
445 return nullptr;
446
447 Value *SimplifiedInst = nullptr;
448 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
449 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
450
451 // Does "X op' Y" always equal "Y op' X"?
452 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
453
454 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
455 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
456 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
457 // commutative case, "(A op' B) op (C op' A)"?
458 if (A == C || (InnerCommutative && A == D)) {
459 if (A != C)
460 std::swap(C, D);
461 // Consider forming "A op' (B op D)".
462 // If "B op D" simplifies then it can be formed with no cost.
463 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
464 // If "B op D" doesn't simplify then only go on if both of the existing
465 // operations "A op' B" and "C op' D" will be zapped as no longer used.
466 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
467 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
468 if (V) {
469 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
470 }
471 }
472
473 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
474 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
475 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
476 // commutative case, "(A op' B) op (B op' D)"?
477 if (B == D || (InnerCommutative && B == C)) {
478 if (B != D)
479 std::swap(C, D);
480 // Consider forming "(A op C) op' B".
481 // If "A op C" simplifies then it can be formed with no cost.
482 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
483
484 // If "A op C" doesn't simplify then only go on if both of the existing
485 // operations "A op' B" and "C op' D" will be zapped as no longer used.
486 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
487 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
488 if (V) {
489 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
490 }
491 }
492
493 if (SimplifiedInst) {
494 ++NumFactor;
495 SimplifiedInst->takeName(&I);
496
497 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
498 // TODO: Check for NUW.
499 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
500 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
501 bool HasNSW = false;
502 if (isa<OverflowingBinaryOperator>(&I))
503 HasNSW = I.hasNoSignedWrap();
504
505 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
506 if (isa<OverflowingBinaryOperator>(Op0))
507 HasNSW &= Op0->hasNoSignedWrap();
508
509 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
510 if (isa<OverflowingBinaryOperator>(Op1))
511 HasNSW &= Op1->hasNoSignedWrap();
512 BO->setHasNoSignedWrap(HasNSW);
513 }
514 }
515 }
516 return SimplifiedInst;
517}
518
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000519/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
520/// which some other binary operation distributes over either by factorizing
521/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
522/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
523/// a win). Returns the simplified value, or null if it didn't simplify.
524Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
525 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
526 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
527 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000528
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000529 // Factorization.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000530 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
531 Instruction::BinaryOps LHSOpcode = getBinOpsForFactorization(Op0, A, B);
532 Instruction::BinaryOps RHSOpcode = getBinOpsForFactorization(Op1, C, D);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000533
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000534 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
535 // a common term.
536 if (LHSOpcode == RHSOpcode) {
537 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
538 return V;
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000539 }
540
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000541 // The instruction has the form "(A op' B) op (C)". Try to factorize common
542 // term.
543 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
544 getIdentityValue(LHSOpcode, RHS)))
545 return V;
546
547 // The instruction has the form "(B) op (C op' D)". Try to factorize common
548 // term.
549 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
550 getIdentityValue(RHSOpcode, LHS), C, D))
551 return V;
552
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000553 // Expansion.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000554 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000555 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
556 // The instruction has the form "(A op' B) op C". See if expanding it out
557 // to "(A op C) op' (B op C)" results in simplifications.
558 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
559 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
560
561 // Do "A op C" and "B op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000562 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
563 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000564 // They do! Return "L op' R".
565 ++NumExpand;
566 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
567 if ((L == A && R == B) ||
568 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
569 return Op0;
570 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000571 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000572 return V;
573 // Otherwise, create a new instruction.
574 C = Builder->CreateBinOp(InnerOpcode, L, R);
575 C->takeName(&I);
576 return C;
577 }
578 }
579
580 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
581 // The instruction has the form "A op (B op' C)". See if expanding it out
582 // to "(A op B) op' (A op C)" results in simplifications.
583 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
584 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
585
586 // Do "A op B" and "A op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000587 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
588 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000589 // They do! Return "L op' R".
590 ++NumExpand;
591 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
592 if ((L == B && R == C) ||
593 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
594 return Op1;
595 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000596 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000597 return V;
598 // Otherwise, create a new instruction.
599 A = Builder->CreateBinOp(InnerOpcode, L, R);
600 A->takeName(&I);
601 return A;
602 }
603 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000604
Craig Topperf40110f2014-04-25 05:29:35 +0000605 return nullptr;
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000606}
607
Chris Lattnerbb74e222003-03-10 23:06:50 +0000608// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
609// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000610//
Chris Lattner2188e402010-01-04 07:37:31 +0000611Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonbb2501b2009-07-13 22:18:28 +0000612 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000613 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000614
Chris Lattner9ad0d552004-12-14 20:08:06 +0000615 // Constants can be considered to be negated values if they can be folded.
616 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000617 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000618
Chris Lattner8213c8a2012-02-06 21:56:39 +0000619 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
620 if (C->getType()->getElementType()->isIntegerTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000621 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000622
Craig Topperf40110f2014-04-25 05:29:35 +0000623 return nullptr;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000624}
625
Dan Gohmana5b96452009-06-04 22:49:04 +0000626// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
627// instruction if the LHS is a constant negative zero (which is the 'negate'
628// form).
629//
Shuxin Yangf0537ab2013-01-09 00:13:41 +0000630Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
631 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
Dan Gohmana5b96452009-06-04 22:49:04 +0000632 return BinaryOperator::getFNegArgument(V);
633
634 // Constants can be considered to be negated values if they can be folded.
635 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000636 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000637
Chris Lattner8213c8a2012-02-06 21:56:39 +0000638 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
639 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000640 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000641
Craig Topperf40110f2014-04-25 05:29:35 +0000642 return nullptr;
Dan Gohmana5b96452009-06-04 22:49:04 +0000643}
644
Chris Lattner86102b82005-01-01 16:22:27 +0000645static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000646 InstCombiner *IC) {
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000647 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattnerc8565392009-08-30 20:01:10 +0000648 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000649 }
Chris Lattner86102b82005-01-01 16:22:27 +0000650
Chris Lattner183b3362004-04-09 19:05:30 +0000651 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000652 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
653 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000654
Chris Lattner183b3362004-04-09 19:05:30 +0000655 if (Constant *SOC = dyn_cast<Constant>(SO)) {
656 if (ConstIsRHS)
Owen Anderson487375e2009-07-29 18:55:55 +0000657 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
658 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000659 }
660
661 Value *Op0 = SO, *Op1 = ConstOperand;
662 if (!ConstIsRHS)
663 std::swap(Op0, Op1);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000664
Owen Anderson1664dc82014-01-20 07:44:53 +0000665 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
666 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
Chris Lattner022a5822009-08-30 07:44:24 +0000667 SO->getName()+".op");
Owen Anderson1664dc82014-01-20 07:44:53 +0000668 Instruction *FPInst = dyn_cast<Instruction>(RI);
669 if (FPInst && isa<FPMathOperator>(FPInst))
670 FPInst->copyFastMathFlags(BO);
671 return RI;
672 }
Chris Lattner022a5822009-08-30 07:44:24 +0000673 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
674 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
675 SO->getName()+".cmp");
676 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
677 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
678 SO->getName()+".cmp");
679 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner86102b82005-01-01 16:22:27 +0000680}
681
682// FoldOpIntoSelect - Given an instruction with a select as one operand and a
683// constant as the other operand, try to fold the binary operator into the
684// select arguments. This also works for Cast instructions, which obviously do
685// not have a second operand.
Chris Lattner2b295a02010-01-04 07:53:58 +0000686Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner86102b82005-01-01 16:22:27 +0000687 // Don't modify shared select instructions
Craig Topperf40110f2014-04-25 05:29:35 +0000688 if (!SI->hasOneUse()) return nullptr;
Chris Lattner86102b82005-01-01 16:22:27 +0000689 Value *TV = SI->getOperand(1);
690 Value *FV = SI->getOperand(2);
691
692 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000693 // Bool selects with constant operands can be folded to logical ops.
Craig Topperf40110f2014-04-25 05:29:35 +0000694 if (SI->getType()->isIntegerTy(1)) return nullptr;
Chris Lattner374e6592005-04-21 05:43:13 +0000695
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000696 // If it's a bitcast involving vectors, make sure it has the same number of
697 // elements on both sides.
698 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000699 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
700 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000701
702 // Verify that either both or neither are vectors.
Craig Topperf40110f2014-04-25 05:29:35 +0000703 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000704 // If vectors, verify that they have the same number of elements.
705 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +0000706 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000707 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000708
Chris Lattner2b295a02010-01-04 07:53:58 +0000709 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
710 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner86102b82005-01-01 16:22:27 +0000711
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000712 return SelectInst::Create(SI->getCondition(),
713 SelectTrueVal, SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +0000714 }
Craig Topperf40110f2014-04-25 05:29:35 +0000715 return nullptr;
Chris Lattner183b3362004-04-09 19:05:30 +0000716}
717
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000718
Chris Lattnerfacb8672009-09-27 19:57:57 +0000719/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
720/// has a PHI node as operand #0, see if we can fold the instruction into the
721/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattnerb391e872009-09-27 20:46:36 +0000722///
Chris Lattnerea7131a2011-01-16 05:14:26 +0000723Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000724 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000725 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner25ce2802011-01-16 04:37:29 +0000726 if (NumPHIValues == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000727 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000728
Chris Lattnerf4ca47b2011-01-21 05:08:26 +0000729 // We normally only transform phis with a single use. However, if a PHI has
730 // multiple uses and they are all the same operation, we can fold *all* of the
731 // uses into the PHI.
Chris Lattnerd55581d2011-01-16 05:28:59 +0000732 if (!PN->hasOneUse()) {
733 // Walk the use list for the instruction, comparing them to I.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000734 for (User *U : PN->users()) {
735 Instruction *UI = cast<Instruction>(U);
736 if (UI != &I && !I.isIdenticalTo(UI))
Craig Topperf40110f2014-04-25 05:29:35 +0000737 return nullptr;
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000738 }
Chris Lattnerd55581d2011-01-16 05:28:59 +0000739 // Otherwise, we can replace *all* users with the new PHI we form.
740 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000741
Chris Lattnerfacb8672009-09-27 19:57:57 +0000742 // Check to see if all of the operands of the PHI are simple constants
743 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerae289632009-09-27 20:18:49 +0000744 // remember the BB it is in. If there is more than one or if *it* is a PHI,
745 // bail out. We don't do arbitrary constant expressions here because moving
746 // their computation can be expensive without a cost model.
Craig Topperf40110f2014-04-25 05:29:35 +0000747 BasicBlock *NonConstBB = nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000748 for (unsigned i = 0; i != NumPHIValues; ++i) {
749 Value *InVal = PN->getIncomingValue(i);
750 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
751 continue;
752
Craig Topperf40110f2014-04-25 05:29:35 +0000753 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
754 if (NonConstBB) return nullptr; // More than one non-const value.
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000755
Chris Lattner25ce2802011-01-16 04:37:29 +0000756 NonConstBB = PN->getIncomingBlock(i);
Chris Lattnerff2e7372011-01-16 05:08:00 +0000757
758 // If the InVal is an invoke at the end of the pred block, then we can't
759 // insert a computation after it without breaking the edge.
760 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
761 if (II->getParent() == NonConstBB)
Craig Topperf40110f2014-04-25 05:29:35 +0000762 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000763
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000764 // If the incoming non-constant value is in I's block, we will remove one
765 // instruction, but insert another equivalent one, leading to infinite
766 // instcombine.
767 if (NonConstBB == I.getParent())
Craig Topperf40110f2014-04-25 05:29:35 +0000768 return nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000769 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000770
Chris Lattner04689872006-09-09 22:02:56 +0000771 // If there is exactly one non-constant value, we can insert a copy of the
772 // operation in that block. However, if this is a critical edge, we would be
773 // inserting the computation one some other paths (e.g. inside a loop). Only
774 // do this if the pred block is unconditionally branching into the phi block.
Craig Topperf40110f2014-04-25 05:29:35 +0000775 if (NonConstBB != nullptr) {
Chris Lattner04689872006-09-09 22:02:56 +0000776 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000777 if (!BI || !BI->isUnconditional()) return nullptr;
Chris Lattner04689872006-09-09 22:02:56 +0000778 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000779
780 // Okay, we can do the transformation: create the new PHI node.
Eli Friedman41e509a2011-05-18 23:58:37 +0000781 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner966526c2009-10-21 23:41:58 +0000782 InsertNewInstBefore(NewPN, *PN);
783 NewPN->takeName(PN);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000784
Chris Lattnerff2e7372011-01-16 05:08:00 +0000785 // If we are going to have to insert a new computation, do so right before the
786 // predecessors terminator.
787 if (NonConstBB)
788 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000789
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000790 // Next, add all of the operands to the PHI.
Chris Lattnerfacb8672009-09-27 19:57:57 +0000791 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
792 // We only currently try to fold the condition of a select when it is a phi,
793 // not the true/false values.
Chris Lattnerae289632009-09-27 20:18:49 +0000794 Value *TrueV = SI->getTrueValue();
795 Value *FalseV = SI->getFalseValue();
Chris Lattner0261b5d2009-09-28 06:49:44 +0000796 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerfacb8672009-09-27 19:57:57 +0000797 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerae289632009-09-27 20:18:49 +0000798 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner0261b5d2009-09-28 06:49:44 +0000799 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
800 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Craig Topperf40110f2014-04-25 05:29:35 +0000801 Value *InV = nullptr;
Duncan P. N. Exon Smithce5f93e2013-12-06 21:48:36 +0000802 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
803 // even if currently isNullValue gives false.
804 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
805 if (InC && !isa<ConstantExpr>(InC))
Chris Lattnerae289632009-09-27 20:18:49 +0000806 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000807 else
808 InV = Builder->CreateSelect(PN->getIncomingValue(i),
809 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerae289632009-09-27 20:18:49 +0000810 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerfacb8672009-09-27 19:57:57 +0000811 }
Chris Lattnerff2e7372011-01-16 05:08:00 +0000812 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
813 Constant *C = cast<Constant>(I.getOperand(1));
814 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000815 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000816 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
817 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
818 else if (isa<ICmpInst>(CI))
819 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
820 C, "phitmp");
821 else
822 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
823 C, "phitmp");
824 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
825 }
Chris Lattnerfacb8672009-09-27 19:57:57 +0000826 } else if (I.getNumOperands() == 2) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000827 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000828 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000829 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000830 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
831 InV = ConstantExpr::get(I.getOpcode(), InC, C);
832 else
833 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
834 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000835 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000836 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000837 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000838 CastInst *CI = cast<CastInst>(&I);
Chris Lattner229907c2011-07-18 04:54:35 +0000839 Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000840 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +0000841 Value *InV;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000842 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Anderson487375e2009-07-29 18:55:55 +0000843 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000844 else
Chris Lattnerff2e7372011-01-16 05:08:00 +0000845 InV = Builder->CreateCast(CI->getOpcode(),
846 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000847 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000848 }
849 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000850
Chandler Carruthcdf47882014-03-09 03:16:01 +0000851 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattnerd55581d2011-01-16 05:28:59 +0000852 Instruction *User = cast<Instruction>(*UI++);
853 if (User == &I) continue;
854 ReplaceInstUsesWith(*User, NewPN);
855 EraseInstFromFunction(*User);
856 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000857 return ReplaceInstUsesWith(I, NewPN);
858}
859
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000860/// FindElementAtOffset - Given a pointer type and a constant offset, determine
861/// whether or not there is a sequence of GEP indices into the pointed type that
862/// will land us at the specified offset. If so, fill them into NewIndices and
863/// return the resultant element type, otherwise return null.
864Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
865 SmallVectorImpl<Value*> &NewIndices) {
866 assert(PtrTy->isPtrOrPtrVectorTy());
867
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000868 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000869 return nullptr;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000870
871 Type *Ty = PtrTy->getPointerElementType();
872 if (!Ty->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +0000873 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000874
Chris Lattnerfef138b2009-01-09 05:44:56 +0000875 // Start with the index over the outer type. Note that the type size
876 // might be zero (even if the offset isn't zero) if the indexed type
877 // is something like [0 x {int, int}]
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000878 Type *IntPtrTy = DL->getIntPtrType(PtrTy);
Chris Lattnerfef138b2009-01-09 05:44:56 +0000879 int64_t FirstIdx = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000880 if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +0000881 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +0000882 Offset -= FirstIdx*TySize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000883
Benjamin Kramere4c46fe2013-01-23 17:52:29 +0000884 // Handle hosts where % returns negative instead of values [0..TySize).
885 if (Offset < 0) {
886 --FirstIdx;
887 Offset += TySize;
888 assert(Offset >= 0);
889 }
Chris Lattnerfef138b2009-01-09 05:44:56 +0000890 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
891 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000892
Owen Andersonedb4a702009-07-24 23:12:02 +0000893 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000894
Chris Lattnerfef138b2009-01-09 05:44:56 +0000895 // Index into the types. If we fail, set OrigBase to null.
896 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +0000897 // Indexing into tail padding between struct/array elements.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000898 if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
Craig Topperf40110f2014-04-25 05:29:35 +0000899 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000900
Chris Lattner229907c2011-07-18 04:54:35 +0000901 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000902 const StructLayout *SL = DL->getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +0000903 assert(Offset < (int64_t)SL->getSizeInBytes() &&
904 "Offset must stay within the indexed type");
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000905
Chris Lattnerfef138b2009-01-09 05:44:56 +0000906 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattnerb8906bd2010-01-04 07:02:48 +0000907 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
908 Elt));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000909
Chris Lattnerfef138b2009-01-09 05:44:56 +0000910 Offset -= SL->getElementOffset(Elt);
911 Ty = STy->getElementType(Elt);
Chris Lattner229907c2011-07-18 04:54:35 +0000912 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000913 uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +0000914 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonedb4a702009-07-24 23:12:02 +0000915 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +0000916 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +0000917 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +0000918 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +0000919 // Otherwise, we can't index into the middle of this atomic type, bail.
Craig Topperf40110f2014-04-25 05:29:35 +0000920 return nullptr;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000921 }
922 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000923
Chris Lattner72cd68f2009-01-24 01:00:13 +0000924 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000925}
926
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +0000927static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
928 // If this GEP has only 0 indices, it is the same pointer as
929 // Src. If Src is not a trivial GEP too, don't combine
930 // the indices.
931 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
932 !Src.hasOneUse())
933 return false;
934 return true;
935}
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000936
Duncan Sands533c8ae2012-10-23 08:28:26 +0000937/// Descale - Return a value X such that Val = X * Scale, or null if none. If
938/// the multiplication is known not to overflow then NoSignedWrap is set.
939Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
940 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
941 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
942 Scale.getBitWidth() && "Scale not compatible with value!");
943
944 // If Val is zero or Scale is one then Val = Val * Scale.
945 if (match(Val, m_Zero()) || Scale == 1) {
946 NoSignedWrap = true;
947 return Val;
948 }
949
950 // If Scale is zero then it does not divide Val.
951 if (Scale.isMinValue())
Craig Topperf40110f2014-04-25 05:29:35 +0000952 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +0000953
954 // Look through chains of multiplications, searching for a constant that is
955 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
956 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
957 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
958 // down from Val:
959 //
960 // Val = M1 * X || Analysis starts here and works down
961 // M1 = M2 * Y || Doesn't descend into terms with more
962 // M2 = Z * 4 \/ than one use
963 //
964 // Then to modify a term at the bottom:
965 //
966 // Val = M1 * X
967 // M1 = Z * Y || Replaced M2 with Z
968 //
969 // Then to work back up correcting nsw flags.
970
971 // Op - the term we are currently analyzing. Starts at Val then drills down.
972 // Replaced with its descaled value before exiting from the drill down loop.
973 Value *Op = Val;
974
975 // Parent - initially null, but after drilling down notes where Op came from.
976 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
977 // 0'th operand of Val.
978 std::pair<Instruction*, unsigned> Parent;
979
980 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
981 // levels that doesn't overflow.
982 bool RequireNoSignedWrap = false;
983
984 // logScale - log base 2 of the scale. Negative if not a power of 2.
985 int32_t logScale = Scale.exactLogBase2();
986
987 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
988
989 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
990 // If Op is a constant divisible by Scale then descale to the quotient.
991 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
992 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
993 if (!Remainder.isMinValue())
994 // Not divisible by Scale.
Craig Topperf40110f2014-04-25 05:29:35 +0000995 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +0000996 // Replace with the quotient in the parent.
997 Op = ConstantInt::get(CI->getType(), Quotient);
998 NoSignedWrap = true;
999 break;
1000 }
1001
1002 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1003
1004 if (BO->getOpcode() == Instruction::Mul) {
1005 // Multiplication.
1006 NoSignedWrap = BO->hasNoSignedWrap();
1007 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001008 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001009
1010 // There are three cases for multiplication: multiplication by exactly
1011 // the scale, multiplication by a constant different to the scale, and
1012 // multiplication by something else.
1013 Value *LHS = BO->getOperand(0);
1014 Value *RHS = BO->getOperand(1);
1015
1016 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1017 // Multiplication by a constant.
1018 if (CI->getValue() == Scale) {
1019 // Multiplication by exactly the scale, replace the multiplication
1020 // by its left-hand side in the parent.
1021 Op = LHS;
1022 break;
1023 }
1024
1025 // Otherwise drill down into the constant.
1026 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001027 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001028
1029 Parent = std::make_pair(BO, 1);
1030 continue;
1031 }
1032
1033 // Multiplication by something else. Drill down into the left-hand side
1034 // since that's where the reassociate pass puts the good stuff.
1035 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001036 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001037
1038 Parent = std::make_pair(BO, 0);
1039 continue;
1040 }
1041
1042 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1043 isa<ConstantInt>(BO->getOperand(1))) {
1044 // Multiplication by a power of 2.
1045 NoSignedWrap = BO->hasNoSignedWrap();
1046 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001047 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001048
1049 Value *LHS = BO->getOperand(0);
1050 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1051 getLimitedValue(Scale.getBitWidth());
1052 // Op = LHS << Amt.
1053
1054 if (Amt == logScale) {
1055 // Multiplication by exactly the scale, replace the multiplication
1056 // by its left-hand side in the parent.
1057 Op = LHS;
1058 break;
1059 }
1060 if (Amt < logScale || !Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001061 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001062
1063 // Multiplication by more than the scale. Reduce the multiplying amount
1064 // by the scale in the parent.
1065 Parent = std::make_pair(BO, 1);
1066 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1067 break;
1068 }
1069 }
1070
1071 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001072 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001073
1074 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1075 if (Cast->getOpcode() == Instruction::SExt) {
1076 // Op is sign-extended from a smaller type, descale in the smaller type.
1077 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1078 APInt SmallScale = Scale.trunc(SmallSize);
1079 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1080 // descale Op as (sext Y) * Scale. In order to have
1081 // sext (Y * SmallScale) = (sext Y) * Scale
1082 // some conditions need to hold however: SmallScale must sign-extend to
1083 // Scale and the multiplication Y * SmallScale should not overflow.
1084 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1085 // SmallScale does not sign-extend to Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001086 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001087 assert(SmallScale.exactLogBase2() == logScale);
1088 // Require that Y * SmallScale must not overflow.
1089 RequireNoSignedWrap = true;
1090
1091 // Drill down through the cast.
1092 Parent = std::make_pair(Cast, 0);
1093 Scale = SmallScale;
1094 continue;
1095 }
1096
Duncan Sands5ed39002012-10-23 09:07:02 +00001097 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001098 // Op is truncated from a larger type, descale in the larger type.
1099 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1100 // trunc (Y * sext Scale) = (trunc Y) * Scale
1101 // always holds. However (trunc Y) * Scale may overflow even if
1102 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1103 // from this point up in the expression (see later).
1104 if (RequireNoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001105 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001106
1107 // Drill down through the cast.
1108 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1109 Parent = std::make_pair(Cast, 0);
1110 Scale = Scale.sext(LargeSize);
1111 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1112 logScale = -1;
1113 assert(Scale.exactLogBase2() == logScale);
1114 continue;
1115 }
1116 }
1117
1118 // Unsupported expression, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +00001119 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001120 }
1121
1122 // We know that we can successfully descale, so from here on we can safely
1123 // modify the IR. Op holds the descaled version of the deepest term in the
1124 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1125 // not to overflow.
1126
1127 if (!Parent.first)
1128 // The expression only had one term.
1129 return Op;
1130
1131 // Rewrite the parent using the descaled version of its operand.
1132 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1133 assert(Op != Parent.first->getOperand(Parent.second) &&
1134 "Descaling was a no-op?");
1135 Parent.first->setOperand(Parent.second, Op);
1136 Worklist.Add(Parent.first);
1137
1138 // Now work back up the expression correcting nsw flags. The logic is based
1139 // on the following observation: if X * Y is known not to overflow as a signed
1140 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1141 // then X * Z will not overflow as a signed multiplication either. As we work
1142 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1143 // current level has strictly smaller absolute value than the original.
1144 Instruction *Ancestor = Parent.first;
1145 do {
1146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1147 // If the multiplication wasn't nsw then we can't say anything about the
1148 // value of the descaled multiplication, and we have to clear nsw flags
1149 // from this point on up.
1150 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1151 NoSignedWrap &= OpNoSignedWrap;
1152 if (NoSignedWrap != OpNoSignedWrap) {
1153 BO->setHasNoSignedWrap(NoSignedWrap);
1154 Worklist.Add(Ancestor);
1155 }
1156 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1157 // The fact that the descaled input to the trunc has smaller absolute
1158 // value than the original input doesn't tell us anything useful about
1159 // the absolute values of the truncations.
1160 NoSignedWrap = false;
1161 }
1162 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1163 "Failed to keep proper track of nsw flags while drilling down?");
1164
1165 if (Ancestor == Val)
1166 // Got to the top, all done!
1167 return Val;
1168
1169 // Move up one level in the expression.
1170 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Chandler Carruthcdf47882014-03-09 03:16:01 +00001171 Ancestor = Ancestor->user_back();
Duncan Sands533c8ae2012-10-23 08:28:26 +00001172 } while (1);
1173}
1174
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001175/// \brief Creates node of binary operation with the same attributes as the
1176/// specified one but with other operands.
Serge Pavlove6de9e32014-05-14 09:05:09 +00001177static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1178 InstCombiner::BuilderTy *B) {
1179 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1180 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1181 if (isa<OverflowingBinaryOperator>(NewBO)) {
1182 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1183 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1184 }
1185 if (isa<PossiblyExactOperator>(NewBO))
1186 NewBO->setIsExact(Inst.isExact());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001187 }
Serge Pavlove6de9e32014-05-14 09:05:09 +00001188 return BORes;
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001189}
1190
1191/// \brief Makes transformation of binary operation specific for vector types.
1192/// \param Inst Binary operator to transform.
1193/// \return Pointer to node that must replace the original binary operator, or
1194/// null pointer if no transformation was made.
1195Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1196 if (!Inst.getType()->isVectorTy()) return nullptr;
1197
1198 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1199 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1200 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1201 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1202
1203 // If both arguments of binary operation are shuffles, which use the same
1204 // mask and shuffle within a single vector, it is worthwhile to move the
1205 // shuffle after binary operation:
1206 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1207 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1208 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1209 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1210 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1211 isa<UndefValue>(RShuf->getOperand(1)) &&
Serge Pavlov05811092014-05-12 05:44:53 +00001212 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001213 LShuf->getMask() == RShuf->getMask()) {
Serge Pavlove6de9e32014-05-14 09:05:09 +00001214 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001215 RShuf->getOperand(0), Builder);
1216 Value *Res = Builder->CreateShuffleVector(NewBO,
Serge Pavlov02ff6202014-05-12 10:11:27 +00001217 UndefValue::get(NewBO->getType()), LShuf->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001218 return Res;
1219 }
1220 }
1221
1222 // If one argument is a shuffle within one vector, the other is a constant,
1223 // try moving the shuffle after the binary operation.
1224 ShuffleVectorInst *Shuffle = nullptr;
1225 Constant *C1 = nullptr;
1226 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1227 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1228 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1229 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
Benjamin Kramer6de78662014-06-24 10:38:10 +00001230 if (Shuffle && C1 &&
1231 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1232 isa<UndefValue>(Shuffle->getOperand(1)) &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001233 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1234 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1235 // Find constant C2 that has property:
1236 // shuffle(C2, ShMask) = C1
1237 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1238 // reorder is not possible.
1239 SmallVector<Constant*, 16> C2M(VWidth,
1240 UndefValue::get(C1->getType()->getScalarType()));
1241 bool MayChange = true;
1242 for (unsigned I = 0; I < VWidth; ++I) {
1243 if (ShMask[I] >= 0) {
1244 assert(ShMask[I] < (int)VWidth);
1245 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1246 MayChange = false;
1247 break;
1248 }
1249 C2M[ShMask[I]] = C1->getAggregateElement(I);
1250 }
1251 }
1252 if (MayChange) {
1253 Constant *C2 = ConstantVector::get(C2M);
1254 Value *NewLHS, *NewRHS;
1255 if (isa<Constant>(LHS)) {
1256 NewLHS = C2;
1257 NewRHS = Shuffle->getOperand(0);
1258 } else {
1259 NewLHS = Shuffle->getOperand(0);
1260 NewRHS = C2;
1261 }
Serge Pavlove6de9e32014-05-14 09:05:09 +00001262 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001263 Value *Res = Builder->CreateShuffleVector(NewBO,
1264 UndefValue::get(Inst.getType()), Shuffle->getMask());
1265 return Res;
1266 }
1267 }
1268
1269 return nullptr;
1270}
1271
Chris Lattner113f4f42002-06-25 16:13:24 +00001272Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001273 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1274
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001275 if (Value *V = SimplifyGEPInst(Ops, DL))
Chris Lattner8574aba2009-11-27 00:29:05 +00001276 return ReplaceInstUsesWith(GEP, V);
1277
Chris Lattner5f667a62004-05-07 22:09:22 +00001278 Value *PtrOp = GEP.getOperand(0);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001279
Duncan Sandsc133c542010-11-22 16:32:50 +00001280 // Eliminate unneeded casts for indices, and replace indices which displace
1281 // by multiples of a zero size type with zero.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001282 if (DL) {
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001283 bool MadeChange = false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001284 Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
Duncan Sandsc133c542010-11-22 16:32:50 +00001285
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001286 gep_type_iterator GTI = gep_type_begin(GEP);
1287 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1288 I != E; ++I, ++GTI) {
Duncan Sandsc133c542010-11-22 16:32:50 +00001289 // Skip indices into struct types.
Chris Lattner229907c2011-07-18 04:54:35 +00001290 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
Duncan Sandsc133c542010-11-22 16:32:50 +00001291 if (!SeqTy) continue;
1292
1293 // If the element type has zero size then any index over it is equivalent
1294 // to an index of zero, so replace it with zero if it is not zero already.
1295 if (SeqTy->getElementType()->isSized() &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001296 DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
Duncan Sandsc133c542010-11-22 16:32:50 +00001297 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1298 *I = Constant::getNullValue(IntPtrTy);
1299 MadeChange = true;
1300 }
1301
Nadav Rotem3924cb02011-12-05 06:29:09 +00001302 Type *IndexTy = (*I)->getType();
Duncan Sandsa318ef62012-11-03 11:44:17 +00001303 if (IndexTy != IntPtrTy) {
Duncan Sandsc133c542010-11-22 16:32:50 +00001304 // If we are using a wider index than needed for this platform, shrink
1305 // it to what we need. If narrower, sign-extend it to what we need.
1306 // This explicit cast can make subsequent optimizations more obvious.
1307 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1308 MadeChange = true;
1309 }
Chris Lattner69193f92004-04-05 01:30:19 +00001310 }
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001311 if (MadeChange) return &GEP;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00001312 }
Chris Lattner69193f92004-04-05 01:30:19 +00001313
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001314 // Check to see if the inputs to the PHI node are getelementptr instructions.
1315 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1316 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1317 if (!Op1)
1318 return nullptr;
1319
1320 signed DI = -1;
1321
1322 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1323 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1324 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1325 return nullptr;
1326
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001327 // Keep track of the type as we walk the GEP.
1328 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1329
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001330 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1331 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1332 return nullptr;
1333
1334 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1335 if (DI == -1) {
1336 // We have not seen any differences yet in the GEPs feeding the
1337 // PHI yet, so we record this one if it is allowed to be a
1338 // variable.
1339
1340 // The first two arguments can vary for any GEP, the rest have to be
1341 // static for struct slots
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001342 if (J > 1 && CurTy->isStructTy())
1343 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001344
1345 DI = J;
1346 } else {
1347 // The GEP is different by more than one input. While this could be
1348 // extended to support GEPs that vary by more than one variable it
1349 // doesn't make sense since it greatly increases the complexity and
1350 // would result in an R+R+R addressing mode which no backend
1351 // directly supports and would need to be broken into several
1352 // simpler instructions anyway.
1353 return nullptr;
1354 }
1355 }
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001356
1357 // Sink down a layer of the type for the next iteration.
1358 if (J > 0) {
1359 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1360 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1361 } else {
1362 CurTy = nullptr;
1363 }
1364 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001365 }
1366 }
1367
1368 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1369
1370 if (DI == -1) {
1371 // All the GEPs feeding the PHI are identical. Clone one down into our
1372 // BB so that it can be merged with the current GEP.
1373 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1374 NewGEP);
1375 } else {
1376 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1377 // into the current block so it can be merged, and create a new PHI to
1378 // set that index.
1379 Instruction *InsertPt = Builder->GetInsertPoint();
1380 Builder->SetInsertPoint(PN);
1381 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1382 PN->getNumOperands());
1383 Builder->SetInsertPoint(InsertPt);
1384
1385 for (auto &I : PN->operands())
1386 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1387 PN->getIncomingBlock(I));
1388
1389 NewGEP->setOperand(DI, NewPN);
1390 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1391 NewGEP);
1392 NewGEP->setOperand(DI, NewPN);
1393 }
1394
1395 GEP.setOperand(0, NewGEP);
1396 PtrOp = NewGEP;
1397 }
1398
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001399 // Combine Indices - If the source pointer to this getelementptr instruction
1400 // is a getelementptr instruction, combine the indices of the two
1401 // getelementptr instructions into a single instruction.
1402 //
Dan Gohman31a9b982009-07-28 01:40:03 +00001403 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001404 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Craig Topperf40110f2014-04-25 05:29:35 +00001405 return nullptr;
Rafael Espindola40325672011-07-11 03:43:47 +00001406
Duncan Sands533c8ae2012-10-23 08:28:26 +00001407 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner5f667a62004-05-07 22:09:22 +00001408 // chain to be resolved before we perform this transformation. This
1409 // avoids us creating a TON of code in some cases.
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001410 if (GEPOperator *SrcGEP =
1411 dyn_cast<GEPOperator>(Src->getOperand(0)))
1412 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Craig Topperf40110f2014-04-25 05:29:35 +00001413 return nullptr; // Wait until our source is folded to completion.
Chris Lattner5f667a62004-05-07 22:09:22 +00001414
Chris Lattneraf6094f2007-02-15 22:48:32 +00001415 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00001416
1417 // Find out whether the last index in the source GEP is a sequential idx.
1418 bool EndsWithSequential = false;
Chris Lattnerb2995e12009-08-30 05:30:55 +00001419 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1420 I != E; ++I)
Duncan Sands19d0b472010-02-16 11:11:14 +00001421 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001422
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001423 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00001424 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00001425 // Replace: gep (gep %P, long B), long A, ...
1426 // With: T = long A+B; gep %P, T, ...
1427 //
Chris Lattner06c687b2009-08-30 05:08:50 +00001428 Value *Sum;
1429 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1430 Value *GO1 = GEP.getOperand(1);
Owen Anderson5a1acd92009-07-31 20:28:14 +00001431 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001432 Sum = GO1;
Owen Anderson5a1acd92009-07-31 20:28:14 +00001433 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001434 Sum = SO1;
1435 } else {
Chris Lattnerb2995e12009-08-30 05:30:55 +00001436 // If they aren't the same type, then the input hasn't been processed
1437 // by the loop above yet (which canonicalizes sequential index types to
1438 // intptr_t). Just avoid transforming this until the input has been
1439 // normalized.
1440 if (SO1->getType() != GO1->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001441 return nullptr;
Chris Lattner59663412009-08-30 18:50:58 +00001442 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner69193f92004-04-05 01:30:19 +00001443 }
Chris Lattner5f667a62004-05-07 22:09:22 +00001444
Chris Lattnerb2995e12009-08-30 05:30:55 +00001445 // Update the GEP in place if possible.
Chris Lattner06c687b2009-08-30 05:08:50 +00001446 if (Src->getNumOperands() == 2) {
1447 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner5f667a62004-05-07 22:09:22 +00001448 GEP.setOperand(1, Sum);
1449 return &GEP;
Chris Lattner5f667a62004-05-07 22:09:22 +00001450 }
Chris Lattnerb2995e12009-08-30 05:30:55 +00001451 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001452 Indices.push_back(Sum);
Chris Lattnerb2995e12009-08-30 05:30:55 +00001453 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001454 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00001455 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner06c687b2009-08-30 05:08:50 +00001456 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001457 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerb2995e12009-08-30 05:30:55 +00001458 Indices.append(Src->op_begin()+1, Src->op_end());
1459 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001460 }
1461
Dan Gohman1b849082009-09-07 23:54:19 +00001462 if (!Indices.empty())
Chris Lattnere903f382010-01-05 07:42:10 +00001463 return (GEP.isInBounds() && Src->isInBounds()) ?
Jay Foadd1b78492011-07-25 09:48:08 +00001464 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1465 GEP.getName()) :
1466 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnere26bf172009-08-30 05:00:50 +00001467 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001468
Benjamin Kramere6461e32013-09-20 14:38:44 +00001469 // Canonicalize (gep i8* X, -(ptrtoint Y)) to (sub (ptrtoint X), (ptrtoint Y))
1470 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1471 // pointer arithmetic.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001472 if (DL && GEP.getNumIndices() == 1 &&
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001473 match(GEP.getOperand(1), m_Neg(m_PtrToInt(m_Value())))) {
1474 unsigned AS = GEP.getPointerAddressSpace();
1475 if (GEP.getType() == Builder->getInt8PtrTy(AS) &&
1476 GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001477 DL->getPointerSizeInBits(AS)) {
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001478 Operator *Index = cast<Operator>(GEP.getOperand(1));
1479 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1480 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1481 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1482 }
Benjamin Kramere6461e32013-09-20 14:38:44 +00001483 }
1484
Chris Lattner06c687b2009-08-30 05:08:50 +00001485 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnere903f382010-01-05 07:42:10 +00001486 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Roteme63e59c2012-03-26 20:39:18 +00001487 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1488
Nadav Rotema8f35622012-03-26 21:00:53 +00001489 // We do not handle pointer-vector geps here.
1490 if (!StrippedPtrTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001491 return nullptr;
Nadav Rotema8f35622012-03-26 21:00:53 +00001492
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001493 if (StrippedPtr != PtrOp) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001494 bool HasZeroPointerIndex = false;
1495 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1496 HasZeroPointerIndex = C->isZero();
Nadav Rotema069c6c2011-04-05 14:29:52 +00001497
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001498 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1499 // into : GEP [10 x i8]* X, i32 0, ...
1500 //
1501 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1502 // into : GEP i8* X, ...
Nadav Rotema069c6c2011-04-05 14:29:52 +00001503 //
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001504 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnere26bf172009-08-30 05:00:50 +00001505 if (HasZeroPointerIndex) {
Chris Lattner229907c2011-07-18 04:54:35 +00001506 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1507 if (ArrayType *CATy =
Duncan Sands5795a602009-03-02 09:18:21 +00001508 dyn_cast<ArrayType>(CPTy->getElementType())) {
1509 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnere903f382010-01-05 07:42:10 +00001510 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001511 // -> GEP i8* X, ...
Chris Lattnere903f382010-01-05 07:42:10 +00001512 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1513 GetElementPtrInst *Res =
Jay Foadd1b78492011-07-25 09:48:08 +00001514 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
Chris Lattnere903f382010-01-05 07:42:10 +00001515 Res->setIsInBounds(GEP.isInBounds());
Eli Bendersky9966b262014-04-03 17:51:58 +00001516 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1517 return Res;
1518 // Insert Res, and create an addrspacecast.
1519 // e.g.,
1520 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1521 // ->
1522 // %0 = GEP i8 addrspace(1)* X, ...
1523 // addrspacecast i8 addrspace(1)* %0 to i8*
1524 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001525 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001526
Chris Lattner229907c2011-07-18 04:54:35 +00001527 if (ArrayType *XATy =
Chris Lattnere903f382010-01-05 07:42:10 +00001528 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5795a602009-03-02 09:18:21 +00001529 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +00001530 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001531 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00001532 // At this point, we know that the cast source type is a pointer
1533 // to an array of the same type as the destination pointer
1534 // array. Because the array type is never stepped over (there
1535 // is a leading zero) we can fold the cast into this GEP.
Eli Bendersky9966b262014-04-03 17:51:58 +00001536 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1537 GEP.setOperand(0, StrippedPtr);
1538 return &GEP;
1539 }
1540 // Cannot replace the base pointer directly because StrippedPtr's
1541 // address space is different. Instead, create a new GEP followed by
1542 // an addrspacecast.
1543 // e.g.,
1544 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1545 // i32 0, ...
1546 // ->
1547 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1548 // addrspacecast i8 addrspace(1)* %0 to i8*
1549 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1550 Value *NewGEP = GEP.isInBounds() ?
1551 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1552 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1553 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner567b81f2005-09-13 00:40:14 +00001554 }
Duncan Sands5795a602009-03-02 09:18:21 +00001555 }
1556 }
Chris Lattner567b81f2005-09-13 00:40:14 +00001557 } else if (GEP.getNumOperands() == 2) {
1558 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001559 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1560 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner229907c2011-07-18 04:54:35 +00001561 Type *SrcElTy = StrippedPtrTy->getElementType();
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001562 Type *ResElTy = PtrOp->getType()->getPointerElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001563 if (DL && SrcElTy->isArrayTy() &&
1564 DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1565 DL->getTypeAllocSize(ResElTy)) {
1566 Type *IdxType = DL->getIntPtrType(GEP.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001567 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
Chris Lattnere903f382010-01-05 07:42:10 +00001568 Value *NewGEP = GEP.isInBounds() ?
Jay Foad040dd822011-07-22 08:16:57 +00001569 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1570 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001571
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001572 // V and GEP are both pointer types --> BitCast
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001573 if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
1574 return new BitCastInst(NewGEP, GEP.getType());
1575 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001576 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001577
Chris Lattner2a893292005-09-13 18:36:04 +00001578 // Transform things like:
Duncan Sands533c8ae2012-10-23 08:28:26 +00001579 // %V = mul i64 %N, 4
1580 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1581 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001582 if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001583 // Check that changing the type amounts to dividing the index by a scale
1584 // factor.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001585 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1586 uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
Duncan Sands533c8ae2012-10-23 08:28:26 +00001587 if (ResSize && SrcSize % ResSize == 0) {
1588 Value *Idx = GEP.getOperand(1);
1589 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1590 uint64_t Scale = SrcSize / ResSize;
1591
1592 // Earlier transforms ensure that the index has type IntPtrType, which
1593 // considerably simplifies the logic by eliminating implicit casts.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001594 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001595 "Index not cast to pointer width?");
1596
1597 bool NSW;
1598 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1599 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1600 // If the multiplication NewIdx * Scale may overflow then the new
1601 // GEP may not be "inbounds".
1602 Value *NewGEP = GEP.isInBounds() && NSW ?
1603 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1604 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001605
Duncan Sands533c8ae2012-10-23 08:28:26 +00001606 // The NewGEP must be pointer typed, so must the old one -> BitCast
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001607 if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
1608 return new BitCastInst(NewGEP, GEP.getType());
1609 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001610 }
1611 }
1612 }
1613
1614 // Similarly, transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001615 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00001616 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001617 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001618 if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001619 SrcElTy->isArrayTy()) {
1620 // Check that changing to the array element type amounts to dividing the
1621 // index by a scale factor.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001622 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001623 uint64_t ArrayEltSize
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001624 = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001625 if (ResSize && ArrayEltSize % ResSize == 0) {
1626 Value *Idx = GEP.getOperand(1);
1627 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1628 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001629
Duncan Sands533c8ae2012-10-23 08:28:26 +00001630 // Earlier transforms ensure that the index has type IntPtrType, which
1631 // considerably simplifies the logic by eliminating implicit casts.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001632 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001633 "Index not cast to pointer width?");
1634
1635 bool NSW;
1636 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1637 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1638 // If the multiplication NewIdx * Scale may overflow then the new
1639 // GEP may not be "inbounds".
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001640 Value *Off[2] = {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001641 Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001642 NewIdx
1643 };
1644
Duncan Sands533c8ae2012-10-23 08:28:26 +00001645 Value *NewGEP = GEP.isInBounds() && NSW ?
1646 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1647 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1648 // The NewGEP must be pointer typed, so must the old one -> BitCast
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001649 if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
1650 return new BitCastInst(NewGEP, GEP.getType());
1651 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00001652 }
1653 }
Chris Lattner2a893292005-09-13 18:36:04 +00001654 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001655 }
Chris Lattnerca081252001-12-14 16:52:21 +00001656 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001657
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001658 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +00001659 return nullptr;
Matt Arsenault98f34e32013-08-19 22:17:34 +00001660
Chris Lattnerfef138b2009-01-09 05:44:56 +00001661 /// See if we can simplify:
Chris Lattner97fd3592009-08-30 05:55:36 +00001662 /// X = bitcast A* to B*
Chris Lattnerfef138b2009-01-09 05:44:56 +00001663 /// Y = gep X, <...constant indices...>
1664 /// into a gep of the original struct. This is important for SROA and alias
1665 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +00001666 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Matt Arsenault98f34e32013-08-19 22:17:34 +00001667 Value *Operand = BCI->getOperand(0);
1668 PointerType *OpType = cast<PointerType>(Operand->getType());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001669 unsigned OffsetBits = DL->getPointerTypeSizeInBits(OpType);
Matt Arsenault98f34e32013-08-19 22:17:34 +00001670 APInt Offset(OffsetBits, 0);
1671 if (!isa<BitCastInst>(Operand) &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001672 GEP.accumulateConstantOffset(*DL, Offset) &&
Nadav Rotema069c6c2011-04-05 14:29:52 +00001673 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1674
Chris Lattnerfef138b2009-01-09 05:44:56 +00001675 // If this GEP instruction doesn't move the pointer, just replace the GEP
1676 // with a bitcast of the real input to the dest type.
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001677 if (!Offset) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001678 // If the bitcast is of an allocation, and the allocation will be
1679 // converted to match the type of the cast, don't touch this.
Matt Arsenault98f34e32013-08-19 22:17:34 +00001680 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001681 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1682 if (Instruction *I = visitBitCast(*BCI)) {
1683 if (I != BCI) {
1684 I->takeName(BCI);
1685 BCI->getParent()->getInstList().insert(BCI, I);
1686 ReplaceInstUsesWith(*BCI, I);
1687 }
1688 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +00001689 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001690 }
Matt Arsenault98f34e32013-08-19 22:17:34 +00001691 return new BitCastInst(Operand, GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +00001692 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001693
Chris Lattnerfef138b2009-01-09 05:44:56 +00001694 // Otherwise, if the offset is non-zero, we need to find out if there is a
1695 // field at Offset in 'A's type. If so, we can pull the cast through the
1696 // GEP.
1697 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001698 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
Chris Lattnere903f382010-01-05 07:42:10 +00001699 Value *NGEP = GEP.isInBounds() ?
Matt Arsenault98f34e32013-08-19 22:17:34 +00001700 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1701 Builder->CreateGEP(Operand, NewIndices);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001702
Chris Lattner59663412009-08-30 18:50:58 +00001703 if (NGEP->getType() == GEP.getType())
1704 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001705 NGEP->takeName(&GEP);
1706 return new BitCastInst(NGEP, GEP.getType());
1707 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001708 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001709 }
1710
Craig Topperf40110f2014-04-25 05:29:35 +00001711 return nullptr;
Chris Lattnerca081252001-12-14 16:52:21 +00001712}
1713
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001714static bool
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001715isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1716 const TargetLibraryInfo *TLI) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001717 SmallVector<Instruction*, 4> Worklist;
1718 Worklist.push_back(AI);
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001719
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001720 do {
1721 Instruction *PI = Worklist.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001722 for (User *U : PI->users()) {
1723 Instruction *I = cast<Instruction>(U);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001724 switch (I->getOpcode()) {
1725 default:
1726 // Give up the moment we see something we can't handle.
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001727 return false;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001728
1729 case Instruction::BitCast:
1730 case Instruction::GetElementPtr:
1731 Users.push_back(I);
1732 Worklist.push_back(I);
1733 continue;
1734
1735 case Instruction::ICmp: {
1736 ICmpInst *ICI = cast<ICmpInst>(I);
1737 // We can fold eq/ne comparisons with null to false/true, respectively.
1738 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1739 return false;
1740 Users.push_back(I);
1741 continue;
1742 }
1743
1744 case Instruction::Call:
1745 // Ignore no-op and store intrinsics.
1746 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1747 switch (II->getIntrinsicID()) {
1748 default:
1749 return false;
1750
1751 case Intrinsic::memmove:
1752 case Intrinsic::memcpy:
1753 case Intrinsic::memset: {
1754 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1755 if (MI->isVolatile() || MI->getRawDest() != PI)
1756 return false;
1757 }
1758 // fall through
1759 case Intrinsic::dbg_declare:
1760 case Intrinsic::dbg_value:
1761 case Intrinsic::invariant_start:
1762 case Intrinsic::invariant_end:
1763 case Intrinsic::lifetime_start:
1764 case Intrinsic::lifetime_end:
1765 case Intrinsic::objectsize:
1766 Users.push_back(I);
1767 continue;
1768 }
1769 }
1770
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001771 if (isFreeCall(I, TLI)) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001772 Users.push_back(I);
1773 continue;
1774 }
1775 return false;
1776
1777 case Instruction::Store: {
1778 StoreInst *SI = cast<StoreInst>(I);
1779 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1780 return false;
1781 Users.push_back(I);
1782 continue;
1783 }
1784 }
1785 llvm_unreachable("missing a return?");
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001786 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001787 } while (!Worklist.empty());
Duncan Sandsf162eac2010-05-27 19:09:06 +00001788 return true;
1789}
1790
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001791Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sandsf162eac2010-05-27 19:09:06 +00001792 // If we have a malloc call which is only used in any amount of comparisons
1793 // to null and free calls, delete the calls and replace the comparisons with
1794 // true or false as appropriate.
Nick Lewycky50f49662011-08-03 00:43:35 +00001795 SmallVector<WeakVH, 64> Users;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001796 if (isAllocSiteRemovable(&MI, Users, TLI)) {
Nick Lewycky50f49662011-08-03 00:43:35 +00001797 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1798 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1799 if (!I) continue;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001800
Nick Lewycky50f49662011-08-03 00:43:35 +00001801 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001802 ReplaceInstUsesWith(*C,
1803 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1804 C->isFalseWhenEqual()));
Nick Lewycky50f49662011-08-03 00:43:35 +00001805 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001806 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001807 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1808 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1809 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1810 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1811 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1812 }
Duncan Sandsf162eac2010-05-27 19:09:06 +00001813 }
Nick Lewycky50f49662011-08-03 00:43:35 +00001814 EraseInstFromFunction(*I);
Duncan Sandsf162eac2010-05-27 19:09:06 +00001815 }
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001816
1817 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopes9ac46612012-06-28 22:31:24 +00001818 // Replace invoke with a NOP intrinsic to maintain the original CFG
Nuno Lopes07594cb2012-06-25 17:11:47 +00001819 Module *M = II->getParent()->getParent()->getParent();
Nuno Lopes9ac46612012-06-28 22:31:24 +00001820 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1821 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001822 None, "", II->getParent());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001823 }
Duncan Sandsf162eac2010-05-27 19:09:06 +00001824 return EraseInstFromFunction(MI);
1825 }
Craig Topperf40110f2014-04-25 05:29:35 +00001826 return nullptr;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001827}
1828
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001829/// \brief Move the call to free before a NULL test.
1830///
1831/// Check if this free is accessed after its argument has been test
1832/// against NULL (property 0).
1833/// If yes, it is legal to move this call in its predecessor block.
1834///
1835/// The move is performed only if the block containing the call to free
1836/// will be removed, i.e.:
1837/// 1. it has only one predecessor P, and P has two successors
1838/// 2. it contains the call and an unconditional branch
1839/// 3. its successor is the same as its predecessor's successor
1840///
1841/// The profitability is out-of concern here and this function should
1842/// be called only if the caller knows this transformation would be
1843/// profitable (e.g., for code size).
1844static Instruction *
1845tryToMoveFreeBeforeNullTest(CallInst &FI) {
1846 Value *Op = FI.getArgOperand(0);
1847 BasicBlock *FreeInstrBB = FI.getParent();
1848 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1849
1850 // Validate part of constraint #1: Only one predecessor
1851 // FIXME: We can extend the number of predecessor, but in that case, we
1852 // would duplicate the call to free in each predecessor and it may
1853 // not be profitable even for code size.
1854 if (!PredBB)
Craig Topperf40110f2014-04-25 05:29:35 +00001855 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001856
1857 // Validate constraint #2: Does this block contains only the call to
1858 // free and an unconditional branch?
1859 // FIXME: We could check if we can speculate everything in the
1860 // predecessor block
1861 if (FreeInstrBB->size() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +00001862 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001863 BasicBlock *SuccBB;
1864 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00001865 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001866
1867 // Validate the rest of constraint #1 by matching on the pred branch.
1868 TerminatorInst *TI = PredBB->getTerminator();
1869 BasicBlock *TrueBB, *FalseBB;
1870 ICmpInst::Predicate Pred;
1871 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00001872 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001873 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
Craig Topperf40110f2014-04-25 05:29:35 +00001874 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001875
1876 // Validate constraint #3: Ensure the null case just falls through.
1877 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
Craig Topperf40110f2014-04-25 05:29:35 +00001878 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001879 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1880 "Broken CFG: missing edge from predecessor to successor");
1881
1882 FI.moveBefore(TI);
1883 return &FI;
1884}
Duncan Sandsf162eac2010-05-27 19:09:06 +00001885
1886
Gabor Greif75f69432010-06-24 12:21:15 +00001887Instruction *InstCombiner::visitFree(CallInst &FI) {
1888 Value *Op = FI.getArgOperand(0);
Victor Hernandeze2971492009-10-24 04:23:03 +00001889
1890 // free undef -> unreachable.
1891 if (isa<UndefValue>(Op)) {
1892 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedman41e509a2011-05-18 23:58:37 +00001893 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1894 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Victor Hernandeze2971492009-10-24 04:23:03 +00001895 return EraseInstFromFunction(FI);
1896 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001897
Victor Hernandeze2971492009-10-24 04:23:03 +00001898 // If we have 'free null' delete the instruction. This can happen in stl code
1899 // when lots of inlining happens.
1900 if (isa<ConstantPointerNull>(Op))
1901 return EraseInstFromFunction(FI);
1902
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001903 // If we optimize for code size, try to move the call to free before the null
1904 // test so that simplify cfg can remove the empty block and dead code
1905 // elimination the branch. I.e., helps to turn something like:
1906 // if (foo) free(foo);
1907 // into
1908 // free(foo);
1909 if (MinimizeSize)
1910 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
1911 return I;
1912
Craig Topperf40110f2014-04-25 05:29:35 +00001913 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +00001914}
Chris Lattner8427bff2003-12-07 01:24:23 +00001915
Chris Lattner14a251b2007-04-15 00:07:55 +00001916
Chris Lattner31f486c2005-01-31 05:36:43 +00001917
Chris Lattner9eef8a72003-06-04 04:46:00 +00001918Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1919 // Change br (not X), label True, label False to: br X, label False, True
Craig Topperf40110f2014-04-25 05:29:35 +00001920 Value *X = nullptr;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001921 BasicBlock *TrueDest;
1922 BasicBlock *FalseDest;
Dan Gohman5476cfd2009-08-12 16:23:25 +00001923 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001924 !isa<Constant>(X)) {
1925 // Swap Destinations and condition...
1926 BI.setCondition(X);
Chandler Carruth3e8aa652011-10-17 01:11:57 +00001927 BI.swapSuccessors();
Chris Lattnerd4252a72004-07-30 07:50:03 +00001928 return &BI;
1929 }
1930
Alp Tokercb402912014-01-24 17:20:08 +00001931 // Canonicalize fcmp_one -> fcmp_oeq
Reid Spencer266e42b2006-12-23 06:05:41 +00001932 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001933 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00001934 TrueDest, FalseDest)) &&
1935 BI.getCondition()->hasOneUse())
1936 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1937 FPred == FCmpInst::FCMP_OGE) {
1938 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1939 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001940
Chris Lattner905976b2009-08-30 06:13:40 +00001941 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00001942 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00001943 Worklist.Add(Cond);
Reid Spencer266e42b2006-12-23 06:05:41 +00001944 return &BI;
1945 }
1946
Alp Tokercb402912014-01-24 17:20:08 +00001947 // Canonicalize icmp_ne -> icmp_eq
Reid Spencer266e42b2006-12-23 06:05:41 +00001948 ICmpInst::Predicate IPred;
1949 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00001950 TrueDest, FalseDest)) &&
1951 BI.getCondition()->hasOneUse())
1952 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1953 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1954 IPred == ICmpInst::ICMP_SGE) {
1955 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1956 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1957 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00001958 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00001959 Worklist.Add(Cond);
Chris Lattnere967b342003-06-04 05:10:11 +00001960 return &BI;
1961 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001962
Craig Topperf40110f2014-04-25 05:29:35 +00001963 return nullptr;
Chris Lattner9eef8a72003-06-04 04:46:00 +00001964}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001965
Chris Lattner4c9c20a2004-07-03 00:26:11 +00001966Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1967 Value *Cond = SI.getCondition();
1968 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1969 if (I->getOpcode() == Instruction::Add)
1970 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1971 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
Eli Friedman95031ed2011-09-29 20:21:17 +00001972 // Skip the first item since that's the default case.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001973 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001974 i != e; ++i) {
1975 ConstantInt* CaseVal = i.getCaseValue();
Eli Friedman95031ed2011-09-29 20:21:17 +00001976 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
1977 AddRHS);
1978 assert(isa<ConstantInt>(NewCaseVal) &&
1979 "Result of expression should be constant");
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001980 i.setValue(cast<ConstantInt>(NewCaseVal));
Eli Friedman95031ed2011-09-29 20:21:17 +00001981 }
1982 SI.setCondition(I->getOperand(0));
Chris Lattner905976b2009-08-30 06:13:40 +00001983 Worklist.Add(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00001984 return &SI;
1985 }
1986 }
Craig Topperf40110f2014-04-25 05:29:35 +00001987 return nullptr;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00001988}
1989
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00001990Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00001991 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00001992
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00001993 if (!EV.hasIndices())
1994 return ReplaceInstUsesWith(EV, Agg);
1995
1996 if (Constant *C = dyn_cast<Constant>(Agg)) {
Chris Lattnerfa775002012-01-26 02:32:04 +00001997 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
1998 if (EV.getNumIndices() == 0)
1999 return ReplaceInstUsesWith(EV, C2);
2000 // Extract the remaining indices out of the constant indexed by the
2001 // first index
2002 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002003 }
Craig Topperf40110f2014-04-25 05:29:35 +00002004 return nullptr; // Can't handle other constants
Chris Lattnerfa775002012-01-26 02:32:04 +00002005 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002006
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002007 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2008 // We're extracting from an insertvalue instruction, compare the indices
2009 const unsigned *exti, *exte, *insi, *inse;
2010 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2011 exte = EV.idx_end(), inse = IV->idx_end();
2012 exti != exte && insi != inse;
2013 ++exti, ++insi) {
2014 if (*insi != *exti)
2015 // The insert and extract both reference distinctly different elements.
2016 // This means the extract is not influenced by the insert, and we can
2017 // replace the aggregate operand of the extract with the aggregate
2018 // operand of the insert. i.e., replace
2019 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2020 // %E = extractvalue { i32, { i32 } } %I, 0
2021 // with
2022 // %E = extractvalue { i32, { i32 } } %A, 0
2023 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002024 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002025 }
2026 if (exti == exte && insi == inse)
2027 // Both iterators are at the end: Index lists are identical. Replace
2028 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2029 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2030 // with "i32 42"
2031 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2032 if (exti == exte) {
2033 // The extract list is a prefix of the insert list. i.e. replace
2034 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2035 // %E = extractvalue { i32, { i32 } } %I, 1
2036 // with
2037 // %X = extractvalue { i32, { i32 } } %A, 1
2038 // %E = insertvalue { i32 } %X, i32 42, 0
2039 // by switching the order of the insert and extract (though the
2040 // insertvalue should be left in, since it may have other uses).
Chris Lattner59663412009-08-30 18:50:58 +00002041 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002042 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002043 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002044 makeArrayRef(insi, inse));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002045 }
2046 if (insi == inse)
2047 // The insert list is a prefix of the extract list
2048 // We can simply remove the common indices from the extract and make it
2049 // operate on the inserted value instead of the insertvalue result.
2050 // i.e., replace
2051 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2052 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2053 // with
2054 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002055 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002056 makeArrayRef(exti, exte));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002057 }
Chris Lattner39c07b22009-11-09 07:07:56 +00002058 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2059 // We're extracting from an intrinsic, see if we're the only user, which
2060 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif75f69432010-06-24 12:21:15 +00002061 // just get one value.
Chris Lattner39c07b22009-11-09 07:07:56 +00002062 if (II->hasOneUse()) {
2063 // Check if we're grabbing the overflow bit or the result of a 'with
2064 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2065 // and replace it with a traditional binary instruction.
2066 switch (II->getIntrinsicID()) {
2067 case Intrinsic::uadd_with_overflow:
2068 case Intrinsic::sadd_with_overflow:
2069 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002070 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002071 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002072 EraseInstFromFunction(*II);
2073 return BinaryOperator::CreateAdd(LHS, RHS);
2074 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002075
Chris Lattner3e635d22010-12-19 19:43:52 +00002076 // If the normal result of the add is dead, and the RHS is a constant,
2077 // we can transform this into a range comparison.
2078 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattner4fb9dd42010-12-19 23:24:04 +00002079 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2080 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2081 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2082 ConstantExpr::getNot(CI));
Chris Lattner39c07b22009-11-09 07:07:56 +00002083 break;
2084 case Intrinsic::usub_with_overflow:
2085 case Intrinsic::ssub_with_overflow:
2086 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002087 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002088 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002089 EraseInstFromFunction(*II);
2090 return BinaryOperator::CreateSub(LHS, RHS);
2091 }
2092 break;
2093 case Intrinsic::umul_with_overflow:
2094 case Intrinsic::smul_with_overflow:
2095 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002096 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002097 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002098 EraseInstFromFunction(*II);
2099 return BinaryOperator::CreateMul(LHS, RHS);
2100 }
2101 break;
2102 default:
2103 break;
2104 }
2105 }
2106 }
Frits van Bommel28218aa2010-11-29 21:56:20 +00002107 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2108 // If the (non-volatile) load only has one use, we can rewrite this to a
2109 // load from a GEP. This reduces the size of the load.
2110 // FIXME: If a load is used only by extractvalue instructions then this
2111 // could be done regardless of having multiple uses.
Eli Friedman8bc586e2011-08-15 22:09:40 +00002112 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel28218aa2010-11-29 21:56:20 +00002113 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2114 SmallVector<Value*, 4> Indices;
2115 // Prefix an i32 0 since we need the first element.
2116 Indices.push_back(Builder->getInt32(0));
2117 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2118 I != E; ++I)
2119 Indices.push_back(Builder->getInt32(*I));
2120
2121 // We need to insert these at the location of the old load, not at that of
2122 // the extractvalue.
2123 Builder->SetInsertPoint(L->getParent(), L);
Jay Foad040dd822011-07-22 08:16:57 +00002124 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
Frits van Bommel28218aa2010-11-29 21:56:20 +00002125 // Returning the load directly will cause the main loop to insert it in
2126 // the wrong spot, so use ReplaceInstUsesWith().
2127 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2128 }
2129 // We could simplify extracts from other values. Note that nested extracts may
2130 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002131 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel28218aa2010-11-29 21:56:20 +00002132 // the value inserted, if appropriate. Similarly for extracts from single-use
2133 // loads: extract (extract (load)) will be translated to extract (load (gep))
2134 // and if again single-use then via load (gep (gep)) to load (gep).
2135 // However, double extracts from e.g. function arguments or return values
2136 // aren't handled yet.
Craig Topperf40110f2014-04-25 05:29:35 +00002137 return nullptr;
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002138}
2139
Duncan Sands5c055792011-09-30 13:12:16 +00002140enum Personality_Type {
2141 Unknown_Personality,
2142 GNU_Ada_Personality,
Bill Wendlingc68c8cb2011-10-17 21:20:24 +00002143 GNU_CXX_Personality,
2144 GNU_ObjC_Personality
Duncan Sands5c055792011-09-30 13:12:16 +00002145};
2146
2147/// RecognizePersonality - See if the given exception handling personality
2148/// function is one that we understand. If so, return a description of it;
2149/// otherwise return Unknown_Personality.
2150static Personality_Type RecognizePersonality(Value *Pers) {
2151 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
2152 if (!F)
2153 return Unknown_Personality;
2154 return StringSwitch<Personality_Type>(F->getName())
2155 .Case("__gnat_eh_personality", GNU_Ada_Personality)
Bill Wendlingc68c8cb2011-10-17 21:20:24 +00002156 .Case("__gxx_personality_v0", GNU_CXX_Personality)
2157 .Case("__objc_personality_v0", GNU_ObjC_Personality)
Duncan Sands5c055792011-09-30 13:12:16 +00002158 .Default(Unknown_Personality);
2159}
2160
2161/// isCatchAll - Return 'true' if the given typeinfo will match anything.
2162static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
2163 switch (Personality) {
2164 case Unknown_Personality:
2165 return false;
2166 case GNU_Ada_Personality:
2167 // While __gnat_all_others_value will match any Ada exception, it doesn't
2168 // match foreign exceptions (or didn't, before gcc-4.7).
2169 return false;
2170 case GNU_CXX_Personality:
Bill Wendlingc68c8cb2011-10-17 21:20:24 +00002171 case GNU_ObjC_Personality:
Duncan Sands5c055792011-09-30 13:12:16 +00002172 return TypeInfo->isNullValue();
2173 }
2174 llvm_unreachable("Unknown personality!");
2175}
2176
2177static bool shorter_filter(const Value *LHS, const Value *RHS) {
2178 return
2179 cast<ArrayType>(LHS->getType())->getNumElements()
2180 <
2181 cast<ArrayType>(RHS->getType())->getNumElements();
2182}
2183
2184Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2185 // The logic here should be correct for any real-world personality function.
2186 // However if that turns out not to be true, the offending logic can always
2187 // be conditioned on the personality function, like the catch-all logic is.
2188 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
2189
2190 // Simplify the list of clauses, eg by removing repeated catch clauses
2191 // (these are often created by inlining).
2192 bool MakeNewInstruction = false; // If true, recreate using the following:
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002193 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
Duncan Sands5c055792011-09-30 13:12:16 +00002194 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2195
2196 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2197 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2198 bool isLastClause = i + 1 == e;
2199 if (LI.isCatch(i)) {
2200 // A catch clause.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002201 Constant *CatchClause = LI.getClause(i);
Rafael Espindola78598d92014-06-04 19:01:48 +00002202 Constant *TypeInfo = CatchClause->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002203
2204 // If we already saw this clause, there is no point in having a second
2205 // copy of it.
2206 if (AlreadyCaught.insert(TypeInfo)) {
2207 // This catch clause was not already seen.
2208 NewClauses.push_back(CatchClause);
2209 } else {
2210 // Repeated catch clause - drop the redundant copy.
2211 MakeNewInstruction = true;
2212 }
2213
2214 // If this is a catch-all then there is no point in keeping any following
2215 // clauses or marking the landingpad as having a cleanup.
2216 if (isCatchAll(Personality, TypeInfo)) {
2217 if (!isLastClause)
2218 MakeNewInstruction = true;
2219 CleanupFlag = false;
2220 break;
2221 }
2222 } else {
2223 // A filter clause. If any of the filter elements were already caught
2224 // then they can be dropped from the filter. It is tempting to try to
2225 // exploit the filter further by saying that any typeinfo that does not
2226 // occur in the filter can't be caught later (and thus can be dropped).
2227 // However this would be wrong, since typeinfos can match without being
2228 // equal (for example if one represents a C++ class, and the other some
2229 // class derived from it).
2230 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002231 Constant *FilterClause = LI.getClause(i);
Duncan Sands5c055792011-09-30 13:12:16 +00002232 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2233 unsigned NumTypeInfos = FilterType->getNumElements();
2234
2235 // An empty filter catches everything, so there is no point in keeping any
2236 // following clauses or marking the landingpad as having a cleanup. By
2237 // dealing with this case here the following code is made a bit simpler.
2238 if (!NumTypeInfos) {
2239 NewClauses.push_back(FilterClause);
2240 if (!isLastClause)
2241 MakeNewInstruction = true;
2242 CleanupFlag = false;
2243 break;
2244 }
2245
2246 bool MakeNewFilter = false; // If true, make a new filter.
2247 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2248 if (isa<ConstantAggregateZero>(FilterClause)) {
2249 // Not an empty filter - it contains at least one null typeinfo.
2250 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2251 Constant *TypeInfo =
2252 Constant::getNullValue(FilterType->getElementType());
2253 // If this typeinfo is a catch-all then the filter can never match.
2254 if (isCatchAll(Personality, TypeInfo)) {
2255 // Throw the filter away.
2256 MakeNewInstruction = true;
2257 continue;
2258 }
2259
2260 // There is no point in having multiple copies of this typeinfo, so
2261 // discard all but the first copy if there is more than one.
2262 NewFilterElts.push_back(TypeInfo);
2263 if (NumTypeInfos > 1)
2264 MakeNewFilter = true;
2265 } else {
2266 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2267 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2268 NewFilterElts.reserve(NumTypeInfos);
2269
2270 // Remove any filter elements that were already caught or that already
2271 // occurred in the filter. While there, see if any of the elements are
2272 // catch-alls. If so, the filter can be discarded.
2273 bool SawCatchAll = false;
2274 for (unsigned j = 0; j != NumTypeInfos; ++j) {
Rafael Espindola78598d92014-06-04 19:01:48 +00002275 Constant *Elt = Filter->getOperand(j);
2276 Constant *TypeInfo = Elt->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002277 if (isCatchAll(Personality, TypeInfo)) {
2278 // This element is a catch-all. Bail out, noting this fact.
2279 SawCatchAll = true;
2280 break;
2281 }
2282 if (AlreadyCaught.count(TypeInfo))
2283 // Already caught by an earlier clause, so having it in the filter
2284 // is pointless.
2285 continue;
2286 // There is no point in having multiple copies of the same typeinfo in
2287 // a filter, so only add it if we didn't already.
2288 if (SeenInFilter.insert(TypeInfo))
2289 NewFilterElts.push_back(cast<Constant>(Elt));
2290 }
2291 // A filter containing a catch-all cannot match anything by definition.
2292 if (SawCatchAll) {
2293 // Throw the filter away.
2294 MakeNewInstruction = true;
2295 continue;
2296 }
2297
2298 // If we dropped something from the filter, make a new one.
2299 if (NewFilterElts.size() < NumTypeInfos)
2300 MakeNewFilter = true;
2301 }
2302 if (MakeNewFilter) {
2303 FilterType = ArrayType::get(FilterType->getElementType(),
2304 NewFilterElts.size());
2305 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2306 MakeNewInstruction = true;
2307 }
2308
2309 NewClauses.push_back(FilterClause);
2310
2311 // If the new filter is empty then it will catch everything so there is
2312 // no point in keeping any following clauses or marking the landingpad
2313 // as having a cleanup. The case of the original filter being empty was
2314 // already handled above.
2315 if (MakeNewFilter && !NewFilterElts.size()) {
2316 assert(MakeNewInstruction && "New filter but not a new instruction!");
2317 CleanupFlag = false;
2318 break;
2319 }
2320 }
2321 }
2322
2323 // If several filters occur in a row then reorder them so that the shortest
2324 // filters come first (those with the smallest number of elements). This is
2325 // advantageous because shorter filters are more likely to match, speeding up
2326 // unwinding, but mostly because it increases the effectiveness of the other
2327 // filter optimizations below.
2328 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2329 unsigned j;
2330 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2331 for (j = i; j != e; ++j)
2332 if (!isa<ArrayType>(NewClauses[j]->getType()))
2333 break;
2334
2335 // Check whether the filters are already sorted by length. We need to know
2336 // if sorting them is actually going to do anything so that we only make a
2337 // new landingpad instruction if it does.
2338 for (unsigned k = i; k + 1 < j; ++k)
2339 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2340 // Not sorted, so sort the filters now. Doing an unstable sort would be
2341 // correct too but reordering filters pointlessly might confuse users.
2342 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2343 shorter_filter);
2344 MakeNewInstruction = true;
2345 break;
2346 }
2347
2348 // Look for the next batch of filters.
2349 i = j + 1;
2350 }
2351
2352 // If typeinfos matched if and only if equal, then the elements of a filter L
2353 // that occurs later than a filter F could be replaced by the intersection of
2354 // the elements of F and L. In reality two typeinfos can match without being
2355 // equal (for example if one represents a C++ class, and the other some class
2356 // derived from it) so it would be wrong to perform this transform in general.
2357 // However the transform is correct and useful if F is a subset of L. In that
2358 // case L can be replaced by F, and thus removed altogether since repeating a
2359 // filter is pointless. So here we look at all pairs of filters F and L where
2360 // L follows F in the list of clauses, and remove L if every element of F is
2361 // an element of L. This can occur when inlining C++ functions with exception
2362 // specifications.
2363 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2364 // Examine each filter in turn.
2365 Value *Filter = NewClauses[i];
2366 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2367 if (!FTy)
2368 // Not a filter - skip it.
2369 continue;
2370 unsigned FElts = FTy->getNumElements();
2371 // Examine each filter following this one. Doing this backwards means that
2372 // we don't have to worry about filters disappearing under us when removed.
2373 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2374 Value *LFilter = NewClauses[j];
2375 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2376 if (!LTy)
2377 // Not a filter - skip it.
2378 continue;
2379 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2380 // an element of LFilter, then discard LFilter.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002381 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
Duncan Sands5c055792011-09-30 13:12:16 +00002382 // If Filter is empty then it is a subset of LFilter.
2383 if (!FElts) {
2384 // Discard LFilter.
2385 NewClauses.erase(J);
2386 MakeNewInstruction = true;
2387 // Move on to the next filter.
2388 continue;
2389 }
2390 unsigned LElts = LTy->getNumElements();
2391 // If Filter is longer than LFilter then it cannot be a subset of it.
2392 if (FElts > LElts)
2393 // Move on to the next filter.
2394 continue;
2395 // At this point we know that LFilter has at least one element.
2396 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002397 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands5c055792011-09-30 13:12:16 +00002398 // already know that Filter is not longer than LFilter).
2399 if (isa<ConstantAggregateZero>(Filter)) {
2400 assert(FElts <= LElts && "Should have handled this case earlier!");
2401 // Discard LFilter.
2402 NewClauses.erase(J);
2403 MakeNewInstruction = true;
2404 }
2405 // Move on to the next filter.
2406 continue;
2407 }
2408 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2409 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2410 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002411 // LFilter iff LFilter contains a zero.
Duncan Sands5c055792011-09-30 13:12:16 +00002412 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2413 for (unsigned l = 0; l != LElts; ++l)
2414 if (LArray->getOperand(l)->isNullValue()) {
2415 // LFilter contains a zero - discard it.
2416 NewClauses.erase(J);
2417 MakeNewInstruction = true;
2418 break;
2419 }
2420 // Move on to the next filter.
2421 continue;
2422 }
2423 // At this point we know that both filters are ConstantArrays. Loop over
2424 // operands to see whether every element of Filter is also an element of
2425 // LFilter. Since filters tend to be short this is probably faster than
2426 // using a method that scales nicely.
2427 ConstantArray *FArray = cast<ConstantArray>(Filter);
2428 bool AllFound = true;
2429 for (unsigned f = 0; f != FElts; ++f) {
2430 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2431 AllFound = false;
2432 for (unsigned l = 0; l != LElts; ++l) {
2433 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2434 if (LTypeInfo == FTypeInfo) {
2435 AllFound = true;
2436 break;
2437 }
2438 }
2439 if (!AllFound)
2440 break;
2441 }
2442 if (AllFound) {
2443 // Discard LFilter.
2444 NewClauses.erase(J);
2445 MakeNewInstruction = true;
2446 }
2447 // Move on to the next filter.
2448 }
2449 }
2450
2451 // If we changed any of the clauses, replace the old landingpad instruction
2452 // with a new one.
2453 if (MakeNewInstruction) {
2454 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2455 LI.getPersonalityFn(),
2456 NewClauses.size());
2457 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2458 NLI->addClause(NewClauses[i]);
2459 // A landing pad with no clauses must have the cleanup flag set. It is
2460 // theoretically possible, though highly unlikely, that we eliminated all
2461 // clauses. If so, force the cleanup flag to true.
2462 if (NewClauses.empty())
2463 CleanupFlag = true;
2464 NLI->setCleanup(CleanupFlag);
2465 return NLI;
2466 }
2467
2468 // Even if none of the clauses changed, we may nonetheless have understood
2469 // that the cleanup flag is pointless. Clear it if so.
2470 if (LI.isCleanup() != CleanupFlag) {
2471 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2472 LI.setCleanup(CleanupFlag);
2473 return &LI;
2474 }
2475
Craig Topperf40110f2014-04-25 05:29:35 +00002476 return nullptr;
Duncan Sands5c055792011-09-30 13:12:16 +00002477}
2478
Chris Lattnerfbb77a42006-04-10 22:45:52 +00002479
Robert Bocchinoa8352962006-01-13 22:48:06 +00002480
Chris Lattner39c98bb2004-12-08 23:43:58 +00002481
2482/// TryToSinkInstruction - Try to move the specified instruction from its
2483/// current block into the beginning of DestBlock, which can only happen if it's
2484/// safe to move the instruction past all of the instructions between it and the
2485/// end of its block.
2486static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2487 assert(I->hasOneUse() && "Invariants didn't hold!");
2488
Bill Wendlinge86965e2011-08-15 21:14:31 +00002489 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Bill Wendlinga9ee09f2011-08-17 20:36:44 +00002490 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2491 isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +00002492 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002493
Chris Lattner39c98bb2004-12-08 23:43:58 +00002494 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00002495 if (isa<AllocaInst>(I) && I->getParent() ==
2496 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002497 return false;
2498
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002499 // We can only sink load instructions if there is nothing between the load and
2500 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +00002501 if (I->mayReadFromMemory()) {
2502 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002503 Scan != E; ++Scan)
2504 if (Scan->mayWriteToMemory())
2505 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002506 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002507
Bill Wendling8ddfc092011-08-16 20:45:24 +00002508 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Chris Lattner9f269e42005-08-08 19:11:57 +00002509 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002510 ++NumSunkInst;
2511 return true;
2512}
2513
Chris Lattnera36ee4e2006-05-10 19:00:36 +00002514
2515/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2516/// all reachable code to the worklist.
2517///
2518/// This has a couple of tricks to make the code faster and more powerful. In
2519/// particular, we constant fold and DCE instructions as we go, to avoid adding
2520/// them to the worklist (this significantly speeds up instcombine on code where
2521/// many instructions are dead or constant). Additionally, if we find a branch
2522/// whose condition is a known constant, we only visit the reachable successors.
2523///
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002524static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00002525 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002526 InstCombiner &IC,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002527 const DataLayout *DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002528 const TargetLibraryInfo *TLI) {
Chris Lattnerc855b452009-10-15 04:59:28 +00002529 bool MadeIRChange = false;
Chris Lattner1d239152008-08-15 04:03:01 +00002530 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner12b89cc2007-03-23 19:17:18 +00002531 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00002532
Benjamin Kramer76229bc2010-10-23 17:10:24 +00002533 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Eli Friedman68aab452011-05-24 18:52:07 +00002534 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2535
Dan Gohman28943872010-01-05 16:27:25 +00002536 do {
2537 BB = Worklist.pop_back_val();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002538
Chris Lattner12b89cc2007-03-23 19:17:18 +00002539 // We have now visited this block! If we've already been here, ignore it.
2540 if (!Visited.insert(BB)) continue;
Devang Patel7ed6c532008-11-19 18:56:50 +00002541
Chris Lattner12b89cc2007-03-23 19:17:18 +00002542 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2543 Instruction *Inst = BBI++;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002544
Chris Lattner12b89cc2007-03-23 19:17:18 +00002545 // DCE instruction if trivially dead.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002546 if (isInstructionTriviallyDead(Inst, TLI)) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00002547 ++NumDeadInst;
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002548 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner12b89cc2007-03-23 19:17:18 +00002549 Inst->eraseFromParent();
2550 continue;
2551 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002552
Chris Lattner12b89cc2007-03-23 19:17:18 +00002553 // ConstantProp instruction if trivially constant.
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002554 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002555 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002556 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002557 << *Inst << '\n');
2558 Inst->replaceAllUsesWith(C);
2559 ++NumConstProp;
2560 Inst->eraseFromParent();
2561 continue;
2562 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002563
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002564 if (DL) {
Chris Lattnerc855b452009-10-15 04:59:28 +00002565 // See if we can constant fold its operands.
2566 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2567 i != e; ++i) {
2568 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002569 if (CE == nullptr) continue;
Eli Friedman68aab452011-05-24 18:52:07 +00002570
2571 Constant*& FoldRes = FoldedConstants[CE];
2572 if (!FoldRes)
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002573 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
Eli Friedman68aab452011-05-24 18:52:07 +00002574 if (!FoldRes)
2575 FoldRes = CE;
2576
2577 if (FoldRes != CE) {
2578 *i = FoldRes;
Chris Lattnerc855b452009-10-15 04:59:28 +00002579 MadeIRChange = true;
2580 }
2581 }
2582 }
Devang Patel7ed6c532008-11-19 18:56:50 +00002583
Chris Lattner8abd5722009-10-12 03:58:40 +00002584 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00002585 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00002586
2587 // Recursively visit successors. If this is a branch or switch on a
2588 // constant, only visit the reachable successor.
2589 TerminatorInst *TI = BB->getTerminator();
2590 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2591 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2592 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky271506f2008-03-09 08:50:23 +00002593 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002594 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +00002595 continue;
2596 }
2597 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2598 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2599 // See if this is an explicit destination.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002600 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002601 i != e; ++i)
2602 if (i.getCaseValue() == Cond) {
2603 BasicBlock *ReachableBB = i.getCaseSuccessor();
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002604 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +00002605 continue;
2606 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002607
Chris Lattner12b89cc2007-03-23 19:17:18 +00002608 // Otherwise it is the default destination.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002609 Worklist.push_back(SI->getDefaultDest());
Chris Lattner12b89cc2007-03-23 19:17:18 +00002610 continue;
2611 }
2612 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002613
Chris Lattner12b89cc2007-03-23 19:17:18 +00002614 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2615 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman28943872010-01-05 16:27:25 +00002616 } while (!Worklist.empty());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002617
Chris Lattner8abd5722009-10-12 03:58:40 +00002618 // Once we've found all of the instructions to add to instcombine's worklist,
2619 // add them in reverse order. This way instcombine will visit from the top
2620 // of the function down. This jives well with the way that it adds all uses
2621 // of instructions to the worklist after doing a transformation, thus avoiding
2622 // some N^2 behavior in pathological cases.
2623 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2624 InstrsForInstCombineWorklist.size());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002625
Chris Lattnerc855b452009-10-15 04:59:28 +00002626 return MadeIRChange;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00002627}
2628
Chris Lattner960a5432007-03-03 02:04:50 +00002629bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002630 MadeIRChange = false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002631
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002632 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +00002633 << F.getName() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00002634
Chris Lattner4ed40f72005-07-07 20:40:38 +00002635 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00002636 // Do a depth-first traversal of the function, populate the worklist with
2637 // the reachable instructions. Ignore blocks that are not reachable. Keep
2638 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00002639 SmallPtrSet<BasicBlock*, 64> Visited;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002640 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002641 TLI);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002642
Chris Lattner4ed40f72005-07-07 20:40:38 +00002643 // Do a quick scan over the function. If we find any blocks that are
2644 // unreachable, remove any instructions inside of them. This prevents
2645 // the instcombine code from having to deal with some bad special cases.
Bill Wendlinga3ba6d32011-09-01 21:29:49 +00002646 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2647 if (Visited.count(BB)) continue;
2648
Bill Wendling321fb372011-09-04 09:43:36 +00002649 // Delete the instructions backwards, as it has a reduced likelihood of
2650 // having to update as many def-use and use-def chains.
2651 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2652 while (EndInst != BB->begin()) {
2653 // Delete the next to last instruction.
2654 BasicBlock::iterator I = EndInst;
2655 Instruction *Inst = --I;
Bill Wendlinga3ba6d32011-09-01 21:29:49 +00002656 if (!Inst->use_empty())
2657 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Bill Wendling321fb372011-09-04 09:43:36 +00002658 if (isa<LandingPadInst>(Inst)) {
2659 EndInst = Inst;
Bill Wendlinga3ba6d32011-09-01 21:29:49 +00002660 continue;
Bill Wendling321fb372011-09-04 09:43:36 +00002661 }
Bill Wendlinga3ba6d32011-09-01 21:29:49 +00002662 if (!isa<DbgInfoIntrinsic>(Inst)) {
2663 ++NumDeadInst;
2664 MadeIRChange = true;
Chris Lattner4ed40f72005-07-07 20:40:38 +00002665 }
Bill Wendlinga3ba6d32011-09-01 21:29:49 +00002666 Inst->eraseFromParent();
Chris Lattner4ed40f72005-07-07 20:40:38 +00002667 }
Bill Wendlinga3ba6d32011-09-01 21:29:49 +00002668 }
Chris Lattner4ed40f72005-07-07 20:40:38 +00002669 }
Chris Lattnerca081252001-12-14 16:52:21 +00002670
Chris Lattner97fd3592009-08-30 05:55:36 +00002671 while (!Worklist.isEmpty()) {
2672 Instruction *I = Worklist.RemoveOne();
Craig Topperf40110f2014-04-25 05:29:35 +00002673 if (I == nullptr) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00002674
Chris Lattner1443bc52006-05-11 17:11:52 +00002675 // Check to see if we can DCE the instruction.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002676 if (isInstructionTriviallyDead(I, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002677 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
Chris Lattner905976b2009-08-30 06:13:40 +00002678 EraseInstFromFunction(*I);
2679 ++NumDeadInst;
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002680 MadeIRChange = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002681 continue;
2682 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002683
Chris Lattner1443bc52006-05-11 17:11:52 +00002684 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002685 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002686 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002687 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnercd517ff2005-01-28 19:32:01 +00002688
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002689 // Add operands to the worklist.
2690 ReplaceInstUsesWith(*I, C);
2691 ++NumConstProp;
2692 EraseInstFromFunction(*I);
2693 MadeIRChange = true;
2694 continue;
2695 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002696
Chris Lattner39c98bb2004-12-08 23:43:58 +00002697 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002698 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002699 BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +00002700 Instruction *UserInst = cast<Instruction>(*I->user_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002701 BasicBlock *UserParent;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002702
Chris Lattner6b9044d2009-10-14 15:21:58 +00002703 // Get the block the use occurs in.
2704 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002705 UserParent = PN->getIncomingBlock(*I->use_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002706 else
2707 UserParent = UserInst->getParent();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002708
Chris Lattner39c98bb2004-12-08 23:43:58 +00002709 if (UserParent != BB) {
2710 bool UserIsSuccessor = false;
2711 // See if the user is one of our successors.
2712 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2713 if (*SI == UserParent) {
2714 UserIsSuccessor = true;
2715 break;
2716 }
2717
2718 // If the user is one of our immediate successors, and if that successor
2719 // only has us as a predecessors (we'd have to split the critical edge
2720 // otherwise), we can keep going.
Chris Lattner6b9044d2009-10-14 15:21:58 +00002721 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002722 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002723 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002724 }
2725 }
2726
Chris Lattner022a5822009-08-30 07:44:24 +00002727 // Now that we have an instruction, try combining it to simplify it.
2728 Builder->SetInsertPoint(I->getParent(), I);
Eli Friedman96254a02011-05-18 01:28:27 +00002729 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002730
Reid Spencer755d0e72007-03-26 17:44:01 +00002731#ifndef NDEBUG
2732 std::string OrigI;
2733#endif
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002734 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002735 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
Jeffrey Yasskindafd08e2009-10-08 00:12:24 +00002736
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002737 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002738 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002739 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002740 if (Result != I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002741 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002742 << " New = " << *Result << '\n');
2743
Eli Friedman35211c62011-05-27 00:19:40 +00002744 if (!I->getDebugLoc().isUnknown())
2745 Result->setDebugLoc(I->getDebugLoc());
Chris Lattner396dbfe2004-06-09 05:08:07 +00002746 // Everything uses the new instruction now.
2747 I->replaceAllUsesWith(Result);
2748
Jim Grosbache7abae02011-10-05 20:53:43 +00002749 // Move the name to the new instruction first.
2750 Result->takeName(I);
2751
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002752 // Push the new instruction and any users onto the worklist.
2753 Worklist.Add(Result);
2754 Worklist.AddUsersToWorkList(*Result);
2755
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002756 // Insert the new instruction into the basic block...
2757 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00002758 BasicBlock::iterator InsertPos = I;
2759
Eli Friedmana49b8282011-11-01 04:49:29 +00002760 // If we replace a PHI with something that isn't a PHI, fix up the
2761 // insertion point.
2762 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2763 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattner7515cab2004-11-14 19:13:23 +00002764
2765 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002766
Chris Lattner905976b2009-08-30 06:13:40 +00002767 EraseInstFromFunction(*I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002768 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00002769#ifndef NDEBUG
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002770 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002771 << " New = " << *I << '\n');
Evan Chenga4ed8a52007-03-27 16:44:48 +00002772#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00002773
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002774 // If the instruction was modified, it's possible that it is now dead.
2775 // if so, remove it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002776 if (isInstructionTriviallyDead(I, TLI)) {
Chris Lattner905976b2009-08-30 06:13:40 +00002777 EraseInstFromFunction(*I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00002778 } else {
Chris Lattner905976b2009-08-30 06:13:40 +00002779 Worklist.Add(I);
Chris Lattnerbacd05c2009-08-30 06:22:51 +00002780 Worklist.AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002781 }
Chris Lattner053c0932002-05-14 15:24:07 +00002782 }
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002783 MadeIRChange = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002784 }
2785 }
2786
Chris Lattner97fd3592009-08-30 05:55:36 +00002787 Worklist.Zap();
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002788 return MadeIRChange;
Chris Lattner04805fa2002-02-26 21:46:54 +00002789}
2790
Meador Inge76fc1a42012-11-11 03:51:43 +00002791namespace {
2792class InstCombinerLibCallSimplifier : public LibCallSimplifier {
2793 InstCombiner *IC;
2794public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002795 InstCombinerLibCallSimplifier(const DataLayout *DL,
Meador Inge76fc1a42012-11-11 03:51:43 +00002796 const TargetLibraryInfo *TLI,
2797 InstCombiner *IC)
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002798 : LibCallSimplifier(DL, TLI, UnsafeFPShrink) {
Meador Inge76fc1a42012-11-11 03:51:43 +00002799 this->IC = IC;
2800 }
2801
2802 /// replaceAllUsesWith - override so that instruction replacement
2803 /// can be defined in terms of the instruction combiner framework.
Craig Topper3e4c6972014-03-05 09:10:37 +00002804 void replaceAllUsesWith(Instruction *I, Value *With) const override {
Meador Inge76fc1a42012-11-11 03:51:43 +00002805 IC->ReplaceInstUsesWith(*I, With);
2806 }
2807};
2808}
Chris Lattner960a5432007-03-03 02:04:50 +00002809
2810bool InstCombiner::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00002811 if (skipOptnoneFunction(F))
2812 return false;
2813
Rafael Espindola93512512014-02-25 17:30:31 +00002814 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00002815 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chad Rosiere6de63d2011-12-01 21:29:16 +00002816 TLI = &getAnalysis<TargetLibraryInfo>();
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002817 // Minimizing size?
2818 MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2819 Attribute::MinSize);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002820
Chris Lattner022a5822009-08-30 07:44:24 +00002821 /// Builder - This is an IRBuilder that automatically inserts new
2822 /// instructions into the worklist when they are created.
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002823 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002824 TheBuilder(F.getContext(), TargetFolder(DL),
Chris Lattner022a5822009-08-30 07:44:24 +00002825 InstCombineIRInserter(Worklist));
2826 Builder = &TheBuilder;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002827
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002828 InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
Meador Ingedf796f82012-10-13 16:45:24 +00002829 Simplifier = &TheSimplifier;
2830
Chris Lattner960a5432007-03-03 02:04:50 +00002831 bool EverMadeChange = false;
2832
Devang Patelaad34d82011-03-17 22:18:16 +00002833 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2834 // by instcombiner.
2835 EverMadeChange = LowerDbgDeclare(F);
2836
Chris Lattner960a5432007-03-03 02:04:50 +00002837 // Iterate while there is work to do.
2838 unsigned Iteration = 0;
Bill Wendling37169522008-05-14 22:45:20 +00002839 while (DoOneIteration(F, Iteration++))
Chris Lattner960a5432007-03-03 02:04:50 +00002840 EverMadeChange = true;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002841
Craig Topperf40110f2014-04-25 05:29:35 +00002842 Builder = nullptr;
Chris Lattner960a5432007-03-03 02:04:50 +00002843 return EverMadeChange;
2844}
2845
Brian Gaeke38b79e82004-07-27 17:43:21 +00002846FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00002847 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00002848}