blob: e6f0bb21dd5e459b5ab8ca20f6aebd219d44b3c6 [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//
3// 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.
Owen Anderson5e72db32007-07-11 00:46:18 +00007//
8//===----------------------------------------------------------------------===//
9//
Chad Rosierd7634fc2015-12-11 18:39:41 +000010// This file implements a trivial dead store elimination that only considers
11// basic-block local redundant stores.
12//
13// FIXME: This should eventually be extended to be a post-dominator tree
14// traversal. Doing so would be pretty trivial.
Owen Anderson5e72db32007-07-11 00:46:18 +000015//
16//===----------------------------------------------------------------------===//
17
Justin Bogner594e07b2016-05-17 21:38:13 +000018#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000019#include "llvm/ADT/APInt.h"
Hal Finkela1271032016-06-23 13:46:39 +000020#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SetVector.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000025#include "llvm/ADT/StringRef.h"
Owen Andersonaa071722007-07-11 23:19:17 +000026#include "llvm/Analysis/AliasAnalysis.h"
Nick Lewycky32f80512011-10-22 21:59:35 +000027#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000028#include "llvm/Analysis/GlobalsModRef.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000030#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000031#include "llvm/Analysis/MemoryLocation.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"
Owen Anderson5e72db32007-07-11 00:46:18 +000059#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000060#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <cstddef>
64#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");
74STATISTIC(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,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000101 InstOverlapIntervalsTy &IOL,
Eli Friedmana6707f52016-08-12 01:09:53 +0000102 DenseMap<Instruction*, size_t> *InstrOrdering,
Justin Bogner594e07b2016-05-17 21:38:13 +0000103 SmallSetVector<Value *, 16> *ValueSet = nullptr) {
Eric Christopher0efe9f62015-08-19 02:15:13 +0000104 SmallVector<Instruction*, 32> NowDeadInsts;
105
106 NowDeadInsts.push_back(I);
107 --NumFastOther;
108
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000109 // Keeping the iterator straight is a pain, so we let this routine tell the
110 // caller what the next instruction is after we're done mucking about.
111 BasicBlock::iterator NewIter = *BBI;
112
Eric Christopher0efe9f62015-08-19 02:15:13 +0000113 // Before we touch this instruction, remove it from memdep!
114 do {
115 Instruction *DeadInst = NowDeadInsts.pop_back_val();
116 ++NumFastOther;
117
Vedant Kumar35fc1032018-02-13 18:15:26 +0000118 // Try to preserve debug information attached to the dead instruction.
119 salvageDebugInfo(*DeadInst);
120
Eric Christopher0efe9f62015-08-19 02:15:13 +0000121 // This instruction is dead, zap it, in stages. Start by removing it from
122 // MemDep, which needs to know the operands and needs it to be in the
123 // function.
124 MD.removeInstruction(DeadInst);
125
126 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
127 Value *Op = DeadInst->getOperand(op);
128 DeadInst->setOperand(op, nullptr);
129
130 // If this operand just became dead, add it to the NowDeadInsts list.
131 if (!Op->use_empty()) continue;
132
133 if (Instruction *OpI = dyn_cast<Instruction>(Op))
134 if (isInstructionTriviallyDead(OpI, &TLI))
135 NowDeadInsts.push_back(OpI);
136 }
137
Eli Friedmana6707f52016-08-12 01:09:53 +0000138 if (ValueSet) ValueSet->remove(DeadInst);
139 InstrOrdering->erase(DeadInst);
140 IOL.erase(DeadInst);
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000141
142 if (NewIter == DeadInst->getIterator())
143 NewIter = DeadInst->eraseFromParent();
144 else
145 DeadInst->eraseFromParent();
Eric Christopher0efe9f62015-08-19 02:15:13 +0000146 } while (!NowDeadInsts.empty());
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000147 *BBI = NewIter;
Eric Christopher0efe9f62015-08-19 02:15:13 +0000148}
149
Justin Bogner594e07b2016-05-17 21:38:13 +0000150/// Does this instruction write some memory? This only returns true for things
151/// that we can analyze with other helpers below.
Philip Reames424e7a12018-01-21 01:44:33 +0000152static bool hasAnalyzableMemoryWrite(Instruction *I,
153 const TargetLibraryInfo &TLI) {
Nick Lewycky90271472009-11-10 06:46:40 +0000154 if (isa<StoreInst>(I))
155 return true;
156 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
157 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000158 default:
159 return false;
160 case Intrinsic::memset:
161 case Intrinsic::memmove:
162 case Intrinsic::memcpy:
163 case Intrinsic::init_trampoline:
164 case Intrinsic::lifetime_end:
165 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000166 }
167 }
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000168 if (auto CS = CallSite(I)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000169 if (Function *F = CS.getCalledFunction()) {
Chad Rosier624fee52016-06-16 17:06:04 +0000170 StringRef FnName = F->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000171 if (TLI.has(LibFunc_strcpy) && FnName == TLI.getName(LibFunc_strcpy))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000172 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000173 if (TLI.has(LibFunc_strncpy) && FnName == TLI.getName(LibFunc_strncpy))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000174 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000175 if (TLI.has(LibFunc_strcat) && FnName == TLI.getName(LibFunc_strcat))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000176 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000177 if (TLI.has(LibFunc_strncat) && FnName == TLI.getName(LibFunc_strncat))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000178 return true;
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000179 }
180 }
Nick Lewycky90271472009-11-10 06:46:40 +0000181 return false;
182}
183
Justin Bogner594e07b2016-05-17 21:38:13 +0000184/// Return a Location stored to by the specified instruction. If isRemovable
185/// returns true, this function and getLocForRead completely describe the memory
186/// operations for this instruction.
Philip Reamesf57714c2018-01-21 02:10:54 +0000187static MemoryLocation getLocForWrite(Instruction *Inst) {
Philip Reames424e7a12018-01-21 01:44:33 +0000188
Chris Lattner58b779e2010-11-30 07:23:21 +0000189 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000190 return MemoryLocation::get(SI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000191
Chris Lattner58b779e2010-11-30 07:23:21 +0000192 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
193 // memcpy/memmove/memset.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000194 MemoryLocation Loc = MemoryLocation::getForDest(MI);
Chris Lattner58b779e2010-11-30 07:23:21 +0000195 return Loc;
196 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000197
Philip Reamesf57714c2018-01-21 02:10:54 +0000198 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
199 switch (II->getIntrinsicID()) {
200 default:
201 return MemoryLocation(); // Unhandled intrinsic.
202 case Intrinsic::init_trampoline:
203 return MemoryLocation(II->getArgOperand(0));
204 case Intrinsic::lifetime_end: {
205 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
206 return MemoryLocation(II->getArgOperand(1), Len);
207 }
208 }
Chris Lattner58b779e2010-11-30 07:23:21 +0000209 }
Philip Reamesf57714c2018-01-21 02:10:54 +0000210 if (auto CS = CallSite(Inst))
211 // All the supported TLI functions so far happen to have dest as their
212 // first argument.
213 return MemoryLocation(CS.getArgument(0));
214 return MemoryLocation();
Chris Lattner58b779e2010-11-30 07:23:21 +0000215}
216
Philip Reames424e7a12018-01-21 01:44:33 +0000217/// Return the location read by the specified "hasAnalyzableMemoryWrite"
218/// instruction if any.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000219static MemoryLocation getLocForRead(Instruction *Inst,
220 const TargetLibraryInfo &TLI) {
Philip Reames424e7a12018-01-21 01:44:33 +0000221 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case");
Owen Anderson58704ee2011-09-06 18:14:09 +0000222
Chris Lattner94fbdf32010-12-06 01:48:06 +0000223 // The only instructions that both read and write are the mem transfer
224 // instructions (memcpy/memmove).
225 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000226 return MemoryLocation::getForSource(MTI);
Chandler Carruthac80dc72015-06-17 07:18:54 +0000227 return MemoryLocation();
Chris Lattner94fbdf32010-12-06 01:48:06 +0000228}
229
Justin Bogner594e07b2016-05-17 21:38:13 +0000230/// If the value of this instruction and the memory it writes to is unused, may
231/// we delete this instruction?
Chris Lattner3590ef82010-11-30 05:30:45 +0000232static bool isRemovable(Instruction *I) {
Eli Friedman9a468152011-08-17 22:22:24 +0000233 // Don't remove volatile/atomic stores.
Nick Lewycky90271472009-11-10 06:46:40 +0000234 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Eli Friedman9a468152011-08-17 22:22:24 +0000235 return SI->isUnordered();
Owen Anderson58704ee2011-09-06 18:14:09 +0000236
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000237 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
238 switch (II->getIntrinsicID()) {
Philip Reames424e7a12018-01-21 01:44:33 +0000239 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate");
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000240 case Intrinsic::lifetime_end:
241 // Never remove dead lifetime_end's, e.g. because it is followed by a
242 // free.
243 return false;
244 case Intrinsic::init_trampoline:
245 // Always safe to remove init_trampoline.
246 return true;
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000247 case Intrinsic::memset:
248 case Intrinsic::memmove:
249 case Intrinsic::memcpy:
250 // Don't remove volatile memory intrinsics.
251 return !cast<MemIntrinsic>(II)->isVolatile();
252 }
Chris Lattnerb63ba732010-11-30 19:12:10 +0000253 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000254
Philip Reames424e7a12018-01-21 01:44:33 +0000255 // note: only get here for calls with analyzable writes - i.e. libcalls
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000256 if (auto CS = CallSite(I))
Nick Lewycky42bca052012-09-25 01:55:59 +0000257 return CS.getInstruction()->use_empty();
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000258
259 return false;
Nick Lewycky90271472009-11-10 06:46:40 +0000260}
261
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000262/// Returns true if the end of this instruction can be safely shortened in
Pete Cooper856977c2011-11-09 23:07:35 +0000263/// length.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000264static bool isShortenableAtTheEnd(Instruction *I) {
Pete Cooper856977c2011-11-09 23:07:35 +0000265 // Don't shorten stores for now
266 if (isa<StoreInst>(I))
267 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000268
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000269 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
270 switch (II->getIntrinsicID()) {
271 default: return false;
272 case Intrinsic::memset:
273 case Intrinsic::memcpy:
274 // Do shorten memory intrinsics.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000275 // FIXME: Add memmove if it's also safe to transform.
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000276 return true;
277 }
Pete Cooper856977c2011-11-09 23:07:35 +0000278 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000279
280 // Don't shorten libcalls calls for now.
281
282 return false;
Pete Cooper856977c2011-11-09 23:07:35 +0000283}
284
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000285/// Returns true if the beginning of this instruction can be safely shortened
286/// in length.
287static bool isShortenableAtTheBeginning(Instruction *I) {
288 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
289 // easily done by offsetting the source address.
290 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
291 return II && II->getIntrinsicID() == Intrinsic::memset;
292}
293
Justin Bogner594e07b2016-05-17 21:38:13 +0000294/// Return the pointer that is being written to.
Chris Lattner67122512010-11-30 21:58:14 +0000295static Value *getStoredPointerOperand(Instruction *I) {
Philip Reames424e7a12018-01-21 01:44:33 +0000296 //TODO: factor this to reuse getLocForWrite
Philip Reamesf57714c2018-01-21 02:10:54 +0000297 MemoryLocation Loc = getLocForWrite(I);
298 assert(Loc.Ptr &&
299 "unable to find pointer writen for analyzable instruction?");
300 // TODO: most APIs don't expect const Value *
301 return const_cast<Value*>(Loc.Ptr);
Nick Lewycky90271472009-11-10 06:46:40 +0000302}
303
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000304static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000305 const TargetLibraryInfo &TLI) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000306 uint64_t Size;
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000307 if (getObjectSize(V, Size, DL, &TLI))
Nuno Lopes55fff832012-06-21 15:45:28 +0000308 return Size;
Chandler Carruthecbd1682015-06-17 07:21:38 +0000309 return MemoryLocation::UnknownSize;
Chris Lattner903add82010-11-30 23:43:23 +0000310}
Chris Lattner51c28a92010-11-30 19:34:42 +0000311
Pete Cooper856977c2011-11-09 23:07:35 +0000312namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000313
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000314enum OverwriteResult {
315 OW_Begin,
316 OW_Complete,
317 OW_End,
318 OW_PartialEarlierWithFullLater,
319 OW_Unknown
320};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000321
322} // end anonymous namespace
Pete Cooper856977c2011-11-09 23:07:35 +0000323
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000324/// Return 'OW_Complete' if a store to the 'Later' location completely
325/// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the
326/// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000327/// beginning of the 'Earlier' location is overwritten by 'Later'.
328/// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was
329/// overwritten by a latter (smaller) store which doesn't write outside the big
330/// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000331static OverwriteResult isOverwrite(const MemoryLocation &Later,
332 const MemoryLocation &Earlier,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000333 const DataLayout &DL,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000334 const TargetLibraryInfo &TLI,
Hal Finkela1271032016-06-23 13:46:39 +0000335 int64_t &EarlierOff, int64_t &LaterOff,
336 Instruction *DepWrite,
337 InstOverlapIntervalsTy &IOL) {
Chad Rosier72a793c2016-06-15 22:17:38 +0000338 // If we don't know the sizes of either access, then we can't do a comparison.
339 if (Later.Size == MemoryLocation::UnknownSize ||
340 Earlier.Size == MemoryLocation::UnknownSize)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000341 return OW_Unknown;
Chad Rosier72a793c2016-06-15 22:17:38 +0000342
Chris Lattnerc0f33792010-11-30 23:05:20 +0000343 const Value *P1 = Earlier.Ptr->stripPointerCasts();
344 const Value *P2 = Later.Ptr->stripPointerCasts();
Owen Anderson58704ee2011-09-06 18:14:09 +0000345
Chris Lattnerc0f33792010-11-30 23:05:20 +0000346 // If the start pointers are the same, we just have to compare sizes to see if
347 // the later store was larger than the earlier store.
348 if (P1 == P2) {
Chris Lattnerc0f33792010-11-30 23:05:20 +0000349 // Make sure that the Later size is >= the Earlier size.
Pete Cooper856977c2011-11-09 23:07:35 +0000350 if (Later.Size >= Earlier.Size)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000351 return OW_Complete;
Chris Lattner77d79fa2010-11-30 19:28:23 +0000352 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000353
Chris Lattner903add82010-11-30 23:43:23 +0000354 // Check to see if the later store is to the entire object (either a global,
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000355 // an alloca, or a byval/inalloca argument). If so, then it clearly
356 // overwrites any other store to the same object.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000357 const Value *UO1 = GetUnderlyingObject(P1, DL),
358 *UO2 = GetUnderlyingObject(P2, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000359
Chris Lattner903add82010-11-30 23:43:23 +0000360 // If we can't resolve the same pointers to the same object, then we can't
361 // analyze them at all.
362 if (UO1 != UO2)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000363 return OW_Unknown;
Owen Anderson58704ee2011-09-06 18:14:09 +0000364
Chris Lattner903add82010-11-30 23:43:23 +0000365 // If the "Later" store is to a recognizable object, get its size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000366 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000367 if (ObjectSize != MemoryLocation::UnknownSize)
Pete Coopera4237c32011-11-10 20:22:08 +0000368 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000369 return OW_Complete;
Owen Anderson58704ee2011-09-06 18:14:09 +0000370
Chris Lattnerc0f33792010-11-30 23:05:20 +0000371 // Okay, we have stores to two completely different pointers. Try to
372 // decompose the pointer into a "base + constant_offset" form. If the base
373 // pointers are equal, then we can reason about the two stores.
Pete Cooper856977c2011-11-09 23:07:35 +0000374 EarlierOff = 0;
375 LaterOff = 0;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000376 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
377 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000378
Chris Lattnerc0f33792010-11-30 23:05:20 +0000379 // If the base pointers still differ, we have two completely different stores.
380 if (BP1 != BP2)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000381 return OW_Unknown;
Bill Wendlingdb40b5c2011-03-26 01:20:37 +0000382
Bill Wendling19f33b92011-03-26 08:02:59 +0000383 // The later store completely overlaps the earlier store if:
Owen Anderson58704ee2011-09-06 18:14:09 +0000384 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000385 // 1. Both start at the same offset and the later one's size is greater than
386 // or equal to the earlier one's, or
387 //
388 // |--earlier--|
389 // |-- later --|
Owen Anderson58704ee2011-09-06 18:14:09 +0000390 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000391 // 2. The earlier store has an offset greater than the later offset, but which
392 // still lies completely within the later store.
393 //
394 // |--earlier--|
395 // |----- later ------|
Bill Wendling50341592011-03-30 21:37:19 +0000396 //
397 // We have to be careful here as *Off is signed while *.Size is unsigned.
Bill Wendlingb5139922011-03-26 09:32:07 +0000398 if (EarlierOff >= LaterOff &&
Craig Topper2a404182012-08-14 07:32:05 +0000399 Later.Size >= Earlier.Size &&
Bill Wendling50341592011-03-30 21:37:19 +0000400 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000401 return OW_Complete;
Nadav Rotem465834c2012-07-24 10:51:42 +0000402
Hal Finkela1271032016-06-23 13:46:39 +0000403 // We may now overlap, although the overlap is not complete. There might also
404 // be other incomplete overlaps, and together, they might cover the complete
405 // earlier write.
406 // Note: The correctness of this logic depends on the fact that this function
407 // is not even called providing DepWrite when there are any intervening reads.
408 if (EnablePartialOverwriteTracking &&
409 LaterOff < int64_t(EarlierOff + Earlier.Size) &&
410 int64_t(LaterOff + Later.Size) >= EarlierOff) {
411
412 // Insert our part of the overlap into the map.
413 auto &IM = IOL[DepWrite];
414 DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff << ", " <<
415 int64_t(EarlierOff + Earlier.Size) << ") Later [" <<
416 LaterOff << ", " << int64_t(LaterOff + Later.Size) << ")\n");
417
418 // Make sure that we only insert non-overlapping intervals and combine
419 // adjacent intervals. The intervals are stored in the map with the ending
420 // offset as the key (in the half-open sense) and the starting offset as
421 // the value.
422 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + Later.Size;
423
424 // Find any intervals ending at, or after, LaterIntStart which start
425 // before LaterIntEnd.
426 auto ILI = IM.lower_bound(LaterIntStart);
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000427 if (ILI != IM.end() && ILI->second <= LaterIntEnd) {
428 // This existing interval is overlapped with the current store somewhere
429 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing
430 // intervals and adjusting our start and end.
Hal Finkela1271032016-06-23 13:46:39 +0000431 LaterIntStart = std::min(LaterIntStart, ILI->second);
432 LaterIntEnd = std::max(LaterIntEnd, ILI->first);
433 ILI = IM.erase(ILI);
434
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000435 // Continue erasing and adjusting our end in case other previous
436 // intervals are also overlapped with the current store.
437 //
438 // |--- ealier 1 ---| |--- ealier 2 ---|
439 // |------- later---------|
440 //
441 while (ILI != IM.end() && ILI->second <= LaterIntEnd) {
442 assert(ILI->second > LaterIntStart && "Unexpected interval");
Hal Finkela1271032016-06-23 13:46:39 +0000443 LaterIntEnd = std::max(LaterIntEnd, ILI->first);
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000444 ILI = IM.erase(ILI);
445 }
Hal Finkela1271032016-06-23 13:46:39 +0000446 }
447
448 IM[LaterIntEnd] = LaterIntStart;
449
450 ILI = IM.begin();
451 if (ILI->second <= EarlierOff &&
452 ILI->first >= int64_t(EarlierOff + Earlier.Size)) {
453 DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" <<
454 EarlierOff << ", " <<
455 int64_t(EarlierOff + Earlier.Size) <<
456 ") Composite Later [" <<
457 ILI->second << ", " << ILI->first << ")\n");
458 ++NumCompletePartials;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000459 return OW_Complete;
Hal Finkela1271032016-06-23 13:46:39 +0000460 }
461 }
462
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000463 // Check for an earlier store which writes to all the memory locations that
464 // the later store writes to.
465 if (EnablePartialStoreMerging && LaterOff >= EarlierOff &&
466 int64_t(EarlierOff + Earlier.Size) > LaterOff &&
467 uint64_t(LaterOff - EarlierOff) + Later.Size <= Earlier.Size) {
468 DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" << EarlierOff
469 << ", " << int64_t(EarlierOff + Earlier.Size)
470 << ") by a later store [" << LaterOff << ", "
471 << int64_t(LaterOff + Later.Size) << ")\n");
472 // TODO: Maybe come up with a better name?
473 return OW_PartialEarlierWithFullLater;
474 }
475
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000476 // Another interesting case is if the later store overwrites the end of the
477 // earlier store.
Pete Cooper856977c2011-11-09 23:07:35 +0000478 //
479 // |--earlier--|
480 // |-- later --|
481 //
482 // In this case we may want to trim the size of earlier to avoid generating
483 // writes to addresses which will definitely be overwritten later
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000484 if (!EnablePartialOverwriteTracking &&
485 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + Earlier.Size) &&
486 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size)))
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000487 return OW_End;
Bill Wendling19f33b92011-03-26 08:02:59 +0000488
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000489 // Finally, we also need to check if the later store overwrites the beginning
490 // of the earlier store.
491 //
492 // |--earlier--|
493 // |-- later --|
494 //
495 // In this case we may want to move the destination address and trim the size
496 // of earlier to avoid generating writes to addresses which will definitely
497 // be overwritten later.
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000498 if (!EnablePartialOverwriteTracking &&
499 (LaterOff <= EarlierOff && int64_t(LaterOff + Later.Size) > EarlierOff)) {
500 assert(int64_t(LaterOff + Later.Size) <
501 int64_t(EarlierOff + Earlier.Size) &&
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000502 "Expect to be handled as OW_Complete");
503 return OW_Begin;
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000504 }
Bill Wendling19f33b92011-03-26 08:02:59 +0000505 // Otherwise, they don't completely overlap.
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000506 return OW_Unknown;
Nick Lewycky90271472009-11-10 06:46:40 +0000507}
508
Justin Bogner594e07b2016-05-17 21:38:13 +0000509/// If 'Inst' might be a self read (i.e. a noop copy of a
Chris Lattner94fbdf32010-12-06 01:48:06 +0000510/// memory region into an identical pointer) then it doesn't actually make its
Owen Anderson58704ee2011-09-06 18:14:09 +0000511/// input dead in the traditional sense. Consider this case:
Chris Lattner94fbdf32010-12-06 01:48:06 +0000512///
513/// memcpy(A <- B)
514/// memcpy(A <- A)
515///
516/// In this case, the second store to A does not make the first store to A dead.
517/// The usual situation isn't an explicit A<-A store like this (which can be
518/// trivially removed) but a case where two pointers may alias.
519///
520/// This function detects when it is unsafe to remove a dependent instruction
521/// because the DSE inducing instruction may be a self-read.
522static bool isPossibleSelfRead(Instruction *Inst,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000523 const MemoryLocation &InstStoreLoc,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000524 Instruction *DepWrite,
525 const TargetLibraryInfo &TLI,
526 AliasAnalysis &AA) {
Chris Lattner94fbdf32010-12-06 01:48:06 +0000527 // Self reads can only happen for instructions that read memory. Get the
528 // location read.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000529 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +0000530 if (!InstReadLoc.Ptr) return false; // Not a reading instruction.
Owen Anderson58704ee2011-09-06 18:14:09 +0000531
Chris Lattner94fbdf32010-12-06 01:48:06 +0000532 // If the read and written loc obviously don't alias, it isn't a read.
533 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000534
Chris Lattner94fbdf32010-12-06 01:48:06 +0000535 // Okay, 'Inst' may copy over itself. However, we can still remove a the
536 // DepWrite instruction if we can prove that it reads from the same location
537 // as Inst. This handles useful cases like:
538 // memcpy(A <- B)
539 // memcpy(A <- B)
540 // Here we don't know if A/B may alias, but we do know that B/B are must
541 // aliases, so removing the first memcpy is safe (assuming it writes <= #
542 // bytes as the second one.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000543 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000544
Chris Lattner94fbdf32010-12-06 01:48:06 +0000545 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
546 return false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000547
Chris Lattner94fbdf32010-12-06 01:48:06 +0000548 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
549 // then it can't be considered dead.
550 return true;
551}
552
Justin Bogner594e07b2016-05-17 21:38:13 +0000553/// Returns true if the memory which is accessed by the second instruction is not
554/// modified between the first and the second instruction.
555/// Precondition: Second instruction must be dominated by the first
556/// instruction.
557static bool memoryIsNotModifiedBetween(Instruction *FirstI,
558 Instruction *SecondI,
559 AliasAnalysis *AA) {
560 SmallVector<BasicBlock *, 16> WorkList;
561 SmallPtrSet<BasicBlock *, 8> Visited;
562 BasicBlock::iterator FirstBBI(FirstI);
563 ++FirstBBI;
564 BasicBlock::iterator SecondBBI(SecondI);
565 BasicBlock *FirstBB = FirstI->getParent();
566 BasicBlock *SecondBB = SecondI->getParent();
567 MemoryLocation MemLoc = MemoryLocation::get(SecondI);
Chris Lattner67122512010-11-30 21:58:14 +0000568
Justin Bogner594e07b2016-05-17 21:38:13 +0000569 // Start checking the store-block.
570 WorkList.push_back(SecondBB);
571 bool isFirstBlock = true;
572
573 // Check all blocks going backward until we reach the load-block.
574 while (!WorkList.empty()) {
575 BasicBlock *B = WorkList.pop_back_val();
576
577 // Ignore instructions before LI if this is the FirstBB.
578 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
579
580 BasicBlock::iterator EI;
581 if (isFirstBlock) {
582 // Ignore instructions after SI if this is the first visit of SecondBB.
583 assert(B == SecondBB && "first block is not the store block");
584 EI = SecondBBI;
585 isFirstBlock = false;
586 } else {
587 // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
588 // In this case we also have to look at instructions after SI.
589 EI = B->end();
590 }
591 for (; BI != EI; ++BI) {
592 Instruction *I = &*BI;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000593 if (I->mayWriteToMemory() && I != SecondI)
594 if (isModSet(AA->getModRefInfo(I, MemLoc)))
Justin Bogner594e07b2016-05-17 21:38:13 +0000595 return false;
Justin Bogner594e07b2016-05-17 21:38:13 +0000596 }
597 if (B != FirstBB) {
598 assert(B != &FirstBB->getParent()->getEntryBlock() &&
599 "Should not hit the entry block because SI must be dominated by LI");
600 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
601 if (!Visited.insert(*PredI).second)
602 continue;
603 WorkList.push_back(*PredI);
604 }
605 }
606 }
607 return true;
608}
609
610/// Find all blocks that will unconditionally lead to the block BB and append
611/// them to F.
612static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
613 BasicBlock *BB, DominatorTree *DT) {
614 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
615 BasicBlock *Pred = *I;
616 if (Pred == BB) continue;
617 TerminatorInst *PredTI = Pred->getTerminator();
618 if (PredTI->getNumSuccessors() != 1)
619 continue;
620
621 if (DT->isReachableFromEntry(Pred))
622 Blocks.push_back(Pred);
623 }
624}
625
626/// Handle frees of entire structures whose dependency is a store
627/// to a field of that structure.
628static bool handleFree(CallInst *F, AliasAnalysis *AA,
629 MemoryDependenceResults *MD, DominatorTree *DT,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000630 const TargetLibraryInfo *TLI,
Eli Friedmana6707f52016-08-12 01:09:53 +0000631 InstOverlapIntervalsTy &IOL,
632 DenseMap<Instruction*, size_t> *InstrOrdering) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000633 bool MadeChange = false;
634
635 MemoryLocation Loc = MemoryLocation(F->getOperand(0));
636 SmallVector<BasicBlock *, 16> Blocks;
637 Blocks.push_back(F->getParent());
638 const DataLayout &DL = F->getModule()->getDataLayout();
639
640 while (!Blocks.empty()) {
641 BasicBlock *BB = Blocks.pop_back_val();
642 Instruction *InstPt = BB->getTerminator();
643 if (BB == F->getParent()) InstPt = F;
644
645 MemDepResult Dep =
646 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB);
647 while (Dep.isDef() || Dep.isClobber()) {
648 Instruction *Dependency = Dep.getInst();
Philip Reames424e7a12018-01-21 01:44:33 +0000649 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) ||
650 !isRemovable(Dependency))
Justin Bogner594e07b2016-05-17 21:38:13 +0000651 break;
652
653 Value *DepPointer =
654 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
655
656 // Check for aliasing.
657 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
658 break;
659
Chad Rosier667b1ca2016-07-19 16:50:57 +0000660 DEBUG(dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: "
661 << *Dependency << '\n');
662
Chad Rosier840b3ef2016-06-10 17:59:22 +0000663 // DCE instructions only used to calculate that store.
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000664 BasicBlock::iterator BBI(Dependency);
Eli Friedmana6707f52016-08-12 01:09:53 +0000665 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, InstrOrdering);
Justin Bogner594e07b2016-05-17 21:38:13 +0000666 ++NumFastStores;
667 MadeChange = true;
668
669 // Inst's old Dependency is now deleted. Compute the next dependency,
670 // which may also be dead, as in
671 // s[0] = 0;
672 // s[1] = 0; // This has just been deleted.
673 // free(s);
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000674 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB);
Justin Bogner594e07b2016-05-17 21:38:13 +0000675 }
676
677 if (Dep.isNonLocal())
678 findUnconditionalPreds(Blocks, BB, DT);
679 }
680
681 return MadeChange;
682}
683
684/// Check to see if the specified location may alias any of the stack objects in
685/// the DeadStackObjects set. If so, they become live because the location is
686/// being loaded.
687static void removeAccessedObjects(const MemoryLocation &LoadedLoc,
688 SmallSetVector<Value *, 16> &DeadStackObjects,
689 const DataLayout &DL, AliasAnalysis *AA,
690 const TargetLibraryInfo *TLI) {
691 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
692
693 // A constant can't be in the dead pointer set.
694 if (isa<Constant>(UnderlyingPointer))
695 return;
696
697 // If the kill pointer can be easily reduced to an alloca, don't bother doing
698 // extraneous AA queries.
699 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
700 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
701 return;
702 }
703
704 // Remove objects that could alias LoadedLoc.
705 DeadStackObjects.remove_if([&](Value *I) {
706 // See if the loaded location could alias the stack location.
707 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
708 return !AA->isNoAlias(StackLoc, LoadedLoc);
709 });
710}
711
712/// Remove dead stores to stack-allocated locations in the function end block.
713/// Ex:
714/// %A = alloca i32
715/// ...
716/// store i32 1, i32* %A
717/// ret void
718static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA,
719 MemoryDependenceResults *MD,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000720 const TargetLibraryInfo *TLI,
Eli Friedmana6707f52016-08-12 01:09:53 +0000721 InstOverlapIntervalsTy &IOL,
722 DenseMap<Instruction*, size_t> *InstrOrdering) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000723 bool MadeChange = false;
724
725 // Keep track of all of the stack objects that are dead at the end of the
726 // function.
727 SmallSetVector<Value*, 16> DeadStackObjects;
728
729 // Find all of the alloca'd pointers in the entry block.
730 BasicBlock &Entry = BB.getParent()->front();
731 for (Instruction &I : Entry) {
732 if (isa<AllocaInst>(&I))
733 DeadStackObjects.insert(&I);
734
735 // Okay, so these are dead heap objects, but if the pointer never escapes
736 // then it's leaked by this function anyways.
737 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
738 DeadStackObjects.insert(&I);
739 }
740
741 // Treat byval or inalloca arguments the same, stores to them are dead at the
742 // end of the function.
743 for (Argument &AI : BB.getParent()->args())
744 if (AI.hasByValOrInAllocaAttr())
745 DeadStackObjects.insert(&AI);
746
747 const DataLayout &DL = BB.getModule()->getDataLayout();
748
749 // Scan the basic block backwards
750 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
751 --BBI;
752
753 // If we find a store, check to see if it points into a dead stack value.
Philip Reames424e7a12018-01-21 01:44:33 +0000754 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000755 // See through pointer-to-pointer bitcasts
756 SmallVector<Value *, 4> Pointers;
757 GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL);
758
759 // Stores to stack values are valid candidates for removal.
760 bool AllDead = true;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000761 for (Value *Pointer : Pointers)
762 if (!DeadStackObjects.count(Pointer)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000763 AllDead = false;
764 break;
765 }
766
767 if (AllDead) {
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000768 Instruction *Dead = &*BBI;
Justin Bogner594e07b2016-05-17 21:38:13 +0000769
770 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
771 << *Dead << "\n Objects: ";
772 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
773 E = Pointers.end(); I != E; ++I) {
774 dbgs() << **I;
775 if (std::next(I) != E)
776 dbgs() << ", ";
777 }
778 dbgs() << '\n');
779
780 // DCE instructions only used to calculate that store.
Eli Friedmana6707f52016-08-12 01:09:53 +0000781 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, InstrOrdering, &DeadStackObjects);
Justin Bogner594e07b2016-05-17 21:38:13 +0000782 ++NumFastStores;
783 MadeChange = true;
784 continue;
785 }
786 }
787
788 // Remove any dead non-memory-mutating instructions.
789 if (isInstructionTriviallyDead(&*BBI, TLI)) {
Chad Rosier8b5fa7a2016-07-19 18:11:11 +0000790 DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: "
791 << *&*BBI << '\n');
Eli Friedmana6707f52016-08-12 01:09:53 +0000792 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, InstrOrdering, &DeadStackObjects);
Justin Bogner594e07b2016-05-17 21:38:13 +0000793 ++NumFastOther;
794 MadeChange = true;
795 continue;
796 }
797
798 if (isa<AllocaInst>(BBI)) {
799 // Remove allocas from the list of dead stack objects; there can't be
800 // any references before the definition.
801 DeadStackObjects.remove(&*BBI);
802 continue;
803 }
804
805 if (auto CS = CallSite(&*BBI)) {
806 // Remove allocation function calls from the list of dead stack objects;
807 // there can't be any references before the definition.
808 if (isAllocLikeFn(&*BBI, TLI))
809 DeadStackObjects.remove(&*BBI);
810
811 // If this call does not access memory, it can't be loading any of our
812 // pointers.
813 if (AA->doesNotAccessMemory(CS))
814 continue;
815
816 // If the call might load from any of our allocas, then any store above
817 // the call is live.
818 DeadStackObjects.remove_if([&](Value *I) {
819 // See if the call site touches the value.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000820 return isRefSet(AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI)));
Justin Bogner594e07b2016-05-17 21:38:13 +0000821 });
822
823 // If all of the allocas were clobbered by the call then we're not going
824 // to find anything else to process.
825 if (DeadStackObjects.empty())
826 break;
827
828 continue;
829 }
830
Anna Thomas6a78c782016-07-07 20:51:42 +0000831 // We can remove the dead stores, irrespective of the fence and its ordering
832 // (release/acquire/seq_cst). Fences only constraints the ordering of
833 // already visible stores, it does not make a store visible to other
834 // threads. So, skipping over a fence does not change a store from being
835 // dead.
836 if (isa<FenceInst>(*BBI))
837 continue;
838
Justin Bogner594e07b2016-05-17 21:38:13 +0000839 MemoryLocation LoadedLoc;
840
841 // If we encounter a use of the pointer, it is no longer considered dead
842 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
843 if (!L->isUnordered()) // Be conservative with atomic/volatile load
844 break;
845 LoadedLoc = MemoryLocation::get(L);
846 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
847 LoadedLoc = MemoryLocation::get(V);
848 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
849 LoadedLoc = MemoryLocation::getForSource(MTI);
850 } else if (!BBI->mayReadFromMemory()) {
851 // Instruction doesn't read memory. Note that stores that weren't removed
852 // above will hit this case.
853 continue;
854 } else {
855 // Unknown inst; assume it clobbers everything.
856 break;
857 }
858
859 // Remove any allocas from the DeadPointer set that are loaded, as this
860 // makes any stores above the access live.
861 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI);
862
863 // If all of the allocas were clobbered by the access then we're not going
864 // to find anything else to process.
865 if (DeadStackObjects.empty())
866 break;
867 }
868
869 return MadeChange;
870}
871
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000872static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset,
873 int64_t &EarlierSize, int64_t LaterOffset,
874 int64_t LaterSize, bool IsOverwriteEnd) {
875 // TODO: base this on the target vector size so that if the earlier
876 // store was too small to get vector writes anyway then its likely
877 // a good idea to shorten it
878 // Power of 2 vector writes are probably always a bad idea to optimize
879 // as any store/memset/memcpy is likely using vector instructions so
880 // shortening it to not vector size is likely to be slower
881 MemIntrinsic *EarlierIntrinsic = cast<MemIntrinsic>(EarlierWrite);
Daniel Neilson83cdf682018-02-06 21:18:33 +0000882 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment();
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000883 if (!IsOverwriteEnd)
884 LaterOffset = int64_t(LaterOffset + LaterSize);
885
Eugene Zelenko3b879392017-10-13 21:17:07 +0000886 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) &&
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000887 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0))
888 return false;
889
890 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW "
891 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " << *EarlierWrite
892 << "\n KILLER (offset " << LaterOffset << ", " << EarlierSize
893 << ")\n");
894
895 int64_t NewLength = IsOverwriteEnd
896 ? LaterOffset - EarlierOffset
897 : EarlierSize - (LaterOffset - EarlierOffset);
898
899 Value *EarlierWriteLength = EarlierIntrinsic->getLength();
900 Value *TrimmedLength =
901 ConstantInt::get(EarlierWriteLength->getType(), NewLength);
902 EarlierIntrinsic->setLength(TrimmedLength);
903
904 EarlierSize = NewLength;
905 if (!IsOverwriteEnd) {
906 int64_t OffsetMoved = (LaterOffset - EarlierOffset);
907 Value *Indices[1] = {
908 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)};
909 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds(
910 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite);
911 EarlierIntrinsic->setDest(NewDestGEP);
912 EarlierOffset = EarlierOffset + OffsetMoved;
913 }
914 return true;
915}
916
917static bool tryToShortenEnd(Instruction *EarlierWrite,
918 OverlapIntervalsTy &IntervalMap,
919 int64_t &EarlierStart, int64_t &EarlierSize) {
920 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite))
921 return false;
922
923 OverlapIntervalsTy::iterator OII = --IntervalMap.end();
924 int64_t LaterStart = OII->second;
925 int64_t LaterSize = OII->first - LaterStart;
926
927 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize &&
928 LaterStart + LaterSize >= EarlierStart + EarlierSize) {
929 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
930 LaterSize, true)) {
931 IntervalMap.erase(OII);
932 return true;
933 }
934 }
935 return false;
936}
937
938static bool tryToShortenBegin(Instruction *EarlierWrite,
939 OverlapIntervalsTy &IntervalMap,
940 int64_t &EarlierStart, int64_t &EarlierSize) {
941 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite))
942 return false;
943
944 OverlapIntervalsTy::iterator OII = IntervalMap.begin();
945 int64_t LaterStart = OII->second;
946 int64_t LaterSize = OII->first - LaterStart;
947
948 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) {
949 assert(LaterStart + LaterSize < EarlierStart + EarlierSize &&
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000950 "Should have been handled as OW_Complete");
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000951 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
952 LaterSize, false)) {
953 IntervalMap.erase(OII);
954 return true;
955 }
956 }
957 return false;
958}
959
960static bool removePartiallyOverlappedStores(AliasAnalysis *AA,
961 const DataLayout &DL,
962 InstOverlapIntervalsTy &IOL) {
963 bool Changed = false;
964 for (auto OI : IOL) {
965 Instruction *EarlierWrite = OI.first;
Philip Reamesf57714c2018-01-21 02:10:54 +0000966 MemoryLocation Loc = getLocForWrite(EarlierWrite);
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000967 assert(isRemovable(EarlierWrite) && "Expect only removable instruction");
968 assert(Loc.Size != MemoryLocation::UnknownSize && "Unexpected mem loc");
969
970 const Value *Ptr = Loc.Ptr->stripPointerCasts();
971 int64_t EarlierStart = 0;
972 int64_t EarlierSize = int64_t(Loc.Size);
973 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL);
974 OverlapIntervalsTy &IntervalMap = OI.second;
Jun Bum Lima0331392016-07-27 17:25:20 +0000975 Changed |=
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000976 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
977 if (IntervalMap.empty())
978 continue;
979 Changed |=
980 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
981 }
982 return Changed;
983}
984
Chad Rosier89c32a92016-07-08 16:48:40 +0000985static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI,
986 AliasAnalysis *AA, MemoryDependenceResults *MD,
987 const DataLayout &DL,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000988 const TargetLibraryInfo *TLI,
Eli Friedmana6707f52016-08-12 01:09:53 +0000989 InstOverlapIntervalsTy &IOL,
990 DenseMap<Instruction*, size_t> *InstrOrdering) {
Chad Rosier89c32a92016-07-08 16:48:40 +0000991 // Must be a store instruction.
992 StoreInst *SI = dyn_cast<StoreInst>(Inst);
993 if (!SI)
994 return false;
995
996 // If we're storing the same value back to a pointer that we just loaded from,
997 // then the store can be removed.
998 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
999 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
1000 isRemovable(SI) && memoryIsNotModifiedBetween(DepLoad, SI, AA)) {
1001
1002 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: "
1003 << *DepLoad << "\n STORE: " << *SI << '\n');
1004
Eli Friedmana6707f52016-08-12 01:09:53 +00001005 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, InstrOrdering);
Chad Rosier89c32a92016-07-08 16:48:40 +00001006 ++NumRedundantStores;
1007 return true;
1008 }
1009 }
1010
1011 // Remove null stores into the calloc'ed objects
1012 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
1013 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) {
1014 Instruction *UnderlyingPointer =
1015 dyn_cast<Instruction>(GetUnderlyingObject(SI->getPointerOperand(), DL));
1016
1017 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
1018 memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) {
1019 DEBUG(
1020 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: "
1021 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n');
1022
Eli Friedmana6707f52016-08-12 01:09:53 +00001023 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, InstrOrdering);
Chad Rosier89c32a92016-07-08 16:48:40 +00001024 ++NumRedundantStores;
1025 return true;
1026 }
1027 }
1028 return false;
1029}
1030
Justin Bogner594e07b2016-05-17 21:38:13 +00001031static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA,
1032 MemoryDependenceResults *MD, DominatorTree *DT,
1033 const TargetLibraryInfo *TLI) {
Igor Laevsky029bd932015-09-23 11:38:44 +00001034 const DataLayout &DL = BB.getModule()->getDataLayout();
Owen Anderson5e72db32007-07-11 00:46:18 +00001035 bool MadeChange = false;
Owen Anderson58704ee2011-09-06 18:14:09 +00001036
Eli Friedmana6707f52016-08-12 01:09:53 +00001037 // FIXME: Maybe change this to use some abstraction like OrderedBasicBlock?
1038 // The current OrderedBasicBlock can't deal with mutation at the moment.
1039 size_t LastThrowingInstIndex = 0;
1040 DenseMap<Instruction*, size_t> InstrOrdering;
1041 size_t InstrIndex = 1;
1042
Hal Finkela1271032016-06-23 13:46:39 +00001043 // A map of interval maps representing partially-overwritten value parts.
1044 InstOverlapIntervalsTy IOL;
1045
Chris Lattner49162672009-09-02 06:31:02 +00001046 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +00001047 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
Chris Lattner9d179d92010-11-30 01:28:33 +00001048 // Handle 'free' calls specially.
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001049 if (CallInst *F = isFreeCall(&*BBI, TLI)) {
Eli Friedmana6707f52016-08-12 01:09:53 +00001050 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, &InstrOrdering);
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001051 // Increment BBI after handleFree has potentially deleted instructions.
1052 // This ensures we maintain a valid iterator.
1053 ++BBI;
Chris Lattner9d179d92010-11-30 01:28:33 +00001054 continue;
1055 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001056
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001057 Instruction *Inst = &*BBI++;
1058
Eli Friedmana6707f52016-08-12 01:09:53 +00001059 size_t CurInstNumber = InstrIndex++;
1060 InstrOrdering.insert(std::make_pair(Inst, CurInstNumber));
1061 if (Inst->mayThrow()) {
1062 LastThrowingInstIndex = CurInstNumber;
1063 continue;
1064 }
1065
Chad Rosier89c32a92016-07-08 16:48:40 +00001066 // Check to see if Inst writes to memory. If not, continue.
Philip Reames424e7a12018-01-21 01:44:33 +00001067 if (!hasAnalyzableMemoryWrite(Inst, *TLI))
Owen Anderson0aecf0e2007-08-08 04:52:29 +00001068 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +00001069
Chad Rosier89c32a92016-07-08 16:48:40 +00001070 // eliminateNoopStore will update in iterator, if necessary.
Eli Friedmana6707f52016-08-12 01:09:53 +00001071 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, &InstrOrdering)) {
Chad Rosier89c32a92016-07-08 16:48:40 +00001072 MadeChange = true;
1073 continue;
Owen Anderson5e72db32007-07-11 00:46:18 +00001074 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001075
Chad Rosier89c32a92016-07-08 16:48:40 +00001076 // If we find something that writes memory, get its memory dependence.
Erik Eckstein11fc8172015-08-13 15:36:11 +00001077 MemDepResult InstDep = MD->getDependency(Inst);
1078
Chad Rosierd7634fc2015-12-11 18:39:41 +00001079 // Ignore any store where we can't find a local dependence.
1080 // FIXME: cross-block DSE would be fun. :)
1081 if (!InstDep.isDef() && !InstDep.isClobber())
1082 continue;
Erik Eckstein11fc8172015-08-13 15:36:11 +00001083
Chad Rosierd7634fc2015-12-11 18:39:41 +00001084 // Figure out what location is being stored to.
Philip Reamesf57714c2018-01-21 02:10:54 +00001085 MemoryLocation Loc = getLocForWrite(Inst);
Chris Lattner58b779e2010-11-30 07:23:21 +00001086
Chad Rosierd7634fc2015-12-11 18:39:41 +00001087 // If we didn't get a useful location, fail.
1088 if (!Loc.Ptr)
1089 continue;
1090
Bob Haarman3db17642016-08-26 16:34:27 +00001091 // Loop until we find a store we can eliminate or a load that
1092 // invalidates the analysis. Without an upper bound on the number of
1093 // instructions examined, this analysis can become very time-consuming.
1094 // However, the potential gain diminishes as we process more instructions
1095 // without eliminating any of them. Therefore, we limit the number of
1096 // instructions we look at.
1097 auto Limit = MD->getDefaultBlockScanLimit();
Chad Rosierd7634fc2015-12-11 18:39:41 +00001098 while (InstDep.isDef() || InstDep.isClobber()) {
1099 // Get the memory clobbered by the instruction we depend on. MemDep will
1100 // skip any instructions that 'Loc' clearly doesn't interact with. If we
1101 // end up depending on a may- or must-aliased load, then we can't optimize
Chad Rosier844e2df2016-06-15 21:41:22 +00001102 // away the store and we bail out. However, if we depend on something
Chad Rosierd7634fc2015-12-11 18:39:41 +00001103 // that overwrites the memory location we *can* potentially optimize it.
1104 //
1105 // Find out what memory location the dependent instruction stores.
1106 Instruction *DepWrite = InstDep.getInst();
Philip Reamesf57714c2018-01-21 02:10:54 +00001107 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI))
1108 break;
1109 MemoryLocation DepLoc = getLocForWrite(DepWrite);
Chad Rosierd7634fc2015-12-11 18:39:41 +00001110 // If we didn't get a useful location, or if it isn't a size, bail out.
1111 if (!DepLoc.Ptr)
1112 break;
1113
Eli Friedmana6707f52016-08-12 01:09:53 +00001114 // Make sure we don't look past a call which might throw. This is an
1115 // issue because MemoryDependenceAnalysis works in the wrong direction:
1116 // it finds instructions which dominate the current instruction, rather than
1117 // instructions which are post-dominated by the current instruction.
1118 //
1119 // If the underlying object is a non-escaping memory allocation, any store
1120 // to it is dead along the unwind edge. Otherwise, we need to preserve
1121 // the store.
1122 size_t DepIndex = InstrOrdering.lookup(DepWrite);
1123 assert(DepIndex && "Unexpected instruction");
1124 if (DepIndex <= LastThrowingInstIndex) {
1125 const Value* Underlying = GetUnderlyingObject(DepLoc.Ptr, DL);
1126 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying);
1127 if (!IsStoreDeadOnUnwind) {
1128 // We're looking for a call to an allocation function
1129 // where the allocation doesn't escape before the last
1130 // throwing instruction; PointerMayBeCaptured
1131 // reasonably fast approximation.
1132 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) &&
1133 !PointerMayBeCaptured(Underlying, false, true);
1134 }
1135 if (!IsStoreDeadOnUnwind)
1136 break;
1137 }
1138
Chad Rosierd7634fc2015-12-11 18:39:41 +00001139 // If we find a write that is a) removable (i.e., non-volatile), b) is
1140 // completely obliterated by the store to 'Loc', and c) which we know that
1141 // 'Inst' doesn't load from, then we can remove it.
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001142 // Also try to merge two stores if a later one only touches memory written
1143 // to by the earlier one.
Chad Rosierd7634fc2015-12-11 18:39:41 +00001144 if (isRemovable(DepWrite) &&
1145 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
1146 int64_t InstWriteOffset, DepWriteOffset;
1147 OverwriteResult OR =
Hal Finkela1271032016-06-23 13:46:39 +00001148 isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset,
1149 DepWrite, IOL);
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001150 if (OR == OW_Complete) {
Chad Rosierd7634fc2015-12-11 18:39:41 +00001151 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
1152 << *DepWrite << "\n KILLER: " << *Inst << '\n');
Alexander Kornienko63dd36f2016-07-18 15:51:31 +00001153
Chad Rosierd7634fc2015-12-11 18:39:41 +00001154 // Delete the store and now-dead instructions that feed it.
Eli Friedmana6707f52016-08-12 01:09:53 +00001155 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, &InstrOrdering);
Chad Rosierd7634fc2015-12-11 18:39:41 +00001156 ++NumFastStores;
1157 MadeChange = true;
1158
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001159 // We erased DepWrite; start over.
1160 InstDep = MD->getDependency(Inst);
1161 continue;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001162 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) ||
1163 ((OR == OW_Begin &&
Jun Bum Limd29a24e2016-04-22 19:51:29 +00001164 isShortenableAtTheBeginning(DepWrite)))) {
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001165 assert(!EnablePartialOverwriteTracking && "Do not expect to perform "
1166 "when partial-overwrite "
1167 "tracking is enabled");
1168 int64_t EarlierSize = DepLoc.Size;
1169 int64_t LaterSize = Loc.Size;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001170 bool IsOverwriteEnd = (OR == OW_End);
Jun Bum Lima0331392016-07-27 17:25:20 +00001171 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001172 InstWriteOffset, LaterSize, IsOverwriteEnd);
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001173 } else if (EnablePartialStoreMerging &&
1174 OR == OW_PartialEarlierWithFullLater) {
1175 auto *Earlier = dyn_cast<StoreInst>(DepWrite);
1176 auto *Later = dyn_cast<StoreInst>(Inst);
1177 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) &&
Sanjay Patel1aef27f2018-01-30 13:53:59 +00001178 Later && isa<ConstantInt>(Later->getValueOperand()) &&
1179 memoryIsNotModifiedBetween(Earlier, Later, AA)) {
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001180 // If the store we find is:
1181 // a) partially overwritten by the store to 'Loc'
1182 // b) the later store is fully contained in the earlier one and
1183 // c) they both have a constant value
1184 // Merge the two stores, replacing the earlier store's value with a
1185 // merge of both values.
1186 // TODO: Deal with other constant types (vectors, etc), and probably
1187 // some mem intrinsics (if needed)
1188
1189 APInt EarlierValue =
1190 cast<ConstantInt>(Earlier->getValueOperand())->getValue();
1191 APInt LaterValue =
1192 cast<ConstantInt>(Later->getValueOperand())->getValue();
1193 unsigned LaterBits = LaterValue.getBitWidth();
1194 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth());
1195 LaterValue = LaterValue.zext(EarlierValue.getBitWidth());
1196
1197 // Offset of the smaller store inside the larger store
1198 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8;
1199 unsigned LShiftAmount =
1200 DL.isBigEndian()
1201 ? EarlierValue.getBitWidth() - BitOffsetDiff - LaterBits
1202 : BitOffsetDiff;
1203 APInt Mask =
1204 APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount,
1205 LShiftAmount + LaterBits);
1206 // Clear the bits we'll be replacing, then OR with the smaller
1207 // store, shifted appropriately.
1208 APInt Merged =
1209 (EarlierValue & ~Mask) | (LaterValue << LShiftAmount);
1210 DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *DepWrite
1211 << "\n Later: " << *Inst
1212 << "\n Merged Value: " << Merged << '\n');
1213
1214 auto *SI = new StoreInst(
1215 ConstantInt::get(Earlier->getValueOperand()->getType(), Merged),
1216 Earlier->getPointerOperand(), false, Earlier->getAlignment(),
1217 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite);
1218
1219 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa,
1220 LLVMContext::MD_alias_scope,
1221 LLVMContext::MD_noalias,
1222 LLVMContext::MD_nontemporal};
1223 SI->copyMetadata(*DepWrite, MDToKeep);
1224 ++NumModifiedStores;
1225
1226 // Remove earlier, wider, store
1227 size_t Idx = InstrOrdering.lookup(DepWrite);
1228 InstrOrdering.erase(DepWrite);
1229 InstrOrdering.insert(std::make_pair(SI, Idx));
1230
1231 // Delete the old stores and now-dead instructions that feed them.
1232 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, &InstrOrdering);
1233 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL,
1234 &InstrOrdering);
1235 MadeChange = true;
1236
1237 // We erased DepWrite and Inst (Loc); start over.
1238 break;
1239 }
Pete Cooper856977c2011-11-09 23:07:35 +00001240 }
Chris Lattner58b779e2010-11-30 07:23:21 +00001241 }
Chad Rosierd7634fc2015-12-11 18:39:41 +00001242
1243 // If this is a may-aliased store that is clobbering the store value, we
1244 // can keep searching past it for another must-aliased pointer that stores
1245 // to the same location. For example, in:
1246 // store -> P
1247 // store -> Q
1248 // store -> P
1249 // we can remove the first store to P even though we don't know if P and Q
1250 // alias.
1251 if (DepWrite == &BB.front()) break;
1252
1253 // Can't look past this instruction if it might read 'Loc'.
Alina Sbirlea63d22502017-12-05 20:12:23 +00001254 if (isRefSet(AA->getModRefInfo(DepWrite, Loc)))
Chad Rosierd7634fc2015-12-11 18:39:41 +00001255 break;
1256
Bob Haarman3db17642016-08-26 16:34:27 +00001257 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false,
1258 DepWrite->getIterator(), &BB,
1259 /*QueryInst=*/ nullptr, &Limit);
Owen Anderson2b2bd282009-10-28 07:05:35 +00001260 }
Owen Anderson5e72db32007-07-11 00:46:18 +00001261 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001262
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001263 if (EnablePartialOverwriteTracking)
1264 MadeChange |= removePartiallyOverlappedStores(AA, DL, IOL);
1265
Chris Lattnerf2a8ba42008-11-28 21:29:52 +00001266 // If this block ends in a return, unwind, or unreachable, all allocas are
1267 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +00001268 if (BB.getTerminator()->getNumSuccessors() == 0)
Eli Friedmana6707f52016-08-12 01:09:53 +00001269 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, &InstrOrdering);
Owen Anderson58704ee2011-09-06 18:14:09 +00001270
Owen Anderson5e72db32007-07-11 00:46:18 +00001271 return MadeChange;
1272}
1273
Justin Bogner594e07b2016-05-17 21:38:13 +00001274static bool eliminateDeadStores(Function &F, AliasAnalysis *AA,
1275 MemoryDependenceResults *MD, DominatorTree *DT,
1276 const TargetLibraryInfo *TLI) {
Eli Friedman7d58bc72011-06-15 00:47:34 +00001277 bool MadeChange = false;
Justin Bogner594e07b2016-05-17 21:38:13 +00001278 for (BasicBlock &BB : F)
1279 // Only check non-dead blocks. Dead blocks may have strange pointer
1280 // cycles that will confuse alias analysis.
1281 if (DT->isReachableFromEntry(&BB))
1282 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI);
Eli Friedmana6707f52016-08-12 01:09:53 +00001283
Eli Friedman7d58bc72011-06-15 00:47:34 +00001284 return MadeChange;
Owen Andersonaa071722007-07-11 23:19:17 +00001285}
1286
Justin Bogner594e07b2016-05-17 21:38:13 +00001287//===----------------------------------------------------------------------===//
1288// DSE Pass
1289//===----------------------------------------------------------------------===//
1290PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
1291 AliasAnalysis *AA = &AM.getResult<AAManager>(F);
1292 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1293 MemoryDependenceResults *MD = &AM.getResult<MemoryDependenceAnalysis>(F);
1294 const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
Owen Anderson58704ee2011-09-06 18:14:09 +00001295
Justin Bogner594e07b2016-05-17 21:38:13 +00001296 if (!eliminateDeadStores(F, AA, MD, DT, TLI))
1297 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001298
Justin Bogner594e07b2016-05-17 21:38:13 +00001299 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001300 PA.preserveSet<CFGAnalyses>();
Justin Bogner594e07b2016-05-17 21:38:13 +00001301 PA.preserve<GlobalsAA>();
1302 PA.preserve<MemoryDependenceAnalysis>();
1303 return PA;
Owen Anderson32c4a052007-07-12 21:41:30 +00001304}
1305
Benjamin Kramer4d098922016-07-10 11:28:51 +00001306namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001307
Justin Bogner594e07b2016-05-17 21:38:13 +00001308/// A legacy pass for the legacy pass manager that wraps \c DSEPass.
1309class DSELegacyPass : public FunctionPass {
1310public:
Eugene Zelenko3b879392017-10-13 21:17:07 +00001311 static char ID; // Pass identification, replacement for typeid
1312
Justin Bogner594e07b2016-05-17 21:38:13 +00001313 DSELegacyPass() : FunctionPass(ID) {
1314 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
Owen Andersonddf4aee2007-08-08 18:38:28 +00001315 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001316
Justin Bogner594e07b2016-05-17 21:38:13 +00001317 bool runOnFunction(Function &F) override {
1318 if (skipFunction(F))
1319 return false;
1320
1321 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1322 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1323 MemoryDependenceResults *MD =
1324 &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1325 const TargetLibraryInfo *TLI =
1326 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1327
1328 return eliminateDeadStores(F, AA, MD, DT, TLI);
1329 }
1330
1331 void getAnalysisUsage(AnalysisUsage &AU) const override {
1332 AU.setPreservesCFG();
1333 AU.addRequired<DominatorTreeWrapperPass>();
1334 AU.addRequired<AAResultsWrapperPass>();
1335 AU.addRequired<MemoryDependenceWrapperPass>();
1336 AU.addRequired<TargetLibraryInfoWrapperPass>();
1337 AU.addPreserved<DominatorTreeWrapperPass>();
1338 AU.addPreserved<GlobalsAAWrapperPass>();
1339 AU.addPreserved<MemoryDependenceWrapperPass>();
1340 }
Justin Bogner594e07b2016-05-17 21:38:13 +00001341};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001342
Benjamin Kramer4d098922016-07-10 11:28:51 +00001343} // end anonymous namespace
Justin Bogner594e07b2016-05-17 21:38:13 +00001344
1345char DSELegacyPass::ID = 0;
Eugene Zelenko3b879392017-10-13 21:17:07 +00001346
Justin Bogner594e07b2016-05-17 21:38:13 +00001347INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
1348 false)
1349INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1350INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1351INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1352INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
1353INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1354INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
1355 false)
1356
1357FunctionPass *llvm::createDeadStoreEliminationPass() {
1358 return new DSELegacyPass();
Owen Anderson32c4a052007-07-12 21:41:30 +00001359}