Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 1 | //===-- 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 Das | b771845 | 2015-07-09 20:13:25 +0000 | [diff] [blame] | 28 | #include "llvm/ADT/DenseSet.h" |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 29 | #include "llvm/ADT/SmallVector.h" |
Sanjoy Das | 8ee6a30 | 2015-07-06 23:32:10 +0000 | [diff] [blame] | 30 | #include "llvm/ADT/Statistic.h" |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 31 | #include "llvm/Analysis/AliasAnalysis.h" |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 32 | #include "llvm/CodeGen/Passes.h" |
| 33 | #include "llvm/CodeGen/MachineFunction.h" |
Sanjoy Das | b771845 | 2015-07-09 20:13:25 +0000 | [diff] [blame] | 34 | #include "llvm/CodeGen/MachineMemOperand.h" |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 35 | #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 Li | 0003878 | 2015-08-04 04:41:34 +0000 | [diff] [blame] | 42 | #include "llvm/IR/LLVMContext.h" |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 43 | #include "llvm/Support/CommandLine.h" |
| 44 | #include "llvm/Support/Debug.h" |
| 45 | #include "llvm/Target/TargetSubtargetInfo.h" |
| 46 | #include "llvm/Target/TargetInstrInfo.h" |
| 47 | |
| 48 | using namespace llvm; |
| 49 | |
Chad Rosier | c27a18f | 2016-03-09 16:00:35 +0000 | [diff] [blame] | 50 | static 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 Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 53 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 54 | static 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 Das | 8ee6a30 | 2015-07-06 23:32:10 +0000 | [diff] [blame] | 60 | #define DEBUG_TYPE "implicit-null-checks" |
| 61 | |
| 62 | STATISTIC(NumImplicitNullChecks, |
| 63 | "Number of explicit null checks made implicit"); |
| 64 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 65 | namespace { |
| 66 | |
| 67 | class ImplicitNullChecks : public MachineFunctionPass { |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 68 | /// 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 Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 106 | /// Represents one null check that can be made implicit. |
Sanjoy Das | e173b9a | 2016-06-21 02:10:18 +0000 | [diff] [blame] | 107 | class NullCheck { |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 108 | // 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 Christopher | 572e03a | 2015-06-19 01:53:21 +0000 | [diff] [blame] | 117 | // The block branched to if the pointer is non-null. |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 118 | MachineBasicBlock *NotNullSucc; |
| 119 | |
Eric Christopher | 572e03a | 2015-06-19 01:53:21 +0000 | [diff] [blame] | 120 | // The block branched to if the pointer is null. |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 121 | MachineBasicBlock *NullSucc; |
| 122 | |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 123 | // 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 Das | e173b9a | 2016-06-21 02:10:18 +0000 | [diff] [blame] | 127 | public: |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 128 | explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation, |
| 129 | MachineBasicBlock *checkBlock, |
| 130 | MachineBasicBlock *notNullSucc, |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 131 | MachineBasicBlock *nullSucc, |
| 132 | MachineInstr *onlyDependency) |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 133 | : MemOperation(memOperation), CheckOperation(checkOperation), |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 134 | CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc), |
| 135 | OnlyDependency(onlyDependency) {} |
Sanjoy Das | e173b9a | 2016-06-21 02:10:18 +0000 | [diff] [blame] | 136 | |
| 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 Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 146 | |
| 147 | MachineInstr *getOnlyDependency() const { return OnlyDependency; } |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 148 | }; |
| 149 | |
| 150 | const TargetInstrInfo *TII = nullptr; |
| 151 | const TargetRegisterInfo *TRI = nullptr; |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 152 | AliasAnalysis *AA = nullptr; |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 153 | MachineModuleInfo *MMI = nullptr; |
| 154 | |
| 155 | bool analyzeBlockForNullChecks(MachineBasicBlock &MBB, |
| 156 | SmallVectorImpl<NullCheck> &NullCheckList); |
| 157 | MachineInstr *insertFaultingLoad(MachineInstr *LoadMI, MachineBasicBlock *MBB, |
Quentin Colombet | 4e1d389 | 2016-05-02 22:58:54 +0000 | [diff] [blame] | 158 | MachineBasicBlock *HandlerMBB); |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 159 | void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList); |
| 160 | |
Sanjoy Das | 50fef43 | 2016-12-23 00:41:24 +0000 | [diff] [blame^] | 161 | /// Is \p MI a memory operation that can be used to implicitly null check the |
| 162 | /// value in \p PointerReg? \p PrevInsts is the set of instruction seen since |
| 163 | /// the explicit null check on \p PointerReg. |
| 164 | bool isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg, |
| 165 | ArrayRef<MachineInstr *> PrevInsts); |
| 166 | |
| 167 | /// Return true if \p FaultingMI can be hoisted from after the the |
| 168 | /// instructions in \p InstsSeenSoFar to before them. Set \p Dependence to a |
| 169 | /// non-null value if we also need to (and legally can) hoist a depedency. |
| 170 | bool canHoistLoadInst(MachineInstr *FaultingMI, unsigned PointerReg, |
| 171 | ArrayRef<MachineInstr *> InstsSeenSoFar, |
| 172 | MachineBasicBlock *NullSucc, MachineInstr *&Dependence); |
| 173 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 174 | public: |
| 175 | static char ID; |
| 176 | |
| 177 | ImplicitNullChecks() : MachineFunctionPass(ID) { |
| 178 | initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry()); |
| 179 | } |
| 180 | |
| 181 | bool runOnMachineFunction(MachineFunction &MF) override; |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 182 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 183 | AU.addRequired<AAResultsWrapperPass>(); |
| 184 | MachineFunctionPass::getAnalysisUsage(AU); |
| 185 | } |
Derek Schuff | ad154c8 | 2016-03-28 17:05:30 +0000 | [diff] [blame] | 186 | |
| 187 | MachineFunctionProperties getRequiredProperties() const override { |
| 188 | return MachineFunctionProperties().set( |
Matthias Braun | 1eb4736 | 2016-08-25 01:27:13 +0000 | [diff] [blame] | 189 | MachineFunctionProperties::Property::NoVRegs); |
Derek Schuff | ad154c8 | 2016-03-28 17:05:30 +0000 | [diff] [blame] | 190 | } |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 191 | }; |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 192 | |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 193 | } |
| 194 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 195 | bool ImplicitNullChecks::canHandle(const MachineInstr *MI) { |
| 196 | if (MI->isCall() || MI->mayStore() || MI->hasUnmodeledSideEffects()) |
| 197 | return false; |
| 198 | auto IsRegMask = [](const MachineOperand &MO) { return MO.isRegMask(); }; |
| 199 | (void)IsRegMask; |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 200 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 201 | assert(!llvm::any_of(MI->operands(), IsRegMask) && |
| 202 | "Calls were filtered out above!"); |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 203 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 204 | auto IsUnordered = [](MachineMemOperand *MMO) { return MMO->isUnordered(); }; |
| 205 | return llvm::all_of(MI->memoperands(), IsUnordered); |
| 206 | } |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 207 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 208 | ImplicitNullChecks::DependenceResult |
| 209 | ImplicitNullChecks::computeDependence(const MachineInstr *MI, |
| 210 | ArrayRef<MachineInstr *> Block) { |
| 211 | assert(llvm::all_of(Block, canHandle) && "Check this first!"); |
| 212 | assert(!llvm::is_contained(Block, MI) && "Block must be exclusive of MI!"); |
| 213 | |
| 214 | Optional<ArrayRef<MachineInstr *>::iterator> Dep; |
| 215 | |
| 216 | for (auto I = Block.begin(), E = Block.end(); I != E; ++I) { |
| 217 | if (canReorder(*I, MI)) |
| 218 | continue; |
| 219 | |
| 220 | if (Dep == None) { |
| 221 | // Found one possible dependency, keep track of it. |
| 222 | Dep = I; |
| 223 | } else { |
| 224 | // We found two dependencies, so bail out. |
| 225 | return {false, None}; |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 226 | } |
| 227 | } |
| 228 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 229 | return {true, Dep}; |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 230 | } |
| 231 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 232 | bool ImplicitNullChecks::canReorder(const MachineInstr *A, |
| 233 | const MachineInstr *B) { |
| 234 | assert(canHandle(A) && canHandle(B) && "Precondition!"); |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 235 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 236 | // canHandle makes sure that we _can_ correctly analyze the dependencies |
| 237 | // between A and B here -- for instance, we should not be dealing with heap |
| 238 | // load-store dependencies here. |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 239 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 240 | for (auto MOA : A->operands()) { |
| 241 | if (!(MOA.isReg() && MOA.getReg())) |
| 242 | continue; |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 243 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 244 | unsigned RegA = MOA.getReg(); |
| 245 | for (auto MOB : B->operands()) { |
| 246 | if (!(MOB.isReg() && MOB.getReg())) |
| 247 | continue; |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 248 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 249 | unsigned RegB = MOB.getReg(); |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 250 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 251 | if (TRI->regsOverlap(RegA, RegB)) |
| 252 | return false; |
Sanjoy Das | edc394f | 2015-11-12 20:51:44 +0000 | [diff] [blame] | 253 | } |
| 254 | } |
| 255 | |
| 256 | return true; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 257 | } |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 258 | |
| 259 | bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) { |
| 260 | TII = MF.getSubtarget().getInstrInfo(); |
| 261 | TRI = MF.getRegInfo().getTargetRegisterInfo(); |
| 262 | MMI = &MF.getMMI(); |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 263 | AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 264 | |
| 265 | SmallVector<NullCheck, 16> NullCheckList; |
| 266 | |
| 267 | for (auto &MBB : MF) |
| 268 | analyzeBlockForNullChecks(MBB, NullCheckList); |
| 269 | |
| 270 | if (!NullCheckList.empty()) |
| 271 | rewriteNullChecks(NullCheckList); |
| 272 | |
| 273 | return !NullCheckList.empty(); |
| 274 | } |
| 275 | |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 276 | // Return true if any register aliasing \p Reg is live-in into \p MBB. |
| 277 | static bool AnyAliasLiveIn(const TargetRegisterInfo *TRI, |
| 278 | MachineBasicBlock *MBB, unsigned Reg) { |
| 279 | for (MCRegAliasIterator AR(Reg, TRI, /*IncludeSelf*/ true); AR.isValid(); |
| 280 | ++AR) |
| 281 | if (MBB->isLiveIn(*AR)) |
| 282 | return true; |
| 283 | return false; |
| 284 | } |
| 285 | |
Sanjoy Das | 50fef43 | 2016-12-23 00:41:24 +0000 | [diff] [blame^] | 286 | bool ImplicitNullChecks::isSuitableMemoryOp( |
| 287 | MachineInstr &MI, unsigned PointerReg, ArrayRef<MachineInstr *> PrevInsts) { |
| 288 | int64_t Offset; |
| 289 | unsigned BaseReg; |
| 290 | |
| 291 | if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI) || |
| 292 | BaseReg != PointerReg) |
| 293 | return false; |
| 294 | |
| 295 | // We want the load to be issued at a sane offset from PointerReg, so that |
| 296 | // if PointerReg is null then the load reliably page faults. |
| 297 | if (!(MI.mayLoad() && !MI.isPredicable() && Offset < PageSize)) |
| 298 | return false; |
| 299 | |
| 300 | // Finally, we need to make sure that the load instruction actually is |
| 301 | // loading from PointerReg, and there isn't some re-definition of PointerReg |
| 302 | // between the compare and the load. |
| 303 | for (auto *PrevMI : PrevInsts) |
| 304 | for (auto &PrevMO : PrevMI->operands()) |
| 305 | if (PrevMO.isReg() && PrevMO.getReg() && |
| 306 | TRI->regsOverlap(PrevMO.getReg(), PointerReg)) |
| 307 | return false; |
| 308 | |
| 309 | return true; |
| 310 | } |
| 311 | |
| 312 | bool ImplicitNullChecks::canHoistLoadInst( |
| 313 | MachineInstr *FaultingMI, unsigned PointerReg, |
| 314 | ArrayRef<MachineInstr *> InstsSeenSoFar, MachineBasicBlock *NullSucc, |
| 315 | MachineInstr *&Dependence) { |
| 316 | auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar); |
| 317 | if (!DepResult.CanReorder) |
| 318 | return false; |
| 319 | |
| 320 | if (!DepResult.PotentialDependence) { |
| 321 | Dependence = nullptr; |
| 322 | return true; |
| 323 | } |
| 324 | |
| 325 | auto DependenceItr = *DepResult.PotentialDependence; |
| 326 | auto *DependenceMI = *DependenceItr; |
| 327 | |
| 328 | // We don't want to reason about speculating loads. Note -- at this point |
| 329 | // we should have already filtered out all of the other non-speculatable |
| 330 | // things, like calls and stores. |
| 331 | assert(canHandle(DependenceMI) && "Should never have reached here!"); |
| 332 | if (DependenceMI->mayLoad()) |
| 333 | return false; |
| 334 | |
| 335 | for (auto &DependenceMO : DependenceMI->operands()) { |
| 336 | if (!(DependenceMO.isReg() && DependenceMO.getReg())) |
| 337 | continue; |
| 338 | |
| 339 | // Make sure that we won't clobber any live ins to the sibling block by |
| 340 | // hoisting Dependency. For instance, we can't hoist INST to before the |
| 341 | // null check (even if it safe, and does not violate any dependencies in |
| 342 | // the non_null_block) if %rdx is live in to _null_block. |
| 343 | // |
| 344 | // test %rcx, %rcx |
| 345 | // je _null_block |
| 346 | // _non_null_block: |
| 347 | // %rdx<def> = INST |
| 348 | // ... |
| 349 | // |
| 350 | // This restriction does not apply to the faulting load inst because in |
| 351 | // case the pointer loaded from is in the null page, the load will not |
| 352 | // semantically execute, and affect machine state. That is, if the load |
| 353 | // was loading into %rax and it faults, the value of %rax should stay the |
| 354 | // same as it would have been had the load not have executed and we'd have |
| 355 | // branched to NullSucc directly. |
| 356 | if (AnyAliasLiveIn(TRI, NullSucc, DependenceMO.getReg())) |
| 357 | return false; |
| 358 | |
| 359 | // The Dependency can't be re-defining the base register -- then we won't |
| 360 | // get the memory operation on the address we want. This is already |
| 361 | // checked in \c IsSuitableMemoryOp. |
| 362 | assert(!TRI->regsOverlap(DependenceMO.getReg(), PointerReg) && |
| 363 | "Should have been checked before!"); |
| 364 | } |
| 365 | |
| 366 | auto DepDepResult = |
| 367 | computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr}); |
| 368 | |
| 369 | if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence) |
| 370 | return false; |
| 371 | |
| 372 | Dependence = DependenceMI; |
| 373 | return true; |
| 374 | } |
| 375 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 376 | /// Analyze MBB to check if its terminating branch can be turned into an |
| 377 | /// implicit null check. If yes, append a description of the said null check to |
| 378 | /// NullCheckList and return true, else return false. |
| 379 | bool ImplicitNullChecks::analyzeBlockForNullChecks( |
| 380 | MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) { |
| 381 | typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate; |
| 382 | |
Sanjoy Das | e8b8164 | 2015-11-12 20:51:49 +0000 | [diff] [blame] | 383 | MDNode *BranchMD = nullptr; |
| 384 | if (auto *BB = MBB.getBasicBlock()) |
| 385 | BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit); |
| 386 | |
Sanjoy Das | 9c41a93 | 2015-06-30 21:22:32 +0000 | [diff] [blame] | 387 | if (!BranchMD) |
| 388 | return false; |
| 389 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 390 | MachineBranchPredicate MBP; |
| 391 | |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 392 | if (TII->analyzeBranchPredicate(MBB, MBP, true)) |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 393 | return false; |
| 394 | |
| 395 | // Is the predicate comparing an integer to zero? |
| 396 | if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 && |
| 397 | (MBP.Predicate == MachineBranchPredicate::PRED_NE || |
| 398 | MBP.Predicate == MachineBranchPredicate::PRED_EQ))) |
| 399 | return false; |
| 400 | |
| 401 | // If we cannot erase the test instruction itself, then making the null check |
| 402 | // implicit does not buy us much. |
| 403 | if (!MBP.SingleUseCondition) |
| 404 | return false; |
| 405 | |
| 406 | MachineBasicBlock *NotNullSucc, *NullSucc; |
| 407 | |
| 408 | if (MBP.Predicate == MachineBranchPredicate::PRED_NE) { |
| 409 | NotNullSucc = MBP.TrueDest; |
| 410 | NullSucc = MBP.FalseDest; |
| 411 | } else { |
| 412 | NotNullSucc = MBP.FalseDest; |
| 413 | NullSucc = MBP.TrueDest; |
| 414 | } |
| 415 | |
| 416 | // We handle the simplest case for now. We can potentially do better by using |
| 417 | // the machine dominator tree. |
| 418 | if (NotNullSucc->pred_size() != 1) |
| 419 | return false; |
| 420 | |
| 421 | // Starting with a code fragment like: |
| 422 | // |
| 423 | // test %RAX, %RAX |
| 424 | // jne LblNotNull |
| 425 | // |
| 426 | // LblNull: |
| 427 | // callq throw_NullPointerException |
| 428 | // |
| 429 | // LblNotNull: |
Sanjoy Das | b771845 | 2015-07-09 20:13:25 +0000 | [diff] [blame] | 430 | // Inst0 |
| 431 | // Inst1 |
| 432 | // ... |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 433 | // Def = Load (%RAX + <offset>) |
| 434 | // ... |
| 435 | // |
| 436 | // |
| 437 | // we want to end up with |
| 438 | // |
Sanjoy Das | ac9c5b1 | 2015-11-13 08:14:00 +0000 | [diff] [blame] | 439 | // Def = FaultingLoad (%RAX + <offset>), LblNull |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 440 | // jmp LblNotNull ;; explicit or fallthrough |
| 441 | // |
| 442 | // LblNotNull: |
Sanjoy Das | b771845 | 2015-07-09 20:13:25 +0000 | [diff] [blame] | 443 | // Inst0 |
| 444 | // Inst1 |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 445 | // ... |
| 446 | // |
| 447 | // LblNull: |
| 448 | // callq throw_NullPointerException |
| 449 | // |
Sanjoy Das | ac9c5b1 | 2015-11-13 08:14:00 +0000 | [diff] [blame] | 450 | // |
| 451 | // To see why this is legal, consider the two possibilities: |
| 452 | // |
| 453 | // 1. %RAX is null: since we constrain <offset> to be less than PageSize, the |
| 454 | // load instruction dereferences the null page, causing a segmentation |
| 455 | // fault. |
| 456 | // |
| 457 | // 2. %RAX is not null: in this case we know that the load cannot fault, as |
| 458 | // otherwise the load would've faulted in the original program too and the |
| 459 | // original program would've been undefined. |
| 460 | // |
| 461 | // This reasoning cannot be extended to justify hoisting through arbitrary |
| 462 | // control flow. For instance, in the example below (in pseudo-C) |
| 463 | // |
| 464 | // if (ptr == null) { throw_npe(); unreachable; } |
| 465 | // if (some_cond) { return 42; } |
| 466 | // v = ptr->field; // LD |
| 467 | // ... |
| 468 | // |
| 469 | // we cannot (without code duplication) use the load marked "LD" to null check |
| 470 | // ptr -- clause (2) above does not apply in this case. In the above program |
| 471 | // the safety of ptr->field can be dependent on some_cond; and, for instance, |
| 472 | // ptr could be some non-null invalid reference that never gets loaded from |
| 473 | // because some_cond is always true. |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 474 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 475 | const unsigned PointerReg = MBP.LHS.getReg(); |
Sanjoy Das | b771845 | 2015-07-09 20:13:25 +0000 | [diff] [blame] | 476 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 477 | SmallVector<MachineInstr *, 8> InstsSeenSoFar; |
Sanjoy Das | b771845 | 2015-07-09 20:13:25 +0000 | [diff] [blame] | 478 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 479 | for (auto &MI : *NotNullSucc) { |
| 480 | if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider) |
| 481 | return false; |
| 482 | |
| 483 | MachineInstr *Dependence; |
Sanjoy Das | 50fef43 | 2016-12-23 00:41:24 +0000 | [diff] [blame^] | 484 | if (isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar) && |
| 485 | canHoistLoadInst(&MI, PointerReg, InstsSeenSoFar, NullSucc, |
| 486 | Dependence)) { |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 487 | NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc, |
| 488 | NullSucc, Dependence); |
| 489 | return true; |
| 490 | } |
| 491 | |
| 492 | InstsSeenSoFar.push_back(&MI); |
Sanjoy Das | b771845 | 2015-07-09 20:13:25 +0000 | [diff] [blame] | 493 | } |
| 494 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 495 | return false; |
| 496 | } |
| 497 | |
| 498 | /// Wrap a machine load instruction, LoadMI, into a FAULTING_LOAD_OP machine |
| 499 | /// instruction. The FAULTING_LOAD_OP instruction does the same load as LoadMI |
Quentin Colombet | 4e1d389 | 2016-05-02 22:58:54 +0000 | [diff] [blame] | 500 | /// (defining the same register), and branches to HandlerMBB if the load |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 501 | /// faults. The FAULTING_LOAD_OP instruction is inserted at the end of MBB. |
Quentin Colombet | 4e1d389 | 2016-05-02 22:58:54 +0000 | [diff] [blame] | 502 | MachineInstr * |
| 503 | ImplicitNullChecks::insertFaultingLoad(MachineInstr *LoadMI, |
| 504 | MachineBasicBlock *MBB, |
| 505 | MachineBasicBlock *HandlerMBB) { |
Sanjoy Das | 93d608c | 2015-07-20 20:31:39 +0000 | [diff] [blame] | 506 | const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for |
| 507 | // all targets. |
| 508 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 509 | DebugLoc DL; |
| 510 | unsigned NumDefs = LoadMI->getDesc().getNumDefs(); |
Sanjoy Das | 93d608c | 2015-07-20 20:31:39 +0000 | [diff] [blame] | 511 | assert(NumDefs <= 1 && "other cases unhandled!"); |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 512 | |
Sanjoy Das | 93d608c | 2015-07-20 20:31:39 +0000 | [diff] [blame] | 513 | unsigned DefReg = NoRegister; |
| 514 | if (NumDefs != 0) { |
| 515 | DefReg = LoadMI->defs().begin()->getReg(); |
| 516 | assert(std::distance(LoadMI->defs().begin(), LoadMI->defs().end()) == 1 && |
| 517 | "expected exactly one def!"); |
| 518 | } |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 519 | |
| 520 | auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_LOAD_OP), DefReg) |
Quentin Colombet | 4e1d389 | 2016-05-02 22:58:54 +0000 | [diff] [blame] | 521 | .addMBB(HandlerMBB) |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 522 | .addImm(LoadMI->getOpcode()); |
| 523 | |
| 524 | for (auto &MO : LoadMI->uses()) |
| 525 | MIB.addOperand(MO); |
| 526 | |
| 527 | MIB.setMemRefs(LoadMI->memoperands_begin(), LoadMI->memoperands_end()); |
| 528 | |
| 529 | return MIB; |
| 530 | } |
| 531 | |
| 532 | /// Rewrite the null checks in NullCheckList into implicit null checks. |
| 533 | void ImplicitNullChecks::rewriteNullChecks( |
| 534 | ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) { |
| 535 | DebugLoc DL; |
| 536 | |
| 537 | for (auto &NC : NullCheckList) { |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 538 | // Remove the conditional branch dependent on the null check. |
Matt Arsenault | 1b9fc8e | 2016-09-14 20:43:16 +0000 | [diff] [blame] | 539 | unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock()); |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 540 | (void)BranchesRemoved; |
| 541 | assert(BranchesRemoved > 0 && "expected at least one branch!"); |
| 542 | |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 543 | if (auto *DepMI = NC.getOnlyDependency()) { |
| 544 | DepMI->removeFromParent(); |
| 545 | NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI); |
| 546 | } |
| 547 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 548 | // Insert a faulting load where the conditional branch was originally. We |
| 549 | // check earlier ensures that this bit of code motion is legal. We do not |
| 550 | // touch the successors list for any basic block since we haven't changed |
| 551 | // control flow, we've just made it implicit. |
Sanjoy Das | e173b9a | 2016-06-21 02:10:18 +0000 | [diff] [blame] | 552 | MachineInstr *FaultingLoad = insertFaultingLoad( |
| 553 | NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc()); |
Quentin Colombet | 26dab3a | 2016-05-03 18:09:06 +0000 | [diff] [blame] | 554 | // Now the values defined by MemOperation, if any, are live-in of |
| 555 | // the block of MemOperation. |
| 556 | // The original load operation may define implicit-defs alongside |
| 557 | // the loaded value. |
Sanjoy Das | e173b9a | 2016-06-21 02:10:18 +0000 | [diff] [blame] | 558 | MachineBasicBlock *MBB = NC.getMemOperation()->getParent(); |
Quentin Colombet | 26dab3a | 2016-05-03 18:09:06 +0000 | [diff] [blame] | 559 | for (const MachineOperand &MO : FaultingLoad->operands()) { |
| 560 | if (!MO.isReg() || !MO.isDef()) |
| 561 | continue; |
| 562 | unsigned Reg = MO.getReg(); |
| 563 | if (!Reg || MBB->isLiveIn(Reg)) |
| 564 | continue; |
| 565 | MBB->addLiveIn(Reg); |
Quentin Colombet | 12b6991 | 2016-04-27 23:26:40 +0000 | [diff] [blame] | 566 | } |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 567 | |
| 568 | if (auto *DepMI = NC.getOnlyDependency()) { |
| 569 | for (auto &MO : DepMI->operands()) { |
| 570 | if (!MO.isReg() || !MO.getReg() || !MO.isDef()) |
| 571 | continue; |
| 572 | if (!NC.getNotNullSucc()->isLiveIn(MO.getReg())) |
| 573 | NC.getNotNullSucc()->addLiveIn(MO.getReg()); |
| 574 | } |
| 575 | } |
| 576 | |
Sanjoy Das | e173b9a | 2016-06-21 02:10:18 +0000 | [diff] [blame] | 577 | NC.getMemOperation()->eraseFromParent(); |
| 578 | NC.getCheckOperation()->eraseFromParent(); |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 579 | |
| 580 | // Insert an *unconditional* branch to not-null successor. |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 581 | TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr, |
Sanjoy Das | e173b9a | 2016-06-21 02:10:18 +0000 | [diff] [blame] | 582 | /*Cond=*/None, DL); |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 583 | |
Sanjoy Das | 8ee6a30 | 2015-07-06 23:32:10 +0000 | [diff] [blame] | 584 | NumImplicitNullChecks++; |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 585 | } |
| 586 | } |
| 587 | |
Sanjoy Das | 9a12980 | 2016-12-23 00:41:21 +0000 | [diff] [blame] | 588 | |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 589 | char ImplicitNullChecks::ID = 0; |
| 590 | char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID; |
| 591 | INITIALIZE_PASS_BEGIN(ImplicitNullChecks, "implicit-null-checks", |
| 592 | "Implicit null checks", false, false) |
Sanjoy Das | e57bf68 | 2016-06-22 22:16:51 +0000 | [diff] [blame] | 593 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
Sanjoy Das | 69fad07 | 2015-06-15 18:44:27 +0000 | [diff] [blame] | 594 | INITIALIZE_PASS_END(ImplicitNullChecks, "implicit-null-checks", |
| 595 | "Implicit null checks", false, false) |