blob: 65728adfeb0cd5343c0fe8def5bf32cd0d93398f [file] [log] [blame]
Eugene Zelenko900b6332017-08-29 22:32:07 +00001//===- ImplicitNullChecks.cpp - Fold null checks into memory accesses -----===//
Sanjoy Das69fad072015-06-15 18:44:27 +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
Sanjoy Das69fad072015-06-15 18:44:27 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass turns explicit null checks of the form
10//
11// test %r10, %r10
12// je throw_npe
13// movl (%r10), %esi
14// ...
15//
16// to
17//
18// faulting_load_op("movl (%r10), %esi", throw_npe)
19// ...
20//
21// With the help of a runtime that understands the .fault_maps section,
22// faulting_load_op branches to throw_npe if executing movl (%r10), %esi incurs
23// a page fault.
Serguei Katkov51c220c2017-04-12 04:41:35 +000024// Store and LoadStore are also supported.
Sanjoy Das69fad072015-06-15 18:44:27 +000025//
26//===----------------------------------------------------------------------===//
27
Eugene Zelenko900b6332017-08-29 22:32:07 +000028#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/None.h"
30#include "llvm/ADT/Optional.h"
31#include "llvm/ADT/STLExtras.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000032#include "llvm/ADT/SmallVector.h"
Sanjoy Das8ee6a302015-07-06 23:32:10 +000033#include "llvm/ADT/Statistic.h"
Sanjoy Dase57bf682016-06-22 22:16:51 +000034#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000035#include "llvm/Analysis/MemoryLocation.h"
Sanjoy Das2f63cbc2017-02-07 19:19:49 +000036#include "llvm/CodeGen/FaultMaps.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000037#include "llvm/CodeGen/MachineBasicBlock.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000038#include "llvm/CodeGen/MachineFunction.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000039#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000040#include "llvm/CodeGen/MachineInstr.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000041#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include "llvm/CodeGen/MachineMemOperand.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000043#include "llvm/CodeGen/MachineOperand.h"
44#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000045#include "llvm/CodeGen/PseudoSourceValue.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000046#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000047#include "llvm/CodeGen/TargetOpcodes.h"
48#include "llvm/CodeGen/TargetRegisterInfo.h"
49#include "llvm/CodeGen/TargetSubtargetInfo.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000050#include "llvm/IR/BasicBlock.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000051#include "llvm/IR/DebugLoc.h"
Chen Li00038782015-08-04 04:41:34 +000052#include "llvm/IR/LLVMContext.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080053#include "llvm/InitializePasses.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000054#include "llvm/MC/MCInstrDesc.h"
55#include "llvm/MC/MCRegisterInfo.h"
56#include "llvm/Pass.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000057#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include <cassert>
59#include <cstdint>
60#include <iterator>
Sanjoy Das69fad072015-06-15 18:44:27 +000061
62using namespace llvm;
63
Chad Rosierc27a18f2016-03-09 16:00:35 +000064static cl::opt<int> PageSize("imp-null-check-page-size",
65 cl::desc("The page size of the target in bytes"),
Zachary Turner8065f0b2017-12-01 00:53:10 +000066 cl::init(4096), cl::Hidden);
Sanjoy Das69fad072015-06-15 18:44:27 +000067
Sanjoy Das9a129802016-12-23 00:41:21 +000068static cl::opt<unsigned> MaxInstsToConsider(
69 "imp-null-max-insts-to-consider",
70 cl::desc("The max number of instructions to consider hoisting loads over "
71 "(the algorithm is quadratic over this number)"),
Zachary Turner8065f0b2017-12-01 00:53:10 +000072 cl::Hidden, cl::init(8));
Sanjoy Das9a129802016-12-23 00:41:21 +000073
Sanjoy Das8ee6a302015-07-06 23:32:10 +000074#define DEBUG_TYPE "implicit-null-checks"
75
76STATISTIC(NumImplicitNullChecks,
77 "Number of explicit null checks made implicit");
78
Sanjoy Das69fad072015-06-15 18:44:27 +000079namespace {
80
81class ImplicitNullChecks : public MachineFunctionPass {
Sanjoy Das9a129802016-12-23 00:41:21 +000082 /// Return true if \c computeDependence can process \p MI.
83 static bool canHandle(const MachineInstr *MI);
84
85 /// Helper function for \c computeDependence. Return true if \p A
86 /// and \p B do not have any dependences between them, and can be
87 /// re-ordered without changing program semantics.
88 bool canReorder(const MachineInstr *A, const MachineInstr *B);
89
90 /// A data type for representing the result computed by \c
91 /// computeDependence. States whether it is okay to reorder the
92 /// instruction passed to \c computeDependence with at most one
Fangrui Song58963e42018-09-08 02:04:20 +000093 /// dependency.
Sanjoy Das9a129802016-12-23 00:41:21 +000094 struct DependenceResult {
95 /// Can we actually re-order \p MI with \p Insts (see \c
96 /// computeDependence).
97 bool CanReorder;
98
99 /// If non-None, then an instruction in \p Insts that also must be
100 /// hoisted.
101 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence;
102
103 /*implicit*/ DependenceResult(
104 bool CanReorder,
105 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence)
106 : CanReorder(CanReorder), PotentialDependence(PotentialDependence) {
107 assert((!PotentialDependence || CanReorder) &&
108 "!CanReorder && PotentialDependence.hasValue() not allowed!");
109 }
110 };
111
112 /// Compute a result for the following question: can \p MI be
113 /// re-ordered from after \p Insts to before it.
114 ///
115 /// \c canHandle should return true for all instructions in \p
116 /// Insts.
117 DependenceResult computeDependence(const MachineInstr *MI,
Fangrui Songcb0bab82018-07-16 18:51:40 +0000118 ArrayRef<MachineInstr *> Block);
Sanjoy Das9a129802016-12-23 00:41:21 +0000119
Sanjoy Das69fad072015-06-15 18:44:27 +0000120 /// Represents one null check that can be made implicit.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000121 class NullCheck {
Sanjoy Das69fad072015-06-15 18:44:27 +0000122 // The memory operation the null check can be folded into.
123 MachineInstr *MemOperation;
124
125 // The instruction actually doing the null check (Ptr != 0).
126 MachineInstr *CheckOperation;
127
128 // The block the check resides in.
129 MachineBasicBlock *CheckBlock;
130
Eric Christopher572e03a2015-06-19 01:53:21 +0000131 // The block branched to if the pointer is non-null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000132 MachineBasicBlock *NotNullSucc;
133
Eric Christopher572e03a2015-06-19 01:53:21 +0000134 // The block branched to if the pointer is null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000135 MachineBasicBlock *NullSucc;
136
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000137 // If this is non-null, then MemOperation has a dependency on this
Sanjoy Dase57bf682016-06-22 22:16:51 +0000138 // instruction; and it needs to be hoisted to execute before MemOperation.
139 MachineInstr *OnlyDependency;
140
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000141 public:
Sanjoy Das69fad072015-06-15 18:44:27 +0000142 explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation,
143 MachineBasicBlock *checkBlock,
144 MachineBasicBlock *notNullSucc,
Sanjoy Dase57bf682016-06-22 22:16:51 +0000145 MachineBasicBlock *nullSucc,
146 MachineInstr *onlyDependency)
Sanjoy Das69fad072015-06-15 18:44:27 +0000147 : MemOperation(memOperation), CheckOperation(checkOperation),
Sanjoy Dase57bf682016-06-22 22:16:51 +0000148 CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc),
149 OnlyDependency(onlyDependency) {}
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000150
151 MachineInstr *getMemOperation() const { return MemOperation; }
152
153 MachineInstr *getCheckOperation() const { return CheckOperation; }
154
155 MachineBasicBlock *getCheckBlock() const { return CheckBlock; }
156
157 MachineBasicBlock *getNotNullSucc() const { return NotNullSucc; }
158
159 MachineBasicBlock *getNullSucc() const { return NullSucc; }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000160
161 MachineInstr *getOnlyDependency() const { return OnlyDependency; }
Sanjoy Das69fad072015-06-15 18:44:27 +0000162 };
163
164 const TargetInstrInfo *TII = nullptr;
165 const TargetRegisterInfo *TRI = nullptr;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000166 AliasAnalysis *AA = nullptr;
Sanjoy Daseef785c2017-02-28 07:04:49 +0000167 MachineFrameInfo *MFI = nullptr;
Sanjoy Das69fad072015-06-15 18:44:27 +0000168
169 bool analyzeBlockForNullChecks(MachineBasicBlock &MBB,
170 SmallVectorImpl<NullCheck> &NullCheckList);
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000171 MachineInstr *insertFaultingInstr(MachineInstr *MI, MachineBasicBlock *MBB,
172 MachineBasicBlock *HandlerMBB);
Sanjoy Das69fad072015-06-15 18:44:27 +0000173 void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList);
174
Sanjoy Daseef785c2017-02-28 07:04:49 +0000175 enum AliasResult {
176 AR_NoAlias,
177 AR_MayAlias,
178 AR_WillAliasEverything
179 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000180
Sanjoy Daseef785c2017-02-28 07:04:49 +0000181 /// Returns AR_NoAlias if \p MI memory operation does not alias with
182 /// \p PrevMI, AR_MayAlias if they may alias and AR_WillAliasEverything if
183 /// they may alias and any further memory operation may alias with \p PrevMI.
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000184 AliasResult areMemoryOpsAliased(const MachineInstr &MI,
185 const MachineInstr *PrevMI) const;
Sanjoy Das15e50b52017-02-01 02:49:25 +0000186
Sanjoy Daseef785c2017-02-28 07:04:49 +0000187 enum SuitabilityResult {
188 SR_Suitable,
189 SR_Unsuitable,
190 SR_Impossible
191 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000192
Sanjoy Das15e50b52017-02-01 02:49:25 +0000193 /// Return SR_Suitable if \p MI a memory operation that can be used to
194 /// implicitly null check the value in \p PointerReg, SR_Unsuitable if
195 /// \p MI cannot be used to null check and SR_Impossible if there is
196 /// no sense to continue lookup due to any other instruction will not be able
197 /// to be used. \p PrevInsts is the set of instruction seen since
Sanjoy Daseef785c2017-02-28 07:04:49 +0000198 /// the explicit null check on \p PointerReg.
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000199 SuitabilityResult isSuitableMemoryOp(const MachineInstr &MI,
200 unsigned PointerReg,
Sanjoy Daseef785c2017-02-28 07:04:49 +0000201 ArrayRef<MachineInstr *> PrevInsts);
Sanjoy Das50fef432016-12-23 00:41:24 +0000202
Anna Thomas425573a2020-09-02 10:19:10 -0400203 /// Returns true if \p DependenceMI can clobber the liveIns in NullSucc block
204 /// if it was hoisted to the NullCheck block. This is used by caller
205 /// canHoistInst to decide if DependenceMI can be hoisted safely.
206 bool canDependenceHoistingClobberLiveIns(MachineInstr *DependenceMI,
Anna Thomasb1b98062020-09-10 15:30:42 -0400207 MachineBasicBlock *NullSucc);
Anna Thomas425573a2020-09-02 10:19:10 -0400208
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000209 /// Return true if \p FaultingMI can be hoisted from after the
Sanjoy Das50fef432016-12-23 00:41:24 +0000210 /// instructions in \p InstsSeenSoFar to before them. Set \p Dependence to a
Simon Pilgrim6a0ed572020-09-21 17:38:23 +0100211 /// non-null value if we also need to (and legally can) hoist a dependency.
Anna Thomasb1b98062020-09-10 15:30:42 -0400212 bool canHoistInst(MachineInstr *FaultingMI,
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000213 ArrayRef<MachineInstr *> InstsSeenSoFar,
214 MachineBasicBlock *NullSucc, MachineInstr *&Dependence);
Sanjoy Das50fef432016-12-23 00:41:24 +0000215
Sanjoy Das69fad072015-06-15 18:44:27 +0000216public:
217 static char ID;
218
219 ImplicitNullChecks() : MachineFunctionPass(ID) {
220 initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry());
221 }
222
223 bool runOnMachineFunction(MachineFunction &MF) override;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000224
Sanjoy Dase57bf682016-06-22 22:16:51 +0000225 void getAnalysisUsage(AnalysisUsage &AU) const override {
226 AU.addRequired<AAResultsWrapperPass>();
227 MachineFunctionPass::getAnalysisUsage(AU);
228 }
Derek Schuffad154c82016-03-28 17:05:30 +0000229
230 MachineFunctionProperties getRequiredProperties() const override {
231 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000232 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000233 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000234};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000235
Eugene Zelenko900b6332017-08-29 22:32:07 +0000236} // end anonymous namespace
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000237
Sanjoy Das9a129802016-12-23 00:41:21 +0000238bool ImplicitNullChecks::canHandle(const MachineInstr *MI) {
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +0000239 if (MI->isCall() || MI->mayRaiseFPException() ||
240 MI->hasUnmodeledSideEffects())
Sanjoy Das9a129802016-12-23 00:41:21 +0000241 return false;
242 auto IsRegMask = [](const MachineOperand &MO) { return MO.isRegMask(); };
243 (void)IsRegMask;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000244
Sanjoy Das9a129802016-12-23 00:41:21 +0000245 assert(!llvm::any_of(MI->operands(), IsRegMask) &&
246 "Calls were filtered out above!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000247
Philip Reames21a50cc2019-03-13 03:25:20 +0000248 auto IsUnordered = [](MachineMemOperand *MMO) { return MMO->isUnordered(); };
249 return llvm::all_of(MI->memoperands(), IsUnordered);
Sanjoy Das9a129802016-12-23 00:41:21 +0000250}
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000251
Sanjoy Das9a129802016-12-23 00:41:21 +0000252ImplicitNullChecks::DependenceResult
253ImplicitNullChecks::computeDependence(const MachineInstr *MI,
254 ArrayRef<MachineInstr *> Block) {
255 assert(llvm::all_of(Block, canHandle) && "Check this first!");
Eugene Zelenko900b6332017-08-29 22:32:07 +0000256 assert(!is_contained(Block, MI) && "Block must be exclusive of MI!");
Sanjoy Das9a129802016-12-23 00:41:21 +0000257
258 Optional<ArrayRef<MachineInstr *>::iterator> Dep;
259
260 for (auto I = Block.begin(), E = Block.end(); I != E; ++I) {
261 if (canReorder(*I, MI))
262 continue;
263
264 if (Dep == None) {
265 // Found one possible dependency, keep track of it.
266 Dep = I;
267 } else {
268 // We found two dependencies, so bail out.
269 return {false, None};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000270 }
271 }
272
Sanjoy Das9a129802016-12-23 00:41:21 +0000273 return {true, Dep};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000274}
275
Sanjoy Das9a129802016-12-23 00:41:21 +0000276bool ImplicitNullChecks::canReorder(const MachineInstr *A,
277 const MachineInstr *B) {
278 assert(canHandle(A) && canHandle(B) && "Precondition!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000279
Sanjoy Das9a129802016-12-23 00:41:21 +0000280 // canHandle makes sure that we _can_ correctly analyze the dependencies
281 // between A and B here -- for instance, we should not be dealing with heap
282 // load-store dependencies here.
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000283
Simon Pilgrim6a0ed572020-09-21 17:38:23 +0100284 for (const auto &MOA : A->operands()) {
Sanjoy Das9a129802016-12-23 00:41:21 +0000285 if (!(MOA.isReg() && MOA.getReg()))
286 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000287
Daniel Sanders0c476112019-08-15 19:22:08 +0000288 Register RegA = MOA.getReg();
Simon Pilgrim6a0ed572020-09-21 17:38:23 +0100289 for (const auto &MOB : B->operands()) {
Sanjoy Das9a129802016-12-23 00:41:21 +0000290 if (!(MOB.isReg() && MOB.getReg()))
291 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000292
Daniel Sanders0c476112019-08-15 19:22:08 +0000293 Register RegB = MOB.getReg();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000294
Sanjoy Das08da2e22017-02-01 16:04:21 +0000295 if (TRI->regsOverlap(RegA, RegB) && (MOA.isDef() || MOB.isDef()))
Sanjoy Das9a129802016-12-23 00:41:21 +0000296 return false;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000297 }
298 }
299
300 return true;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000301}
Sanjoy Das69fad072015-06-15 18:44:27 +0000302
303bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) {
304 TII = MF.getSubtarget().getInstrInfo();
305 TRI = MF.getRegInfo().getTargetRegisterInfo();
Sanjoy Daseef785c2017-02-28 07:04:49 +0000306 MFI = &MF.getFrameInfo();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000307 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Sanjoy Das69fad072015-06-15 18:44:27 +0000308
309 SmallVector<NullCheck, 16> NullCheckList;
310
311 for (auto &MBB : MF)
312 analyzeBlockForNullChecks(MBB, NullCheckList);
313
314 if (!NullCheckList.empty())
315 rewriteNullChecks(NullCheckList);
316
317 return !NullCheckList.empty();
318}
319
Sanjoy Dase57bf682016-06-22 22:16:51 +0000320// Return true if any register aliasing \p Reg is live-in into \p MBB.
321static bool AnyAliasLiveIn(const TargetRegisterInfo *TRI,
322 MachineBasicBlock *MBB, unsigned Reg) {
323 for (MCRegAliasIterator AR(Reg, TRI, /*IncludeSelf*/ true); AR.isValid();
324 ++AR)
325 if (MBB->isLiveIn(*AR))
326 return true;
327 return false;
328}
329
Sanjoy Daseef785c2017-02-28 07:04:49 +0000330ImplicitNullChecks::AliasResult
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000331ImplicitNullChecks::areMemoryOpsAliased(const MachineInstr &MI,
332 const MachineInstr *PrevMI) const {
Sanjoy Daseef785c2017-02-28 07:04:49 +0000333 // If it is not memory access, skip the check.
334 if (!(PrevMI->mayStore() || PrevMI->mayLoad()))
335 return AR_NoAlias;
336 // Load-Load may alias
337 if (!(MI.mayStore() || PrevMI->mayStore()))
338 return AR_NoAlias;
339 // We lost info, conservatively alias. If it was store then no sense to
340 // continue because we won't be able to check against it further.
341 if (MI.memoperands_empty())
342 return MI.mayStore() ? AR_WillAliasEverything : AR_MayAlias;
343 if (PrevMI->memoperands_empty())
344 return PrevMI->mayStore() ? AR_WillAliasEverything : AR_MayAlias;
345
346 for (MachineMemOperand *MMO1 : MI.memoperands()) {
347 // MMO1 should have a value due it comes from operation we'd like to use
348 // as implicit null check.
349 assert(MMO1->getValue() && "MMO1 should have a Value!");
350 for (MachineMemOperand *MMO2 : PrevMI->memoperands()) {
351 if (const PseudoSourceValue *PSV = MMO2->getPseudoValue()) {
352 if (PSV->mayAlias(MFI))
353 return AR_MayAlias;
354 continue;
355 }
George Burgess IV6ef80022018-10-10 21:28:44 +0000356 llvm::AliasResult AAResult =
357 AA->alias(MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
358 MMO1->getAAInfo()),
359 MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
360 MMO2->getAAInfo()));
Sanjoy Daseef785c2017-02-28 07:04:49 +0000361 if (AAResult != NoAlias)
362 return AR_MayAlias;
363 }
364 }
365 return AR_NoAlias;
366}
367
Sanjoy Das15e50b52017-02-01 02:49:25 +0000368ImplicitNullChecks::SuitabilityResult
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000369ImplicitNullChecks::isSuitableMemoryOp(const MachineInstr &MI,
370 unsigned PointerReg,
Sanjoy Daseef785c2017-02-28 07:04:49 +0000371 ArrayRef<MachineInstr *> PrevInsts) {
Sanjoy Das50fef432016-12-23 00:41:24 +0000372 int64_t Offset;
Sander de Smalen8fbc9252020-02-18 14:32:26 +0000373 bool OffsetIsScalable;
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000374 const MachineOperand *BaseOp;
Sanjoy Das50fef432016-12-23 00:41:24 +0000375
Philip Reamesb04c1812020-09-17 15:39:50 -0700376 // Implementation restriction for faulting_op insertion
377 // TODO: This could be relaxed if we find a test case which warrants it.
378 if (MI.getDesc().getNumDefs() > 1)
379 return SR_Unsuitable;
Sander de Smalen8fbc9252020-02-18 14:32:26 +0000380
Anna Thomas6f7737c2020-09-02 10:06:27 -0400381 // FIXME: This handles only simple addressing mode.
382 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
Philip Reamesb04c1812020-09-17 15:39:50 -0700383 return SR_Unsuitable;
Anna Thomas6f7737c2020-09-02 10:06:27 -0400384
385 // We need the base of the memory instruction to be same as the register
386 // where the null check is performed (i.e. PointerReg).
387 if (!BaseOp->isReg() || BaseOp->getReg() != PointerReg)
Sanjoy Daseef785c2017-02-28 07:04:49 +0000388 return SR_Unsuitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000389
Anna Thomas6f7737c2020-09-02 10:06:27 -0400390 // Scalable offsets are a part of scalable vectors (SVE for AArch64). That
391 // target is in-practice unsupported for ImplicitNullChecks.
Sander de Smalen8fbc9252020-02-18 14:32:26 +0000392 if (OffsetIsScalable)
393 return SR_Unsuitable;
394
Anna Thomas6f7737c2020-09-02 10:06:27 -0400395 if (!MI.mayLoadOrStore() || MI.isPredicable())
396 return SR_Unsuitable;
397
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000398 // We want the mem access to be issued at a sane offset from PointerReg,
399 // so that if PointerReg is null then the access reliably page faults.
Anna Thomas6f7737c2020-09-02 10:06:27 -0400400 if (!(-PageSize < Offset && Offset < PageSize))
Sanjoy Daseef785c2017-02-28 07:04:49 +0000401 return SR_Unsuitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000402
Serguei Katkov0b0dc572017-06-21 06:38:23 +0000403 // Finally, check whether the current memory access aliases with previous one.
404 for (auto *PrevMI : PrevInsts) {
405 AliasResult AR = areMemoryOpsAliased(MI, PrevMI);
406 if (AR == AR_WillAliasEverything)
407 return SR_Impossible;
408 if (AR == AR_MayAlias)
409 return SR_Unsuitable;
410 }
411 return SR_Suitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000412}
413
Anna Thomas425573a2020-09-02 10:19:10 -0400414bool ImplicitNullChecks::canDependenceHoistingClobberLiveIns(
Anna Thomasb1b98062020-09-10 15:30:42 -0400415 MachineInstr *DependenceMI, MachineBasicBlock *NullSucc) {
Simon Pilgrim6a0ed572020-09-21 17:38:23 +0100416 for (const auto &DependenceMO : DependenceMI->operands()) {
Anna Thomas425573a2020-09-02 10:19:10 -0400417 if (!(DependenceMO.isReg() && DependenceMO.getReg()))
418 continue;
419
420 // Make sure that we won't clobber any live ins to the sibling block by
421 // hoisting Dependency. For instance, we can't hoist INST to before the
422 // null check (even if it safe, and does not violate any dependencies in
423 // the non_null_block) if %rdx is live in to _null_block.
424 //
425 // test %rcx, %rcx
426 // je _null_block
427 // _non_null_block:
428 // %rdx = INST
429 // ...
430 //
431 // This restriction does not apply to the faulting load inst because in
432 // case the pointer loaded from is in the null page, the load will not
433 // semantically execute, and affect machine state. That is, if the load
434 // was loading into %rax and it faults, the value of %rax should stay the
435 // same as it would have been had the load not have executed and we'd have
436 // branched to NullSucc directly.
437 if (AnyAliasLiveIn(TRI, NullSucc, DependenceMO.getReg()))
438 return true;
439
Anna Thomas425573a2020-09-02 10:19:10 -0400440 }
441
442 // The dependence does not clobber live-ins in NullSucc block.
443 return false;
444}
445
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000446bool ImplicitNullChecks::canHoistInst(MachineInstr *FaultingMI,
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000447 ArrayRef<MachineInstr *> InstsSeenSoFar,
448 MachineBasicBlock *NullSucc,
449 MachineInstr *&Dependence) {
Sanjoy Das50fef432016-12-23 00:41:24 +0000450 auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar);
451 if (!DepResult.CanReorder)
452 return false;
453
454 if (!DepResult.PotentialDependence) {
455 Dependence = nullptr;
456 return true;
457 }
458
459 auto DependenceItr = *DepResult.PotentialDependence;
460 auto *DependenceMI = *DependenceItr;
461
462 // We don't want to reason about speculating loads. Note -- at this point
463 // we should have already filtered out all of the other non-speculatable
464 // things, like calls and stores.
Serguei Katkov6ea2e812017-08-09 05:17:02 +0000465 // We also do not want to hoist stores because it might change the memory
466 // while the FaultingMI may result in faulting.
Sanjoy Das50fef432016-12-23 00:41:24 +0000467 assert(canHandle(DependenceMI) && "Should never have reached here!");
Serguei Katkov6ea2e812017-08-09 05:17:02 +0000468 if (DependenceMI->mayLoadOrStore())
Sanjoy Das50fef432016-12-23 00:41:24 +0000469 return false;
470
Anna Thomasb1b98062020-09-10 15:30:42 -0400471 if (canDependenceHoistingClobberLiveIns(DependenceMI, NullSucc))
Anna Thomas425573a2020-09-02 10:19:10 -0400472 return false;
Sanjoy Das50fef432016-12-23 00:41:24 +0000473
474 auto DepDepResult =
475 computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr});
476
477 if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence)
478 return false;
479
480 Dependence = DependenceMI;
481 return true;
482}
483
Sanjoy Das69fad072015-06-15 18:44:27 +0000484/// Analyze MBB to check if its terminating branch can be turned into an
485/// implicit null check. If yes, append a description of the said null check to
486/// NullCheckList and return true, else return false.
487bool ImplicitNullChecks::analyzeBlockForNullChecks(
488 MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000489 using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
Sanjoy Das69fad072015-06-15 18:44:27 +0000490
Sanjoy Dase8b81642015-11-12 20:51:49 +0000491 MDNode *BranchMD = nullptr;
492 if (auto *BB = MBB.getBasicBlock())
493 BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
494
Sanjoy Das9c41a932015-06-30 21:22:32 +0000495 if (!BranchMD)
496 return false;
497
Sanjoy Das69fad072015-06-15 18:44:27 +0000498 MachineBranchPredicate MBP;
499
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000500 if (TII->analyzeBranchPredicate(MBB, MBP, true))
Sanjoy Das69fad072015-06-15 18:44:27 +0000501 return false;
502
503 // Is the predicate comparing an integer to zero?
504 if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
505 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
506 MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
507 return false;
508
Philip Reamesb04c1812020-09-17 15:39:50 -0700509 // If there is a separate condition generation instruction, we chose not to
510 // transform unless we can remove both condition and consuming branch.
511 if (MBP.ConditionDef && !MBP.SingleUseCondition)
Sanjoy Das69fad072015-06-15 18:44:27 +0000512 return false;
513
514 MachineBasicBlock *NotNullSucc, *NullSucc;
515
516 if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
517 NotNullSucc = MBP.TrueDest;
518 NullSucc = MBP.FalseDest;
519 } else {
520 NotNullSucc = MBP.FalseDest;
521 NullSucc = MBP.TrueDest;
522 }
523
524 // We handle the simplest case for now. We can potentially do better by using
525 // the machine dominator tree.
526 if (NotNullSucc->pred_size() != 1)
527 return false;
528
Daniel Sanders0c476112019-08-15 19:22:08 +0000529 const Register PointerReg = MBP.LHS.getReg();
Max Kazantseve8e01142018-07-04 08:01:26 +0000530
Philip Reamesb04c1812020-09-17 15:39:50 -0700531 if (MBP.ConditionDef) {
532 // To prevent the invalid transformation of the following code:
533 //
534 // mov %rax, %rcx
535 // test %rax, %rax
536 // %rax = ...
537 // je throw_npe
538 // mov(%rcx), %r9
539 // mov(%rax), %r10
540 //
541 // into:
542 //
543 // mov %rax, %rcx
544 // %rax = ....
545 // faulting_load_op("movl (%rax), %r10", throw_npe)
546 // mov(%rcx), %r9
547 //
548 // we must ensure that there are no instructions between the 'test' and
549 // conditional jump that modify %rax.
550 assert(MBP.ConditionDef->getParent() == &MBB &&
551 "Should be in basic block");
Max Kazantseve8e01142018-07-04 08:01:26 +0000552
Philip Reamesb04c1812020-09-17 15:39:50 -0700553 for (auto I = MBB.rbegin(); MBP.ConditionDef != &*I; ++I)
554 if (I->modifiesRegister(PointerReg, TRI))
555 return false;
556 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000557 // Starting with a code fragment like:
558 //
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000559 // test %rax, %rax
Sanjoy Das69fad072015-06-15 18:44:27 +0000560 // jne LblNotNull
561 //
562 // LblNull:
563 // callq throw_NullPointerException
564 //
565 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000566 // Inst0
567 // Inst1
568 // ...
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000569 // Def = Load (%rax + <offset>)
Sanjoy Das69fad072015-06-15 18:44:27 +0000570 // ...
571 //
572 //
573 // we want to end up with
574 //
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000575 // Def = FaultingLoad (%rax + <offset>), LblNull
Sanjoy Das69fad072015-06-15 18:44:27 +0000576 // jmp LblNotNull ;; explicit or fallthrough
577 //
578 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000579 // Inst0
580 // Inst1
Sanjoy Das69fad072015-06-15 18:44:27 +0000581 // ...
582 //
583 // LblNull:
584 // callq throw_NullPointerException
585 //
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000586 //
587 // To see why this is legal, consider the two possibilities:
588 //
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000589 // 1. %rax is null: since we constrain <offset> to be less than PageSize, the
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000590 // load instruction dereferences the null page, causing a segmentation
591 // fault.
592 //
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000593 // 2. %rax is not null: in this case we know that the load cannot fault, as
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000594 // otherwise the load would've faulted in the original program too and the
595 // original program would've been undefined.
596 //
597 // This reasoning cannot be extended to justify hoisting through arbitrary
598 // control flow. For instance, in the example below (in pseudo-C)
599 //
600 // if (ptr == null) { throw_npe(); unreachable; }
601 // if (some_cond) { return 42; }
602 // v = ptr->field; // LD
603 // ...
604 //
605 // we cannot (without code duplication) use the load marked "LD" to null check
606 // ptr -- clause (2) above does not apply in this case. In the above program
607 // the safety of ptr->field can be dependent on some_cond; and, for instance,
608 // ptr could be some non-null invalid reference that never gets loaded from
609 // because some_cond is always true.
Sanjoy Das69fad072015-06-15 18:44:27 +0000610
Sanjoy Das9a129802016-12-23 00:41:21 +0000611 SmallVector<MachineInstr *, 8> InstsSeenSoFar;
Sanjoy Dasb7718452015-07-09 20:13:25 +0000612
Sanjoy Das9a129802016-12-23 00:41:21 +0000613 for (auto &MI : *NotNullSucc) {
614 if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider)
615 return false;
616
617 MachineInstr *Dependence;
Sanjoy Daseef785c2017-02-28 07:04:49 +0000618 SuitabilityResult SR = isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar);
Sanjoy Das15e50b52017-02-01 02:49:25 +0000619 if (SR == SR_Impossible)
620 return false;
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000621 if (SR == SR_Suitable &&
Anna Thomasb1b98062020-09-10 15:30:42 -0400622 canHoistInst(&MI, InstsSeenSoFar, NullSucc, Dependence)) {
Sanjoy Das9a129802016-12-23 00:41:21 +0000623 NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc,
624 NullSucc, Dependence);
625 return true;
626 }
627
Anna Thomas46329f62020-09-10 13:14:44 -0400628 // If MI re-defines the PointerReg in a way that changes the value of
629 // PointerReg if it was null, then we cannot move further.
630 if (!TII->preservesZeroValueInReg(&MI, PointerReg, TRI))
Serguei Katkov0b0dc572017-06-21 06:38:23 +0000631 return false;
Sanjoy Das9a129802016-12-23 00:41:21 +0000632 InstsSeenSoFar.push_back(&MI);
Sanjoy Dasb7718452015-07-09 20:13:25 +0000633 }
634
Sanjoy Das69fad072015-06-15 18:44:27 +0000635 return false;
636}
637
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000638/// Wrap a machine instruction, MI, into a FAULTING machine instruction.
639/// The FAULTING instruction does the same load/store as MI
640/// (defining the same register), and branches to HandlerMBB if the mem access
641/// faults. The FAULTING instruction is inserted at the end of MBB.
642MachineInstr *ImplicitNullChecks::insertFaultingInstr(
643 MachineInstr *MI, MachineBasicBlock *MBB, MachineBasicBlock *HandlerMBB) {
Sanjoy Das93d608c2015-07-20 20:31:39 +0000644 const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
645 // all targets.
646
Sanjoy Das69fad072015-06-15 18:44:27 +0000647 DebugLoc DL;
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000648 unsigned NumDefs = MI->getDesc().getNumDefs();
Sanjoy Das93d608c2015-07-20 20:31:39 +0000649 assert(NumDefs <= 1 && "other cases unhandled!");
Sanjoy Das69fad072015-06-15 18:44:27 +0000650
Sanjoy Das93d608c2015-07-20 20:31:39 +0000651 unsigned DefReg = NoRegister;
652 if (NumDefs != 0) {
Craig Topper342273a2018-05-16 23:39:27 +0000653 DefReg = MI->getOperand(0).getReg();
Vedant Kumar5a0872c2018-05-16 23:20:42 +0000654 assert(NumDefs == 1 && "expected exactly one def!");
Sanjoy Das93d608c2015-07-20 20:31:39 +0000655 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000656
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000657 FaultMaps::FaultKind FK;
658 if (MI->mayLoad())
659 FK =
660 MI->mayStore() ? FaultMaps::FaultingLoadStore : FaultMaps::FaultingLoad;
661 else
662 FK = FaultMaps::FaultingStore;
Sanjoy Das69fad072015-06-15 18:44:27 +0000663
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000664 auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_OP), DefReg)
665 .addImm(FK)
666 .addMBB(HandlerMBB)
667 .addImm(MI->getOpcode());
668
Matthias Braun605f77952017-05-31 22:23:08 +0000669 for (auto &MO : MI->uses()) {
670 if (MO.isReg()) {
671 MachineOperand NewMO = MO;
672 if (MO.isUse()) {
673 NewMO.setIsKill(false);
674 } else {
675 assert(MO.isDef() && "Expected def or use");
676 NewMO.setIsDead(false);
677 }
678 MIB.add(NewMO);
679 } else {
680 MIB.add(MO);
681 }
682 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000683
Chandler Carruthc73c0302018-08-16 21:30:05 +0000684 MIB.setMemRefs(MI->memoperands());
Sanjoy Das69fad072015-06-15 18:44:27 +0000685
686 return MIB;
687}
688
689/// Rewrite the null checks in NullCheckList into implicit null checks.
690void ImplicitNullChecks::rewriteNullChecks(
691 ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
692 DebugLoc DL;
693
694 for (auto &NC : NullCheckList) {
Sanjoy Das69fad072015-06-15 18:44:27 +0000695 // Remove the conditional branch dependent on the null check.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000696 unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock());
Sanjoy Das69fad072015-06-15 18:44:27 +0000697 (void)BranchesRemoved;
698 assert(BranchesRemoved > 0 && "expected at least one branch!");
699
Sanjoy Dase57bf682016-06-22 22:16:51 +0000700 if (auto *DepMI = NC.getOnlyDependency()) {
701 DepMI->removeFromParent();
702 NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI);
703 }
704
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000705 // Insert a faulting instruction where the conditional branch was
706 // originally. We check earlier ensures that this bit of code motion
707 // is legal. We do not touch the successors list for any basic block
708 // since we haven't changed control flow, we've just made it implicit.
709 MachineInstr *FaultingInstr = insertFaultingInstr(
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000710 NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc());
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000711 // Now the values defined by MemOperation, if any, are live-in of
712 // the block of MemOperation.
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000713 // The original operation may define implicit-defs alongside
714 // the value.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000715 MachineBasicBlock *MBB = NC.getMemOperation()->getParent();
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000716 for (const MachineOperand &MO : FaultingInstr->operands()) {
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000717 if (!MO.isReg() || !MO.isDef())
718 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000719 Register Reg = MO.getReg();
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000720 if (!Reg || MBB->isLiveIn(Reg))
721 continue;
722 MBB->addLiveIn(Reg);
Quentin Colombet12b69912016-04-27 23:26:40 +0000723 }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000724
725 if (auto *DepMI = NC.getOnlyDependency()) {
726 for (auto &MO : DepMI->operands()) {
Jonas Paulssonf8c0cfc2019-11-19 13:15:12 +0100727 if (!MO.isReg() || !MO.getReg() || !MO.isDef() || MO.isDead())
Sanjoy Dase57bf682016-06-22 22:16:51 +0000728 continue;
729 if (!NC.getNotNullSucc()->isLiveIn(MO.getReg()))
730 NC.getNotNullSucc()->addLiveIn(MO.getReg());
731 }
732 }
733
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000734 NC.getMemOperation()->eraseFromParent();
Philip Reamesb04c1812020-09-17 15:39:50 -0700735 if (auto *CheckOp = NC.getCheckOperation())
736 CheckOp->eraseFromParent();
Sanjoy Das69fad072015-06-15 18:44:27 +0000737
Philip Reamesb04c1812020-09-17 15:39:50 -0700738 // Insert an *unconditional* branch to not-null successor - we expect
739 // block placement to remove fallthroughs later.
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000740 TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr,
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000741 /*Cond=*/None, DL);
Sanjoy Das69fad072015-06-15 18:44:27 +0000742
Sanjoy Das8ee6a302015-07-06 23:32:10 +0000743 NumImplicitNullChecks++;
Sanjoy Das69fad072015-06-15 18:44:27 +0000744 }
745}
746
747char ImplicitNullChecks::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000748
Sanjoy Das69fad072015-06-15 18:44:27 +0000749char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000750
Matthias Braun1527baa2017-05-25 21:26:32 +0000751INITIALIZE_PASS_BEGIN(ImplicitNullChecks, DEBUG_TYPE,
Sanjoy Das69fad072015-06-15 18:44:27 +0000752 "Implicit null checks", false, false)
Sanjoy Dase57bf682016-06-22 22:16:51 +0000753INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000754INITIALIZE_PASS_END(ImplicitNullChecks, DEBUG_TYPE,
Sanjoy Das69fad072015-06-15 18:44:27 +0000755 "Implicit null checks", false, false)