blob: 3a0551ed03469441c81c410ebcb006070b595319 [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.
25//
26//===----------------------------------------------------------------------===//
27
Sanjoy Dasb7718452015-07-09 20:13:25 +000028#include "llvm/ADT/DenseSet.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000029#include "llvm/ADT/SmallVector.h"
Sanjoy Das8ee6a302015-07-06 23:32:10 +000030#include "llvm/ADT/Statistic.h"
Sanjoy Dase57bf682016-06-22 22:16:51 +000031#include "llvm/Analysis/AliasAnalysis.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000032#include "llvm/CodeGen/Passes.h"
33#include "llvm/CodeGen/MachineFunction.h"
Sanjoy Dasb7718452015-07-09 20:13:25 +000034#include "llvm/CodeGen/MachineMemOperand.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000035#include "llvm/CodeGen/MachineOperand.h"
36#include "llvm/CodeGen/MachineFunctionPass.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/CodeGen/MachineModuleInfo.h"
40#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Instruction.h"
Chen Li00038782015-08-04 04:41:34 +000042#include "llvm/IR/LLVMContext.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Target/TargetSubtargetInfo.h"
46#include "llvm/Target/TargetInstrInfo.h"
47
48using namespace llvm;
49
Chad Rosierc27a18f2016-03-09 16:00:35 +000050static cl::opt<int> PageSize("imp-null-check-page-size",
51 cl::desc("The page size of the target in bytes"),
52 cl::init(4096));
Sanjoy Das69fad072015-06-15 18:44:27 +000053
Sanjoy Das9a129802016-12-23 00:41:21 +000054static cl::opt<unsigned> MaxInstsToConsider(
55 "imp-null-max-insts-to-consider",
56 cl::desc("The max number of instructions to consider hoisting loads over "
57 "(the algorithm is quadratic over this number)"),
58 cl::init(8));
59
Sanjoy Das8ee6a302015-07-06 23:32:10 +000060#define DEBUG_TYPE "implicit-null-checks"
61
62STATISTIC(NumImplicitNullChecks,
63 "Number of explicit null checks made implicit");
64
Sanjoy Das69fad072015-06-15 18:44:27 +000065namespace {
66
67class ImplicitNullChecks : public MachineFunctionPass {
Sanjoy Das9a129802016-12-23 00:41:21 +000068 /// Return true if \c computeDependence can process \p MI.
69 static bool canHandle(const MachineInstr *MI);
70
71 /// Helper function for \c computeDependence. Return true if \p A
72 /// and \p B do not have any dependences between them, and can be
73 /// re-ordered without changing program semantics.
74 bool canReorder(const MachineInstr *A, const MachineInstr *B);
75
76 /// A data type for representing the result computed by \c
77 /// computeDependence. States whether it is okay to reorder the
78 /// instruction passed to \c computeDependence with at most one
79 /// depednency.
80 struct DependenceResult {
81 /// Can we actually re-order \p MI with \p Insts (see \c
82 /// computeDependence).
83 bool CanReorder;
84
85 /// If non-None, then an instruction in \p Insts that also must be
86 /// hoisted.
87 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence;
88
89 /*implicit*/ DependenceResult(
90 bool CanReorder,
91 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence)
92 : CanReorder(CanReorder), PotentialDependence(PotentialDependence) {
93 assert((!PotentialDependence || CanReorder) &&
94 "!CanReorder && PotentialDependence.hasValue() not allowed!");
95 }
96 };
97
98 /// Compute a result for the following question: can \p MI be
99 /// re-ordered from after \p Insts to before it.
100 ///
101 /// \c canHandle should return true for all instructions in \p
102 /// Insts.
103 DependenceResult computeDependence(const MachineInstr *MI,
104 ArrayRef<MachineInstr *> Insts);
105
Sanjoy Das69fad072015-06-15 18:44:27 +0000106 /// Represents one null check that can be made implicit.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000107 class NullCheck {
Sanjoy Das69fad072015-06-15 18:44:27 +0000108 // The memory operation the null check can be folded into.
109 MachineInstr *MemOperation;
110
111 // The instruction actually doing the null check (Ptr != 0).
112 MachineInstr *CheckOperation;
113
114 // The block the check resides in.
115 MachineBasicBlock *CheckBlock;
116
Eric Christopher572e03a2015-06-19 01:53:21 +0000117 // The block branched to if the pointer is non-null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000118 MachineBasicBlock *NotNullSucc;
119
Eric Christopher572e03a2015-06-19 01:53:21 +0000120 // The block branched to if the pointer is null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000121 MachineBasicBlock *NullSucc;
122
Sanjoy Dase57bf682016-06-22 22:16:51 +0000123 // If this is non-null, then MemOperation has a dependency on on this
124 // instruction; and it needs to be hoisted to execute before MemOperation.
125 MachineInstr *OnlyDependency;
126
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000127 public:
Sanjoy Das69fad072015-06-15 18:44:27 +0000128 explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation,
129 MachineBasicBlock *checkBlock,
130 MachineBasicBlock *notNullSucc,
Sanjoy Dase57bf682016-06-22 22:16:51 +0000131 MachineBasicBlock *nullSucc,
132 MachineInstr *onlyDependency)
Sanjoy Das69fad072015-06-15 18:44:27 +0000133 : MemOperation(memOperation), CheckOperation(checkOperation),
Sanjoy Dase57bf682016-06-22 22:16:51 +0000134 CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc),
135 OnlyDependency(onlyDependency) {}
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000136
137 MachineInstr *getMemOperation() const { return MemOperation; }
138
139 MachineInstr *getCheckOperation() const { return CheckOperation; }
140
141 MachineBasicBlock *getCheckBlock() const { return CheckBlock; }
142
143 MachineBasicBlock *getNotNullSucc() const { return NotNullSucc; }
144
145 MachineBasicBlock *getNullSucc() const { return NullSucc; }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000146
147 MachineInstr *getOnlyDependency() const { return OnlyDependency; }
Sanjoy Das69fad072015-06-15 18:44:27 +0000148 };
149
150 const TargetInstrInfo *TII = nullptr;
151 const TargetRegisterInfo *TRI = nullptr;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000152 AliasAnalysis *AA = nullptr;
Sanjoy Das69fad072015-06-15 18:44:27 +0000153 MachineModuleInfo *MMI = nullptr;
154
155 bool analyzeBlockForNullChecks(MachineBasicBlock &MBB,
156 SmallVectorImpl<NullCheck> &NullCheckList);
157 MachineInstr *insertFaultingLoad(MachineInstr *LoadMI, MachineBasicBlock *MBB,
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000158 MachineBasicBlock *HandlerMBB);
Sanjoy Das69fad072015-06-15 18:44:27 +0000159 void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList);
160
Sanjoy Das15e50b52017-02-01 02:49:25 +0000161 enum SuitabilityResult { SR_Suitable, SR_Unsuitable, SR_Impossible };
162
163 /// Return SR_Suitable if \p MI a memory operation that can be used to
164 /// implicitly null check the value in \p PointerReg, SR_Unsuitable if
165 /// \p MI cannot be used to null check and SR_Impossible if there is
166 /// no sense to continue lookup due to any other instruction will not be able
167 /// to be used. \p PrevInsts is the set of instruction seen since
Sanjoy Das50fef432016-12-23 00:41:24 +0000168 /// the explicit null check on \p PointerReg.
Sanjoy Das15e50b52017-02-01 02:49:25 +0000169 SuitabilityResult isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg,
170 ArrayRef<MachineInstr *> PrevInsts);
Sanjoy Das50fef432016-12-23 00:41:24 +0000171
172 /// Return true if \p FaultingMI can be hoisted from after the the
173 /// instructions in \p InstsSeenSoFar to before them. Set \p Dependence to a
174 /// non-null value if we also need to (and legally can) hoist a depedency.
175 bool canHoistLoadInst(MachineInstr *FaultingMI, unsigned PointerReg,
176 ArrayRef<MachineInstr *> InstsSeenSoFar,
177 MachineBasicBlock *NullSucc, MachineInstr *&Dependence);
178
Sanjoy Das69fad072015-06-15 18:44:27 +0000179public:
180 static char ID;
181
182 ImplicitNullChecks() : MachineFunctionPass(ID) {
183 initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry());
184 }
185
186 bool runOnMachineFunction(MachineFunction &MF) override;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000187 void getAnalysisUsage(AnalysisUsage &AU) const override {
188 AU.addRequired<AAResultsWrapperPass>();
189 MachineFunctionPass::getAnalysisUsage(AU);
190 }
Derek Schuffad154c82016-03-28 17:05:30 +0000191
192 MachineFunctionProperties getRequiredProperties() const override {
193 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000194 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000195 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000196};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000197
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000198}
199
Sanjoy Das9a129802016-12-23 00:41:21 +0000200bool ImplicitNullChecks::canHandle(const MachineInstr *MI) {
201 if (MI->isCall() || MI->mayStore() || MI->hasUnmodeledSideEffects())
202 return false;
203 auto IsRegMask = [](const MachineOperand &MO) { return MO.isRegMask(); };
204 (void)IsRegMask;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000205
Sanjoy Das9a129802016-12-23 00:41:21 +0000206 assert(!llvm::any_of(MI->operands(), IsRegMask) &&
207 "Calls were filtered out above!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000208
Sanjoy Das9a129802016-12-23 00:41:21 +0000209 auto IsUnordered = [](MachineMemOperand *MMO) { return MMO->isUnordered(); };
210 return llvm::all_of(MI->memoperands(), IsUnordered);
211}
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000212
Sanjoy Das9a129802016-12-23 00:41:21 +0000213ImplicitNullChecks::DependenceResult
214ImplicitNullChecks::computeDependence(const MachineInstr *MI,
215 ArrayRef<MachineInstr *> Block) {
216 assert(llvm::all_of(Block, canHandle) && "Check this first!");
217 assert(!llvm::is_contained(Block, MI) && "Block must be exclusive of MI!");
218
219 Optional<ArrayRef<MachineInstr *>::iterator> Dep;
220
221 for (auto I = Block.begin(), E = Block.end(); I != E; ++I) {
222 if (canReorder(*I, MI))
223 continue;
224
225 if (Dep == None) {
226 // Found one possible dependency, keep track of it.
227 Dep = I;
228 } else {
229 // We found two dependencies, so bail out.
230 return {false, None};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000231 }
232 }
233
Sanjoy Das9a129802016-12-23 00:41:21 +0000234 return {true, Dep};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000235}
236
Sanjoy Das9a129802016-12-23 00:41:21 +0000237bool ImplicitNullChecks::canReorder(const MachineInstr *A,
238 const MachineInstr *B) {
239 assert(canHandle(A) && canHandle(B) && "Precondition!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000240
Sanjoy Das9a129802016-12-23 00:41:21 +0000241 // canHandle makes sure that we _can_ correctly analyze the dependencies
242 // between A and B here -- for instance, we should not be dealing with heap
243 // load-store dependencies here.
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000244
Sanjoy Das9a129802016-12-23 00:41:21 +0000245 for (auto MOA : A->operands()) {
246 if (!(MOA.isReg() && MOA.getReg()))
247 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000248
Sanjoy Das9a129802016-12-23 00:41:21 +0000249 unsigned RegA = MOA.getReg();
250 for (auto MOB : B->operands()) {
251 if (!(MOB.isReg() && MOB.getReg()))
252 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000253
Sanjoy Das9a129802016-12-23 00:41:21 +0000254 unsigned RegB = MOB.getReg();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000255
Sanjoy Das9a129802016-12-23 00:41:21 +0000256 if (TRI->regsOverlap(RegA, RegB))
257 return false;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000258 }
259 }
260
261 return true;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000262}
Sanjoy Das69fad072015-06-15 18:44:27 +0000263
264bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) {
265 TII = MF.getSubtarget().getInstrInfo();
266 TRI = MF.getRegInfo().getTargetRegisterInfo();
267 MMI = &MF.getMMI();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000268 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Sanjoy Das69fad072015-06-15 18:44:27 +0000269
270 SmallVector<NullCheck, 16> NullCheckList;
271
272 for (auto &MBB : MF)
273 analyzeBlockForNullChecks(MBB, NullCheckList);
274
275 if (!NullCheckList.empty())
276 rewriteNullChecks(NullCheckList);
277
278 return !NullCheckList.empty();
279}
280
Sanjoy Dase57bf682016-06-22 22:16:51 +0000281// Return true if any register aliasing \p Reg is live-in into \p MBB.
282static bool AnyAliasLiveIn(const TargetRegisterInfo *TRI,
283 MachineBasicBlock *MBB, unsigned Reg) {
284 for (MCRegAliasIterator AR(Reg, TRI, /*IncludeSelf*/ true); AR.isValid();
285 ++AR)
286 if (MBB->isLiveIn(*AR))
287 return true;
288 return false;
289}
290
Sanjoy Das15e50b52017-02-01 02:49:25 +0000291ImplicitNullChecks::SuitabilityResult
292ImplicitNullChecks::isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg,
293 ArrayRef<MachineInstr *> PrevInsts) {
Sanjoy Das50fef432016-12-23 00:41:24 +0000294 int64_t Offset;
295 unsigned BaseReg;
296
297 if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI) ||
298 BaseReg != PointerReg)
Sanjoy Das15e50b52017-02-01 02:49:25 +0000299 return SR_Unsuitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000300
301 // We want the load to be issued at a sane offset from PointerReg, so that
302 // if PointerReg is null then the load reliably page faults.
303 if (!(MI.mayLoad() && !MI.isPredicable() && Offset < PageSize))
Sanjoy Das15e50b52017-02-01 02:49:25 +0000304 return SR_Unsuitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000305
306 // Finally, we need to make sure that the load instruction actually is
307 // loading from PointerReg, and there isn't some re-definition of PointerReg
308 // between the compare and the load.
Sanjoy Das15e50b52017-02-01 02:49:25 +0000309 // If PointerReg has been redefined before then there is no sense to continue
310 // lookup due to this condition will fail for any further instruction.
Sanjoy Das50fef432016-12-23 00:41:24 +0000311 for (auto *PrevMI : PrevInsts)
312 for (auto &PrevMO : PrevMI->operands())
313 if (PrevMO.isReg() && PrevMO.getReg() &&
314 TRI->regsOverlap(PrevMO.getReg(), PointerReg))
Sanjoy Das15e50b52017-02-01 02:49:25 +0000315 return SR_Impossible;
Sanjoy Das50fef432016-12-23 00:41:24 +0000316
Sanjoy Das15e50b52017-02-01 02:49:25 +0000317 return SR_Suitable;
Sanjoy Das50fef432016-12-23 00:41:24 +0000318}
319
320bool ImplicitNullChecks::canHoistLoadInst(
321 MachineInstr *FaultingMI, unsigned PointerReg,
322 ArrayRef<MachineInstr *> InstsSeenSoFar, MachineBasicBlock *NullSucc,
323 MachineInstr *&Dependence) {
324 auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar);
325 if (!DepResult.CanReorder)
326 return false;
327
328 if (!DepResult.PotentialDependence) {
329 Dependence = nullptr;
330 return true;
331 }
332
333 auto DependenceItr = *DepResult.PotentialDependence;
334 auto *DependenceMI = *DependenceItr;
335
336 // We don't want to reason about speculating loads. Note -- at this point
337 // we should have already filtered out all of the other non-speculatable
338 // things, like calls and stores.
339 assert(canHandle(DependenceMI) && "Should never have reached here!");
340 if (DependenceMI->mayLoad())
341 return false;
342
343 for (auto &DependenceMO : DependenceMI->operands()) {
344 if (!(DependenceMO.isReg() && DependenceMO.getReg()))
345 continue;
346
347 // Make sure that we won't clobber any live ins to the sibling block by
348 // hoisting Dependency. For instance, we can't hoist INST to before the
349 // null check (even if it safe, and does not violate any dependencies in
350 // the non_null_block) if %rdx is live in to _null_block.
351 //
352 // test %rcx, %rcx
353 // je _null_block
354 // _non_null_block:
355 // %rdx<def> = INST
356 // ...
357 //
358 // This restriction does not apply to the faulting load inst because in
359 // case the pointer loaded from is in the null page, the load will not
360 // semantically execute, and affect machine state. That is, if the load
361 // was loading into %rax and it faults, the value of %rax should stay the
362 // same as it would have been had the load not have executed and we'd have
363 // branched to NullSucc directly.
364 if (AnyAliasLiveIn(TRI, NullSucc, DependenceMO.getReg()))
365 return false;
366
367 // The Dependency can't be re-defining the base register -- then we won't
368 // get the memory operation on the address we want. This is already
369 // checked in \c IsSuitableMemoryOp.
370 assert(!TRI->regsOverlap(DependenceMO.getReg(), PointerReg) &&
371 "Should have been checked before!");
372 }
373
374 auto DepDepResult =
375 computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr});
376
377 if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence)
378 return false;
379
380 Dependence = DependenceMI;
381 return true;
382}
383
Sanjoy Das69fad072015-06-15 18:44:27 +0000384/// Analyze MBB to check if its terminating branch can be turned into an
385/// implicit null check. If yes, append a description of the said null check to
386/// NullCheckList and return true, else return false.
387bool ImplicitNullChecks::analyzeBlockForNullChecks(
388 MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
389 typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
390
Sanjoy Dase8b81642015-11-12 20:51:49 +0000391 MDNode *BranchMD = nullptr;
392 if (auto *BB = MBB.getBasicBlock())
393 BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
394
Sanjoy Das9c41a932015-06-30 21:22:32 +0000395 if (!BranchMD)
396 return false;
397
Sanjoy Das69fad072015-06-15 18:44:27 +0000398 MachineBranchPredicate MBP;
399
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000400 if (TII->analyzeBranchPredicate(MBB, MBP, true))
Sanjoy Das69fad072015-06-15 18:44:27 +0000401 return false;
402
403 // Is the predicate comparing an integer to zero?
404 if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
405 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
406 MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
407 return false;
408
409 // If we cannot erase the test instruction itself, then making the null check
410 // implicit does not buy us much.
411 if (!MBP.SingleUseCondition)
412 return false;
413
414 MachineBasicBlock *NotNullSucc, *NullSucc;
415
416 if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
417 NotNullSucc = MBP.TrueDest;
418 NullSucc = MBP.FalseDest;
419 } else {
420 NotNullSucc = MBP.FalseDest;
421 NullSucc = MBP.TrueDest;
422 }
423
424 // We handle the simplest case for now. We can potentially do better by using
425 // the machine dominator tree.
426 if (NotNullSucc->pred_size() != 1)
427 return false;
428
429 // Starting with a code fragment like:
430 //
431 // test %RAX, %RAX
432 // jne LblNotNull
433 //
434 // LblNull:
435 // callq throw_NullPointerException
436 //
437 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000438 // Inst0
439 // Inst1
440 // ...
Sanjoy Das69fad072015-06-15 18:44:27 +0000441 // Def = Load (%RAX + <offset>)
442 // ...
443 //
444 //
445 // we want to end up with
446 //
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000447 // Def = FaultingLoad (%RAX + <offset>), LblNull
Sanjoy Das69fad072015-06-15 18:44:27 +0000448 // jmp LblNotNull ;; explicit or fallthrough
449 //
450 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000451 // Inst0
452 // Inst1
Sanjoy Das69fad072015-06-15 18:44:27 +0000453 // ...
454 //
455 // LblNull:
456 // callq throw_NullPointerException
457 //
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000458 //
459 // To see why this is legal, consider the two possibilities:
460 //
461 // 1. %RAX is null: since we constrain <offset> to be less than PageSize, the
462 // load instruction dereferences the null page, causing a segmentation
463 // fault.
464 //
465 // 2. %RAX is not null: in this case we know that the load cannot fault, as
466 // otherwise the load would've faulted in the original program too and the
467 // original program would've been undefined.
468 //
469 // This reasoning cannot be extended to justify hoisting through arbitrary
470 // control flow. For instance, in the example below (in pseudo-C)
471 //
472 // if (ptr == null) { throw_npe(); unreachable; }
473 // if (some_cond) { return 42; }
474 // v = ptr->field; // LD
475 // ...
476 //
477 // we cannot (without code duplication) use the load marked "LD" to null check
478 // ptr -- clause (2) above does not apply in this case. In the above program
479 // the safety of ptr->field can be dependent on some_cond; and, for instance,
480 // ptr could be some non-null invalid reference that never gets loaded from
481 // because some_cond is always true.
Sanjoy Das69fad072015-06-15 18:44:27 +0000482
Sanjoy Das9a129802016-12-23 00:41:21 +0000483 const unsigned PointerReg = MBP.LHS.getReg();
Sanjoy Dasb7718452015-07-09 20:13:25 +0000484
Sanjoy Das9a129802016-12-23 00:41:21 +0000485 SmallVector<MachineInstr *, 8> InstsSeenSoFar;
Sanjoy Dasb7718452015-07-09 20:13:25 +0000486
Sanjoy Das9a129802016-12-23 00:41:21 +0000487 for (auto &MI : *NotNullSucc) {
488 if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider)
489 return false;
490
491 MachineInstr *Dependence;
Sanjoy Das15e50b52017-02-01 02:49:25 +0000492 SuitabilityResult SR = isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar);
493 if (SR == SR_Impossible)
494 return false;
495 if (SR == SR_Suitable && canHoistLoadInst(&MI, PointerReg, InstsSeenSoFar,
496 NullSucc, Dependence)) {
Sanjoy Das9a129802016-12-23 00:41:21 +0000497 NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc,
498 NullSucc, Dependence);
499 return true;
500 }
501
502 InstsSeenSoFar.push_back(&MI);
Sanjoy Dasb7718452015-07-09 20:13:25 +0000503 }
504
Sanjoy Das69fad072015-06-15 18:44:27 +0000505 return false;
506}
507
508/// Wrap a machine load instruction, LoadMI, into a FAULTING_LOAD_OP machine
509/// instruction. The FAULTING_LOAD_OP instruction does the same load as LoadMI
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000510/// (defining the same register), and branches to HandlerMBB if the load
Sanjoy Das69fad072015-06-15 18:44:27 +0000511/// faults. The FAULTING_LOAD_OP instruction is inserted at the end of MBB.
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000512MachineInstr *
513ImplicitNullChecks::insertFaultingLoad(MachineInstr *LoadMI,
514 MachineBasicBlock *MBB,
515 MachineBasicBlock *HandlerMBB) {
Sanjoy Das93d608c2015-07-20 20:31:39 +0000516 const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
517 // all targets.
518
Sanjoy Das69fad072015-06-15 18:44:27 +0000519 DebugLoc DL;
520 unsigned NumDefs = LoadMI->getDesc().getNumDefs();
Sanjoy Das93d608c2015-07-20 20:31:39 +0000521 assert(NumDefs <= 1 && "other cases unhandled!");
Sanjoy Das69fad072015-06-15 18:44:27 +0000522
Sanjoy Das93d608c2015-07-20 20:31:39 +0000523 unsigned DefReg = NoRegister;
524 if (NumDefs != 0) {
525 DefReg = LoadMI->defs().begin()->getReg();
526 assert(std::distance(LoadMI->defs().begin(), LoadMI->defs().end()) == 1 &&
527 "expected exactly one def!");
528 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000529
530 auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_LOAD_OP), DefReg)
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000531 .addMBB(HandlerMBB)
Sanjoy Das69fad072015-06-15 18:44:27 +0000532 .addImm(LoadMI->getOpcode());
533
534 for (auto &MO : LoadMI->uses())
Diana Picus116bbab2017-01-13 09:58:52 +0000535 MIB.add(MO);
Sanjoy Das69fad072015-06-15 18:44:27 +0000536
537 MIB.setMemRefs(LoadMI->memoperands_begin(), LoadMI->memoperands_end());
538
539 return MIB;
540}
541
542/// Rewrite the null checks in NullCheckList into implicit null checks.
543void ImplicitNullChecks::rewriteNullChecks(
544 ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
545 DebugLoc DL;
546
547 for (auto &NC : NullCheckList) {
Sanjoy Das69fad072015-06-15 18:44:27 +0000548 // Remove the conditional branch dependent on the null check.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000549 unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock());
Sanjoy Das69fad072015-06-15 18:44:27 +0000550 (void)BranchesRemoved;
551 assert(BranchesRemoved > 0 && "expected at least one branch!");
552
Sanjoy Dase57bf682016-06-22 22:16:51 +0000553 if (auto *DepMI = NC.getOnlyDependency()) {
554 DepMI->removeFromParent();
555 NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI);
556 }
557
Sanjoy Das69fad072015-06-15 18:44:27 +0000558 // Insert a faulting load where the conditional branch was originally. We
559 // check earlier ensures that this bit of code motion is legal. We do not
560 // touch the successors list for any basic block since we haven't changed
561 // control flow, we've just made it implicit.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000562 MachineInstr *FaultingLoad = insertFaultingLoad(
563 NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc());
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000564 // Now the values defined by MemOperation, if any, are live-in of
565 // the block of MemOperation.
566 // The original load operation may define implicit-defs alongside
567 // the loaded value.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000568 MachineBasicBlock *MBB = NC.getMemOperation()->getParent();
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000569 for (const MachineOperand &MO : FaultingLoad->operands()) {
570 if (!MO.isReg() || !MO.isDef())
571 continue;
572 unsigned Reg = MO.getReg();
573 if (!Reg || MBB->isLiveIn(Reg))
574 continue;
575 MBB->addLiveIn(Reg);
Quentin Colombet12b69912016-04-27 23:26:40 +0000576 }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000577
578 if (auto *DepMI = NC.getOnlyDependency()) {
579 for (auto &MO : DepMI->operands()) {
580 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
581 continue;
582 if (!NC.getNotNullSucc()->isLiveIn(MO.getReg()))
583 NC.getNotNullSucc()->addLiveIn(MO.getReg());
584 }
585 }
586
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000587 NC.getMemOperation()->eraseFromParent();
588 NC.getCheckOperation()->eraseFromParent();
Sanjoy Das69fad072015-06-15 18:44:27 +0000589
590 // Insert an *unconditional* branch to not-null successor.
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000591 TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr,
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000592 /*Cond=*/None, DL);
Sanjoy Das69fad072015-06-15 18:44:27 +0000593
Sanjoy Das8ee6a302015-07-06 23:32:10 +0000594 NumImplicitNullChecks++;
Sanjoy Das69fad072015-06-15 18:44:27 +0000595 }
596}
597
Sanjoy Das9a129802016-12-23 00:41:21 +0000598
Sanjoy Das69fad072015-06-15 18:44:27 +0000599char ImplicitNullChecks::ID = 0;
600char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
601INITIALIZE_PASS_BEGIN(ImplicitNullChecks, "implicit-null-checks",
602 "Implicit null checks", false, false)
Sanjoy Dase57bf682016-06-22 22:16:51 +0000603INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Sanjoy Das69fad072015-06-15 18:44:27 +0000604INITIALIZE_PASS_END(ImplicitNullChecks, "implicit-null-checks",
605 "Implicit null checks", false, false)