blob: e308f49ec4e85cb5999c246461415f472736445a [file] [log] [blame]
Sanjoy Das69fad072015-06-15 18:44:27 +00001//===-- ImplicitNullChecks.cpp - Fold null checks into memory accesses ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass turns explicit null checks of the form
11//
12// test %r10, %r10
13// je throw_npe
14// movl (%r10), %esi
15// ...
16//
17// to
18//
19// faulting_load_op("movl (%r10), %esi", throw_npe)
20// ...
21//
22// With the help of a runtime that understands the .fault_maps section,
23// faulting_load_op branches to throw_npe if executing movl (%r10), %esi incurs
24// a page fault.
Serguei Katkov51c220c2017-04-12 04:41:35 +000025// Store and LoadStore are also supported.
Sanjoy Das69fad072015-06-15 18:44:27 +000026//
27//===----------------------------------------------------------------------===//
28
Sanjoy Dasb7718452015-07-09 20:13:25 +000029#include "llvm/ADT/DenseSet.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000030#include "llvm/ADT/SmallVector.h"
Sanjoy Das8ee6a302015-07-06 23:32:10 +000031#include "llvm/ADT/Statistic.h"
Sanjoy Dase57bf682016-06-22 22:16:51 +000032#include "llvm/Analysis/AliasAnalysis.h"
Sanjoy Das2f63cbc2017-02-07 19:19:49 +000033#include "llvm/CodeGen/FaultMaps.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000034#include "llvm/CodeGen/MachineFunction.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
36#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/CodeGen/MachineMemOperand.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000038#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/MachineOperand.h"
40#include "llvm/CodeGen/MachineRegisterInfo.h"
41#include "llvm/CodeGen/Passes.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000042#include "llvm/IR/BasicBlock.h"
43#include "llvm/IR/Instruction.h"
Chen Li00038782015-08-04 04:41:34 +000044#include "llvm/IR/LLVMContext.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000047#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000048#include "llvm/Target/TargetSubtargetInfo.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000049
50using namespace llvm;
51
Chad Rosierc27a18f2016-03-09 16:00:35 +000052static cl::opt<int> PageSize("imp-null-check-page-size",
53 cl::desc("The page size of the target in bytes"),
54 cl::init(4096));
Sanjoy Das69fad072015-06-15 18:44:27 +000055
Sanjoy Das9a129802016-12-23 00:41:21 +000056static cl::opt<unsigned> MaxInstsToConsider(
57 "imp-null-max-insts-to-consider",
58 cl::desc("The max number of instructions to consider hoisting loads over "
59 "(the algorithm is quadratic over this number)"),
60 cl::init(8));
61
Sanjoy Das8ee6a302015-07-06 23:32:10 +000062#define DEBUG_TYPE "implicit-null-checks"
63
64STATISTIC(NumImplicitNullChecks,
65 "Number of explicit null checks made implicit");
66
Sanjoy Das69fad072015-06-15 18:44:27 +000067namespace {
68
69class ImplicitNullChecks : public MachineFunctionPass {
Sanjoy Das9a129802016-12-23 00:41:21 +000070 /// Return true if \c computeDependence can process \p MI.
71 static bool canHandle(const MachineInstr *MI);
72
73 /// Helper function for \c computeDependence. Return true if \p A
74 /// and \p B do not have any dependences between them, and can be
75 /// re-ordered without changing program semantics.
76 bool canReorder(const MachineInstr *A, const MachineInstr *B);
77
78 /// A data type for representing the result computed by \c
79 /// computeDependence. States whether it is okay to reorder the
80 /// instruction passed to \c computeDependence with at most one
81 /// depednency.
82 struct DependenceResult {
83 /// Can we actually re-order \p MI with \p Insts (see \c
84 /// computeDependence).
85 bool CanReorder;
86
87 /// If non-None, then an instruction in \p Insts that also must be
88 /// hoisted.
89 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence;
90
91 /*implicit*/ DependenceResult(
92 bool CanReorder,
93 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence)
94 : CanReorder(CanReorder), PotentialDependence(PotentialDependence) {
95 assert((!PotentialDependence || CanReorder) &&
96 "!CanReorder && PotentialDependence.hasValue() not allowed!");
97 }
98 };
99
100 /// Compute a result for the following question: can \p MI be
101 /// re-ordered from after \p Insts to before it.
102 ///
103 /// \c canHandle should return true for all instructions in \p
104 /// Insts.
105 DependenceResult computeDependence(const MachineInstr *MI,
106 ArrayRef<MachineInstr *> Insts);
107
Sanjoy Das69fad072015-06-15 18:44:27 +0000108 /// Represents one null check that can be made implicit.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000109 class NullCheck {
Sanjoy Das69fad072015-06-15 18:44:27 +0000110 // The memory operation the null check can be folded into.
111 MachineInstr *MemOperation;
112
113 // The instruction actually doing the null check (Ptr != 0).
114 MachineInstr *CheckOperation;
115
116 // The block the check resides in.
117 MachineBasicBlock *CheckBlock;
118
Eric Christopher572e03a2015-06-19 01:53:21 +0000119 // The block branched to if the pointer is non-null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000120 MachineBasicBlock *NotNullSucc;
121
Eric Christopher572e03a2015-06-19 01:53:21 +0000122 // The block branched to if the pointer is null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000123 MachineBasicBlock *NullSucc;
124
Sanjoy Dase57bf682016-06-22 22:16:51 +0000125 // If this is non-null, then MemOperation has a dependency on on this
126 // instruction; and it needs to be hoisted to execute before MemOperation.
127 MachineInstr *OnlyDependency;
128
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000129 public:
Sanjoy Das69fad072015-06-15 18:44:27 +0000130 explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation,
131 MachineBasicBlock *checkBlock,
132 MachineBasicBlock *notNullSucc,
Sanjoy Dase57bf682016-06-22 22:16:51 +0000133 MachineBasicBlock *nullSucc,
134 MachineInstr *onlyDependency)
Sanjoy Das69fad072015-06-15 18:44:27 +0000135 : MemOperation(memOperation), CheckOperation(checkOperation),
Sanjoy Dase57bf682016-06-22 22:16:51 +0000136 CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc),
137 OnlyDependency(onlyDependency) {}
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000138
139 MachineInstr *getMemOperation() const { return MemOperation; }
140
141 MachineInstr *getCheckOperation() const { return CheckOperation; }
142
143 MachineBasicBlock *getCheckBlock() const { return CheckBlock; }
144
145 MachineBasicBlock *getNotNullSucc() const { return NotNullSucc; }
146
147 MachineBasicBlock *getNullSucc() const { return NullSucc; }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000148
149 MachineInstr *getOnlyDependency() const { return OnlyDependency; }
Sanjoy Das69fad072015-06-15 18:44:27 +0000150 };
151
152 const TargetInstrInfo *TII = nullptr;
153 const TargetRegisterInfo *TRI = nullptr;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000154 AliasAnalysis *AA = nullptr;
Sanjoy Das69fad072015-06-15 18:44:27 +0000155 MachineModuleInfo *MMI = nullptr;
Sanjoy Daseef785c2017-02-28 07:04:49 +0000156 MachineFrameInfo *MFI = nullptr;
Sanjoy Das69fad072015-06-15 18:44:27 +0000157
158 bool analyzeBlockForNullChecks(MachineBasicBlock &MBB,
159 SmallVectorImpl<NullCheck> &NullCheckList);
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000160 MachineInstr *insertFaultingInstr(MachineInstr *MI, MachineBasicBlock *MBB,
161 MachineBasicBlock *HandlerMBB);
Sanjoy Das69fad072015-06-15 18:44:27 +0000162 void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList);
163
Sanjoy Daseef785c2017-02-28 07:04:49 +0000164 enum AliasResult {
165 AR_NoAlias,
166 AR_MayAlias,
167 AR_WillAliasEverything
168 };
169 /// Returns AR_NoAlias if \p MI memory operation does not alias with
170 /// \p PrevMI, AR_MayAlias if they may alias and AR_WillAliasEverything if
171 /// they may alias and any further memory operation may alias with \p PrevMI.
172 AliasResult areMemoryOpsAliased(MachineInstr &MI, MachineInstr *PrevMI);
Sanjoy Das15e50b52017-02-01 02:49:25 +0000173
Sanjoy Daseef785c2017-02-28 07:04:49 +0000174 enum SuitabilityResult {
175 SR_Suitable,
176 SR_Unsuitable,
177 SR_Impossible
178 };
Sanjoy Das15e50b52017-02-01 02:49:25 +0000179 /// Return SR_Suitable if \p MI a memory operation that can be used to
180 /// implicitly null check the value in \p PointerReg, SR_Unsuitable if
181 /// \p MI cannot be used to null check and SR_Impossible if there is
182 /// no sense to continue lookup due to any other instruction will not be able
183 /// to be used. \p PrevInsts is the set of instruction seen since
Sanjoy Daseef785c2017-02-28 07:04:49 +0000184 /// the explicit null check on \p PointerReg.
Sanjoy Das15e50b52017-02-01 02:49:25 +0000185 SuitabilityResult isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg,
Sanjoy Daseef785c2017-02-28 07:04:49 +0000186 ArrayRef<MachineInstr *> PrevInsts);
Sanjoy Das50fef432016-12-23 00:41:24 +0000187
188 /// Return true if \p FaultingMI can be hoisted from after the the
189 /// instructions in \p InstsSeenSoFar to before them. Set \p Dependence to a
190 /// non-null value if we also need to (and legally can) hoist a depedency.
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000191 bool canHoistInst(MachineInstr *FaultingMI, unsigned PointerReg,
192 ArrayRef<MachineInstr *> InstsSeenSoFar,
193 MachineBasicBlock *NullSucc, MachineInstr *&Dependence);
Sanjoy Das50fef432016-12-23 00:41:24 +0000194
Sanjoy Das69fad072015-06-15 18:44:27 +0000195public:
196 static char ID;
197
198 ImplicitNullChecks() : MachineFunctionPass(ID) {
199 initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry());
200 }
201
202 bool runOnMachineFunction(MachineFunction &MF) override;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000203 void getAnalysisUsage(AnalysisUsage &AU) const override {
204 AU.addRequired<AAResultsWrapperPass>();
205 MachineFunctionPass::getAnalysisUsage(AU);
206 }
Derek Schuffad154c82016-03-28 17:05:30 +0000207
208 MachineFunctionProperties getRequiredProperties() const override {
209 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000210 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000211 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000212};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000213
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000214}
215
Sanjoy Das9a129802016-12-23 00:41:21 +0000216bool ImplicitNullChecks::canHandle(const MachineInstr *MI) {
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000217 if (MI->isCall() || MI->hasUnmodeledSideEffects())
Sanjoy Das9a129802016-12-23 00:41:21 +0000218 return false;
219 auto IsRegMask = [](const MachineOperand &MO) { return MO.isRegMask(); };
220 (void)IsRegMask;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000221
Sanjoy Das9a129802016-12-23 00:41:21 +0000222 assert(!llvm::any_of(MI->operands(), IsRegMask) &&
223 "Calls were filtered out above!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000224
Sanjoy Das9a129802016-12-23 00:41:21 +0000225 auto IsUnordered = [](MachineMemOperand *MMO) { return MMO->isUnordered(); };
226 return llvm::all_of(MI->memoperands(), IsUnordered);
227}
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000228
Sanjoy Das9a129802016-12-23 00:41:21 +0000229ImplicitNullChecks::DependenceResult
230ImplicitNullChecks::computeDependence(const MachineInstr *MI,
231 ArrayRef<MachineInstr *> Block) {
232 assert(llvm::all_of(Block, canHandle) && "Check this first!");
233 assert(!llvm::is_contained(Block, MI) && "Block must be exclusive of MI!");
234
235 Optional<ArrayRef<MachineInstr *>::iterator> Dep;
236
237 for (auto I = Block.begin(), E = Block.end(); I != E; ++I) {
238 if (canReorder(*I, MI))
239 continue;
240
241 if (Dep == None) {
242 // Found one possible dependency, keep track of it.
243 Dep = I;
244 } else {
245 // We found two dependencies, so bail out.
246 return {false, None};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000247 }
248 }
249
Sanjoy Das9a129802016-12-23 00:41:21 +0000250 return {true, Dep};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000251}
252
Sanjoy Das9a129802016-12-23 00:41:21 +0000253bool ImplicitNullChecks::canReorder(const MachineInstr *A,
254 const MachineInstr *B) {
255 assert(canHandle(A) && canHandle(B) && "Precondition!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000256
Sanjoy Das9a129802016-12-23 00:41:21 +0000257 // canHandle makes sure that we _can_ correctly analyze the dependencies
258 // between A and B here -- for instance, we should not be dealing with heap
259 // load-store dependencies here.
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000260
Sanjoy Das9a129802016-12-23 00:41:21 +0000261 for (auto MOA : A->operands()) {
262 if (!(MOA.isReg() && MOA.getReg()))
263 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000264
Sanjoy Das9a129802016-12-23 00:41:21 +0000265 unsigned RegA = MOA.getReg();
266 for (auto MOB : B->operands()) {
267 if (!(MOB.isReg() && MOB.getReg()))
268 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000269
Sanjoy Das9a129802016-12-23 00:41:21 +0000270 unsigned RegB = MOB.getReg();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000271
Sanjoy Das08da2e22017-02-01 16:04:21 +0000272 if (TRI->regsOverlap(RegA, RegB) && (MOA.isDef() || MOB.isDef()))
Sanjoy Das9a129802016-12-23 00:41:21 +0000273 return false;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000274 }
275 }
276
277 return true;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000278}
Sanjoy Das69fad072015-06-15 18:44:27 +0000279
280bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) {
281 TII = MF.getSubtarget().getInstrInfo();
282 TRI = MF.getRegInfo().getTargetRegisterInfo();
283 MMI = &MF.getMMI();
Sanjoy Daseef785c2017-02-28 07:04:49 +0000284 MFI = &MF.getFrameInfo();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000285 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Sanjoy Das69fad072015-06-15 18:44:27 +0000286
287 SmallVector<NullCheck, 16> NullCheckList;
288
289 for (auto &MBB : MF)
290 analyzeBlockForNullChecks(MBB, NullCheckList);
291
292 if (!NullCheckList.empty())
293 rewriteNullChecks(NullCheckList);
294
295 return !NullCheckList.empty();
296}
297
Sanjoy Dase57bf682016-06-22 22:16:51 +0000298// Return true if any register aliasing \p Reg is live-in into \p MBB.
299static bool AnyAliasLiveIn(const TargetRegisterInfo *TRI,
300 MachineBasicBlock *MBB, unsigned Reg) {
301 for (MCRegAliasIterator AR(Reg, TRI, /*IncludeSelf*/ true); AR.isValid();
302 ++AR)
303 if (MBB->isLiveIn(*AR))
304 return true;
305 return false;
306}
307
Sanjoy Daseef785c2017-02-28 07:04:49 +0000308ImplicitNullChecks::AliasResult
309ImplicitNullChecks::areMemoryOpsAliased(MachineInstr &MI,
310 MachineInstr *PrevMI) {
311 // If it is not memory access, skip the check.
312 if (!(PrevMI->mayStore() || PrevMI->mayLoad()))
313 return AR_NoAlias;
314 // Load-Load may alias
315 if (!(MI.mayStore() || PrevMI->mayStore()))
316 return AR_NoAlias;
317 // We lost info, conservatively alias. If it was store then no sense to
318 // continue because we won't be able to check against it further.
319 if (MI.memoperands_empty())
320 return MI.mayStore() ? AR_WillAliasEverything : AR_MayAlias;
321 if (PrevMI->memoperands_empty())
322 return PrevMI->mayStore() ? AR_WillAliasEverything : AR_MayAlias;
323
324 for (MachineMemOperand *MMO1 : MI.memoperands()) {
325 // MMO1 should have a value due it comes from operation we'd like to use
326 // as implicit null check.
327 assert(MMO1->getValue() && "MMO1 should have a Value!");
328 for (MachineMemOperand *MMO2 : PrevMI->memoperands()) {
329 if (const PseudoSourceValue *PSV = MMO2->getPseudoValue()) {
330 if (PSV->mayAlias(MFI))
331 return AR_MayAlias;
332 continue;
333 }
334 llvm::AliasResult AAResult = AA->alias(
335 MemoryLocation(MMO1->getValue(), MemoryLocation::UnknownSize,
336 MMO1->getAAInfo()),
337 MemoryLocation(MMO2->getValue(), MemoryLocation::UnknownSize,
338 MMO2->getAAInfo()));
339 if (AAResult != NoAlias)
340 return AR_MayAlias;
341 }
342 }
343 return AR_NoAlias;
344}
345
Sanjoy Das15e50b52017-02-01 02:49:25 +0000346ImplicitNullChecks::SuitabilityResult
347ImplicitNullChecks::isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg,
Sanjoy Daseef785c2017-02-28 07:04:49 +0000348 ArrayRef<MachineInstr *> PrevInsts) {
Sanjoy Das50fef432016-12-23 00:41:24 +0000349 int64_t Offset;
350 unsigned BaseReg;
351
352 if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI) ||
353 BaseReg != PointerReg)
Sanjoy Daseef785c2017-02-28 07:04:49 +0000354 return SR_Unsuitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000355
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000356 // We want the mem access to be issued at a sane offset from PointerReg,
357 // so that if PointerReg is null then the access reliably page faults.
358 if (!((MI.mayLoad() || MI.mayStore()) && !MI.isPredicable() &&
359 Offset < PageSize))
Sanjoy Daseef785c2017-02-28 07:04:49 +0000360 return SR_Unsuitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000361
Serguei Katkov0b0dc572017-06-21 06:38:23 +0000362 // Finally, check whether the current memory access aliases with previous one.
363 for (auto *PrevMI : PrevInsts) {
364 AliasResult AR = areMemoryOpsAliased(MI, PrevMI);
365 if (AR == AR_WillAliasEverything)
366 return SR_Impossible;
367 if (AR == AR_MayAlias)
368 return SR_Unsuitable;
369 }
370 return SR_Suitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000371}
372
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000373bool ImplicitNullChecks::canHoistInst(MachineInstr *FaultingMI,
374 unsigned PointerReg,
375 ArrayRef<MachineInstr *> InstsSeenSoFar,
376 MachineBasicBlock *NullSucc,
377 MachineInstr *&Dependence) {
Sanjoy Das50fef432016-12-23 00:41:24 +0000378 auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar);
379 if (!DepResult.CanReorder)
380 return false;
381
382 if (!DepResult.PotentialDependence) {
383 Dependence = nullptr;
384 return true;
385 }
386
387 auto DependenceItr = *DepResult.PotentialDependence;
388 auto *DependenceMI = *DependenceItr;
389
390 // We don't want to reason about speculating loads. Note -- at this point
391 // we should have already filtered out all of the other non-speculatable
392 // things, like calls and stores.
393 assert(canHandle(DependenceMI) && "Should never have reached here!");
394 if (DependenceMI->mayLoad())
395 return false;
396
397 for (auto &DependenceMO : DependenceMI->operands()) {
398 if (!(DependenceMO.isReg() && DependenceMO.getReg()))
399 continue;
400
401 // Make sure that we won't clobber any live ins to the sibling block by
402 // hoisting Dependency. For instance, we can't hoist INST to before the
403 // null check (even if it safe, and does not violate any dependencies in
404 // the non_null_block) if %rdx is live in to _null_block.
405 //
406 // test %rcx, %rcx
407 // je _null_block
408 // _non_null_block:
409 // %rdx<def> = INST
410 // ...
411 //
412 // This restriction does not apply to the faulting load inst because in
413 // case the pointer loaded from is in the null page, the load will not
414 // semantically execute, and affect machine state. That is, if the load
415 // was loading into %rax and it faults, the value of %rax should stay the
416 // same as it would have been had the load not have executed and we'd have
417 // branched to NullSucc directly.
418 if (AnyAliasLiveIn(TRI, NullSucc, DependenceMO.getReg()))
419 return false;
420
421 // The Dependency can't be re-defining the base register -- then we won't
422 // get the memory operation on the address we want. This is already
423 // checked in \c IsSuitableMemoryOp.
Sanjoy Das08da2e22017-02-01 16:04:21 +0000424 assert(!(DependenceMO.isDef() &&
425 TRI->regsOverlap(DependenceMO.getReg(), PointerReg)) &&
Sanjoy Das50fef432016-12-23 00:41:24 +0000426 "Should have been checked before!");
427 }
428
429 auto DepDepResult =
430 computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr});
431
432 if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence)
433 return false;
434
435 Dependence = DependenceMI;
436 return true;
437}
438
Sanjoy Das69fad072015-06-15 18:44:27 +0000439/// Analyze MBB to check if its terminating branch can be turned into an
440/// implicit null check. If yes, append a description of the said null check to
441/// NullCheckList and return true, else return false.
442bool ImplicitNullChecks::analyzeBlockForNullChecks(
443 MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
444 typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
445
Sanjoy Dase8b81642015-11-12 20:51:49 +0000446 MDNode *BranchMD = nullptr;
447 if (auto *BB = MBB.getBasicBlock())
448 BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
449
Sanjoy Das9c41a932015-06-30 21:22:32 +0000450 if (!BranchMD)
451 return false;
452
Sanjoy Das69fad072015-06-15 18:44:27 +0000453 MachineBranchPredicate MBP;
454
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000455 if (TII->analyzeBranchPredicate(MBB, MBP, true))
Sanjoy Das69fad072015-06-15 18:44:27 +0000456 return false;
457
458 // Is the predicate comparing an integer to zero?
459 if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
460 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
461 MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
462 return false;
463
464 // If we cannot erase the test instruction itself, then making the null check
465 // implicit does not buy us much.
466 if (!MBP.SingleUseCondition)
467 return false;
468
469 MachineBasicBlock *NotNullSucc, *NullSucc;
470
471 if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
472 NotNullSucc = MBP.TrueDest;
473 NullSucc = MBP.FalseDest;
474 } else {
475 NotNullSucc = MBP.FalseDest;
476 NullSucc = MBP.TrueDest;
477 }
478
479 // We handle the simplest case for now. We can potentially do better by using
480 // the machine dominator tree.
481 if (NotNullSucc->pred_size() != 1)
482 return false;
483
484 // Starting with a code fragment like:
485 //
486 // test %RAX, %RAX
487 // jne LblNotNull
488 //
489 // LblNull:
490 // callq throw_NullPointerException
491 //
492 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000493 // Inst0
494 // Inst1
495 // ...
Sanjoy Das69fad072015-06-15 18:44:27 +0000496 // Def = Load (%RAX + <offset>)
497 // ...
498 //
499 //
500 // we want to end up with
501 //
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000502 // Def = FaultingLoad (%RAX + <offset>), LblNull
Sanjoy Das69fad072015-06-15 18:44:27 +0000503 // jmp LblNotNull ;; explicit or fallthrough
504 //
505 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000506 // Inst0
507 // Inst1
Sanjoy Das69fad072015-06-15 18:44:27 +0000508 // ...
509 //
510 // LblNull:
511 // callq throw_NullPointerException
512 //
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000513 //
514 // To see why this is legal, consider the two possibilities:
515 //
516 // 1. %RAX is null: since we constrain <offset> to be less than PageSize, the
517 // load instruction dereferences the null page, causing a segmentation
518 // fault.
519 //
520 // 2. %RAX is not null: in this case we know that the load cannot fault, as
521 // otherwise the load would've faulted in the original program too and the
522 // original program would've been undefined.
523 //
524 // This reasoning cannot be extended to justify hoisting through arbitrary
525 // control flow. For instance, in the example below (in pseudo-C)
526 //
527 // if (ptr == null) { throw_npe(); unreachable; }
528 // if (some_cond) { return 42; }
529 // v = ptr->field; // LD
530 // ...
531 //
532 // we cannot (without code duplication) use the load marked "LD" to null check
533 // ptr -- clause (2) above does not apply in this case. In the above program
534 // the safety of ptr->field can be dependent on some_cond; and, for instance,
535 // ptr could be some non-null invalid reference that never gets loaded from
536 // because some_cond is always true.
Sanjoy Das69fad072015-06-15 18:44:27 +0000537
Sanjoy Das9a129802016-12-23 00:41:21 +0000538 const unsigned PointerReg = MBP.LHS.getReg();
Sanjoy Dasb7718452015-07-09 20:13:25 +0000539
Sanjoy Das9a129802016-12-23 00:41:21 +0000540 SmallVector<MachineInstr *, 8> InstsSeenSoFar;
Sanjoy Dasb7718452015-07-09 20:13:25 +0000541
Sanjoy Das9a129802016-12-23 00:41:21 +0000542 for (auto &MI : *NotNullSucc) {
543 if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider)
544 return false;
545
546 MachineInstr *Dependence;
Sanjoy Daseef785c2017-02-28 07:04:49 +0000547 SuitabilityResult SR = isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar);
Sanjoy Das15e50b52017-02-01 02:49:25 +0000548 if (SR == SR_Impossible)
549 return false;
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000550 if (SR == SR_Suitable &&
551 canHoistInst(&MI, PointerReg, InstsSeenSoFar, NullSucc, Dependence)) {
Sanjoy Das9a129802016-12-23 00:41:21 +0000552 NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc,
553 NullSucc, Dependence);
554 return true;
555 }
556
Serguei Katkov0b0dc572017-06-21 06:38:23 +0000557 // If MI re-defines the PointerReg then we cannot move further.
558 if (any_of(MI.operands(), [&](MachineOperand &MO) {
559 return MO.isReg() && MO.getReg() && MO.isDef() &&
560 TRI->regsOverlap(MO.getReg(), PointerReg);
561 }))
562 return false;
Sanjoy Das9a129802016-12-23 00:41:21 +0000563 InstsSeenSoFar.push_back(&MI);
Sanjoy Dasb7718452015-07-09 20:13:25 +0000564 }
565
Sanjoy Das69fad072015-06-15 18:44:27 +0000566 return false;
567}
568
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000569/// Wrap a machine instruction, MI, into a FAULTING machine instruction.
570/// The FAULTING instruction does the same load/store as MI
571/// (defining the same register), and branches to HandlerMBB if the mem access
572/// faults. The FAULTING instruction is inserted at the end of MBB.
573MachineInstr *ImplicitNullChecks::insertFaultingInstr(
574 MachineInstr *MI, MachineBasicBlock *MBB, MachineBasicBlock *HandlerMBB) {
Sanjoy Das93d608c2015-07-20 20:31:39 +0000575 const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
576 // all targets.
577
Sanjoy Das69fad072015-06-15 18:44:27 +0000578 DebugLoc DL;
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000579 unsigned NumDefs = MI->getDesc().getNumDefs();
Sanjoy Das93d608c2015-07-20 20:31:39 +0000580 assert(NumDefs <= 1 && "other cases unhandled!");
Sanjoy Das69fad072015-06-15 18:44:27 +0000581
Sanjoy Das93d608c2015-07-20 20:31:39 +0000582 unsigned DefReg = NoRegister;
583 if (NumDefs != 0) {
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000584 DefReg = MI->defs().begin()->getReg();
585 assert(std::distance(MI->defs().begin(), MI->defs().end()) == 1 &&
Sanjoy Das93d608c2015-07-20 20:31:39 +0000586 "expected exactly one def!");
587 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000588
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000589 FaultMaps::FaultKind FK;
590 if (MI->mayLoad())
591 FK =
592 MI->mayStore() ? FaultMaps::FaultingLoadStore : FaultMaps::FaultingLoad;
593 else
594 FK = FaultMaps::FaultingStore;
Sanjoy Das69fad072015-06-15 18:44:27 +0000595
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000596 auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_OP), DefReg)
597 .addImm(FK)
598 .addMBB(HandlerMBB)
599 .addImm(MI->getOpcode());
600
Matthias Braun605f77952017-05-31 22:23:08 +0000601 for (auto &MO : MI->uses()) {
602 if (MO.isReg()) {
603 MachineOperand NewMO = MO;
604 if (MO.isUse()) {
605 NewMO.setIsKill(false);
606 } else {
607 assert(MO.isDef() && "Expected def or use");
608 NewMO.setIsDead(false);
609 }
610 MIB.add(NewMO);
611 } else {
612 MIB.add(MO);
613 }
614 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000615
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000616 MIB.setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
Sanjoy Das69fad072015-06-15 18:44:27 +0000617
618 return MIB;
619}
620
621/// Rewrite the null checks in NullCheckList into implicit null checks.
622void ImplicitNullChecks::rewriteNullChecks(
623 ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
624 DebugLoc DL;
625
626 for (auto &NC : NullCheckList) {
Sanjoy Das69fad072015-06-15 18:44:27 +0000627 // Remove the conditional branch dependent on the null check.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000628 unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock());
Sanjoy Das69fad072015-06-15 18:44:27 +0000629 (void)BranchesRemoved;
630 assert(BranchesRemoved > 0 && "expected at least one branch!");
631
Sanjoy Dase57bf682016-06-22 22:16:51 +0000632 if (auto *DepMI = NC.getOnlyDependency()) {
633 DepMI->removeFromParent();
634 NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI);
635 }
636
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000637 // Insert a faulting instruction where the conditional branch was
638 // originally. We check earlier ensures that this bit of code motion
639 // is legal. We do not touch the successors list for any basic block
640 // since we haven't changed control flow, we've just made it implicit.
641 MachineInstr *FaultingInstr = insertFaultingInstr(
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000642 NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc());
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000643 // Now the values defined by MemOperation, if any, are live-in of
644 // the block of MemOperation.
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000645 // The original operation may define implicit-defs alongside
646 // the value.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000647 MachineBasicBlock *MBB = NC.getMemOperation()->getParent();
Sanjoy Das2f63cbc2017-02-07 19:19:49 +0000648 for (const MachineOperand &MO : FaultingInstr->operands()) {
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000649 if (!MO.isReg() || !MO.isDef())
650 continue;
651 unsigned Reg = MO.getReg();
652 if (!Reg || MBB->isLiveIn(Reg))
653 continue;
654 MBB->addLiveIn(Reg);
Quentin Colombet12b69912016-04-27 23:26:40 +0000655 }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000656
657 if (auto *DepMI = NC.getOnlyDependency()) {
658 for (auto &MO : DepMI->operands()) {
659 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
660 continue;
661 if (!NC.getNotNullSucc()->isLiveIn(MO.getReg()))
662 NC.getNotNullSucc()->addLiveIn(MO.getReg());
663 }
664 }
665
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000666 NC.getMemOperation()->eraseFromParent();
667 NC.getCheckOperation()->eraseFromParent();
Sanjoy Das69fad072015-06-15 18:44:27 +0000668
669 // Insert an *unconditional* branch to not-null successor.
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000670 TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr,
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000671 /*Cond=*/None, DL);
Sanjoy Das69fad072015-06-15 18:44:27 +0000672
Sanjoy Das8ee6a302015-07-06 23:32:10 +0000673 NumImplicitNullChecks++;
Sanjoy Das69fad072015-06-15 18:44:27 +0000674 }
675}
676
Sanjoy Das9a129802016-12-23 00:41:21 +0000677
Sanjoy Das69fad072015-06-15 18:44:27 +0000678char ImplicitNullChecks::ID = 0;
679char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
Matthias Braun1527baa2017-05-25 21:26:32 +0000680INITIALIZE_PASS_BEGIN(ImplicitNullChecks, DEBUG_TYPE,
Sanjoy Das69fad072015-06-15 18:44:27 +0000681 "Implicit null checks", false, false)
Sanjoy Dase57bf682016-06-22 22:16:51 +0000682INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000683INITIALIZE_PASS_END(ImplicitNullChecks, DEBUG_TYPE,
Sanjoy Das69fad072015-06-15 18:44:27 +0000684 "Implicit null checks", false, false)