blob: 75206c28dde341c8836d4743a9c553bfe23e37b2 [file] [log] [blame]
Owen Andersone3590582007-08-02 18:11:11 +00001//===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
Owen Anderson5e72db32007-07-11 00:46:18 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Owen Anderson5e72db32007-07-11 00:46:18 +00006//
7//===----------------------------------------------------------------------===//
8//
Chad Rosierd7634fc2015-12-11 18:39:41 +00009// This file implements a trivial dead store elimination that only considers
10// basic-block local redundant stores.
11//
12// FIXME: This should eventually be extended to be a post-dominator tree
13// traversal. Doing so would be pretty trivial.
Owen Anderson5e72db32007-07-11 00:46:18 +000014//
15//===----------------------------------------------------------------------===//
16
Justin Bogner594e07b2016-05-17 21:38:13 +000017#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000018#include "llvm/ADT/APInt.h"
Hal Finkela1271032016-06-23 13:46:39 +000019#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SetVector.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000024#include "llvm/ADT/StringRef.h"
Owen Andersonaa071722007-07-11 23:19:17 +000025#include "llvm/Analysis/AliasAnalysis.h"
Nick Lewycky32f80512011-10-22 21:59:35 +000026#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000027#include "llvm/Analysis/GlobalsModRef.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000029#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000030#include "llvm/Analysis/MemoryLocation.h"
Florian Hahn9b41a732019-03-29 14:10:24 +000031#include "llvm/Analysis/OrderedBasicBlock.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattnerc0f33792010-11-30 23:05:20 +000033#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000034#include "llvm/IR/Argument.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/CallSite.h"
37#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Function.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000042#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000046#include "llvm/IR/Intrinsics.h"
Sanjay Patel1d04b5b2017-09-26 13:54:28 +000047#include "llvm/IR/LLVMContext.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000048#include "llvm/IR/Module.h"
49#include "llvm/IR/PassManager.h"
50#include "llvm/IR/Value.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include "llvm/Pass.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000052#include "llvm/Support/Casting.h"
Hal Finkela1271032016-06-23 13:46:39 +000053#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/Debug.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000055#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000057#include "llvm/Support/raw_ostream.h"
Justin Bogner594e07b2016-05-17 21:38:13 +000058#include "llvm/Transforms/Scalar.h"
Florian Hahn9b41a732019-03-29 14:10:24 +000059#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000060#include <algorithm>
61#include <cassert>
Eugene Zelenko3b879392017-10-13 21:17:07 +000062#include <cstddef>
David Blaikie2be39222018-03-21 22:34:23 +000063#include <cstdint>
Eugene Zelenko3b879392017-10-13 21:17:07 +000064#include <iterator>
Hal Finkela1271032016-06-23 13:46:39 +000065#include <map>
Eugene Zelenko3b879392017-10-13 21:17:07 +000066#include <utility>
67
Owen Anderson5e72db32007-07-11 00:46:18 +000068using namespace llvm;
69
Chandler Carruth964daaa2014-04-22 02:55:47 +000070#define DEBUG_TYPE "dse"
71
Erik Eckstein11fc8172015-08-13 15:36:11 +000072STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
Owen Anderson5e72db32007-07-11 00:46:18 +000073STATISTIC(NumFastStores, "Number of stores deleted");
Jun Limda5864c2018-08-17 18:40:41 +000074STATISTIC(NumFastOther, "Number of other instrs removed");
Hal Finkela1271032016-06-23 13:46:39 +000075STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
Sanjay Patel1d04b5b2017-09-26 13:54:28 +000076STATISTIC(NumModifiedStores, "Number of stores modified");
Hal Finkela1271032016-06-23 13:46:39 +000077
78static cl::opt<bool>
79EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking",
80 cl::init(true), cl::Hidden,
81 cl::desc("Enable partial-overwrite tracking in DSE"));
Owen Anderson5e72db32007-07-11 00:46:18 +000082
Sanjay Patel1d04b5b2017-09-26 13:54:28 +000083static cl::opt<bool>
84EnablePartialStoreMerging("enable-dse-partial-store-merging",
85 cl::init(true), cl::Hidden,
86 cl::desc("Enable partial store merging in DSE"));
87
Chris Lattner67122512010-11-30 21:58:14 +000088//===----------------------------------------------------------------------===//
89// Helper functions
90//===----------------------------------------------------------------------===//
Eugene Zelenko3b879392017-10-13 21:17:07 +000091using OverlapIntervalsTy = std::map<int64_t, int64_t>;
92using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>;
Chris Lattner67122512010-11-30 21:58:14 +000093
Chad Rosiera8bc5122016-06-10 17:58:01 +000094/// Delete this instruction. Before we do, go through and zero out all the
Justin Bogner594e07b2016-05-17 21:38:13 +000095/// operands of this instruction. If any of them become dead, delete them and
96/// the computation tree that feeds them.
Eric Christopher0efe9f62015-08-19 02:15:13 +000097/// If ValueSet is non-null, remove any deleted instructions from it as well.
Justin Bogner594e07b2016-05-17 21:38:13 +000098static void
Chad Rosierdcfce2d2016-07-06 19:48:52 +000099deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI,
100 MemoryDependenceResults &MD, const TargetLibraryInfo &TLI,
Florian Hahn9b41a732019-03-29 14:10:24 +0000101 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB,
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000102 SmallSetVector<const Value *, 16> *ValueSet = nullptr) {
Eric Christopher0efe9f62015-08-19 02:15:13 +0000103 SmallVector<Instruction*, 32> NowDeadInsts;
104
105 NowDeadInsts.push_back(I);
106 --NumFastOther;
107
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000108 // Keeping the iterator straight is a pain, so we let this routine tell the
109 // caller what the next instruction is after we're done mucking about.
110 BasicBlock::iterator NewIter = *BBI;
111
Eric Christopher0efe9f62015-08-19 02:15:13 +0000112 // Before we touch this instruction, remove it from memdep!
113 do {
114 Instruction *DeadInst = NowDeadInsts.pop_back_val();
115 ++NumFastOther;
116
Vedant Kumar35fc1032018-02-13 18:15:26 +0000117 // Try to preserve debug information attached to the dead instruction.
118 salvageDebugInfo(*DeadInst);
119
Eric Christopher0efe9f62015-08-19 02:15:13 +0000120 // This instruction is dead, zap it, in stages. Start by removing it from
121 // MemDep, which needs to know the operands and needs it to be in the
122 // function.
123 MD.removeInstruction(DeadInst);
124
125 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
126 Value *Op = DeadInst->getOperand(op);
127 DeadInst->setOperand(op, nullptr);
128
129 // If this operand just became dead, add it to the NowDeadInsts list.
130 if (!Op->use_empty()) continue;
131
132 if (Instruction *OpI = dyn_cast<Instruction>(Op))
133 if (isInstructionTriviallyDead(OpI, &TLI))
134 NowDeadInsts.push_back(OpI);
135 }
136
Eli Friedmana6707f52016-08-12 01:09:53 +0000137 if (ValueSet) ValueSet->remove(DeadInst);
Eli Friedmana6707f52016-08-12 01:09:53 +0000138 IOL.erase(DeadInst);
Florian Hahn9b41a732019-03-29 14:10:24 +0000139 OBB.eraseInstruction(DeadInst);
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000140
141 if (NewIter == DeadInst->getIterator())
142 NewIter = DeadInst->eraseFromParent();
143 else
144 DeadInst->eraseFromParent();
Eric Christopher0efe9f62015-08-19 02:15:13 +0000145 } while (!NowDeadInsts.empty());
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000146 *BBI = NewIter;
Eric Christopher0efe9f62015-08-19 02:15:13 +0000147}
148
Justin Bogner594e07b2016-05-17 21:38:13 +0000149/// Does this instruction write some memory? This only returns true for things
150/// that we can analyze with other helpers below.
Philip Reames424e7a12018-01-21 01:44:33 +0000151static bool hasAnalyzableMemoryWrite(Instruction *I,
152 const TargetLibraryInfo &TLI) {
Nick Lewycky90271472009-11-10 06:46:40 +0000153 if (isa<StoreInst>(I))
154 return true;
155 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
156 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000157 default:
158 return false;
159 case Intrinsic::memset:
160 case Intrinsic::memmove:
161 case Intrinsic::memcpy:
Daniel Neilsoncc45e922018-04-23 19:06:49 +0000162 case Intrinsic::memcpy_element_unordered_atomic:
163 case Intrinsic::memmove_element_unordered_atomic:
164 case Intrinsic::memset_element_unordered_atomic:
Chris Lattner2764b4d2009-12-02 06:35:55 +0000165 case Intrinsic::init_trampoline:
166 case Intrinsic::lifetime_end:
167 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000168 }
169 }
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000170 if (auto CS = CallSite(I)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000171 if (Function *F = CS.getCalledFunction()) {
Chad Rosier624fee52016-06-16 17:06:04 +0000172 StringRef FnName = F->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000173 if (TLI.has(LibFunc_strcpy) && FnName == TLI.getName(LibFunc_strcpy))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000174 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000175 if (TLI.has(LibFunc_strncpy) && FnName == TLI.getName(LibFunc_strncpy))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000176 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000177 if (TLI.has(LibFunc_strcat) && FnName == TLI.getName(LibFunc_strcat))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000178 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000179 if (TLI.has(LibFunc_strncat) && FnName == TLI.getName(LibFunc_strncat))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000180 return true;
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000181 }
182 }
Nick Lewycky90271472009-11-10 06:46:40 +0000183 return false;
184}
185
Justin Bogner594e07b2016-05-17 21:38:13 +0000186/// Return a Location stored to by the specified instruction. If isRemovable
187/// returns true, this function and getLocForRead completely describe the memory
188/// operations for this instruction.
Philip Reamesf57714c2018-01-21 02:10:54 +0000189static MemoryLocation getLocForWrite(Instruction *Inst) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000190
Chris Lattner58b779e2010-11-30 07:23:21 +0000191 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000192 return MemoryLocation::get(SI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000193
Daniel Neilsoncc45e922018-04-23 19:06:49 +0000194 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) {
Chris Lattner58b779e2010-11-30 07:23:21 +0000195 // memcpy/memmove/memset.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000196 MemoryLocation Loc = MemoryLocation::getForDest(MI);
Chris Lattner58b779e2010-11-30 07:23:21 +0000197 return Loc;
198 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000199
Philip Reamesf57714c2018-01-21 02:10:54 +0000200 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
201 switch (II->getIntrinsicID()) {
202 default:
203 return MemoryLocation(); // Unhandled intrinsic.
204 case Intrinsic::init_trampoline:
205 return MemoryLocation(II->getArgOperand(0));
206 case Intrinsic::lifetime_end: {
207 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
208 return MemoryLocation(II->getArgOperand(1), Len);
209 }
210 }
Chris Lattner58b779e2010-11-30 07:23:21 +0000211 }
Philip Reamesf57714c2018-01-21 02:10:54 +0000212 if (auto CS = CallSite(Inst))
213 // All the supported TLI functions so far happen to have dest as their
214 // first argument.
215 return MemoryLocation(CS.getArgument(0));
216 return MemoryLocation();
Chris Lattner58b779e2010-11-30 07:23:21 +0000217}
218
Philip Reames424e7a12018-01-21 01:44:33 +0000219/// Return the location read by the specified "hasAnalyzableMemoryWrite"
220/// instruction if any.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000221static MemoryLocation getLocForRead(Instruction *Inst,
222 const TargetLibraryInfo &TLI) {
Philip Reames424e7a12018-01-21 01:44:33 +0000223 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case");
Owen Anderson58704ee2011-09-06 18:14:09 +0000224
Chris Lattner94fbdf32010-12-06 01:48:06 +0000225 // The only instructions that both read and write are the mem transfer
226 // instructions (memcpy/memmove).
Daniel Neilsoncc45e922018-04-23 19:06:49 +0000227 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000228 return MemoryLocation::getForSource(MTI);
Chandler Carruthac80dc72015-06-17 07:18:54 +0000229 return MemoryLocation();
Chris Lattner94fbdf32010-12-06 01:48:06 +0000230}
231
Justin Bogner594e07b2016-05-17 21:38:13 +0000232/// If the value of this instruction and the memory it writes to is unused, may
233/// we delete this instruction?
Chris Lattner3590ef82010-11-30 05:30:45 +0000234static bool isRemovable(Instruction *I) {
Eli Friedman9a468152011-08-17 22:22:24 +0000235 // Don't remove volatile/atomic stores.
Nick Lewycky90271472009-11-10 06:46:40 +0000236 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Eli Friedman9a468152011-08-17 22:22:24 +0000237 return SI->isUnordered();
Owen Anderson58704ee2011-09-06 18:14:09 +0000238
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000239 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
240 switch (II->getIntrinsicID()) {
Philip Reames424e7a12018-01-21 01:44:33 +0000241 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate");
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000242 case Intrinsic::lifetime_end:
243 // Never remove dead lifetime_end's, e.g. because it is followed by a
244 // free.
245 return false;
246 case Intrinsic::init_trampoline:
247 // Always safe to remove init_trampoline.
248 return true;
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000249 case Intrinsic::memset:
250 case Intrinsic::memmove:
251 case Intrinsic::memcpy:
252 // Don't remove volatile memory intrinsics.
253 return !cast<MemIntrinsic>(II)->isVolatile();
Daniel Neilsoncc45e922018-04-23 19:06:49 +0000254 case Intrinsic::memcpy_element_unordered_atomic:
255 case Intrinsic::memmove_element_unordered_atomic:
256 case Intrinsic::memset_element_unordered_atomic:
257 return true;
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000258 }
Chris Lattnerb63ba732010-11-30 19:12:10 +0000259 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000260
Philip Reames424e7a12018-01-21 01:44:33 +0000261 // note: only get here for calls with analyzable writes - i.e. libcalls
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000262 if (auto CS = CallSite(I))
Nick Lewycky42bca052012-09-25 01:55:59 +0000263 return CS.getInstruction()->use_empty();
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000264
265 return false;
Nick Lewycky90271472009-11-10 06:46:40 +0000266}
267
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000268/// Returns true if the end of this instruction can be safely shortened in
Pete Cooper856977c2011-11-09 23:07:35 +0000269/// length.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000270static bool isShortenableAtTheEnd(Instruction *I) {
Pete Cooper856977c2011-11-09 23:07:35 +0000271 // Don't shorten stores for now
272 if (isa<StoreInst>(I))
273 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000274
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000275 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
276 switch (II->getIntrinsicID()) {
277 default: return false;
278 case Intrinsic::memset:
279 case Intrinsic::memcpy:
Daniel Neilson71fa1b92018-05-10 15:12:49 +0000280 case Intrinsic::memcpy_element_unordered_atomic:
281 case Intrinsic::memset_element_unordered_atomic:
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000282 // Do shorten memory intrinsics.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000283 // FIXME: Add memmove if it's also safe to transform.
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000284 return true;
285 }
Pete Cooper856977c2011-11-09 23:07:35 +0000286 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000287
288 // Don't shorten libcalls calls for now.
289
290 return false;
Pete Cooper856977c2011-11-09 23:07:35 +0000291}
292
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000293/// Returns true if the beginning of this instruction can be safely shortened
294/// in length.
295static bool isShortenableAtTheBeginning(Instruction *I) {
296 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
297 // easily done by offsetting the source address.
Daniel Neilson71fa1b92018-05-10 15:12:49 +0000298 return isa<AnyMemSetInst>(I);
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000299}
300
Justin Bogner594e07b2016-05-17 21:38:13 +0000301/// Return the pointer that is being written to.
Chris Lattner67122512010-11-30 21:58:14 +0000302static Value *getStoredPointerOperand(Instruction *I) {
Philip Reames424e7a12018-01-21 01:44:33 +0000303 //TODO: factor this to reuse getLocForWrite
Philip Reamesf57714c2018-01-21 02:10:54 +0000304 MemoryLocation Loc = getLocForWrite(I);
305 assert(Loc.Ptr &&
Hiroshi Inouef2096492018-06-14 05:41:49 +0000306 "unable to find pointer written for analyzable instruction?");
Philip Reamesf57714c2018-01-21 02:10:54 +0000307 // TODO: most APIs don't expect const Value *
308 return const_cast<Value*>(Loc.Ptr);
Nick Lewycky90271472009-11-10 06:46:40 +0000309}
310
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000311static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
Manoj Gupta77eeac32018-07-09 22:27:23 +0000312 const TargetLibraryInfo &TLI,
313 const Function *F) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000314 uint64_t Size;
Manoj Gupta77eeac32018-07-09 22:27:23 +0000315 ObjectSizeOpts Opts;
316 Opts.NullIsUnknownSize = NullPointerIsDefined(F);
317
318 if (getObjectSize(V, Size, DL, &TLI, Opts))
Nuno Lopes55fff832012-06-21 15:45:28 +0000319 return Size;
Chandler Carruthecbd1682015-06-17 07:21:38 +0000320 return MemoryLocation::UnknownSize;
Chris Lattner903add82010-11-30 23:43:23 +0000321}
Chris Lattner51c28a92010-11-30 19:34:42 +0000322
Pete Cooper856977c2011-11-09 23:07:35 +0000323namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000324
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000325enum OverwriteResult {
326 OW_Begin,
327 OW_Complete,
328 OW_End,
329 OW_PartialEarlierWithFullLater,
330 OW_Unknown
331};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000332
333} // end anonymous namespace
Pete Cooper856977c2011-11-09 23:07:35 +0000334
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000335/// Return 'OW_Complete' if a store to the 'Later' location completely
336/// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the
337/// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000338/// beginning of the 'Earlier' location is overwritten by 'Later'.
339/// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was
340/// overwritten by a latter (smaller) store which doesn't write outside the big
341/// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000342static OverwriteResult isOverwrite(const MemoryLocation &Later,
343 const MemoryLocation &Earlier,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000344 const DataLayout &DL,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000345 const TargetLibraryInfo &TLI,
Hal Finkela1271032016-06-23 13:46:39 +0000346 int64_t &EarlierOff, int64_t &LaterOff,
347 Instruction *DepWrite,
Piotr Padlewskic77ab8e2018-05-03 11:03:53 +0000348 InstOverlapIntervalsTy &IOL,
Manoj Gupta77eeac32018-07-09 22:27:23 +0000349 AliasAnalysis &AA,
350 const Function *F) {
George Burgess IV40dc63e2018-10-10 06:39:40 +0000351 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll
352 // get imprecise values here, though (except for unknown sizes).
353 if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise())
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000354 return OW_Unknown;
Chad Rosier72a793c2016-06-15 22:17:38 +0000355
George Burgess IVf96e6182018-10-09 03:18:56 +0000356 const uint64_t LaterSize = Later.Size.getValue();
357 const uint64_t EarlierSize = Earlier.Size.getValue();
George Burgess IVfefc42c2018-10-09 02:14:33 +0000358
Chris Lattnerc0f33792010-11-30 23:05:20 +0000359 const Value *P1 = Earlier.Ptr->stripPointerCasts();
360 const Value *P2 = Later.Ptr->stripPointerCasts();
Owen Anderson58704ee2011-09-06 18:14:09 +0000361
Chris Lattnerc0f33792010-11-30 23:05:20 +0000362 // If the start pointers are the same, we just have to compare sizes to see if
363 // the later store was larger than the earlier store.
Piotr Padlewskic77ab8e2018-05-03 11:03:53 +0000364 if (P1 == P2 || AA.isMustAlias(P1, P2)) {
Chris Lattnerc0f33792010-11-30 23:05:20 +0000365 // Make sure that the Later size is >= the Earlier size.
George Burgess IVfefc42c2018-10-09 02:14:33 +0000366 if (LaterSize >= EarlierSize)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000367 return OW_Complete;
Chris Lattner77d79fa2010-11-30 19:28:23 +0000368 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000369
Chris Lattner903add82010-11-30 23:43:23 +0000370 // Check to see if the later store is to the entire object (either a global,
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000371 // an alloca, or a byval/inalloca argument). If so, then it clearly
372 // overwrites any other store to the same object.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000373 const Value *UO1 = GetUnderlyingObject(P1, DL),
374 *UO2 = GetUnderlyingObject(P2, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000375
Chris Lattner903add82010-11-30 23:43:23 +0000376 // If we can't resolve the same pointers to the same object, then we can't
377 // analyze them at all.
378 if (UO1 != UO2)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000379 return OW_Unknown;
Owen Anderson58704ee2011-09-06 18:14:09 +0000380
Chris Lattner903add82010-11-30 23:43:23 +0000381 // If the "Later" store is to a recognizable object, get its size.
Manoj Gupta77eeac32018-07-09 22:27:23 +0000382 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000383 if (ObjectSize != MemoryLocation::UnknownSize)
George Burgess IVfefc42c2018-10-09 02:14:33 +0000384 if (ObjectSize == LaterSize && ObjectSize >= EarlierSize)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000385 return OW_Complete;
Owen Anderson58704ee2011-09-06 18:14:09 +0000386
Chris Lattnerc0f33792010-11-30 23:05:20 +0000387 // Okay, we have stores to two completely different pointers. Try to
388 // decompose the pointer into a "base + constant_offset" form. If the base
389 // pointers are equal, then we can reason about the two stores.
Pete Cooper856977c2011-11-09 23:07:35 +0000390 EarlierOff = 0;
391 LaterOff = 0;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000392 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
393 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000394
Chris Lattnerc0f33792010-11-30 23:05:20 +0000395 // If the base pointers still differ, we have two completely different stores.
396 if (BP1 != BP2)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000397 return OW_Unknown;
Bill Wendlingdb40b5c2011-03-26 01:20:37 +0000398
Bill Wendling19f33b92011-03-26 08:02:59 +0000399 // The later store completely overlaps the earlier store if:
Owen Anderson58704ee2011-09-06 18:14:09 +0000400 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000401 // 1. Both start at the same offset and the later one's size is greater than
402 // or equal to the earlier one's, or
403 //
404 // |--earlier--|
405 // |-- later --|
Owen Anderson58704ee2011-09-06 18:14:09 +0000406 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000407 // 2. The earlier store has an offset greater than the later offset, but which
408 // still lies completely within the later store.
409 //
410 // |--earlier--|
411 // |----- later ------|
Bill Wendling50341592011-03-30 21:37:19 +0000412 //
413 // We have to be careful here as *Off is signed while *.Size is unsigned.
Bill Wendlingb5139922011-03-26 09:32:07 +0000414 if (EarlierOff >= LaterOff &&
George Burgess IVfefc42c2018-10-09 02:14:33 +0000415 LaterSize >= EarlierSize &&
416 uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000417 return OW_Complete;
Nadav Rotem465834c2012-07-24 10:51:42 +0000418
Hal Finkela1271032016-06-23 13:46:39 +0000419 // We may now overlap, although the overlap is not complete. There might also
420 // be other incomplete overlaps, and together, they might cover the complete
421 // earlier write.
422 // Note: The correctness of this logic depends on the fact that this function
423 // is not even called providing DepWrite when there are any intervening reads.
424 if (EnablePartialOverwriteTracking &&
George Burgess IVfefc42c2018-10-09 02:14:33 +0000425 LaterOff < int64_t(EarlierOff + EarlierSize) &&
426 int64_t(LaterOff + LaterSize) >= EarlierOff) {
Hal Finkela1271032016-06-23 13:46:39 +0000427
428 // Insert our part of the overlap into the map.
429 auto &IM = IOL[DepWrite];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000430 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff
George Burgess IVfefc42c2018-10-09 02:14:33 +0000431 << ", " << int64_t(EarlierOff + EarlierSize)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000432 << ") Later [" << LaterOff << ", "
George Burgess IVfefc42c2018-10-09 02:14:33 +0000433 << int64_t(LaterOff + LaterSize) << ")\n");
Hal Finkela1271032016-06-23 13:46:39 +0000434
435 // Make sure that we only insert non-overlapping intervals and combine
436 // adjacent intervals. The intervals are stored in the map with the ending
437 // offset as the key (in the half-open sense) and the starting offset as
438 // the value.
George Burgess IVfefc42c2018-10-09 02:14:33 +0000439 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize;
Hal Finkela1271032016-06-23 13:46:39 +0000440
441 // Find any intervals ending at, or after, LaterIntStart which start
442 // before LaterIntEnd.
443 auto ILI = IM.lower_bound(LaterIntStart);
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000444 if (ILI != IM.end() && ILI->second <= LaterIntEnd) {
445 // This existing interval is overlapped with the current store somewhere
446 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing
447 // intervals and adjusting our start and end.
Hal Finkela1271032016-06-23 13:46:39 +0000448 LaterIntStart = std::min(LaterIntStart, ILI->second);
449 LaterIntEnd = std::max(LaterIntEnd, ILI->first);
450 ILI = IM.erase(ILI);
451
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000452 // Continue erasing and adjusting our end in case other previous
453 // intervals are also overlapped with the current store.
454 //
455 // |--- ealier 1 ---| |--- ealier 2 ---|
456 // |------- later---------|
457 //
458 while (ILI != IM.end() && ILI->second <= LaterIntEnd) {
459 assert(ILI->second > LaterIntStart && "Unexpected interval");
Hal Finkela1271032016-06-23 13:46:39 +0000460 LaterIntEnd = std::max(LaterIntEnd, ILI->first);
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000461 ILI = IM.erase(ILI);
462 }
Hal Finkela1271032016-06-23 13:46:39 +0000463 }
464
465 IM[LaterIntEnd] = LaterIntStart;
466
467 ILI = IM.begin();
468 if (ILI->second <= EarlierOff &&
George Burgess IVfefc42c2018-10-09 02:14:33 +0000469 ILI->first >= int64_t(EarlierOff + EarlierSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000470 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier ["
471 << EarlierOff << ", "
George Burgess IVfefc42c2018-10-09 02:14:33 +0000472 << int64_t(EarlierOff + EarlierSize)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000473 << ") Composite Later [" << ILI->second << ", "
474 << ILI->first << ")\n");
Hal Finkela1271032016-06-23 13:46:39 +0000475 ++NumCompletePartials;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000476 return OW_Complete;
Hal Finkela1271032016-06-23 13:46:39 +0000477 }
478 }
479
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000480 // Check for an earlier store which writes to all the memory locations that
481 // the later store writes to.
482 if (EnablePartialStoreMerging && LaterOff >= EarlierOff &&
George Burgess IVfefc42c2018-10-09 02:14:33 +0000483 int64_t(EarlierOff + EarlierSize) > LaterOff &&
484 uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000485 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load ["
486 << EarlierOff << ", "
George Burgess IVfefc42c2018-10-09 02:14:33 +0000487 << int64_t(EarlierOff + EarlierSize)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000488 << ") by a later store [" << LaterOff << ", "
George Burgess IVfefc42c2018-10-09 02:14:33 +0000489 << int64_t(LaterOff + LaterSize) << ")\n");
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000490 // TODO: Maybe come up with a better name?
491 return OW_PartialEarlierWithFullLater;
492 }
493
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000494 // Another interesting case is if the later store overwrites the end of the
495 // earlier store.
Pete Cooper856977c2011-11-09 23:07:35 +0000496 //
497 // |--earlier--|
498 // |-- later --|
499 //
500 // In this case we may want to trim the size of earlier to avoid generating
501 // writes to addresses which will definitely be overwritten later
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000502 if (!EnablePartialOverwriteTracking &&
George Burgess IVfefc42c2018-10-09 02:14:33 +0000503 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) &&
504 int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize)))
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000505 return OW_End;
Bill Wendling19f33b92011-03-26 08:02:59 +0000506
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000507 // Finally, we also need to check if the later store overwrites the beginning
508 // of the earlier store.
509 //
510 // |--earlier--|
511 // |-- later --|
512 //
513 // In this case we may want to move the destination address and trim the size
514 // of earlier to avoid generating writes to addresses which will definitely
515 // be overwritten later.
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000516 if (!EnablePartialOverwriteTracking &&
George Burgess IVfefc42c2018-10-09 02:14:33 +0000517 (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) {
518 assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) &&
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000519 "Expect to be handled as OW_Complete");
520 return OW_Begin;
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000521 }
Bill Wendling19f33b92011-03-26 08:02:59 +0000522 // Otherwise, they don't completely overlap.
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000523 return OW_Unknown;
Nick Lewycky90271472009-11-10 06:46:40 +0000524}
525
Justin Bogner594e07b2016-05-17 21:38:13 +0000526/// If 'Inst' might be a self read (i.e. a noop copy of a
Chris Lattner94fbdf32010-12-06 01:48:06 +0000527/// memory region into an identical pointer) then it doesn't actually make its
Owen Anderson58704ee2011-09-06 18:14:09 +0000528/// input dead in the traditional sense. Consider this case:
Chris Lattner94fbdf32010-12-06 01:48:06 +0000529///
Sanjoy Das737fa402018-02-20 23:19:34 +0000530/// memmove(A <- B)
531/// memmove(A <- A)
Chris Lattner94fbdf32010-12-06 01:48:06 +0000532///
533/// In this case, the second store to A does not make the first store to A dead.
534/// The usual situation isn't an explicit A<-A store like this (which can be
535/// trivially removed) but a case where two pointers may alias.
536///
537/// This function detects when it is unsafe to remove a dependent instruction
538/// because the DSE inducing instruction may be a self-read.
539static bool isPossibleSelfRead(Instruction *Inst,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000540 const MemoryLocation &InstStoreLoc,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000541 Instruction *DepWrite,
542 const TargetLibraryInfo &TLI,
543 AliasAnalysis &AA) {
Chris Lattner94fbdf32010-12-06 01:48:06 +0000544 // Self reads can only happen for instructions that read memory. Get the
545 // location read.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000546 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
Sanjoy Das737fa402018-02-20 23:19:34 +0000547 if (!InstReadLoc.Ptr)
548 return false; // Not a reading instruction.
Owen Anderson58704ee2011-09-06 18:14:09 +0000549
Chris Lattner94fbdf32010-12-06 01:48:06 +0000550 // If the read and written loc obviously don't alias, it isn't a read.
Sanjoy Das737fa402018-02-20 23:19:34 +0000551 if (AA.isNoAlias(InstReadLoc, InstStoreLoc))
Chris Lattner94fbdf32010-12-06 01:48:06 +0000552 return false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000553
Daniel Neilsoncc45e922018-04-23 19:06:49 +0000554 if (isa<AnyMemCpyInst>(Inst)) {
Sanjoy Das737fa402018-02-20 23:19:34 +0000555 // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763)
556 // but in practice memcpy(A <- B) either means that A and B are disjoint or
557 // are equal (i.e. there are not partial overlaps). Given that, if we have:
558 //
559 // memcpy/memmove(A <- B) // DepWrite
560 // memcpy(A <- B) // Inst
561 //
562 // with Inst reading/writing a >= size than DepWrite, we can reason as
563 // follows:
564 //
565 // - If A == B then both the copies are no-ops, so the DepWrite can be
566 // removed.
567 // - If A != B then A and B are disjoint locations in Inst. Since
568 // Inst.size >= DepWrite.size A and B are disjoint in DepWrite too.
569 // Therefore DepWrite can be removed.
570 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
571
572 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
573 return false;
574 }
575
Chris Lattner94fbdf32010-12-06 01:48:06 +0000576 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
577 // then it can't be considered dead.
578 return true;
579}
580
Justin Bogner594e07b2016-05-17 21:38:13 +0000581/// Returns true if the memory which is accessed by the second instruction is not
582/// modified between the first and the second instruction.
583/// Precondition: Second instruction must be dominated by the first
584/// instruction.
585static bool memoryIsNotModifiedBetween(Instruction *FirstI,
586 Instruction *SecondI,
587 AliasAnalysis *AA) {
588 SmallVector<BasicBlock *, 16> WorkList;
589 SmallPtrSet<BasicBlock *, 8> Visited;
590 BasicBlock::iterator FirstBBI(FirstI);
591 ++FirstBBI;
592 BasicBlock::iterator SecondBBI(SecondI);
593 BasicBlock *FirstBB = FirstI->getParent();
594 BasicBlock *SecondBB = SecondI->getParent();
595 MemoryLocation MemLoc = MemoryLocation::get(SecondI);
Chris Lattner67122512010-11-30 21:58:14 +0000596
Justin Bogner594e07b2016-05-17 21:38:13 +0000597 // Start checking the store-block.
598 WorkList.push_back(SecondBB);
599 bool isFirstBlock = true;
600
601 // Check all blocks going backward until we reach the load-block.
602 while (!WorkList.empty()) {
603 BasicBlock *B = WorkList.pop_back_val();
604
605 // Ignore instructions before LI if this is the FirstBB.
606 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
607
608 BasicBlock::iterator EI;
609 if (isFirstBlock) {
610 // Ignore instructions after SI if this is the first visit of SecondBB.
611 assert(B == SecondBB && "first block is not the store block");
612 EI = SecondBBI;
613 isFirstBlock = false;
614 } else {
615 // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
616 // In this case we also have to look at instructions after SI.
617 EI = B->end();
618 }
619 for (; BI != EI; ++BI) {
620 Instruction *I = &*BI;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000621 if (I->mayWriteToMemory() && I != SecondI)
622 if (isModSet(AA->getModRefInfo(I, MemLoc)))
Justin Bogner594e07b2016-05-17 21:38:13 +0000623 return false;
Justin Bogner594e07b2016-05-17 21:38:13 +0000624 }
625 if (B != FirstBB) {
626 assert(B != &FirstBB->getParent()->getEntryBlock() &&
627 "Should not hit the entry block because SI must be dominated by LI");
628 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
629 if (!Visited.insert(*PredI).second)
630 continue;
631 WorkList.push_back(*PredI);
632 }
633 }
634 }
635 return true;
636}
637
638/// Find all blocks that will unconditionally lead to the block BB and append
639/// them to F.
640static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
641 BasicBlock *BB, DominatorTree *DT) {
642 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
643 BasicBlock *Pred = *I;
644 if (Pred == BB) continue;
Chandler Carruthedb12a82018-10-15 10:04:59 +0000645 Instruction *PredTI = Pred->getTerminator();
Justin Bogner594e07b2016-05-17 21:38:13 +0000646 if (PredTI->getNumSuccessors() != 1)
647 continue;
648
649 if (DT->isReachableFromEntry(Pred))
650 Blocks.push_back(Pred);
651 }
652}
653
654/// Handle frees of entire structures whose dependency is a store
655/// to a field of that structure.
656static bool handleFree(CallInst *F, AliasAnalysis *AA,
657 MemoryDependenceResults *MD, DominatorTree *DT,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000658 const TargetLibraryInfo *TLI,
Florian Hahn9b41a732019-03-29 14:10:24 +0000659 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000660 bool MadeChange = false;
661
662 MemoryLocation Loc = MemoryLocation(F->getOperand(0));
663 SmallVector<BasicBlock *, 16> Blocks;
664 Blocks.push_back(F->getParent());
665 const DataLayout &DL = F->getModule()->getDataLayout();
666
667 while (!Blocks.empty()) {
668 BasicBlock *BB = Blocks.pop_back_val();
669 Instruction *InstPt = BB->getTerminator();
670 if (BB == F->getParent()) InstPt = F;
671
672 MemDepResult Dep =
673 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB);
674 while (Dep.isDef() || Dep.isClobber()) {
675 Instruction *Dependency = Dep.getInst();
Philip Reames424e7a12018-01-21 01:44:33 +0000676 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) ||
677 !isRemovable(Dependency))
Justin Bogner594e07b2016-05-17 21:38:13 +0000678 break;
679
680 Value *DepPointer =
681 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
682
683 // Check for aliasing.
684 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
685 break;
686
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000687 LLVM_DEBUG(
688 dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: "
689 << *Dependency << '\n');
Chad Rosier667b1ca2016-07-19 16:50:57 +0000690
Chad Rosier840b3ef2016-06-10 17:59:22 +0000691 // DCE instructions only used to calculate that store.
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000692 BasicBlock::iterator BBI(Dependency);
Florian Hahn9b41a732019-03-29 14:10:24 +0000693 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, OBB);
Justin Bogner594e07b2016-05-17 21:38:13 +0000694 ++NumFastStores;
695 MadeChange = true;
696
697 // Inst's old Dependency is now deleted. Compute the next dependency,
698 // which may also be dead, as in
699 // s[0] = 0;
700 // s[1] = 0; // This has just been deleted.
701 // free(s);
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000702 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB);
Justin Bogner594e07b2016-05-17 21:38:13 +0000703 }
704
705 if (Dep.isNonLocal())
706 findUnconditionalPreds(Blocks, BB, DT);
707 }
708
709 return MadeChange;
710}
711
712/// Check to see if the specified location may alias any of the stack objects in
713/// the DeadStackObjects set. If so, they become live because the location is
714/// being loaded.
715static void removeAccessedObjects(const MemoryLocation &LoadedLoc,
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000716 SmallSetVector<const Value *, 16> &DeadStackObjects,
Justin Bogner594e07b2016-05-17 21:38:13 +0000717 const DataLayout &DL, AliasAnalysis *AA,
Manoj Gupta77eeac32018-07-09 22:27:23 +0000718 const TargetLibraryInfo *TLI,
719 const Function *F) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000720 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
721
722 // A constant can't be in the dead pointer set.
723 if (isa<Constant>(UnderlyingPointer))
724 return;
725
726 // If the kill pointer can be easily reduced to an alloca, don't bother doing
727 // extraneous AA queries.
728 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000729 DeadStackObjects.remove(UnderlyingPointer);
Justin Bogner594e07b2016-05-17 21:38:13 +0000730 return;
731 }
732
733 // Remove objects that could alias LoadedLoc.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000734 DeadStackObjects.remove_if([&](const Value *I) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000735 // See if the loaded location could alias the stack location.
Manoj Gupta77eeac32018-07-09 22:27:23 +0000736 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F));
Justin Bogner594e07b2016-05-17 21:38:13 +0000737 return !AA->isNoAlias(StackLoc, LoadedLoc);
738 });
739}
740
741/// Remove dead stores to stack-allocated locations in the function end block.
742/// Ex:
743/// %A = alloca i32
744/// ...
745/// store i32 1, i32* %A
746/// ret void
747static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA,
Florian Hahn9b41a732019-03-29 14:10:24 +0000748 MemoryDependenceResults *MD,
749 const TargetLibraryInfo *TLI,
750 InstOverlapIntervalsTy &IOL,
751 OrderedBasicBlock &OBB) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000752 bool MadeChange = false;
753
754 // Keep track of all of the stack objects that are dead at the end of the
755 // function.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000756 SmallSetVector<const Value*, 16> DeadStackObjects;
Justin Bogner594e07b2016-05-17 21:38:13 +0000757
758 // Find all of the alloca'd pointers in the entry block.
759 BasicBlock &Entry = BB.getParent()->front();
760 for (Instruction &I : Entry) {
761 if (isa<AllocaInst>(&I))
762 DeadStackObjects.insert(&I);
763
764 // Okay, so these are dead heap objects, but if the pointer never escapes
765 // then it's leaked by this function anyways.
766 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
767 DeadStackObjects.insert(&I);
768 }
769
770 // Treat byval or inalloca arguments the same, stores to them are dead at the
771 // end of the function.
772 for (Argument &AI : BB.getParent()->args())
773 if (AI.hasByValOrInAllocaAttr())
774 DeadStackObjects.insert(&AI);
775
776 const DataLayout &DL = BB.getModule()->getDataLayout();
777
778 // Scan the basic block backwards
779 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
780 --BBI;
781
782 // If we find a store, check to see if it points into a dead stack value.
Philip Reames424e7a12018-01-21 01:44:33 +0000783 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000784 // See through pointer-to-pointer bitcasts
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000785 SmallVector<const Value *, 4> Pointers;
Justin Bogner594e07b2016-05-17 21:38:13 +0000786 GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL);
787
788 // Stores to stack values are valid candidates for removal.
789 bool AllDead = true;
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000790 for (const Value *Pointer : Pointers)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000791 if (!DeadStackObjects.count(Pointer)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000792 AllDead = false;
793 break;
794 }
795
796 if (AllDead) {
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000797 Instruction *Dead = &*BBI;
Justin Bogner594e07b2016-05-17 21:38:13 +0000798
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000799 LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
800 << *Dead << "\n Objects: ";
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000801 for (SmallVectorImpl<const Value *>::iterator I =
802 Pointers.begin(),
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000803 E = Pointers.end();
804 I != E; ++I) {
805 dbgs() << **I;
806 if (std::next(I) != E)
807 dbgs() << ", ";
808 } dbgs()
809 << '\n');
Justin Bogner594e07b2016-05-17 21:38:13 +0000810
811 // DCE instructions only used to calculate that store.
Florian Hahn9b41a732019-03-29 14:10:24 +0000812 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, OBB,
813 &DeadStackObjects);
Justin Bogner594e07b2016-05-17 21:38:13 +0000814 ++NumFastStores;
815 MadeChange = true;
816 continue;
817 }
818 }
819
820 // Remove any dead non-memory-mutating instructions.
821 if (isInstructionTriviallyDead(&*BBI, TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000822 LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: "
823 << *&*BBI << '\n');
Florian Hahn9b41a732019-03-29 14:10:24 +0000824 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, OBB,
825 &DeadStackObjects);
Justin Bogner594e07b2016-05-17 21:38:13 +0000826 ++NumFastOther;
827 MadeChange = true;
828 continue;
829 }
830
831 if (isa<AllocaInst>(BBI)) {
832 // Remove allocas from the list of dead stack objects; there can't be
833 // any references before the definition.
834 DeadStackObjects.remove(&*BBI);
835 continue;
836 }
837
Chandler Carruth363ac682019-01-07 05:42:51 +0000838 if (auto *Call = dyn_cast<CallBase>(&*BBI)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000839 // Remove allocation function calls from the list of dead stack objects;
840 // there can't be any references before the definition.
841 if (isAllocLikeFn(&*BBI, TLI))
842 DeadStackObjects.remove(&*BBI);
843
844 // If this call does not access memory, it can't be loading any of our
845 // pointers.
Chandler Carruth363ac682019-01-07 05:42:51 +0000846 if (AA->doesNotAccessMemory(Call))
Justin Bogner594e07b2016-05-17 21:38:13 +0000847 continue;
848
849 // If the call might load from any of our allocas, then any store above
850 // the call is live.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000851 DeadStackObjects.remove_if([&](const Value *I) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000852 // See if the call site touches the value.
Chandler Carruth363ac682019-01-07 05:42:51 +0000853 return isRefSet(AA->getModRefInfo(
854 Call, I, getPointerSize(I, DL, *TLI, BB.getParent())));
Justin Bogner594e07b2016-05-17 21:38:13 +0000855 });
856
857 // If all of the allocas were clobbered by the call then we're not going
858 // to find anything else to process.
859 if (DeadStackObjects.empty())
860 break;
861
862 continue;
863 }
864
Anna Thomas6a78c782016-07-07 20:51:42 +0000865 // We can remove the dead stores, irrespective of the fence and its ordering
866 // (release/acquire/seq_cst). Fences only constraints the ordering of
867 // already visible stores, it does not make a store visible to other
868 // threads. So, skipping over a fence does not change a store from being
869 // dead.
870 if (isa<FenceInst>(*BBI))
871 continue;
872
Justin Bogner594e07b2016-05-17 21:38:13 +0000873 MemoryLocation LoadedLoc;
874
875 // If we encounter a use of the pointer, it is no longer considered dead
876 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
877 if (!L->isUnordered()) // Be conservative with atomic/volatile load
878 break;
879 LoadedLoc = MemoryLocation::get(L);
880 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
881 LoadedLoc = MemoryLocation::get(V);
Justin Bogner594e07b2016-05-17 21:38:13 +0000882 } else if (!BBI->mayReadFromMemory()) {
883 // Instruction doesn't read memory. Note that stores that weren't removed
884 // above will hit this case.
885 continue;
886 } else {
887 // Unknown inst; assume it clobbers everything.
888 break;
889 }
890
891 // Remove any allocas from the DeadPointer set that are loaded, as this
892 // makes any stores above the access live.
Manoj Gupta77eeac32018-07-09 22:27:23 +0000893 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent());
Justin Bogner594e07b2016-05-17 21:38:13 +0000894
895 // If all of the allocas were clobbered by the access then we're not going
896 // to find anything else to process.
897 if (DeadStackObjects.empty())
898 break;
899 }
900
901 return MadeChange;
902}
903
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000904static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset,
905 int64_t &EarlierSize, int64_t LaterOffset,
906 int64_t LaterSize, bool IsOverwriteEnd) {
907 // TODO: base this on the target vector size so that if the earlier
908 // store was too small to get vector writes anyway then its likely
909 // a good idea to shorten it
910 // Power of 2 vector writes are probably always a bad idea to optimize
911 // as any store/memset/memcpy is likely using vector instructions so
912 // shortening it to not vector size is likely to be slower
Daniel Neilson71fa1b92018-05-10 15:12:49 +0000913 auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite);
Daniel Neilson83cdf682018-02-06 21:18:33 +0000914 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment();
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000915 if (!IsOverwriteEnd)
916 LaterOffset = int64_t(LaterOffset + LaterSize);
917
Eugene Zelenko3b879392017-10-13 21:17:07 +0000918 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) &&
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000919 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0))
920 return false;
921
Daniel Neilson71fa1b92018-05-10 15:12:49 +0000922 int64_t NewLength = IsOverwriteEnd
923 ? LaterOffset - EarlierOffset
924 : EarlierSize - (LaterOffset - EarlierOffset);
925
926 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) {
927 // When shortening an atomic memory intrinsic, the newly shortened
928 // length must remain an integer multiple of the element size.
929 const uint32_t ElementSize = AMI->getElementSizeInBytes();
930 if (0 != NewLength % ElementSize)
931 return false;
932 }
933
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000934 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW "
935 << (IsOverwriteEnd ? "END" : "BEGIN") << ": "
936 << *EarlierWrite << "\n KILLER (offset " << LaterOffset
937 << ", " << EarlierSize << ")\n");
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000938
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000939 Value *EarlierWriteLength = EarlierIntrinsic->getLength();
940 Value *TrimmedLength =
941 ConstantInt::get(EarlierWriteLength->getType(), NewLength);
942 EarlierIntrinsic->setLength(TrimmedLength);
943
944 EarlierSize = NewLength;
945 if (!IsOverwriteEnd) {
946 int64_t OffsetMoved = (LaterOffset - EarlierOffset);
947 Value *Indices[1] = {
948 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)};
949 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds(
James Y Knight77160752019-02-01 20:44:47 +0000950 EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(),
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000951 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite);
Jeremy Morse32afe6a2019-04-12 09:47:35 +0000952 NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc());
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000953 EarlierIntrinsic->setDest(NewDestGEP);
954 EarlierOffset = EarlierOffset + OffsetMoved;
955 }
956 return true;
957}
958
959static bool tryToShortenEnd(Instruction *EarlierWrite,
960 OverlapIntervalsTy &IntervalMap,
961 int64_t &EarlierStart, int64_t &EarlierSize) {
962 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite))
963 return false;
964
965 OverlapIntervalsTy::iterator OII = --IntervalMap.end();
966 int64_t LaterStart = OII->second;
967 int64_t LaterSize = OII->first - LaterStart;
968
969 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize &&
970 LaterStart + LaterSize >= EarlierStart + EarlierSize) {
971 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
972 LaterSize, true)) {
973 IntervalMap.erase(OII);
974 return true;
975 }
976 }
977 return false;
978}
979
980static bool tryToShortenBegin(Instruction *EarlierWrite,
981 OverlapIntervalsTy &IntervalMap,
982 int64_t &EarlierStart, int64_t &EarlierSize) {
983 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite))
984 return false;
985
986 OverlapIntervalsTy::iterator OII = IntervalMap.begin();
987 int64_t LaterStart = OII->second;
988 int64_t LaterSize = OII->first - LaterStart;
989
990 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) {
991 assert(LaterStart + LaterSize < EarlierStart + EarlierSize &&
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000992 "Should have been handled as OW_Complete");
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000993 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
994 LaterSize, false)) {
995 IntervalMap.erase(OII);
996 return true;
997 }
998 }
999 return false;
1000}
1001
1002static bool removePartiallyOverlappedStores(AliasAnalysis *AA,
1003 const DataLayout &DL,
1004 InstOverlapIntervalsTy &IOL) {
1005 bool Changed = false;
1006 for (auto OI : IOL) {
1007 Instruction *EarlierWrite = OI.first;
Philip Reamesf57714c2018-01-21 02:10:54 +00001008 MemoryLocation Loc = getLocForWrite(EarlierWrite);
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001009 assert(isRemovable(EarlierWrite) && "Expect only removable instruction");
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001010
1011 const Value *Ptr = Loc.Ptr->stripPointerCasts();
1012 int64_t EarlierStart = 0;
George Burgess IVf96e6182018-10-09 03:18:56 +00001013 int64_t EarlierSize = int64_t(Loc.Size.getValue());
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001014 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL);
1015 OverlapIntervalsTy &IntervalMap = OI.second;
Jun Bum Lima0331392016-07-27 17:25:20 +00001016 Changed |=
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001017 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
1018 if (IntervalMap.empty())
1019 continue;
1020 Changed |=
1021 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
1022 }
1023 return Changed;
1024}
1025
Chad Rosier89c32a92016-07-08 16:48:40 +00001026static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI,
1027 AliasAnalysis *AA, MemoryDependenceResults *MD,
1028 const DataLayout &DL,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001029 const TargetLibraryInfo *TLI,
Eli Friedmana6707f52016-08-12 01:09:53 +00001030 InstOverlapIntervalsTy &IOL,
Florian Hahn9b41a732019-03-29 14:10:24 +00001031 OrderedBasicBlock &OBB) {
Chad Rosier89c32a92016-07-08 16:48:40 +00001032 // Must be a store instruction.
1033 StoreInst *SI = dyn_cast<StoreInst>(Inst);
1034 if (!SI)
1035 return false;
1036
1037 // If we're storing the same value back to a pointer that we just loaded from,
1038 // then the store can be removed.
1039 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
1040 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
1041 isRemovable(SI) && memoryIsNotModifiedBetween(DepLoad, SI, AA)) {
1042
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001043 LLVM_DEBUG(
1044 dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: "
1045 << *DepLoad << "\n STORE: " << *SI << '\n');
Chad Rosier89c32a92016-07-08 16:48:40 +00001046
Florian Hahn9b41a732019-03-29 14:10:24 +00001047 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, OBB);
Chad Rosier89c32a92016-07-08 16:48:40 +00001048 ++NumRedundantStores;
1049 return true;
1050 }
1051 }
1052
1053 // Remove null stores into the calloc'ed objects
1054 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
1055 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) {
1056 Instruction *UnderlyingPointer =
1057 dyn_cast<Instruction>(GetUnderlyingObject(SI->getPointerOperand(), DL));
1058
1059 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
1060 memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001061 LLVM_DEBUG(
Chad Rosier89c32a92016-07-08 16:48:40 +00001062 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: "
1063 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n');
1064
Florian Hahn9b41a732019-03-29 14:10:24 +00001065 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, OBB);
Chad Rosier89c32a92016-07-08 16:48:40 +00001066 ++NumRedundantStores;
1067 return true;
1068 }
1069 }
1070 return false;
1071}
1072
Justin Bogner594e07b2016-05-17 21:38:13 +00001073static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA,
1074 MemoryDependenceResults *MD, DominatorTree *DT,
1075 const TargetLibraryInfo *TLI) {
Igor Laevsky029bd932015-09-23 11:38:44 +00001076 const DataLayout &DL = BB.getModule()->getDataLayout();
Owen Anderson5e72db32007-07-11 00:46:18 +00001077 bool MadeChange = false;
Owen Anderson58704ee2011-09-06 18:14:09 +00001078
Florian Hahn9b41a732019-03-29 14:10:24 +00001079 OrderedBasicBlock OBB(&BB);
1080 Instruction *LastThrowing = nullptr;
Eli Friedmana6707f52016-08-12 01:09:53 +00001081
Hal Finkela1271032016-06-23 13:46:39 +00001082 // A map of interval maps representing partially-overwritten value parts.
1083 InstOverlapIntervalsTy IOL;
1084
Chris Lattner49162672009-09-02 06:31:02 +00001085 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +00001086 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
Chris Lattner9d179d92010-11-30 01:28:33 +00001087 // Handle 'free' calls specially.
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001088 if (CallInst *F = isFreeCall(&*BBI, TLI)) {
Florian Hahn9b41a732019-03-29 14:10:24 +00001089 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, OBB);
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001090 // Increment BBI after handleFree has potentially deleted instructions.
1091 // This ensures we maintain a valid iterator.
1092 ++BBI;
Chris Lattner9d179d92010-11-30 01:28:33 +00001093 continue;
1094 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001095
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001096 Instruction *Inst = &*BBI++;
1097
Eli Friedmana6707f52016-08-12 01:09:53 +00001098 if (Inst->mayThrow()) {
Florian Hahn9b41a732019-03-29 14:10:24 +00001099 LastThrowing = Inst;
Eli Friedmana6707f52016-08-12 01:09:53 +00001100 continue;
1101 }
1102
Chad Rosier89c32a92016-07-08 16:48:40 +00001103 // Check to see if Inst writes to memory. If not, continue.
Philip Reames424e7a12018-01-21 01:44:33 +00001104 if (!hasAnalyzableMemoryWrite(Inst, *TLI))
Owen Anderson0aecf0e2007-08-08 04:52:29 +00001105 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +00001106
Chad Rosier89c32a92016-07-08 16:48:40 +00001107 // eliminateNoopStore will update in iterator, if necessary.
Florian Hahn9b41a732019-03-29 14:10:24 +00001108 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, OBB)) {
Chad Rosier89c32a92016-07-08 16:48:40 +00001109 MadeChange = true;
1110 continue;
Owen Anderson5e72db32007-07-11 00:46:18 +00001111 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001112
Chad Rosier89c32a92016-07-08 16:48:40 +00001113 // If we find something that writes memory, get its memory dependence.
Florian Hahn9b41a732019-03-29 14:10:24 +00001114 MemDepResult InstDep = MD->getDependency(Inst, &OBB);
Erik Eckstein11fc8172015-08-13 15:36:11 +00001115
Chad Rosierd7634fc2015-12-11 18:39:41 +00001116 // Ignore any store where we can't find a local dependence.
1117 // FIXME: cross-block DSE would be fun. :)
1118 if (!InstDep.isDef() && !InstDep.isClobber())
1119 continue;
Erik Eckstein11fc8172015-08-13 15:36:11 +00001120
Chad Rosierd7634fc2015-12-11 18:39:41 +00001121 // Figure out what location is being stored to.
Philip Reamesf57714c2018-01-21 02:10:54 +00001122 MemoryLocation Loc = getLocForWrite(Inst);
Chris Lattner58b779e2010-11-30 07:23:21 +00001123
Chad Rosierd7634fc2015-12-11 18:39:41 +00001124 // If we didn't get a useful location, fail.
1125 if (!Loc.Ptr)
1126 continue;
1127
Bob Haarman3db17642016-08-26 16:34:27 +00001128 // Loop until we find a store we can eliminate or a load that
1129 // invalidates the analysis. Without an upper bound on the number of
1130 // instructions examined, this analysis can become very time-consuming.
1131 // However, the potential gain diminishes as we process more instructions
1132 // without eliminating any of them. Therefore, we limit the number of
1133 // instructions we look at.
1134 auto Limit = MD->getDefaultBlockScanLimit();
Chad Rosierd7634fc2015-12-11 18:39:41 +00001135 while (InstDep.isDef() || InstDep.isClobber()) {
1136 // Get the memory clobbered by the instruction we depend on. MemDep will
1137 // skip any instructions that 'Loc' clearly doesn't interact with. If we
1138 // end up depending on a may- or must-aliased load, then we can't optimize
Chad Rosier844e2df2016-06-15 21:41:22 +00001139 // away the store and we bail out. However, if we depend on something
Chad Rosierd7634fc2015-12-11 18:39:41 +00001140 // that overwrites the memory location we *can* potentially optimize it.
1141 //
1142 // Find out what memory location the dependent instruction stores.
1143 Instruction *DepWrite = InstDep.getInst();
Philip Reamesf57714c2018-01-21 02:10:54 +00001144 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI))
1145 break;
1146 MemoryLocation DepLoc = getLocForWrite(DepWrite);
Chad Rosierd7634fc2015-12-11 18:39:41 +00001147 // If we didn't get a useful location, or if it isn't a size, bail out.
1148 if (!DepLoc.Ptr)
1149 break;
1150
Eli Friedmana6707f52016-08-12 01:09:53 +00001151 // Make sure we don't look past a call which might throw. This is an
1152 // issue because MemoryDependenceAnalysis works in the wrong direction:
1153 // it finds instructions which dominate the current instruction, rather than
1154 // instructions which are post-dominated by the current instruction.
1155 //
1156 // If the underlying object is a non-escaping memory allocation, any store
1157 // to it is dead along the unwind edge. Otherwise, we need to preserve
1158 // the store.
Florian Hahn9b41a732019-03-29 14:10:24 +00001159 if (LastThrowing && OBB.dominates(DepWrite, LastThrowing)) {
Eli Friedmana6707f52016-08-12 01:09:53 +00001160 const Value* Underlying = GetUnderlyingObject(DepLoc.Ptr, DL);
1161 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying);
1162 if (!IsStoreDeadOnUnwind) {
1163 // We're looking for a call to an allocation function
1164 // where the allocation doesn't escape before the last
1165 // throwing instruction; PointerMayBeCaptured
1166 // reasonably fast approximation.
1167 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) &&
1168 !PointerMayBeCaptured(Underlying, false, true);
1169 }
1170 if (!IsStoreDeadOnUnwind)
1171 break;
1172 }
1173
Chad Rosierd7634fc2015-12-11 18:39:41 +00001174 // If we find a write that is a) removable (i.e., non-volatile), b) is
1175 // completely obliterated by the store to 'Loc', and c) which we know that
1176 // 'Inst' doesn't load from, then we can remove it.
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001177 // Also try to merge two stores if a later one only touches memory written
1178 // to by the earlier one.
Chad Rosierd7634fc2015-12-11 18:39:41 +00001179 if (isRemovable(DepWrite) &&
1180 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
1181 int64_t InstWriteOffset, DepWriteOffset;
Piotr Padlewskic77ab8e2018-05-03 11:03:53 +00001182 OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset,
Manoj Gupta77eeac32018-07-09 22:27:23 +00001183 InstWriteOffset, DepWrite, IOL, *AA,
1184 BB.getParent());
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001185 if (OR == OW_Complete) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001186 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DepWrite
1187 << "\n KILLER: " << *Inst << '\n');
Alexander Kornienko63dd36f2016-07-18 15:51:31 +00001188
Chad Rosierd7634fc2015-12-11 18:39:41 +00001189 // Delete the store and now-dead instructions that feed it.
Florian Hahn9b41a732019-03-29 14:10:24 +00001190 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, OBB);
Chad Rosierd7634fc2015-12-11 18:39:41 +00001191 ++NumFastStores;
1192 MadeChange = true;
1193
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001194 // We erased DepWrite; start over.
Florian Hahn9b41a732019-03-29 14:10:24 +00001195 InstDep = MD->getDependency(Inst, &OBB);
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001196 continue;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001197 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) ||
1198 ((OR == OW_Begin &&
Jun Bum Limd29a24e2016-04-22 19:51:29 +00001199 isShortenableAtTheBeginning(DepWrite)))) {
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001200 assert(!EnablePartialOverwriteTracking && "Do not expect to perform "
1201 "when partial-overwrite "
1202 "tracking is enabled");
George Burgess IVf96e6182018-10-09 03:18:56 +00001203 // The overwrite result is known, so these must be known, too.
1204 int64_t EarlierSize = DepLoc.Size.getValue();
1205 int64_t LaterSize = Loc.Size.getValue();
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001206 bool IsOverwriteEnd = (OR == OW_End);
Jun Bum Lima0331392016-07-27 17:25:20 +00001207 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001208 InstWriteOffset, LaterSize, IsOverwriteEnd);
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001209 } else if (EnablePartialStoreMerging &&
1210 OR == OW_PartialEarlierWithFullLater) {
1211 auto *Earlier = dyn_cast<StoreInst>(DepWrite);
1212 auto *Later = dyn_cast<StoreInst>(Inst);
1213 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) &&
Sanjay Patel1aef27f2018-01-30 13:53:59 +00001214 Later && isa<ConstantInt>(Later->getValueOperand()) &&
1215 memoryIsNotModifiedBetween(Earlier, Later, AA)) {
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001216 // If the store we find is:
1217 // a) partially overwritten by the store to 'Loc'
1218 // b) the later store is fully contained in the earlier one and
1219 // c) they both have a constant value
1220 // Merge the two stores, replacing the earlier store's value with a
1221 // merge of both values.
1222 // TODO: Deal with other constant types (vectors, etc), and probably
1223 // some mem intrinsics (if needed)
1224
1225 APInt EarlierValue =
1226 cast<ConstantInt>(Earlier->getValueOperand())->getValue();
1227 APInt LaterValue =
1228 cast<ConstantInt>(Later->getValueOperand())->getValue();
1229 unsigned LaterBits = LaterValue.getBitWidth();
1230 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth());
1231 LaterValue = LaterValue.zext(EarlierValue.getBitWidth());
1232
1233 // Offset of the smaller store inside the larger store
1234 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8;
1235 unsigned LShiftAmount =
1236 DL.isBigEndian()
1237 ? EarlierValue.getBitWidth() - BitOffsetDiff - LaterBits
1238 : BitOffsetDiff;
1239 APInt Mask =
1240 APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount,
1241 LShiftAmount + LaterBits);
1242 // Clear the bits we'll be replacing, then OR with the smaller
1243 // store, shifted appropriately.
1244 APInt Merged =
1245 (EarlierValue & ~Mask) | (LaterValue << LShiftAmount);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001246 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *DepWrite
1247 << "\n Later: " << *Inst
1248 << "\n Merged Value: " << Merged << '\n');
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001249
1250 auto *SI = new StoreInst(
1251 ConstantInt::get(Earlier->getValueOperand()->getType(), Merged),
1252 Earlier->getPointerOperand(), false, Earlier->getAlignment(),
1253 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite);
1254
1255 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa,
1256 LLVMContext::MD_alias_scope,
1257 LLVMContext::MD_noalias,
1258 LLVMContext::MD_nontemporal};
1259 SI->copyMetadata(*DepWrite, MDToKeep);
1260 ++NumModifiedStores;
1261
1262 // Remove earlier, wider, store
Florian Hahn9b41a732019-03-29 14:10:24 +00001263 OBB.replaceInstruction(DepWrite, SI);
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001264
1265 // Delete the old stores and now-dead instructions that feed them.
Florian Hahn9b41a732019-03-29 14:10:24 +00001266 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, OBB);
1267 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, OBB);
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001268 MadeChange = true;
1269
1270 // We erased DepWrite and Inst (Loc); start over.
1271 break;
1272 }
Pete Cooper856977c2011-11-09 23:07:35 +00001273 }
Chris Lattner58b779e2010-11-30 07:23:21 +00001274 }
Chad Rosierd7634fc2015-12-11 18:39:41 +00001275
1276 // If this is a may-aliased store that is clobbering the store value, we
1277 // can keep searching past it for another must-aliased pointer that stores
1278 // to the same location. For example, in:
1279 // store -> P
1280 // store -> Q
1281 // store -> P
1282 // we can remove the first store to P even though we don't know if P and Q
1283 // alias.
1284 if (DepWrite == &BB.front()) break;
1285
1286 // Can't look past this instruction if it might read 'Loc'.
Alina Sbirlea63d22502017-12-05 20:12:23 +00001287 if (isRefSet(AA->getModRefInfo(DepWrite, Loc)))
Chad Rosierd7634fc2015-12-11 18:39:41 +00001288 break;
1289
Bob Haarman3db17642016-08-26 16:34:27 +00001290 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false,
1291 DepWrite->getIterator(), &BB,
1292 /*QueryInst=*/ nullptr, &Limit);
Owen Anderson2b2bd282009-10-28 07:05:35 +00001293 }
Owen Anderson5e72db32007-07-11 00:46:18 +00001294 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001295
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001296 if (EnablePartialOverwriteTracking)
1297 MadeChange |= removePartiallyOverlappedStores(AA, DL, IOL);
1298
Chris Lattnerf2a8ba42008-11-28 21:29:52 +00001299 // If this block ends in a return, unwind, or unreachable, all allocas are
1300 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +00001301 if (BB.getTerminator()->getNumSuccessors() == 0)
Florian Hahn9b41a732019-03-29 14:10:24 +00001302 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, OBB);
Owen Anderson58704ee2011-09-06 18:14:09 +00001303
Owen Anderson5e72db32007-07-11 00:46:18 +00001304 return MadeChange;
1305}
1306
Justin Bogner594e07b2016-05-17 21:38:13 +00001307static bool eliminateDeadStores(Function &F, AliasAnalysis *AA,
1308 MemoryDependenceResults *MD, DominatorTree *DT,
1309 const TargetLibraryInfo *TLI) {
Eli Friedman7d58bc72011-06-15 00:47:34 +00001310 bool MadeChange = false;
Justin Bogner594e07b2016-05-17 21:38:13 +00001311 for (BasicBlock &BB : F)
1312 // Only check non-dead blocks. Dead blocks may have strange pointer
1313 // cycles that will confuse alias analysis.
1314 if (DT->isReachableFromEntry(&BB))
1315 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI);
Eli Friedmana6707f52016-08-12 01:09:53 +00001316
Eli Friedman7d58bc72011-06-15 00:47:34 +00001317 return MadeChange;
Owen Andersonaa071722007-07-11 23:19:17 +00001318}
1319
Justin Bogner594e07b2016-05-17 21:38:13 +00001320//===----------------------------------------------------------------------===//
1321// DSE Pass
1322//===----------------------------------------------------------------------===//
1323PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
1324 AliasAnalysis *AA = &AM.getResult<AAManager>(F);
1325 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1326 MemoryDependenceResults *MD = &AM.getResult<MemoryDependenceAnalysis>(F);
1327 const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
Owen Anderson58704ee2011-09-06 18:14:09 +00001328
Justin Bogner594e07b2016-05-17 21:38:13 +00001329 if (!eliminateDeadStores(F, AA, MD, DT, TLI))
1330 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001331
Justin Bogner594e07b2016-05-17 21:38:13 +00001332 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001333 PA.preserveSet<CFGAnalyses>();
Justin Bogner594e07b2016-05-17 21:38:13 +00001334 PA.preserve<GlobalsAA>();
1335 PA.preserve<MemoryDependenceAnalysis>();
1336 return PA;
Owen Anderson32c4a052007-07-12 21:41:30 +00001337}
1338
Benjamin Kramer4d098922016-07-10 11:28:51 +00001339namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001340
Justin Bogner594e07b2016-05-17 21:38:13 +00001341/// A legacy pass for the legacy pass manager that wraps \c DSEPass.
1342class DSELegacyPass : public FunctionPass {
1343public:
Eugene Zelenko3b879392017-10-13 21:17:07 +00001344 static char ID; // Pass identification, replacement for typeid
1345
Justin Bogner594e07b2016-05-17 21:38:13 +00001346 DSELegacyPass() : FunctionPass(ID) {
1347 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
Owen Andersonddf4aee2007-08-08 18:38:28 +00001348 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001349
Justin Bogner594e07b2016-05-17 21:38:13 +00001350 bool runOnFunction(Function &F) override {
1351 if (skipFunction(F))
1352 return false;
1353
1354 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1355 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1356 MemoryDependenceResults *MD =
1357 &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1358 const TargetLibraryInfo *TLI =
1359 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1360
1361 return eliminateDeadStores(F, AA, MD, DT, TLI);
1362 }
1363
1364 void getAnalysisUsage(AnalysisUsage &AU) const override {
1365 AU.setPreservesCFG();
1366 AU.addRequired<DominatorTreeWrapperPass>();
1367 AU.addRequired<AAResultsWrapperPass>();
1368 AU.addRequired<MemoryDependenceWrapperPass>();
1369 AU.addRequired<TargetLibraryInfoWrapperPass>();
1370 AU.addPreserved<DominatorTreeWrapperPass>();
1371 AU.addPreserved<GlobalsAAWrapperPass>();
1372 AU.addPreserved<MemoryDependenceWrapperPass>();
1373 }
Justin Bogner594e07b2016-05-17 21:38:13 +00001374};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001375
Benjamin Kramer4d098922016-07-10 11:28:51 +00001376} // end anonymous namespace
Justin Bogner594e07b2016-05-17 21:38:13 +00001377
1378char DSELegacyPass::ID = 0;
Eugene Zelenko3b879392017-10-13 21:17:07 +00001379
Justin Bogner594e07b2016-05-17 21:38:13 +00001380INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
1381 false)
1382INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1383INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1384INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1385INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
1386INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1387INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
1388 false)
1389
1390FunctionPass *llvm::createDeadStoreEliminationPass() {
1391 return new DSELegacyPass();
Owen Anderson32c4a052007-07-12 21:41:30 +00001392}