| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 1 | //===- Attributor.cpp - Module-wide attribute deduction -------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements an inter procedural pass that deduces and/or propagating |
| 10 | // attributes. This is done in an abstract interpretation style fixpoint |
| 11 | // iteration. See the Attributor.h file comment and the class descriptions in |
| 12 | // that file for more information. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #include "llvm/Transforms/IPO/Attributor.h" |
| 17 | |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/DepthFirstIterator.h" |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/STLExtras.h" |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/SetVector.h" |
| 21 | #include "llvm/ADT/SmallPtrSet.h" |
| 22 | #include "llvm/ADT/SmallVector.h" |
| 23 | #include "llvm/ADT/Statistic.h" |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/CaptureTracking.h" |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/GlobalsModRef.h" |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/Loads.h" |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/ValueTracking.h" |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Argument.h" |
| 29 | #include "llvm/IR/Attributes.h" |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 30 | #include "llvm/IR/CFG.h" |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 31 | #include "llvm/IR/InstIterator.h" |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 32 | #include "llvm/IR/IntrinsicInst.h" |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 33 | #include "llvm/Support/CommandLine.h" |
| 34 | #include "llvm/Support/Debug.h" |
| 35 | #include "llvm/Support/raw_ostream.h" |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 36 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 37 | #include "llvm/Transforms/Utils/Local.h" |
| 38 | |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 39 | #include <cassert> |
| 40 | |
| 41 | using namespace llvm; |
| 42 | |
| 43 | #define DEBUG_TYPE "attributor" |
| 44 | |
| 45 | STATISTIC(NumFnWithExactDefinition, |
| 46 | "Number of function with exact definitions"); |
| 47 | STATISTIC(NumFnWithoutExactDefinition, |
| 48 | "Number of function without exact definitions"); |
| 49 | STATISTIC(NumAttributesTimedOut, |
| 50 | "Number of abstract attributes timed out before fixpoint"); |
| 51 | STATISTIC(NumAttributesValidFixpoint, |
| 52 | "Number of abstract attributes in a valid fixpoint state"); |
| 53 | STATISTIC(NumAttributesManifested, |
| 54 | "Number of abstract attributes manifested in IR"); |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 55 | STATISTIC(NumFnNoUnwind, "Number of functions marked nounwind"); |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 56 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 57 | STATISTIC(NumFnUniqueReturned, "Number of function with unique return"); |
| 58 | STATISTIC(NumFnKnownReturns, "Number of function with known return values"); |
| 59 | STATISTIC(NumFnArgumentReturned, |
| 60 | "Number of function arguments marked returned"); |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 61 | STATISTIC(NumFnNoSync, "Number of functions marked nosync"); |
| Hideto Ueno | 65bbaf9 | 2019-07-12 17:38:51 +0000 | [diff] [blame] | 62 | STATISTIC(NumFnNoFree, "Number of functions marked nofree"); |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 63 | STATISTIC(NumFnReturnedNonNull, |
| 64 | "Number of function return values marked nonnull"); |
| 65 | STATISTIC(NumFnArgumentNonNull, "Number of function arguments marked nonnull"); |
| 66 | STATISTIC(NumCSArgumentNonNull, "Number of call site arguments marked nonnull"); |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 67 | STATISTIC(NumFnWillReturn, "Number of functions marked willreturn"); |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 68 | STATISTIC(NumFnArgumentNoAlias, "Number of function arguments marked noalias"); |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 69 | STATISTIC(NumFnReturnedDereferenceable, |
| 70 | "Number of function return values marked dereferenceable"); |
| 71 | STATISTIC(NumFnArgumentDereferenceable, |
| 72 | "Number of function arguments marked dereferenceable"); |
| 73 | STATISTIC(NumCSArgumentDereferenceable, |
| 74 | "Number of call site arguments marked dereferenceable"); |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 75 | STATISTIC(NumFnReturnedAlign, "Number of function return values marked align"); |
| 76 | STATISTIC(NumFnArgumentAlign, "Number of function arguments marked align"); |
| 77 | STATISTIC(NumCSArgumentAlign, "Number of call site arguments marked align"); |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 78 | |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 79 | // TODO: Determine a good default value. |
| 80 | // |
| 81 | // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads |
| 82 | // (when run with the first 5 abstract attributes). The results also indicate |
| 83 | // that we never reach 32 iterations but always find a fixpoint sooner. |
| 84 | // |
| 85 | // This will become more evolved once we perform two interleaved fixpoint |
| 86 | // iterations: bottom-up and top-down. |
| 87 | static cl::opt<unsigned> |
| 88 | MaxFixpointIterations("attributor-max-iterations", cl::Hidden, |
| 89 | cl::desc("Maximal number of fixpoint iterations."), |
| 90 | cl::init(32)); |
| 91 | |
| 92 | static cl::opt<bool> DisableAttributor( |
| 93 | "attributor-disable", cl::Hidden, |
| 94 | cl::desc("Disable the attributor inter-procedural deduction pass."), |
| Johannes Doerfert | 282d34e | 2019-06-14 14:53:41 +0000 | [diff] [blame] | 95 | cl::init(true)); |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 96 | |
| 97 | static cl::opt<bool> VerifyAttributor( |
| 98 | "attributor-verify", cl::Hidden, |
| 99 | cl::desc("Verify the Attributor deduction and " |
| 100 | "manifestation of attributes -- may issue false-positive errors"), |
| 101 | cl::init(false)); |
| 102 | |
| 103 | /// Logic operators for the change status enum class. |
| 104 | /// |
| 105 | ///{ |
| 106 | ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) { |
| 107 | return l == ChangeStatus::CHANGED ? l : r; |
| 108 | } |
| 109 | ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) { |
| 110 | return l == ChangeStatus::UNCHANGED ? l : r; |
| 111 | } |
| 112 | ///} |
| 113 | |
| 114 | /// Helper to adjust the statistics. |
| 115 | static void bookkeeping(AbstractAttribute::ManifestPosition MP, |
| 116 | const Attribute &Attr) { |
| 117 | if (!AreStatisticsEnabled()) |
| 118 | return; |
| 119 | |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 120 | switch (Attr.getKindAsEnum()) { |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 121 | case Attribute::Alignment: |
| 122 | switch (MP) { |
| 123 | case AbstractAttribute::MP_RETURNED: |
| 124 | NumFnReturnedAlign++; |
| 125 | break; |
| 126 | case AbstractAttribute::MP_ARGUMENT: |
| 127 | NumFnArgumentAlign++; |
| 128 | break; |
| 129 | case AbstractAttribute::MP_CALL_SITE_ARGUMENT: |
| 130 | NumCSArgumentAlign++; |
| 131 | break; |
| 132 | default: |
| 133 | break; |
| 134 | } |
| 135 | break; |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 136 | case Attribute::Dereferenceable: |
| 137 | switch (MP) { |
| 138 | case AbstractAttribute::MP_RETURNED: |
| 139 | NumFnReturnedDereferenceable++; |
| 140 | break; |
| 141 | case AbstractAttribute::MP_ARGUMENT: |
| 142 | NumFnArgumentDereferenceable++; |
| 143 | break; |
| 144 | case AbstractAttribute::MP_CALL_SITE_ARGUMENT: |
| 145 | NumCSArgumentDereferenceable++; |
| 146 | break; |
| 147 | default: |
| 148 | break; |
| 149 | } |
| 150 | break; |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 151 | case Attribute::NoUnwind: |
| 152 | NumFnNoUnwind++; |
| 153 | return; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 154 | case Attribute::Returned: |
| 155 | NumFnArgumentReturned++; |
| 156 | return; |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 157 | case Attribute::NoSync: |
| 158 | NumFnNoSync++; |
| 159 | break; |
| Hideto Ueno | 65bbaf9 | 2019-07-12 17:38:51 +0000 | [diff] [blame] | 160 | case Attribute::NoFree: |
| 161 | NumFnNoFree++; |
| 162 | break; |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 163 | case Attribute::NonNull: |
| 164 | switch (MP) { |
| 165 | case AbstractAttribute::MP_RETURNED: |
| 166 | NumFnReturnedNonNull++; |
| 167 | break; |
| 168 | case AbstractAttribute::MP_ARGUMENT: |
| 169 | NumFnArgumentNonNull++; |
| 170 | break; |
| 171 | case AbstractAttribute::MP_CALL_SITE_ARGUMENT: |
| 172 | NumCSArgumentNonNull++; |
| 173 | break; |
| 174 | default: |
| 175 | break; |
| 176 | } |
| 177 | break; |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 178 | case Attribute::WillReturn: |
| 179 | NumFnWillReturn++; |
| 180 | break; |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 181 | case Attribute::NoAlias: |
| 182 | NumFnArgumentNoAlias++; |
| 183 | return; |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 184 | default: |
| 185 | return; |
| 186 | } |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 187 | } |
| 188 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 189 | template <typename StateTy> |
| 190 | using followValueCB_t = std::function<bool(Value *, StateTy &State)>; |
| 191 | template <typename StateTy> |
| 192 | using visitValueCB_t = std::function<void(Value *, StateTy &State)>; |
| 193 | |
| 194 | /// Recursively visit all values that might become \p InitV at some point. This |
| 195 | /// will be done by looking through cast instructions, selects, phis, and calls |
| 196 | /// with the "returned" attribute. The callback \p FollowValueCB is asked before |
| 197 | /// a potential origin value is looked at. If no \p FollowValueCB is passed, a |
| 198 | /// default one is used that will make sure we visit every value only once. Once |
| 199 | /// we cannot look through the value any further, the callback \p VisitValueCB |
| 200 | /// is invoked and passed the current value and the \p State. To limit how much |
| 201 | /// effort is invested, we will never visit more than \p MaxValues values. |
| 202 | template <typename StateTy> |
| 203 | static bool genericValueTraversal( |
| 204 | Value *InitV, StateTy &State, visitValueCB_t<StateTy> &VisitValueCB, |
| 205 | followValueCB_t<StateTy> *FollowValueCB = nullptr, int MaxValues = 8) { |
| 206 | |
| 207 | SmallPtrSet<Value *, 16> Visited; |
| 208 | followValueCB_t<bool> DefaultFollowValueCB = [&](Value *Val, bool &) { |
| 209 | return Visited.insert(Val).second; |
| 210 | }; |
| 211 | |
| 212 | if (!FollowValueCB) |
| 213 | FollowValueCB = &DefaultFollowValueCB; |
| 214 | |
| 215 | SmallVector<Value *, 16> Worklist; |
| 216 | Worklist.push_back(InitV); |
| 217 | |
| 218 | int Iteration = 0; |
| 219 | do { |
| 220 | Value *V = Worklist.pop_back_val(); |
| 221 | |
| 222 | // Check if we should process the current value. To prevent endless |
| 223 | // recursion keep a record of the values we followed! |
| 224 | if (!(*FollowValueCB)(V, State)) |
| 225 | continue; |
| 226 | |
| 227 | // Make sure we limit the compile time for complex expressions. |
| 228 | if (Iteration++ >= MaxValues) |
| 229 | return false; |
| 230 | |
| 231 | // Explicitly look through calls with a "returned" attribute if we do |
| 232 | // not have a pointer as stripPointerCasts only works on them. |
| 233 | if (V->getType()->isPointerTy()) { |
| 234 | V = V->stripPointerCasts(); |
| 235 | } else { |
| 236 | CallSite CS(V); |
| 237 | if (CS && CS.getCalledFunction()) { |
| 238 | Value *NewV = nullptr; |
| 239 | for (Argument &Arg : CS.getCalledFunction()->args()) |
| 240 | if (Arg.hasReturnedAttr()) { |
| 241 | NewV = CS.getArgOperand(Arg.getArgNo()); |
| 242 | break; |
| 243 | } |
| 244 | if (NewV) { |
| 245 | Worklist.push_back(NewV); |
| 246 | continue; |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | // Look through select instructions, visit both potential values. |
| 252 | if (auto *SI = dyn_cast<SelectInst>(V)) { |
| 253 | Worklist.push_back(SI->getTrueValue()); |
| 254 | Worklist.push_back(SI->getFalseValue()); |
| 255 | continue; |
| 256 | } |
| 257 | |
| 258 | // Look through phi nodes, visit all operands. |
| 259 | if (auto *PHI = dyn_cast<PHINode>(V)) { |
| 260 | Worklist.append(PHI->op_begin(), PHI->op_end()); |
| 261 | continue; |
| 262 | } |
| 263 | |
| 264 | // Once a leaf is reached we inform the user through the callback. |
| 265 | VisitValueCB(V, State); |
| 266 | } while (!Worklist.empty()); |
| 267 | |
| 268 | // All values have been visited. |
| 269 | return true; |
| 270 | } |
| 271 | |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 272 | /// Helper to identify the correct offset into an attribute list. |
| 273 | static unsigned getAttrIndex(AbstractAttribute::ManifestPosition MP, |
| 274 | unsigned ArgNo = 0) { |
| 275 | switch (MP) { |
| 276 | case AbstractAttribute::MP_ARGUMENT: |
| 277 | case AbstractAttribute::MP_CALL_SITE_ARGUMENT: |
| 278 | return ArgNo + AttributeList::FirstArgIndex; |
| 279 | case AbstractAttribute::MP_FUNCTION: |
| 280 | return AttributeList::FunctionIndex; |
| 281 | case AbstractAttribute::MP_RETURNED: |
| 282 | return AttributeList::ReturnIndex; |
| 283 | } |
| Michael Liao | fa449a9 | 2019-06-05 04:18:12 +0000 | [diff] [blame] | 284 | llvm_unreachable("Unknown manifest position!"); |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 285 | } |
| 286 | |
| 287 | /// Return true if \p New is equal or worse than \p Old. |
| 288 | static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) { |
| 289 | if (!Old.isIntAttribute()) |
| 290 | return true; |
| 291 | |
| 292 | return Old.getValueAsInt() >= New.getValueAsInt(); |
| 293 | } |
| 294 | |
| 295 | /// Return true if the information provided by \p Attr was added to the |
| 296 | /// attribute list \p Attrs. This is only the case if it was not already present |
| 297 | /// in \p Attrs at the position describe by \p MP and \p ArgNo. |
| 298 | static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, |
| 299 | AttributeList &Attrs, |
| 300 | AbstractAttribute::ManifestPosition MP, |
| 301 | unsigned ArgNo = 0) { |
| 302 | unsigned AttrIdx = getAttrIndex(MP, ArgNo); |
| 303 | |
| 304 | if (Attr.isEnumAttribute()) { |
| 305 | Attribute::AttrKind Kind = Attr.getKindAsEnum(); |
| 306 | if (Attrs.hasAttribute(AttrIdx, Kind)) |
| 307 | if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) |
| 308 | return false; |
| 309 | Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); |
| 310 | return true; |
| 311 | } |
| 312 | if (Attr.isStringAttribute()) { |
| 313 | StringRef Kind = Attr.getKindAsString(); |
| 314 | if (Attrs.hasAttribute(AttrIdx, Kind)) |
| 315 | if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) |
| 316 | return false; |
| 317 | Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); |
| 318 | return true; |
| 319 | } |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 320 | if (Attr.isIntAttribute()) { |
| 321 | Attribute::AttrKind Kind = Attr.getKindAsEnum(); |
| 322 | if (Attrs.hasAttribute(AttrIdx, Kind)) |
| 323 | if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) |
| 324 | return false; |
| 325 | Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind); |
| 326 | Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); |
| 327 | return true; |
| 328 | } |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 329 | |
| 330 | llvm_unreachable("Expected enum or string attribute!"); |
| 331 | } |
| 332 | |
| 333 | ChangeStatus AbstractAttribute::update(Attributor &A) { |
| 334 | ChangeStatus HasChanged = ChangeStatus::UNCHANGED; |
| 335 | if (getState().isAtFixpoint()) |
| 336 | return HasChanged; |
| 337 | |
| 338 | LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n"); |
| 339 | |
| 340 | HasChanged = updateImpl(A); |
| 341 | |
| 342 | LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this |
| 343 | << "\n"); |
| 344 | |
| 345 | return HasChanged; |
| 346 | } |
| 347 | |
| 348 | ChangeStatus AbstractAttribute::manifest(Attributor &A) { |
| 349 | assert(getState().isValidState() && |
| 350 | "Attempted to manifest an invalid state!"); |
| 351 | assert(getAssociatedValue() && |
| 352 | "Attempted to manifest an attribute without associated value!"); |
| 353 | |
| 354 | ChangeStatus HasChanged = ChangeStatus::UNCHANGED; |
| 355 | SmallVector<Attribute, 4> DeducedAttrs; |
| 356 | getDeducedAttributes(DeducedAttrs); |
| 357 | |
| 358 | Function &ScopeFn = getAnchorScope(); |
| 359 | LLVMContext &Ctx = ScopeFn.getContext(); |
| 360 | ManifestPosition MP = getManifestPosition(); |
| 361 | |
| 362 | AttributeList Attrs; |
| 363 | SmallVector<unsigned, 4> ArgNos; |
| 364 | |
| 365 | // In the following some generic code that will manifest attributes in |
| 366 | // DeducedAttrs if they improve the current IR. Due to the different |
| 367 | // annotation positions we use the underlying AttributeList interface. |
| 368 | // Note that MP_CALL_SITE_ARGUMENT can annotate multiple locations. |
| 369 | |
| 370 | switch (MP) { |
| 371 | case MP_ARGUMENT: |
| 372 | ArgNos.push_back(cast<Argument>(getAssociatedValue())->getArgNo()); |
| 373 | Attrs = ScopeFn.getAttributes(); |
| 374 | break; |
| 375 | case MP_FUNCTION: |
| 376 | case MP_RETURNED: |
| 377 | ArgNos.push_back(0); |
| 378 | Attrs = ScopeFn.getAttributes(); |
| 379 | break; |
| 380 | case MP_CALL_SITE_ARGUMENT: { |
| 381 | CallSite CS(&getAnchoredValue()); |
| 382 | for (unsigned u = 0, e = CS.getNumArgOperands(); u != e; u++) |
| 383 | if (CS.getArgOperand(u) == getAssociatedValue()) |
| 384 | ArgNos.push_back(u); |
| 385 | Attrs = CS.getAttributes(); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | for (const Attribute &Attr : DeducedAttrs) { |
| 390 | for (unsigned ArgNo : ArgNos) { |
| 391 | if (!addIfNotExistent(Ctx, Attr, Attrs, MP, ArgNo)) |
| 392 | continue; |
| 393 | |
| 394 | HasChanged = ChangeStatus::CHANGED; |
| 395 | bookkeeping(MP, Attr); |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | if (HasChanged == ChangeStatus::UNCHANGED) |
| 400 | return HasChanged; |
| 401 | |
| 402 | switch (MP) { |
| 403 | case MP_ARGUMENT: |
| 404 | case MP_FUNCTION: |
| 405 | case MP_RETURNED: |
| 406 | ScopeFn.setAttributes(Attrs); |
| 407 | break; |
| 408 | case MP_CALL_SITE_ARGUMENT: |
| 409 | CallSite(&getAnchoredValue()).setAttributes(Attrs); |
| 410 | } |
| 411 | |
| 412 | return HasChanged; |
| 413 | } |
| 414 | |
| 415 | Function &AbstractAttribute::getAnchorScope() { |
| 416 | Value &V = getAnchoredValue(); |
| 417 | if (isa<Function>(V)) |
| 418 | return cast<Function>(V); |
| 419 | if (isa<Argument>(V)) |
| 420 | return *cast<Argument>(V).getParent(); |
| 421 | if (isa<Instruction>(V)) |
| 422 | return *cast<Instruction>(V).getFunction(); |
| 423 | llvm_unreachable("No scope for anchored value found!"); |
| 424 | } |
| 425 | |
| 426 | const Function &AbstractAttribute::getAnchorScope() const { |
| 427 | return const_cast<AbstractAttribute *>(this)->getAnchorScope(); |
| 428 | } |
| 429 | |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 430 | // Helper function that returns argument index of value. |
| 431 | // If the value is not an argument, this returns -1. |
| 432 | static int getArgNo(Value &V) { |
| 433 | if (auto *Arg = dyn_cast<Argument>(&V)) |
| 434 | return Arg->getArgNo(); |
| 435 | return -1; |
| 436 | } |
| 437 | |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 438 | /// -----------------------NoUnwind Function Attribute-------------------------- |
| 439 | |
| 440 | struct AANoUnwindFunction : AANoUnwind, BooleanState { |
| 441 | |
| 442 | AANoUnwindFunction(Function &F, InformationCache &InfoCache) |
| 443 | : AANoUnwind(F, InfoCache) {} |
| 444 | |
| 445 | /// See AbstractAttribute::getState() |
| 446 | /// { |
| 447 | AbstractState &getState() override { return *this; } |
| 448 | const AbstractState &getState() const override { return *this; } |
| 449 | /// } |
| 450 | |
| 451 | /// See AbstractAttribute::getManifestPosition(). |
| Johannes Doerfert | c7a1db3 | 2019-07-13 01:09:27 +0000 | [diff] [blame] | 452 | ManifestPosition getManifestPosition() const override { return MP_FUNCTION; } |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 453 | |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 454 | const std::string getAsStr() const override { |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 455 | return getAssumed() ? "nounwind" : "may-unwind"; |
| 456 | } |
| 457 | |
| 458 | /// See AbstractAttribute::updateImpl(...). |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 459 | ChangeStatus updateImpl(Attributor &A) override; |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 460 | |
| 461 | /// See AANoUnwind::isAssumedNoUnwind(). |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 462 | bool isAssumedNoUnwind() const override { return getAssumed(); } |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 463 | |
| 464 | /// See AANoUnwind::isKnownNoUnwind(). |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 465 | bool isKnownNoUnwind() const override { return getKnown(); } |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 466 | }; |
| 467 | |
| 468 | ChangeStatus AANoUnwindFunction::updateImpl(Attributor &A) { |
| 469 | Function &F = getAnchorScope(); |
| 470 | |
| 471 | // The map from instruction opcodes to those instructions in the function. |
| 472 | auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); |
| 473 | auto Opcodes = { |
| 474 | (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, |
| 475 | (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet, |
| 476 | (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume}; |
| 477 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 478 | auto *LivenessAA = A.getAAFor<AAIsDead>(*this, F); |
| 479 | |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 480 | for (unsigned Opcode : Opcodes) { |
| 481 | for (Instruction *I : OpcodeInstMap[Opcode]) { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 482 | // Skip dead instructions. |
| 483 | if (LivenessAA && LivenessAA->isAssumedDead(I)) |
| 484 | continue; |
| 485 | |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 486 | if (!I->mayThrow()) |
| 487 | continue; |
| 488 | |
| 489 | auto *NoUnwindAA = A.getAAFor<AANoUnwind>(*this, *I); |
| 490 | |
| 491 | if (!NoUnwindAA || !NoUnwindAA->isAssumedNoUnwind()) { |
| 492 | indicatePessimisticFixpoint(); |
| 493 | return ChangeStatus::CHANGED; |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | return ChangeStatus::UNCHANGED; |
| 498 | } |
| 499 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 500 | /// --------------------- Function Return Values ------------------------------- |
| 501 | |
| 502 | /// "Attribute" that collects all potential returned values and the return |
| 503 | /// instructions that they arise from. |
| 504 | /// |
| 505 | /// If there is a unique returned value R, the manifest method will: |
| 506 | /// - mark R with the "returned" attribute, if R is an argument. |
| 507 | class AAReturnedValuesImpl final : public AAReturnedValues, AbstractState { |
| 508 | |
| 509 | /// Mapping of values potentially returned by the associated function to the |
| 510 | /// return instructions that might return them. |
| 511 | DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> ReturnedValues; |
| 512 | |
| 513 | /// State flags |
| 514 | /// |
| 515 | ///{ |
| 516 | bool IsFixed; |
| 517 | bool IsValidState; |
| 518 | bool HasOverdefinedReturnedCalls; |
| 519 | ///} |
| 520 | |
| 521 | /// Collect values that could become \p V in the set \p Values, each mapped to |
| 522 | /// \p ReturnInsts. |
| 523 | void collectValuesRecursively( |
| 524 | Attributor &A, Value *V, SmallPtrSetImpl<ReturnInst *> &ReturnInsts, |
| 525 | DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> &Values) { |
| 526 | |
| 527 | visitValueCB_t<bool> VisitValueCB = [&](Value *Val, bool &) { |
| 528 | assert(!isa<Instruction>(Val) || |
| 529 | &getAnchorScope() == cast<Instruction>(Val)->getFunction()); |
| 530 | Values[Val].insert(ReturnInsts.begin(), ReturnInsts.end()); |
| 531 | }; |
| 532 | |
| 533 | bool UnusedBool; |
| 534 | bool Success = genericValueTraversal(V, UnusedBool, VisitValueCB); |
| 535 | |
| 536 | // If we did abort the above traversal we haven't see all the values. |
| 537 | // Consequently, we cannot know if the information we would derive is |
| 538 | // accurate so we give up early. |
| 539 | if (!Success) |
| 540 | indicatePessimisticFixpoint(); |
| 541 | } |
| 542 | |
| 543 | public: |
| 544 | /// See AbstractAttribute::AbstractAttribute(...). |
| 545 | AAReturnedValuesImpl(Function &F, InformationCache &InfoCache) |
| 546 | : AAReturnedValues(F, InfoCache) { |
| 547 | // We do not have an associated argument yet. |
| 548 | AssociatedVal = nullptr; |
| 549 | } |
| 550 | |
| 551 | /// See AbstractAttribute::initialize(...). |
| 552 | void initialize(Attributor &A) override { |
| 553 | // Reset the state. |
| 554 | AssociatedVal = nullptr; |
| 555 | IsFixed = false; |
| 556 | IsValidState = true; |
| 557 | HasOverdefinedReturnedCalls = false; |
| 558 | ReturnedValues.clear(); |
| 559 | |
| 560 | Function &F = cast<Function>(getAnchoredValue()); |
| 561 | |
| 562 | // The map from instruction opcodes to those instructions in the function. |
| 563 | auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); |
| 564 | |
| 565 | // Look through all arguments, if one is marked as returned we are done. |
| 566 | for (Argument &Arg : F.args()) { |
| 567 | if (Arg.hasReturnedAttr()) { |
| 568 | |
| 569 | auto &ReturnInstSet = ReturnedValues[&Arg]; |
| 570 | for (Instruction *RI : OpcodeInstMap[Instruction::Ret]) |
| 571 | ReturnInstSet.insert(cast<ReturnInst>(RI)); |
| 572 | |
| 573 | indicateOptimisticFixpoint(); |
| 574 | return; |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | // If no argument was marked as returned we look at all return instructions |
| 579 | // and collect potentially returned values. |
| 580 | for (Instruction *RI : OpcodeInstMap[Instruction::Ret]) { |
| 581 | SmallPtrSet<ReturnInst *, 1> RISet({cast<ReturnInst>(RI)}); |
| 582 | collectValuesRecursively(A, cast<ReturnInst>(RI)->getReturnValue(), RISet, |
| 583 | ReturnedValues); |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | /// See AbstractAttribute::manifest(...). |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 588 | ChangeStatus manifest(Attributor &A) override; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 589 | |
| 590 | /// See AbstractAttribute::getState(...). |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 591 | AbstractState &getState() override { return *this; } |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 592 | |
| 593 | /// See AbstractAttribute::getState(...). |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 594 | const AbstractState &getState() const override { return *this; } |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 595 | |
| 596 | /// See AbstractAttribute::getManifestPosition(). |
| Johannes Doerfert | c7a1db3 | 2019-07-13 01:09:27 +0000 | [diff] [blame] | 597 | ManifestPosition getManifestPosition() const override { return MP_ARGUMENT; } |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 598 | |
| 599 | /// See AbstractAttribute::updateImpl(Attributor &A). |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 600 | ChangeStatus updateImpl(Attributor &A) override; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 601 | |
| 602 | /// Return the number of potential return values, -1 if unknown. |
| 603 | size_t getNumReturnValues() const { |
| 604 | return isValidState() ? ReturnedValues.size() : -1; |
| 605 | } |
| 606 | |
| 607 | /// Return an assumed unique return value if a single candidate is found. If |
| 608 | /// there cannot be one, return a nullptr. If it is not clear yet, return the |
| 609 | /// Optional::NoneType. |
| Stefan Stipanovic | 7849e41 | 2019-08-03 15:27:41 +0000 | [diff] [blame] | 610 | Optional<Value *> |
| 611 | getAssumedUniqueReturnValue(const AAIsDead *LivenessAA) const; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 612 | |
| 613 | /// See AbstractState::checkForallReturnedValues(...). |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 614 | bool checkForallReturnedValues( |
| 615 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> &Pred) |
| 616 | const override; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 617 | |
| 618 | /// Pretty print the attribute similar to the IR representation. |
| Stefan Stipanovic | 15e86f7 | 2019-07-12 17:42:14 +0000 | [diff] [blame] | 619 | const std::string getAsStr() const override; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 620 | |
| 621 | /// See AbstractState::isAtFixpoint(). |
| 622 | bool isAtFixpoint() const override { return IsFixed; } |
| 623 | |
| 624 | /// See AbstractState::isValidState(). |
| 625 | bool isValidState() const override { return IsValidState; } |
| 626 | |
| 627 | /// See AbstractState::indicateOptimisticFixpoint(...). |
| 628 | void indicateOptimisticFixpoint() override { |
| 629 | IsFixed = true; |
| 630 | IsValidState &= true; |
| 631 | } |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 632 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 633 | void indicatePessimisticFixpoint() override { |
| 634 | IsFixed = true; |
| 635 | IsValidState = false; |
| 636 | } |
| 637 | }; |
| 638 | |
| 639 | ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) { |
| 640 | ChangeStatus Changed = ChangeStatus::UNCHANGED; |
| 641 | |
| 642 | // Bookkeeping. |
| 643 | assert(isValidState()); |
| 644 | NumFnKnownReturns++; |
| 645 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 646 | auto *LivenessAA = A.getAAFor<AAIsDead>(*this, getAnchorScope()); |
| 647 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 648 | // Check if we have an assumed unique return value that we could manifest. |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 649 | Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(LivenessAA); |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 650 | |
| 651 | if (!UniqueRV.hasValue() || !UniqueRV.getValue()) |
| 652 | return Changed; |
| 653 | |
| 654 | // Bookkeeping. |
| 655 | NumFnUniqueReturned++; |
| 656 | |
| 657 | // If the assumed unique return value is an argument, annotate it. |
| 658 | if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) { |
| 659 | AssociatedVal = UniqueRVArg; |
| 660 | Changed = AbstractAttribute::manifest(A) | Changed; |
| 661 | } |
| 662 | |
| 663 | return Changed; |
| 664 | } |
| 665 | |
| 666 | const std::string AAReturnedValuesImpl::getAsStr() const { |
| 667 | return (isAtFixpoint() ? "returns(#" : "may-return(#") + |
| 668 | (isValidState() ? std::to_string(getNumReturnValues()) : "?") + ")"; |
| 669 | } |
| 670 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 671 | Optional<Value *> AAReturnedValuesImpl::getAssumedUniqueReturnValue( |
| 672 | const AAIsDead *LivenessAA) const { |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 673 | // If checkForallReturnedValues provides a unique value, ignoring potential |
| 674 | // undef values that can also be present, it is assumed to be the actual |
| 675 | // return value and forwarded to the caller of this method. If there are |
| 676 | // multiple, a nullptr is returned indicating there cannot be a unique |
| 677 | // returned value. |
| 678 | Optional<Value *> UniqueRV; |
| 679 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 680 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred = |
| 681 | [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 682 | // If all ReturnInsts are dead, then ReturnValue is dead as well |
| 683 | // and can be ignored. |
| 684 | if (LivenessAA && |
| 685 | !LivenessAA->isLiveInstSet(RetInsts.begin(), RetInsts.end())) |
| 686 | return true; |
| 687 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 688 | // If we found a second returned value and neither the current nor the saved |
| 689 | // one is an undef, there is no unique returned value. Undefs are special |
| 690 | // since we can pretend they have any value. |
| 691 | if (UniqueRV.hasValue() && UniqueRV != &RV && |
| 692 | !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) { |
| 693 | UniqueRV = nullptr; |
| 694 | return false; |
| 695 | } |
| 696 | |
| 697 | // Do not overwrite a value with an undef. |
| 698 | if (!UniqueRV.hasValue() || !isa<UndefValue>(RV)) |
| 699 | UniqueRV = &RV; |
| 700 | |
| 701 | return true; |
| 702 | }; |
| 703 | |
| 704 | if (!checkForallReturnedValues(Pred)) |
| 705 | UniqueRV = nullptr; |
| 706 | |
| 707 | return UniqueRV; |
| 708 | } |
| 709 | |
| 710 | bool AAReturnedValuesImpl::checkForallReturnedValues( |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 711 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> &Pred) |
| 712 | const { |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 713 | if (!isValidState()) |
| 714 | return false; |
| 715 | |
| 716 | // Check all returned values but ignore call sites as long as we have not |
| 717 | // encountered an overdefined one during an update. |
| 718 | for (auto &It : ReturnedValues) { |
| 719 | Value *RV = It.first; |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 720 | const SmallPtrSetImpl<ReturnInst *> &RetInsts = It.second; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 721 | |
| 722 | ImmutableCallSite ICS(RV); |
| 723 | if (ICS && !HasOverdefinedReturnedCalls) |
| 724 | continue; |
| 725 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 726 | if (!Pred(*RV, RetInsts)) |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 727 | return false; |
| 728 | } |
| 729 | |
| 730 | return true; |
| 731 | } |
| 732 | |
| 733 | ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) { |
| 734 | |
| 735 | // Check if we know of any values returned by the associated function, |
| 736 | // if not, we are done. |
| 737 | if (getNumReturnValues() == 0) { |
| 738 | indicateOptimisticFixpoint(); |
| 739 | return ChangeStatus::UNCHANGED; |
| 740 | } |
| 741 | |
| 742 | // Check if any of the returned values is a call site we can refine. |
| 743 | decltype(ReturnedValues) AddRVs; |
| 744 | bool HasCallSite = false; |
| 745 | |
| Johannes Doerfert | da4d811 | 2019-08-01 16:21:54 +0000 | [diff] [blame] | 746 | // Keep track of any change to trigger updates on dependent attributes. |
| 747 | ChangeStatus Changed = ChangeStatus::UNCHANGED; |
| 748 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 749 | auto *LivenessAA = A.getAAFor<AAIsDead>(*this, getAnchorScope()); |
| 750 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 751 | // Look at all returned call sites. |
| 752 | for (auto &It : ReturnedValues) { |
| 753 | SmallPtrSet<ReturnInst *, 2> &ReturnInsts = It.second; |
| 754 | Value *RV = It.first; |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 755 | |
| 756 | // Ignore dead ReturnValues. |
| Stefan Stipanovic | 7849e41 | 2019-08-03 15:27:41 +0000 | [diff] [blame] | 757 | if (LivenessAA && |
| 758 | !LivenessAA->isLiveInstSet(ReturnInsts.begin(), ReturnInsts.end())) |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 759 | continue; |
| 760 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 761 | LLVM_DEBUG(dbgs() << "[AAReturnedValues] Potentially returned value " << *RV |
| 762 | << "\n"); |
| 763 | |
| 764 | // Only call sites can change during an update, ignore the rest. |
| 765 | CallSite RetCS(RV); |
| 766 | if (!RetCS) |
| 767 | continue; |
| 768 | |
| 769 | // For now, any call site we see will prevent us from directly fixing the |
| 770 | // state. However, if the information on the callees is fixed, the call |
| 771 | // sites will be removed and we will fix the information for this state. |
| 772 | HasCallSite = true; |
| 773 | |
| 774 | // Try to find a assumed unique return value for the called function. |
| 775 | auto *RetCSAA = A.getAAFor<AAReturnedValuesImpl>(*this, *RV); |
| Johannes Doerfert | 0a7f4cd | 2019-07-13 01:09:21 +0000 | [diff] [blame] | 776 | if (!RetCSAA) { |
| Johannes Doerfert | da4d811 | 2019-08-01 16:21:54 +0000 | [diff] [blame] | 777 | if (!HasOverdefinedReturnedCalls) |
| 778 | Changed = ChangeStatus::CHANGED; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 779 | HasOverdefinedReturnedCalls = true; |
| 780 | LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned call site (" << *RV |
| 781 | << ") with " << (RetCSAA ? "invalid" : "no") |
| 782 | << " associated state\n"); |
| 783 | continue; |
| 784 | } |
| 785 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 786 | auto *LivenessCSAA = A.getAAFor<AAIsDead>(*this, RetCSAA->getAnchorScope()); |
| 787 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 788 | // Try to find a assumed unique return value for the called function. |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 789 | Optional<Value *> AssumedUniqueRV = |
| 790 | RetCSAA->getAssumedUniqueReturnValue(LivenessCSAA); |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 791 | |
| 792 | // If no assumed unique return value was found due to the lack of |
| 793 | // candidates, we may need to resolve more calls (through more update |
| 794 | // iterations) or the called function will not return. Either way, we simply |
| 795 | // stick with the call sites as return values. Because there were not |
| 796 | // multiple possibilities, we do not treat it as overdefined. |
| 797 | if (!AssumedUniqueRV.hasValue()) |
| 798 | continue; |
| 799 | |
| 800 | // If multiple, non-refinable values were found, there cannot be a unique |
| 801 | // return value for the called function. The returned call is overdefined! |
| 802 | if (!AssumedUniqueRV.getValue()) { |
| Johannes Doerfert | da4d811 | 2019-08-01 16:21:54 +0000 | [diff] [blame] | 803 | if (!HasOverdefinedReturnedCalls) |
| 804 | Changed = ChangeStatus::CHANGED; |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 805 | HasOverdefinedReturnedCalls = true; |
| 806 | LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned call site has multiple " |
| 807 | "potentially returned values\n"); |
| 808 | continue; |
| 809 | } |
| 810 | |
| 811 | LLVM_DEBUG({ |
| 812 | bool UniqueRVIsKnown = RetCSAA->isAtFixpoint(); |
| 813 | dbgs() << "[AAReturnedValues] Returned call site " |
| 814 | << (UniqueRVIsKnown ? "known" : "assumed") |
| 815 | << " unique return value: " << *AssumedUniqueRV << "\n"; |
| 816 | }); |
| 817 | |
| 818 | // The assumed unique return value. |
| 819 | Value *AssumedRetVal = AssumedUniqueRV.getValue(); |
| 820 | |
| 821 | // If the assumed unique return value is an argument, lookup the matching |
| 822 | // call site operand and recursively collect new returned values. |
| 823 | // If it is not an argument, it is just put into the set of returned values |
| 824 | // as we would have already looked through casts, phis, and similar values. |
| 825 | if (Argument *AssumedRetArg = dyn_cast<Argument>(AssumedRetVal)) |
| 826 | collectValuesRecursively(A, |
| 827 | RetCS.getArgOperand(AssumedRetArg->getArgNo()), |
| 828 | ReturnInsts, AddRVs); |
| 829 | else |
| 830 | AddRVs[AssumedRetVal].insert(ReturnInsts.begin(), ReturnInsts.end()); |
| 831 | } |
| 832 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 833 | for (auto &It : AddRVs) { |
| 834 | assert(!It.second.empty() && "Entry does not add anything."); |
| 835 | auto &ReturnInsts = ReturnedValues[It.first]; |
| 836 | for (ReturnInst *RI : It.second) |
| 837 | if (ReturnInsts.insert(RI).second) { |
| 838 | LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value " |
| 839 | << *It.first << " => " << *RI << "\n"); |
| 840 | Changed = ChangeStatus::CHANGED; |
| 841 | } |
| 842 | } |
| 843 | |
| 844 | // If there is no call site in the returned values we are done. |
| 845 | if (!HasCallSite) { |
| 846 | indicateOptimisticFixpoint(); |
| 847 | return ChangeStatus::CHANGED; |
| 848 | } |
| 849 | |
| 850 | return Changed; |
| 851 | } |
| 852 | |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 853 | /// ------------------------ NoSync Function Attribute ------------------------- |
| 854 | |
| 855 | struct AANoSyncFunction : AANoSync, BooleanState { |
| 856 | |
| 857 | AANoSyncFunction(Function &F, InformationCache &InfoCache) |
| 858 | : AANoSync(F, InfoCache) {} |
| 859 | |
| 860 | /// See AbstractAttribute::getState() |
| 861 | /// { |
| 862 | AbstractState &getState() override { return *this; } |
| 863 | const AbstractState &getState() const override { return *this; } |
| 864 | /// } |
| 865 | |
| 866 | /// See AbstractAttribute::getManifestPosition(). |
| Johannes Doerfert | c7a1db3 | 2019-07-13 01:09:27 +0000 | [diff] [blame] | 867 | ManifestPosition getManifestPosition() const override { return MP_FUNCTION; } |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 868 | |
| Stefan Stipanovic | cb5ecae | 2019-07-12 18:34:06 +0000 | [diff] [blame] | 869 | const std::string getAsStr() const override { |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 870 | return getAssumed() ? "nosync" : "may-sync"; |
| 871 | } |
| 872 | |
| 873 | /// See AbstractAttribute::updateImpl(...). |
| Stefan Stipanovic | cb5ecae | 2019-07-12 18:34:06 +0000 | [diff] [blame] | 874 | ChangeStatus updateImpl(Attributor &A) override; |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 875 | |
| 876 | /// See AANoSync::isAssumedNoSync() |
| Stefan Stipanovic | cb5ecae | 2019-07-12 18:34:06 +0000 | [diff] [blame] | 877 | bool isAssumedNoSync() const override { return getAssumed(); } |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 878 | |
| 879 | /// See AANoSync::isKnownNoSync() |
| Stefan Stipanovic | cb5ecae | 2019-07-12 18:34:06 +0000 | [diff] [blame] | 880 | bool isKnownNoSync() const override { return getKnown(); } |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 881 | |
| 882 | /// Helper function used to determine whether an instruction is non-relaxed |
| 883 | /// atomic. In other words, if an atomic instruction does not have unordered |
| 884 | /// or monotonic ordering |
| 885 | static bool isNonRelaxedAtomic(Instruction *I); |
| 886 | |
| 887 | /// Helper function used to determine whether an instruction is volatile. |
| 888 | static bool isVolatile(Instruction *I); |
| 889 | |
| Johannes Doerfert | c7a1db3 | 2019-07-13 01:09:27 +0000 | [diff] [blame] | 890 | /// Helper function uset to check if intrinsic is volatile (memcpy, memmove, |
| 891 | /// memset). |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 892 | static bool isNoSyncIntrinsic(Instruction *I); |
| 893 | }; |
| 894 | |
| 895 | bool AANoSyncFunction::isNonRelaxedAtomic(Instruction *I) { |
| 896 | if (!I->isAtomic()) |
| 897 | return false; |
| 898 | |
| 899 | AtomicOrdering Ordering; |
| 900 | switch (I->getOpcode()) { |
| 901 | case Instruction::AtomicRMW: |
| 902 | Ordering = cast<AtomicRMWInst>(I)->getOrdering(); |
| 903 | break; |
| 904 | case Instruction::Store: |
| 905 | Ordering = cast<StoreInst>(I)->getOrdering(); |
| 906 | break; |
| 907 | case Instruction::Load: |
| 908 | Ordering = cast<LoadInst>(I)->getOrdering(); |
| 909 | break; |
| 910 | case Instruction::Fence: { |
| 911 | auto *FI = cast<FenceInst>(I); |
| 912 | if (FI->getSyncScopeID() == SyncScope::SingleThread) |
| 913 | return false; |
| 914 | Ordering = FI->getOrdering(); |
| 915 | break; |
| 916 | } |
| 917 | case Instruction::AtomicCmpXchg: { |
| 918 | AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering(); |
| 919 | AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering(); |
| 920 | // Only if both are relaxed, than it can be treated as relaxed. |
| 921 | // Otherwise it is non-relaxed. |
| 922 | if (Success != AtomicOrdering::Unordered && |
| 923 | Success != AtomicOrdering::Monotonic) |
| 924 | return true; |
| 925 | if (Failure != AtomicOrdering::Unordered && |
| 926 | Failure != AtomicOrdering::Monotonic) |
| 927 | return true; |
| 928 | return false; |
| 929 | } |
| 930 | default: |
| 931 | llvm_unreachable( |
| 932 | "New atomic operations need to be known in the attributor."); |
| 933 | } |
| 934 | |
| 935 | // Relaxed. |
| 936 | if (Ordering == AtomicOrdering::Unordered || |
| 937 | Ordering == AtomicOrdering::Monotonic) |
| 938 | return false; |
| 939 | return true; |
| 940 | } |
| 941 | |
| 942 | /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics. |
| 943 | /// FIXME: We should ipmrove the handling of intrinsics. |
| 944 | bool AANoSyncFunction::isNoSyncIntrinsic(Instruction *I) { |
| 945 | if (auto *II = dyn_cast<IntrinsicInst>(I)) { |
| 946 | switch (II->getIntrinsicID()) { |
| 947 | /// Element wise atomic memory intrinsics are can only be unordered, |
| 948 | /// therefore nosync. |
| 949 | case Intrinsic::memset_element_unordered_atomic: |
| 950 | case Intrinsic::memmove_element_unordered_atomic: |
| 951 | case Intrinsic::memcpy_element_unordered_atomic: |
| 952 | return true; |
| 953 | case Intrinsic::memset: |
| 954 | case Intrinsic::memmove: |
| 955 | case Intrinsic::memcpy: |
| 956 | if (!cast<MemIntrinsic>(II)->isVolatile()) |
| 957 | return true; |
| 958 | return false; |
| 959 | default: |
| 960 | return false; |
| 961 | } |
| 962 | } |
| 963 | return false; |
| 964 | } |
| 965 | |
| 966 | bool AANoSyncFunction::isVolatile(Instruction *I) { |
| 967 | assert(!ImmutableCallSite(I) && !isa<CallBase>(I) && |
| 968 | "Calls should not be checked here"); |
| 969 | |
| 970 | switch (I->getOpcode()) { |
| 971 | case Instruction::AtomicRMW: |
| 972 | return cast<AtomicRMWInst>(I)->isVolatile(); |
| 973 | case Instruction::Store: |
| 974 | return cast<StoreInst>(I)->isVolatile(); |
| 975 | case Instruction::Load: |
| 976 | return cast<LoadInst>(I)->isVolatile(); |
| 977 | case Instruction::AtomicCmpXchg: |
| 978 | return cast<AtomicCmpXchgInst>(I)->isVolatile(); |
| 979 | default: |
| 980 | return false; |
| 981 | } |
| 982 | } |
| 983 | |
| 984 | ChangeStatus AANoSyncFunction::updateImpl(Attributor &A) { |
| 985 | Function &F = getAnchorScope(); |
| 986 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 987 | auto *LivenessAA = A.getAAFor<AAIsDead>(*this, F); |
| 988 | |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 989 | /// We are looking for volatile instructions or Non-Relaxed atomics. |
| 990 | /// FIXME: We should ipmrove the handling of intrinsics. |
| 991 | for (Instruction *I : InfoCache.getReadOrWriteInstsForFunction(F)) { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 992 | // Skip assumed dead instructions. |
| 993 | if (LivenessAA && LivenessAA->isAssumedDead(I)) |
| 994 | continue; |
| 995 | |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 996 | ImmutableCallSite ICS(I); |
| 997 | auto *NoSyncAA = A.getAAFor<AANoSyncFunction>(*this, *I); |
| 998 | |
| 999 | if (isa<IntrinsicInst>(I) && isNoSyncIntrinsic(I)) |
| Johannes Doerfert | c7a1db3 | 2019-07-13 01:09:27 +0000 | [diff] [blame] | 1000 | continue; |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 1001 | |
| 1002 | if (ICS && (!NoSyncAA || !NoSyncAA->isAssumedNoSync()) && |
| 1003 | !ICS.hasFnAttr(Attribute::NoSync)) { |
| 1004 | indicatePessimisticFixpoint(); |
| 1005 | return ChangeStatus::CHANGED; |
| 1006 | } |
| 1007 | |
| Johannes Doerfert | c7a1db3 | 2019-07-13 01:09:27 +0000 | [diff] [blame] | 1008 | if (ICS) |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 1009 | continue; |
| 1010 | |
| 1011 | if (!isVolatile(I) && !isNonRelaxedAtomic(I)) |
| 1012 | continue; |
| 1013 | |
| 1014 | indicatePessimisticFixpoint(); |
| 1015 | return ChangeStatus::CHANGED; |
| 1016 | } |
| 1017 | |
| 1018 | auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); |
| 1019 | auto Opcodes = {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, |
| 1020 | (unsigned)Instruction::Call}; |
| 1021 | |
| 1022 | for (unsigned Opcode : Opcodes) { |
| 1023 | for (Instruction *I : OpcodeInstMap[Opcode]) { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1024 | // Skip assumed dead instructions. |
| 1025 | if (LivenessAA && LivenessAA->isAssumedDead(I)) |
| 1026 | continue; |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 1027 | // At this point we handled all read/write effects and they are all |
| 1028 | // nosync, so they can be skipped. |
| 1029 | if (I->mayReadOrWriteMemory()) |
| 1030 | continue; |
| 1031 | |
| 1032 | ImmutableCallSite ICS(I); |
| 1033 | |
| 1034 | // non-convergent and readnone imply nosync. |
| 1035 | if (!ICS.isConvergent()) |
| 1036 | continue; |
| 1037 | |
| 1038 | indicatePessimisticFixpoint(); |
| 1039 | return ChangeStatus::CHANGED; |
| 1040 | } |
| 1041 | } |
| 1042 | |
| 1043 | return ChangeStatus::UNCHANGED; |
| 1044 | } |
| 1045 | |
| Hideto Ueno | 65bbaf9 | 2019-07-12 17:38:51 +0000 | [diff] [blame] | 1046 | /// ------------------------ No-Free Attributes ---------------------------- |
| 1047 | |
| 1048 | struct AANoFreeFunction : AbstractAttribute, BooleanState { |
| 1049 | |
| 1050 | /// See AbstractAttribute::AbstractAttribute(...). |
| 1051 | AANoFreeFunction(Function &F, InformationCache &InfoCache) |
| 1052 | : AbstractAttribute(F, InfoCache) {} |
| 1053 | |
| 1054 | /// See AbstractAttribute::getState() |
| 1055 | ///{ |
| 1056 | AbstractState &getState() override { return *this; } |
| 1057 | const AbstractState &getState() const override { return *this; } |
| 1058 | ///} |
| 1059 | |
| 1060 | /// See AbstractAttribute::getManifestPosition(). |
| 1061 | ManifestPosition getManifestPosition() const override { return MP_FUNCTION; } |
| 1062 | |
| 1063 | /// See AbstractAttribute::getAsStr(). |
| 1064 | const std::string getAsStr() const override { |
| 1065 | return getAssumed() ? "nofree" : "may-free"; |
| 1066 | } |
| 1067 | |
| 1068 | /// See AbstractAttribute::updateImpl(...). |
| 1069 | ChangeStatus updateImpl(Attributor &A) override; |
| 1070 | |
| 1071 | /// See AbstractAttribute::getAttrKind(). |
| 1072 | Attribute::AttrKind getAttrKind() const override { return ID; } |
| 1073 | |
| 1074 | /// Return true if "nofree" is assumed. |
| 1075 | bool isAssumedNoFree() const { return getAssumed(); } |
| 1076 | |
| 1077 | /// Return true if "nofree" is known. |
| 1078 | bool isKnownNoFree() const { return getKnown(); } |
| 1079 | |
| 1080 | /// The identifier used by the Attributor for this class of attributes. |
| 1081 | static constexpr Attribute::AttrKind ID = Attribute::NoFree; |
| 1082 | }; |
| 1083 | |
| 1084 | ChangeStatus AANoFreeFunction::updateImpl(Attributor &A) { |
| 1085 | Function &F = getAnchorScope(); |
| 1086 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1087 | auto *LivenessAA = A.getAAFor<AAIsDead>(*this, F); |
| 1088 | |
| Hideto Ueno | 65bbaf9 | 2019-07-12 17:38:51 +0000 | [diff] [blame] | 1089 | // The map from instruction opcodes to those instructions in the function. |
| 1090 | auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); |
| 1091 | |
| 1092 | for (unsigned Opcode : |
| 1093 | {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, |
| 1094 | (unsigned)Instruction::Call}) { |
| 1095 | for (Instruction *I : OpcodeInstMap[Opcode]) { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1096 | // Skip assumed dead instructions. |
| 1097 | if (LivenessAA && LivenessAA->isAssumedDead(I)) |
| 1098 | continue; |
| Hideto Ueno | 65bbaf9 | 2019-07-12 17:38:51 +0000 | [diff] [blame] | 1099 | auto ICS = ImmutableCallSite(I); |
| 1100 | auto *NoFreeAA = A.getAAFor<AANoFreeFunction>(*this, *I); |
| 1101 | |
| Johannes Doerfert | 0a7f4cd | 2019-07-13 01:09:21 +0000 | [diff] [blame] | 1102 | if ((!NoFreeAA || !NoFreeAA->isAssumedNoFree()) && |
| Hideto Ueno | 65bbaf9 | 2019-07-12 17:38:51 +0000 | [diff] [blame] | 1103 | !ICS.hasFnAttr(Attribute::NoFree)) { |
| 1104 | indicatePessimisticFixpoint(); |
| 1105 | return ChangeStatus::CHANGED; |
| 1106 | } |
| 1107 | } |
| 1108 | } |
| 1109 | return ChangeStatus::UNCHANGED; |
| 1110 | } |
| 1111 | |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1112 | /// ------------------------ NonNull Argument Attribute ------------------------ |
| 1113 | struct AANonNullImpl : AANonNull, BooleanState { |
| 1114 | |
| 1115 | AANonNullImpl(Value &V, InformationCache &InfoCache) |
| 1116 | : AANonNull(V, InfoCache) {} |
| 1117 | |
| 1118 | AANonNullImpl(Value *AssociatedVal, Value &AnchoredValue, |
| 1119 | InformationCache &InfoCache) |
| 1120 | : AANonNull(AssociatedVal, AnchoredValue, InfoCache) {} |
| 1121 | |
| 1122 | /// See AbstractAttribute::getState() |
| 1123 | /// { |
| 1124 | AbstractState &getState() override { return *this; } |
| 1125 | const AbstractState &getState() const override { return *this; } |
| 1126 | /// } |
| 1127 | |
| 1128 | /// See AbstractAttribute::getAsStr(). |
| 1129 | const std::string getAsStr() const override { |
| 1130 | return getAssumed() ? "nonnull" : "may-null"; |
| 1131 | } |
| 1132 | |
| 1133 | /// See AANonNull::isAssumedNonNull(). |
| 1134 | bool isAssumedNonNull() const override { return getAssumed(); } |
| 1135 | |
| 1136 | /// See AANonNull::isKnownNonNull(). |
| 1137 | bool isKnownNonNull() const override { return getKnown(); } |
| 1138 | |
| 1139 | /// Generate a predicate that checks if a given value is assumed nonnull. |
| 1140 | /// The generated function returns true if a value satisfies any of |
| 1141 | /// following conditions. |
| 1142 | /// (i) A value is known nonZero(=nonnull). |
| 1143 | /// (ii) A value is associated with AANonNull and its isAssumedNonNull() is |
| 1144 | /// true. |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1145 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> |
| 1146 | generatePredicate(Attributor &); |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1147 | }; |
| 1148 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1149 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> |
| 1150 | AANonNullImpl::generatePredicate(Attributor &A) { |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1151 | // FIXME: The `AAReturnedValues` should provide the predicate with the |
| 1152 | // `ReturnInst` vector as well such that we can use the control flow sensitive |
| 1153 | // version of `isKnownNonZero`. This should fix `test11` in |
| 1154 | // `test/Transforms/FunctionAttrs/nonnull.ll` |
| 1155 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1156 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred = |
| 1157 | [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool { |
| 1158 | Function &F = getAnchorScope(); |
| 1159 | |
| 1160 | if (isKnownNonZero(&RV, F.getParent()->getDataLayout())) |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1161 | return true; |
| 1162 | |
| 1163 | auto *NonNullAA = A.getAAFor<AANonNull>(*this, RV); |
| 1164 | |
| 1165 | ImmutableCallSite ICS(&RV); |
| 1166 | |
| 1167 | if ((!NonNullAA || !NonNullAA->isAssumedNonNull()) && |
| 1168 | (!ICS || !ICS.hasRetAttr(Attribute::NonNull))) |
| 1169 | return false; |
| 1170 | |
| 1171 | return true; |
| 1172 | }; |
| 1173 | |
| 1174 | return Pred; |
| 1175 | } |
| 1176 | |
| 1177 | /// NonNull attribute for function return value. |
| 1178 | struct AANonNullReturned : AANonNullImpl { |
| 1179 | |
| 1180 | AANonNullReturned(Function &F, InformationCache &InfoCache) |
| 1181 | : AANonNullImpl(F, InfoCache) {} |
| 1182 | |
| 1183 | /// See AbstractAttribute::getManifestPosition(). |
| 1184 | ManifestPosition getManifestPosition() const override { return MP_RETURNED; } |
| 1185 | |
| 1186 | /// See AbstractAttriubute::initialize(...). |
| 1187 | void initialize(Attributor &A) override { |
| 1188 | Function &F = getAnchorScope(); |
| 1189 | |
| 1190 | // Already nonnull. |
| 1191 | if (F.getAttributes().hasAttribute(AttributeList::ReturnIndex, |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 1192 | Attribute::NonNull) || |
| 1193 | F.getAttributes().hasAttribute(AttributeList::ReturnIndex, |
| 1194 | Attribute::Dereferenceable)) |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1195 | indicateOptimisticFixpoint(); |
| 1196 | } |
| 1197 | |
| 1198 | /// See AbstractAttribute::updateImpl(...). |
| 1199 | ChangeStatus updateImpl(Attributor &A) override; |
| 1200 | }; |
| 1201 | |
| 1202 | ChangeStatus AANonNullReturned::updateImpl(Attributor &A) { |
| 1203 | Function &F = getAnchorScope(); |
| 1204 | |
| 1205 | auto *AARetVal = A.getAAFor<AAReturnedValues>(*this, F); |
| 1206 | if (!AARetVal) { |
| 1207 | indicatePessimisticFixpoint(); |
| 1208 | return ChangeStatus::CHANGED; |
| 1209 | } |
| 1210 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1211 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred = |
| 1212 | this->generatePredicate(A); |
| 1213 | |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1214 | if (!AARetVal->checkForallReturnedValues(Pred)) { |
| 1215 | indicatePessimisticFixpoint(); |
| 1216 | return ChangeStatus::CHANGED; |
| 1217 | } |
| 1218 | return ChangeStatus::UNCHANGED; |
| 1219 | } |
| 1220 | |
| 1221 | /// NonNull attribute for function argument. |
| 1222 | struct AANonNullArgument : AANonNullImpl { |
| 1223 | |
| 1224 | AANonNullArgument(Argument &A, InformationCache &InfoCache) |
| 1225 | : AANonNullImpl(A, InfoCache) {} |
| 1226 | |
| 1227 | /// See AbstractAttribute::getManifestPosition(). |
| 1228 | ManifestPosition getManifestPosition() const override { return MP_ARGUMENT; } |
| 1229 | |
| 1230 | /// See AbstractAttriubute::initialize(...). |
| 1231 | void initialize(Attributor &A) override { |
| 1232 | Argument *Arg = cast<Argument>(getAssociatedValue()); |
| 1233 | if (Arg->hasNonNullAttr()) |
| 1234 | indicateOptimisticFixpoint(); |
| 1235 | } |
| 1236 | |
| 1237 | /// See AbstractAttribute::updateImpl(...). |
| 1238 | ChangeStatus updateImpl(Attributor &A) override; |
| 1239 | }; |
| 1240 | |
| 1241 | /// NonNull attribute for a call site argument. |
| 1242 | struct AANonNullCallSiteArgument : AANonNullImpl { |
| 1243 | |
| 1244 | /// See AANonNullImpl::AANonNullImpl(...). |
| 1245 | AANonNullCallSiteArgument(CallSite CS, unsigned ArgNo, |
| 1246 | InformationCache &InfoCache) |
| 1247 | : AANonNullImpl(CS.getArgOperand(ArgNo), *CS.getInstruction(), InfoCache), |
| 1248 | ArgNo(ArgNo) {} |
| 1249 | |
| 1250 | /// See AbstractAttribute::initialize(...). |
| 1251 | void initialize(Attributor &A) override { |
| 1252 | CallSite CS(&getAnchoredValue()); |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 1253 | if (CS.paramHasAttr(ArgNo, getAttrKind()) || |
| 1254 | CS.paramHasAttr(ArgNo, Attribute::Dereferenceable) || |
| 1255 | isKnownNonZero(getAssociatedValue(), |
| 1256 | getAnchorScope().getParent()->getDataLayout())) |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1257 | indicateOptimisticFixpoint(); |
| 1258 | } |
| 1259 | |
| 1260 | /// See AbstractAttribute::updateImpl(Attributor &A). |
| 1261 | ChangeStatus updateImpl(Attributor &A) override; |
| 1262 | |
| 1263 | /// See AbstractAttribute::getManifestPosition(). |
| 1264 | ManifestPosition getManifestPosition() const override { |
| 1265 | return MP_CALL_SITE_ARGUMENT; |
| 1266 | }; |
| 1267 | |
| 1268 | // Return argument index of associated value. |
| 1269 | int getArgNo() const { return ArgNo; } |
| 1270 | |
| 1271 | private: |
| 1272 | unsigned ArgNo; |
| 1273 | }; |
| 1274 | ChangeStatus AANonNullArgument::updateImpl(Attributor &A) { |
| 1275 | Function &F = getAnchorScope(); |
| 1276 | Argument &Arg = cast<Argument>(getAnchoredValue()); |
| 1277 | |
| 1278 | unsigned ArgNo = Arg.getArgNo(); |
| 1279 | |
| 1280 | // Callback function |
| 1281 | std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) { |
| 1282 | assert(CS && "Sanity check: Call site was not initialized properly!"); |
| 1283 | |
| 1284 | auto *NonNullAA = A.getAAFor<AANonNull>(*this, *CS.getInstruction(), ArgNo); |
| 1285 | |
| 1286 | // Check that NonNullAA is AANonNullCallSiteArgument. |
| 1287 | if (NonNullAA) { |
| 1288 | ImmutableCallSite ICS(&NonNullAA->getAnchoredValue()); |
| 1289 | if (ICS && CS.getInstruction() == ICS.getInstruction()) |
| 1290 | return NonNullAA->isAssumedNonNull(); |
| 1291 | return false; |
| 1292 | } |
| 1293 | |
| 1294 | if (CS.paramHasAttr(ArgNo, Attribute::NonNull)) |
| 1295 | return true; |
| 1296 | |
| 1297 | Value *V = CS.getArgOperand(ArgNo); |
| 1298 | if (isKnownNonZero(V, getAnchorScope().getParent()->getDataLayout())) |
| 1299 | return true; |
| 1300 | |
| 1301 | return false; |
| 1302 | }; |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1303 | if (!A.checkForAllCallSites(F, CallSiteCheck, true, *this)) { |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 1304 | indicatePessimisticFixpoint(); |
| 1305 | return ChangeStatus::CHANGED; |
| 1306 | } |
| 1307 | return ChangeStatus::UNCHANGED; |
| 1308 | } |
| 1309 | |
| 1310 | ChangeStatus AANonNullCallSiteArgument::updateImpl(Attributor &A) { |
| 1311 | // NOTE: Never look at the argument of the callee in this method. |
| 1312 | // If we do this, "nonnull" is always deduced because of the assumption. |
| 1313 | |
| 1314 | Value &V = *getAssociatedValue(); |
| 1315 | |
| 1316 | auto *NonNullAA = A.getAAFor<AANonNull>(*this, V); |
| 1317 | |
| 1318 | if (!NonNullAA || !NonNullAA->isAssumedNonNull()) { |
| 1319 | indicatePessimisticFixpoint(); |
| 1320 | return ChangeStatus::CHANGED; |
| 1321 | } |
| 1322 | |
| 1323 | return ChangeStatus::UNCHANGED; |
| 1324 | } |
| 1325 | |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 1326 | /// ------------------------ Will-Return Attributes ---------------------------- |
| 1327 | |
| 1328 | struct AAWillReturnImpl : public AAWillReturn, BooleanState { |
| 1329 | |
| 1330 | /// See AbstractAttribute::AbstractAttribute(...). |
| 1331 | AAWillReturnImpl(Function &F, InformationCache &InfoCache) |
| 1332 | : AAWillReturn(F, InfoCache) {} |
| 1333 | |
| 1334 | /// See AAWillReturn::isKnownWillReturn(). |
| 1335 | bool isKnownWillReturn() const override { return getKnown(); } |
| 1336 | |
| 1337 | /// See AAWillReturn::isAssumedWillReturn(). |
| 1338 | bool isAssumedWillReturn() const override { return getAssumed(); } |
| 1339 | |
| 1340 | /// See AbstractAttribute::getState(...). |
| 1341 | AbstractState &getState() override { return *this; } |
| 1342 | |
| 1343 | /// See AbstractAttribute::getState(...). |
| 1344 | const AbstractState &getState() const override { return *this; } |
| 1345 | |
| 1346 | /// See AbstractAttribute::getAsStr() |
| 1347 | const std::string getAsStr() const override { |
| 1348 | return getAssumed() ? "willreturn" : "may-noreturn"; |
| 1349 | } |
| 1350 | }; |
| 1351 | |
| 1352 | struct AAWillReturnFunction final : AAWillReturnImpl { |
| 1353 | |
| 1354 | /// See AbstractAttribute::AbstractAttribute(...). |
| 1355 | AAWillReturnFunction(Function &F, InformationCache &InfoCache) |
| 1356 | : AAWillReturnImpl(F, InfoCache) {} |
| 1357 | |
| 1358 | /// See AbstractAttribute::getManifestPosition(). |
| Hideto Ueno | 9f5d80d | 2019-07-23 08:29:22 +0000 | [diff] [blame] | 1359 | ManifestPosition getManifestPosition() const override { return MP_FUNCTION; } |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 1360 | |
| 1361 | /// See AbstractAttribute::initialize(...). |
| 1362 | void initialize(Attributor &A) override; |
| 1363 | |
| 1364 | /// See AbstractAttribute::updateImpl(...). |
| 1365 | ChangeStatus updateImpl(Attributor &A) override; |
| 1366 | }; |
| 1367 | |
| 1368 | // Helper function that checks whether a function has any cycle. |
| 1369 | // TODO: Replace with more efficent code |
| 1370 | bool containsCycle(Function &F) { |
| 1371 | SmallPtrSet<BasicBlock *, 32> Visited; |
| 1372 | |
| 1373 | // Traverse BB by dfs and check whether successor is already visited. |
| 1374 | for (BasicBlock *BB : depth_first(&F)) { |
| 1375 | Visited.insert(BB); |
| 1376 | for (auto *SuccBB : successors(BB)) { |
| 1377 | if (Visited.count(SuccBB)) |
| 1378 | return true; |
| 1379 | } |
| 1380 | } |
| 1381 | return false; |
| 1382 | } |
| 1383 | |
| 1384 | // Helper function that checks the function have a loop which might become an |
| 1385 | // endless loop |
| 1386 | // FIXME: Any cycle is regarded as endless loop for now. |
| 1387 | // We have to allow some patterns. |
| 1388 | bool containsPossiblyEndlessLoop(Function &F) { return containsCycle(F); } |
| 1389 | |
| 1390 | void AAWillReturnFunction::initialize(Attributor &A) { |
| 1391 | Function &F = getAnchorScope(); |
| 1392 | |
| 1393 | if (containsPossiblyEndlessLoop(F)) |
| 1394 | indicatePessimisticFixpoint(); |
| 1395 | } |
| 1396 | |
| 1397 | ChangeStatus AAWillReturnFunction::updateImpl(Attributor &A) { |
| 1398 | Function &F = getAnchorScope(); |
| 1399 | |
| 1400 | // The map from instruction opcodes to those instructions in the function. |
| 1401 | auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); |
| 1402 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1403 | auto *LivenessAA = A.getAAFor<AAIsDead>(*this, F); |
| 1404 | |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 1405 | for (unsigned Opcode : |
| 1406 | {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, |
| 1407 | (unsigned)Instruction::Call}) { |
| 1408 | for (Instruction *I : OpcodeInstMap[Opcode]) { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1409 | // Skip assumed dead instructions. |
| 1410 | if (LivenessAA && LivenessAA->isAssumedDead(I)) |
| 1411 | continue; |
| 1412 | |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 1413 | auto ICS = ImmutableCallSite(I); |
| 1414 | |
| 1415 | if (ICS.hasFnAttr(Attribute::WillReturn)) |
| 1416 | continue; |
| 1417 | |
| 1418 | auto *WillReturnAA = A.getAAFor<AAWillReturn>(*this, *I); |
| 1419 | if (!WillReturnAA || !WillReturnAA->isAssumedWillReturn()) { |
| 1420 | indicatePessimisticFixpoint(); |
| 1421 | return ChangeStatus::CHANGED; |
| 1422 | } |
| 1423 | |
| 1424 | auto *NoRecurseAA = A.getAAFor<AANoRecurse>(*this, *I); |
| 1425 | |
| 1426 | // FIXME: (i) Prohibit any recursion for now. |
| 1427 | // (ii) AANoRecurse isn't implemented yet so currently any call is |
| 1428 | // regarded as having recursion. |
| 1429 | // Code below should be |
| 1430 | // if ((!NoRecurseAA || !NoRecurseAA->isAssumedNoRecurse()) && |
| 1431 | if (!NoRecurseAA && !ICS.hasFnAttr(Attribute::NoRecurse)) { |
| 1432 | indicatePessimisticFixpoint(); |
| 1433 | return ChangeStatus::CHANGED; |
| 1434 | } |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | return ChangeStatus::UNCHANGED; |
| 1439 | } |
| 1440 | |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 1441 | /// ------------------------ NoAlias Argument Attribute ------------------------ |
| 1442 | |
| 1443 | struct AANoAliasImpl : AANoAlias, BooleanState { |
| 1444 | |
| 1445 | AANoAliasImpl(Value &V, InformationCache &InfoCache) |
| 1446 | : AANoAlias(V, InfoCache) {} |
| 1447 | |
| 1448 | /// See AbstractAttribute::getState() |
| 1449 | /// { |
| 1450 | AbstractState &getState() override { return *this; } |
| 1451 | const AbstractState &getState() const override { return *this; } |
| 1452 | /// } |
| 1453 | |
| 1454 | const std::string getAsStr() const override { |
| 1455 | return getAssumed() ? "noalias" : "may-alias"; |
| 1456 | } |
| 1457 | |
| 1458 | /// See AANoAlias::isAssumedNoAlias(). |
| 1459 | bool isAssumedNoAlias() const override { return getAssumed(); } |
| 1460 | |
| 1461 | /// See AANoAlias::isKnowndNoAlias(). |
| 1462 | bool isKnownNoAlias() const override { return getKnown(); } |
| 1463 | }; |
| 1464 | |
| 1465 | /// NoAlias attribute for function return value. |
| 1466 | struct AANoAliasReturned : AANoAliasImpl { |
| 1467 | |
| 1468 | AANoAliasReturned(Function &F, InformationCache &InfoCache) |
| 1469 | : AANoAliasImpl(F, InfoCache) {} |
| 1470 | |
| 1471 | /// See AbstractAttribute::getManifestPosition(). |
| 1472 | virtual ManifestPosition getManifestPosition() const override { |
| 1473 | return MP_RETURNED; |
| 1474 | } |
| 1475 | |
| 1476 | /// See AbstractAttriubute::initialize(...). |
| 1477 | void initialize(Attributor &A) override { |
| 1478 | Function &F = getAnchorScope(); |
| 1479 | |
| 1480 | // Already noalias. |
| 1481 | if (F.returnDoesNotAlias()) { |
| 1482 | indicateOptimisticFixpoint(); |
| 1483 | return; |
| 1484 | } |
| 1485 | } |
| 1486 | |
| 1487 | /// See AbstractAttribute::updateImpl(...). |
| 1488 | virtual ChangeStatus updateImpl(Attributor &A) override; |
| 1489 | }; |
| 1490 | |
| 1491 | ChangeStatus AANoAliasReturned::updateImpl(Attributor &A) { |
| 1492 | Function &F = getAnchorScope(); |
| 1493 | |
| 1494 | auto *AARetValImpl = A.getAAFor<AAReturnedValuesImpl>(*this, F); |
| 1495 | if (!AARetValImpl) { |
| 1496 | indicatePessimisticFixpoint(); |
| 1497 | return ChangeStatus::CHANGED; |
| 1498 | } |
| 1499 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1500 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred = |
| 1501 | [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool { |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 1502 | if (Constant *C = dyn_cast<Constant>(&RV)) |
| 1503 | if (C->isNullValue() || isa<UndefValue>(C)) |
| 1504 | return true; |
| 1505 | |
| 1506 | /// For now, we can only deduce noalias if we have call sites. |
| 1507 | /// FIXME: add more support. |
| 1508 | ImmutableCallSite ICS(&RV); |
| 1509 | if (!ICS) |
| 1510 | return false; |
| 1511 | |
| 1512 | auto *NoAliasAA = A.getAAFor<AANoAlias>(*this, RV); |
| 1513 | |
| Hideto Ueno | 9f5d80d | 2019-07-23 08:29:22 +0000 | [diff] [blame] | 1514 | if (!ICS.returnDoesNotAlias() && |
| 1515 | (!NoAliasAA || !NoAliasAA->isAssumedNoAlias())) |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 1516 | return false; |
| 1517 | |
| 1518 | /// FIXME: We can improve capture check in two ways: |
| 1519 | /// 1. Use the AANoCapture facilities. |
| 1520 | /// 2. Use the location of return insts for escape queries. |
| 1521 | if (PointerMayBeCaptured(&RV, /* ReturnCaptures */ false, |
| 1522 | /* StoreCaptures */ true)) |
| 1523 | return false; |
| 1524 | |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 1525 | return true; |
| 1526 | }; |
| 1527 | |
| 1528 | if (!AARetValImpl->checkForallReturnedValues(Pred)) { |
| 1529 | indicatePessimisticFixpoint(); |
| 1530 | return ChangeStatus::CHANGED; |
| 1531 | } |
| 1532 | |
| 1533 | return ChangeStatus::UNCHANGED; |
| 1534 | } |
| 1535 | |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1536 | /// -------------------AAIsDead Function Attribute----------------------- |
| 1537 | |
| 1538 | struct AAIsDeadFunction : AAIsDead, BooleanState { |
| 1539 | |
| 1540 | AAIsDeadFunction(Function &F, InformationCache &InfoCache) |
| 1541 | : AAIsDead(F, InfoCache) {} |
| 1542 | |
| 1543 | /// See AbstractAttribute::getState() |
| 1544 | /// { |
| 1545 | AbstractState &getState() override { return *this; } |
| 1546 | const AbstractState &getState() const override { return *this; } |
| 1547 | /// } |
| 1548 | |
| 1549 | /// See AbstractAttribute::getManifestPosition(). |
| 1550 | ManifestPosition getManifestPosition() const override { return MP_FUNCTION; } |
| 1551 | |
| 1552 | void initialize(Attributor &A) override { |
| 1553 | Function &F = getAnchorScope(); |
| 1554 | |
| 1555 | ToBeExploredPaths.insert(&(F.getEntryBlock().front())); |
| 1556 | AssumedLiveBlocks.insert(&(F.getEntryBlock())); |
| 1557 | for (size_t i = 0; i < ToBeExploredPaths.size(); ++i) |
| 1558 | explorePath(A, ToBeExploredPaths[i]); |
| 1559 | } |
| 1560 | |
| 1561 | /// Explores new instructions starting from \p I. If instruction is dead, stop |
| 1562 | /// and return true if it discovered a new instruction. |
| 1563 | bool explorePath(Attributor &A, Instruction *I); |
| 1564 | |
| 1565 | const std::string getAsStr() const override { |
| 1566 | return "LiveBBs(" + std::to_string(AssumedLiveBlocks.size()) + "/" + |
| 1567 | std::to_string(getAnchorScope().size()) + ")"; |
| 1568 | } |
| 1569 | |
| 1570 | /// See AbstractAttribute::manifest(...). |
| 1571 | ChangeStatus manifest(Attributor &A) override { |
| 1572 | assert(getState().isValidState() && |
| 1573 | "Attempted to manifest an invalid state!"); |
| 1574 | |
| 1575 | ChangeStatus HasChanged = ChangeStatus::UNCHANGED; |
| 1576 | |
| 1577 | for (Instruction *I : NoReturnCalls) { |
| 1578 | BasicBlock *BB = I->getParent(); |
| 1579 | |
| 1580 | /// Invoke is replaced with a call and unreachable is placed after it. |
| 1581 | if (auto *II = dyn_cast<InvokeInst>(I)) { |
| 1582 | changeToCall(II); |
| 1583 | changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false); |
| 1584 | LLVM_DEBUG(dbgs() << "[AAIsDead] Replaced invoke with call inst\n"); |
| 1585 | continue; |
| 1586 | } |
| 1587 | |
| 1588 | SplitBlock(BB, I->getNextNode()); |
| 1589 | changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false); |
| 1590 | HasChanged = ChangeStatus::CHANGED; |
| 1591 | } |
| 1592 | |
| 1593 | return HasChanged; |
| 1594 | } |
| 1595 | |
| 1596 | /// See AbstractAttribute::updateImpl(...). |
| 1597 | ChangeStatus updateImpl(Attributor &A) override; |
| 1598 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1599 | /// See AAIsDead::isAssumedDead(BasicBlock *). |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1600 | bool isAssumedDead(BasicBlock *BB) const override { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1601 | assert(BB->getParent() == &getAnchorScope() && |
| 1602 | "BB must be in the same anchor scope function."); |
| 1603 | |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1604 | if (!getAssumed()) |
| 1605 | return false; |
| 1606 | return !AssumedLiveBlocks.count(BB); |
| 1607 | } |
| 1608 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1609 | /// See AAIsDead::isKnownDead(BasicBlock *). |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1610 | bool isKnownDead(BasicBlock *BB) const override { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1611 | return getKnown() && isAssumedDead(BB); |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1612 | } |
| 1613 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1614 | /// See AAIsDead::isAssumed(Instruction *I). |
| 1615 | bool isAssumedDead(Instruction *I) const override { |
| 1616 | assert(I->getParent()->getParent() == &getAnchorScope() && |
| 1617 | "Instruction must be in the same anchor scope function."); |
| 1618 | |
| Stefan Stipanovic | 7849e41 | 2019-08-03 15:27:41 +0000 | [diff] [blame] | 1619 | if (!getAssumed()) |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1620 | return false; |
| 1621 | |
| 1622 | // If it is not in AssumedLiveBlocks then it for sure dead. |
| 1623 | // Otherwise, it can still be after noreturn call in a live block. |
| 1624 | if (!AssumedLiveBlocks.count(I->getParent())) |
| 1625 | return true; |
| 1626 | |
| 1627 | // If it is not after a noreturn call, than it is live. |
| 1628 | if (!isAfterNoReturn(I)) |
| 1629 | return false; |
| 1630 | |
| 1631 | // Definitely dead. |
| 1632 | return true; |
| 1633 | } |
| 1634 | |
| 1635 | /// See AAIsDead::isKnownDead(Instruction *I). |
| 1636 | bool isKnownDead(Instruction *I) const override { |
| 1637 | return getKnown() && isAssumedDead(I); |
| 1638 | } |
| 1639 | |
| 1640 | /// Check if instruction is after noreturn call, in other words, assumed dead. |
| 1641 | bool isAfterNoReturn(Instruction *I) const; |
| 1642 | |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1643 | /// Collection of to be explored paths. |
| 1644 | SmallSetVector<Instruction *, 8> ToBeExploredPaths; |
| 1645 | |
| 1646 | /// Collection of all assumed live BasicBlocks. |
| 1647 | DenseSet<BasicBlock *> AssumedLiveBlocks; |
| 1648 | |
| 1649 | /// Collection of calls with noreturn attribute, assumed or knwon. |
| 1650 | SmallSetVector<Instruction *, 4> NoReturnCalls; |
| 1651 | }; |
| 1652 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1653 | bool AAIsDeadFunction::isAfterNoReturn(Instruction *I) const { |
| 1654 | Instruction *PrevI = I->getPrevNode(); |
| 1655 | while (PrevI) { |
| 1656 | if (NoReturnCalls.count(PrevI)) |
| 1657 | return true; |
| 1658 | PrevI = PrevI->getPrevNode(); |
| 1659 | } |
| 1660 | return false; |
| 1661 | } |
| 1662 | |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1663 | bool AAIsDeadFunction::explorePath(Attributor &A, Instruction *I) { |
| 1664 | BasicBlock *BB = I->getParent(); |
| 1665 | |
| 1666 | while (I) { |
| 1667 | ImmutableCallSite ICS(I); |
| 1668 | |
| 1669 | if (ICS) { |
| 1670 | auto *NoReturnAA = A.getAAFor<AANoReturn>(*this, *I); |
| 1671 | |
| 1672 | if (NoReturnAA && NoReturnAA->isAssumedNoReturn()) { |
| 1673 | if (!NoReturnCalls.insert(I)) |
| 1674 | // If I is already in the NoReturnCalls set, then it stayed noreturn |
| 1675 | // and we didn't discover any new instructions. |
| 1676 | return false; |
| 1677 | |
| 1678 | // Discovered new noreturn call, return true to indicate that I is not |
| 1679 | // noreturn anymore and should be deleted from NoReturnCalls. |
| 1680 | return true; |
| 1681 | } |
| 1682 | |
| 1683 | if (ICS.hasFnAttr(Attribute::NoReturn)) { |
| Hideto Ueno | 9f5d80d | 2019-07-23 08:29:22 +0000 | [diff] [blame] | 1684 | if (!NoReturnCalls.insert(I)) |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1685 | return false; |
| 1686 | |
| 1687 | return true; |
| 1688 | } |
| 1689 | } |
| 1690 | |
| 1691 | I = I->getNextNode(); |
| 1692 | } |
| 1693 | |
| 1694 | // get new paths (reachable blocks). |
| 1695 | for (BasicBlock *SuccBB : successors(BB)) { |
| 1696 | Instruction *Inst = &(SuccBB->front()); |
| 1697 | AssumedLiveBlocks.insert(SuccBB); |
| 1698 | ToBeExploredPaths.insert(Inst); |
| 1699 | } |
| 1700 | |
| 1701 | return true; |
| 1702 | } |
| 1703 | |
| 1704 | ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) { |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1705 | // Temporary collection to iterate over existing noreturn instructions. This |
| 1706 | // will alow easier modification of NoReturnCalls collection |
| 1707 | SmallVector<Instruction *, 8> NoReturnChanged; |
| 1708 | ChangeStatus Status = ChangeStatus::UNCHANGED; |
| 1709 | |
| 1710 | for (Instruction *I : NoReturnCalls) |
| 1711 | NoReturnChanged.push_back(I); |
| 1712 | |
| 1713 | for (Instruction *I : NoReturnChanged) { |
| 1714 | size_t Size = ToBeExploredPaths.size(); |
| 1715 | |
| 1716 | // Still noreturn. |
| 1717 | if (!explorePath(A, I)) |
| 1718 | continue; |
| 1719 | |
| 1720 | NoReturnCalls.remove(I); |
| 1721 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1722 | // At least one new path. |
| 1723 | Status = ChangeStatus::CHANGED; |
| 1724 | |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1725 | // No new paths. |
| 1726 | if (Size == ToBeExploredPaths.size()) |
| 1727 | continue; |
| 1728 | |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1729 | // explore new paths. |
| 1730 | while (Size != ToBeExploredPaths.size()) |
| 1731 | explorePath(A, ToBeExploredPaths[Size++]); |
| 1732 | } |
| 1733 | |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 1734 | LLVM_DEBUG( |
| 1735 | dbgs() << "[AAIsDead] AssumedLiveBlocks: " << AssumedLiveBlocks.size() |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1736 | << " Total number of blocks: " << getAnchorScope().size() << "\n"); |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 1737 | |
| 1738 | return Status; |
| 1739 | } |
| 1740 | |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 1741 | /// -------------------- Dereferenceable Argument Attribute -------------------- |
| 1742 | |
| 1743 | struct DerefState : AbstractState { |
| 1744 | |
| 1745 | /// State representing for dereferenceable bytes. |
| 1746 | IntegerState DerefBytesState; |
| 1747 | |
| 1748 | /// State representing that whether the value is nonnull or global. |
| 1749 | IntegerState NonNullGlobalState; |
| 1750 | |
| 1751 | /// Bits encoding for NonNullGlobalState. |
| 1752 | enum { |
| 1753 | DEREF_NONNULL = 1 << 0, |
| 1754 | DEREF_GLOBAL = 1 << 1, |
| 1755 | }; |
| 1756 | |
| 1757 | /// See AbstractState::isValidState() |
| 1758 | bool isValidState() const override { return DerefBytesState.isValidState(); } |
| 1759 | |
| Johannes Doerfert | b6acee5 | 2019-08-04 17:55:15 +0000 | [diff] [blame^] | 1760 | /// See AbstractState::isAtFixpoint() |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 1761 | bool isAtFixpoint() const override { |
| Johannes Doerfert | b6acee5 | 2019-08-04 17:55:15 +0000 | [diff] [blame^] | 1762 | return !isValidState() || (DerefBytesState.isAtFixpoint() && |
| 1763 | NonNullGlobalState.isAtFixpoint()); |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 1764 | } |
| 1765 | |
| 1766 | /// See AbstractState::indicateOptimisticFixpoint(...) |
| 1767 | void indicateOptimisticFixpoint() override { |
| 1768 | DerefBytesState.indicateOptimisticFixpoint(); |
| 1769 | NonNullGlobalState.indicateOptimisticFixpoint(); |
| 1770 | } |
| 1771 | |
| 1772 | /// See AbstractState::indicatePessimisticFixpoint(...) |
| 1773 | void indicatePessimisticFixpoint() override { |
| 1774 | DerefBytesState.indicatePessimisticFixpoint(); |
| 1775 | NonNullGlobalState.indicatePessimisticFixpoint(); |
| 1776 | } |
| 1777 | |
| 1778 | /// Update known dereferenceable bytes. |
| 1779 | void takeKnownDerefBytesMaximum(uint64_t Bytes) { |
| 1780 | DerefBytesState.takeKnownMaximum(Bytes); |
| 1781 | } |
| 1782 | |
| 1783 | /// Update assumed dereferenceable bytes. |
| 1784 | void takeAssumedDerefBytesMinimum(uint64_t Bytes) { |
| 1785 | DerefBytesState.takeAssumedMinimum(Bytes); |
| 1786 | } |
| 1787 | |
| 1788 | /// Update assumed NonNullGlobalState |
| 1789 | void updateAssumedNonNullGlobalState(bool IsNonNull, bool IsGlobal) { |
| 1790 | if (!IsNonNull) |
| 1791 | NonNullGlobalState.removeAssumedBits(DEREF_NONNULL); |
| 1792 | if (!IsGlobal) |
| 1793 | NonNullGlobalState.removeAssumedBits(DEREF_GLOBAL); |
| 1794 | } |
| 1795 | |
| 1796 | /// Equality for DerefState. |
| 1797 | bool operator==(const DerefState &R) { |
| 1798 | return this->DerefBytesState == R.DerefBytesState && |
| 1799 | this->NonNullGlobalState == R.NonNullGlobalState; |
| 1800 | } |
| 1801 | }; |
| 1802 | struct AADereferenceableImpl : AADereferenceable, DerefState { |
| 1803 | |
| 1804 | AADereferenceableImpl(Value &V, InformationCache &InfoCache) |
| 1805 | : AADereferenceable(V, InfoCache) {} |
| 1806 | |
| 1807 | AADereferenceableImpl(Value *AssociatedVal, Value &AnchoredValue, |
| 1808 | InformationCache &InfoCache) |
| 1809 | : AADereferenceable(AssociatedVal, AnchoredValue, InfoCache) {} |
| 1810 | |
| 1811 | /// See AbstractAttribute::getState() |
| 1812 | /// { |
| 1813 | AbstractState &getState() override { return *this; } |
| 1814 | const AbstractState &getState() const override { return *this; } |
| 1815 | /// } |
| 1816 | |
| 1817 | /// See AADereferenceable::getAssumedDereferenceableBytes(). |
| 1818 | uint32_t getAssumedDereferenceableBytes() const override { |
| 1819 | return DerefBytesState.getAssumed(); |
| 1820 | } |
| 1821 | |
| 1822 | /// See AADereferenceable::getKnownDereferenceableBytes(). |
| 1823 | uint32_t getKnownDereferenceableBytes() const override { |
| 1824 | return DerefBytesState.getKnown(); |
| 1825 | } |
| 1826 | |
| 1827 | // Helper function for syncing nonnull state. |
| 1828 | void syncNonNull(const AANonNull *NonNullAA) { |
| 1829 | if (!NonNullAA) { |
| 1830 | NonNullGlobalState.removeAssumedBits(DEREF_NONNULL); |
| 1831 | return; |
| 1832 | } |
| 1833 | |
| 1834 | if (NonNullAA->isKnownNonNull()) |
| 1835 | NonNullGlobalState.addKnownBits(DEREF_NONNULL); |
| 1836 | |
| 1837 | if (!NonNullAA->isAssumedNonNull()) |
| 1838 | NonNullGlobalState.removeAssumedBits(DEREF_NONNULL); |
| 1839 | } |
| 1840 | |
| 1841 | /// See AADereferenceable::isAssumedGlobal(). |
| 1842 | bool isAssumedGlobal() const override { |
| 1843 | return NonNullGlobalState.isAssumed(DEREF_GLOBAL); |
| 1844 | } |
| 1845 | |
| 1846 | /// See AADereferenceable::isKnownGlobal(). |
| 1847 | bool isKnownGlobal() const override { |
| 1848 | return NonNullGlobalState.isKnown(DEREF_GLOBAL); |
| 1849 | } |
| 1850 | |
| 1851 | /// See AADereferenceable::isAssumedNonNull(). |
| 1852 | bool isAssumedNonNull() const override { |
| 1853 | return NonNullGlobalState.isAssumed(DEREF_NONNULL); |
| 1854 | } |
| 1855 | |
| 1856 | /// See AADereferenceable::isKnownNonNull(). |
| 1857 | bool isKnownNonNull() const override { |
| 1858 | return NonNullGlobalState.isKnown(DEREF_NONNULL); |
| 1859 | } |
| 1860 | |
| 1861 | void getDeducedAttributes(SmallVectorImpl<Attribute> &Attrs) const override { |
| 1862 | LLVMContext &Ctx = AnchoredVal.getContext(); |
| 1863 | |
| 1864 | // TODO: Add *_globally support |
| 1865 | if (isAssumedNonNull()) |
| 1866 | Attrs.emplace_back(Attribute::getWithDereferenceableBytes( |
| 1867 | Ctx, getAssumedDereferenceableBytes())); |
| 1868 | else |
| 1869 | Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes( |
| 1870 | Ctx, getAssumedDereferenceableBytes())); |
| 1871 | } |
| 1872 | uint64_t computeAssumedDerefenceableBytes(Attributor &A, Value &V, |
| 1873 | bool &IsNonNull, bool &IsGlobal); |
| 1874 | |
| 1875 | void initialize(Attributor &A) override { |
| 1876 | Function &F = getAnchorScope(); |
| 1877 | unsigned AttrIdx = |
| 1878 | getAttrIndex(getManifestPosition(), getArgNo(getAnchoredValue())); |
| 1879 | |
| 1880 | for (Attribute::AttrKind AK : |
| 1881 | {Attribute::Dereferenceable, Attribute::DereferenceableOrNull}) |
| 1882 | if (F.getAttributes().hasAttribute(AttrIdx, AK)) |
| 1883 | takeKnownDerefBytesMaximum(F.getAttribute(AttrIdx, AK).getValueAsInt()); |
| 1884 | } |
| 1885 | |
| 1886 | /// See AbstractAttribute::getAsStr(). |
| 1887 | const std::string getAsStr() const override { |
| 1888 | if (!getAssumedDereferenceableBytes()) |
| 1889 | return "unknown-dereferenceable"; |
| 1890 | return std::string("dereferenceable") + |
| 1891 | (isAssumedNonNull() ? "" : "_or_null") + |
| 1892 | (isAssumedGlobal() ? "_globally" : "") + "<" + |
| 1893 | std::to_string(getKnownDereferenceableBytes()) + "-" + |
| 1894 | std::to_string(getAssumedDereferenceableBytes()) + ">"; |
| 1895 | } |
| 1896 | }; |
| 1897 | |
| 1898 | struct AADereferenceableReturned : AADereferenceableImpl { |
| 1899 | AADereferenceableReturned(Function &F, InformationCache &InfoCache) |
| 1900 | : AADereferenceableImpl(F, InfoCache) {} |
| 1901 | |
| 1902 | /// See AbstractAttribute::getManifestPosition(). |
| 1903 | ManifestPosition getManifestPosition() const override { return MP_RETURNED; } |
| 1904 | |
| 1905 | /// See AbstractAttribute::updateImpl(...). |
| 1906 | ChangeStatus updateImpl(Attributor &A) override; |
| 1907 | }; |
| 1908 | |
| 1909 | // Helper function that returns dereferenceable bytes. |
| 1910 | static uint64_t calcDifferenceIfBaseIsNonNull(int64_t DerefBytes, |
| 1911 | int64_t Offset, bool IsNonNull) { |
| 1912 | if (!IsNonNull) |
| 1913 | return 0; |
| 1914 | return std::max((int64_t)0, DerefBytes - Offset); |
| 1915 | } |
| 1916 | |
| 1917 | uint64_t AADereferenceableImpl::computeAssumedDerefenceableBytes( |
| 1918 | Attributor &A, Value &V, bool &IsNonNull, bool &IsGlobal) { |
| 1919 | // TODO: Tracking the globally flag. |
| 1920 | IsGlobal = false; |
| 1921 | |
| 1922 | // First, we try to get information about V from Attributor. |
| 1923 | if (auto *DerefAA = A.getAAFor<AADereferenceable>(*this, V)) { |
| 1924 | IsNonNull &= DerefAA->isAssumedNonNull(); |
| 1925 | return DerefAA->getAssumedDereferenceableBytes(); |
| 1926 | } |
| 1927 | |
| 1928 | // Otherwise, we try to compute assumed bytes from base pointer. |
| 1929 | const DataLayout &DL = getAnchorScope().getParent()->getDataLayout(); |
| 1930 | unsigned IdxWidth = |
| 1931 | DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace()); |
| 1932 | APInt Offset(IdxWidth, 0); |
| 1933 | Value *Base = V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset); |
| 1934 | |
| 1935 | if (auto *BaseDerefAA = A.getAAFor<AADereferenceable>(*this, *Base)) { |
| 1936 | IsNonNull &= Offset != 0; |
| 1937 | return calcDifferenceIfBaseIsNonNull( |
| 1938 | BaseDerefAA->getAssumedDereferenceableBytes(), Offset.getSExtValue(), |
| 1939 | Offset != 0 || BaseDerefAA->isAssumedNonNull()); |
| 1940 | } |
| 1941 | |
| 1942 | // Then, use IR information. |
| 1943 | |
| 1944 | if (isDereferenceablePointer(Base, Base->getType(), DL)) |
| 1945 | return calcDifferenceIfBaseIsNonNull( |
| 1946 | DL.getTypeStoreSize(Base->getType()->getPointerElementType()), |
| 1947 | Offset.getSExtValue(), |
| 1948 | !NullPointerIsDefined(&getAnchorScope(), |
| 1949 | V.getType()->getPointerAddressSpace())); |
| 1950 | |
| 1951 | IsNonNull = false; |
| 1952 | return 0; |
| 1953 | } |
| 1954 | ChangeStatus AADereferenceableReturned::updateImpl(Attributor &A) { |
| 1955 | Function &F = getAnchorScope(); |
| 1956 | auto BeforeState = static_cast<DerefState>(*this); |
| 1957 | |
| 1958 | syncNonNull(A.getAAFor<AANonNull>(*this, F)); |
| 1959 | |
| 1960 | auto *AARetVal = A.getAAFor<AAReturnedValues>(*this, F); |
| 1961 | if (!AARetVal) { |
| 1962 | indicatePessimisticFixpoint(); |
| 1963 | return ChangeStatus::CHANGED; |
| 1964 | } |
| 1965 | |
| 1966 | bool IsNonNull = isAssumedNonNull(); |
| 1967 | bool IsGlobal = isAssumedGlobal(); |
| 1968 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 1969 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred = |
| 1970 | [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool { |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 1971 | takeAssumedDerefBytesMinimum( |
| 1972 | computeAssumedDerefenceableBytes(A, RV, IsNonNull, IsGlobal)); |
| 1973 | return isValidState(); |
| 1974 | }; |
| 1975 | |
| 1976 | if (AARetVal->checkForallReturnedValues(Pred)) { |
| 1977 | updateAssumedNonNullGlobalState(IsNonNull, IsGlobal); |
| 1978 | return BeforeState == static_cast<DerefState>(*this) |
| 1979 | ? ChangeStatus::UNCHANGED |
| 1980 | : ChangeStatus::CHANGED; |
| 1981 | } |
| 1982 | indicatePessimisticFixpoint(); |
| 1983 | return ChangeStatus::CHANGED; |
| 1984 | } |
| 1985 | |
| 1986 | struct AADereferenceableArgument : AADereferenceableImpl { |
| 1987 | AADereferenceableArgument(Argument &A, InformationCache &InfoCache) |
| 1988 | : AADereferenceableImpl(A, InfoCache) {} |
| 1989 | |
| 1990 | /// See AbstractAttribute::getManifestPosition(). |
| 1991 | ManifestPosition getManifestPosition() const override { return MP_ARGUMENT; } |
| 1992 | |
| 1993 | /// See AbstractAttribute::updateImpl(...). |
| 1994 | ChangeStatus updateImpl(Attributor &A) override; |
| 1995 | }; |
| 1996 | |
| 1997 | ChangeStatus AADereferenceableArgument::updateImpl(Attributor &A) { |
| 1998 | Function &F = getAnchorScope(); |
| 1999 | Argument &Arg = cast<Argument>(getAnchoredValue()); |
| 2000 | |
| 2001 | auto BeforeState = static_cast<DerefState>(*this); |
| 2002 | |
| 2003 | unsigned ArgNo = Arg.getArgNo(); |
| 2004 | |
| 2005 | syncNonNull(A.getAAFor<AANonNull>(*this, F, ArgNo)); |
| 2006 | |
| 2007 | bool IsNonNull = isAssumedNonNull(); |
| 2008 | bool IsGlobal = isAssumedGlobal(); |
| 2009 | |
| 2010 | // Callback function |
| 2011 | std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) -> bool { |
| 2012 | assert(CS && "Sanity check: Call site was not initialized properly!"); |
| 2013 | |
| 2014 | // Check that DereferenceableAA is AADereferenceableCallSiteArgument. |
| 2015 | if (auto *DereferenceableAA = |
| 2016 | A.getAAFor<AADereferenceable>(*this, *CS.getInstruction(), ArgNo)) { |
| 2017 | ImmutableCallSite ICS(&DereferenceableAA->getAnchoredValue()); |
| 2018 | if (ICS && CS.getInstruction() == ICS.getInstruction()) { |
| 2019 | takeAssumedDerefBytesMinimum( |
| 2020 | DereferenceableAA->getAssumedDereferenceableBytes()); |
| 2021 | IsNonNull &= DereferenceableAA->isAssumedNonNull(); |
| 2022 | IsGlobal &= DereferenceableAA->isAssumedGlobal(); |
| 2023 | return isValidState(); |
| 2024 | } |
| 2025 | } |
| 2026 | |
| 2027 | takeAssumedDerefBytesMinimum(computeAssumedDerefenceableBytes( |
| 2028 | A, *CS.getArgOperand(ArgNo), IsNonNull, IsGlobal)); |
| 2029 | |
| 2030 | return isValidState(); |
| 2031 | }; |
| 2032 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 2033 | if (!A.checkForAllCallSites(F, CallSiteCheck, true, *this)) { |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 2034 | indicatePessimisticFixpoint(); |
| 2035 | return ChangeStatus::CHANGED; |
| 2036 | } |
| 2037 | |
| 2038 | updateAssumedNonNullGlobalState(IsNonNull, IsGlobal); |
| 2039 | |
| 2040 | return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED |
| 2041 | : ChangeStatus::CHANGED; |
| 2042 | } |
| 2043 | |
| 2044 | /// Dereferenceable attribute for a call site argument. |
| 2045 | struct AADereferenceableCallSiteArgument : AADereferenceableImpl { |
| 2046 | |
| 2047 | /// See AADereferenceableImpl::AADereferenceableImpl(...). |
| 2048 | AADereferenceableCallSiteArgument(CallSite CS, unsigned ArgNo, |
| 2049 | InformationCache &InfoCache) |
| 2050 | : AADereferenceableImpl(CS.getArgOperand(ArgNo), *CS.getInstruction(), |
| 2051 | InfoCache), |
| 2052 | ArgNo(ArgNo) {} |
| 2053 | |
| 2054 | /// See AbstractAttribute::initialize(...). |
| 2055 | void initialize(Attributor &A) override { |
| 2056 | CallSite CS(&getAnchoredValue()); |
| 2057 | if (CS.paramHasAttr(ArgNo, Attribute::Dereferenceable)) |
| Hideto Ueno | 96bb347 | 2019-08-03 04:10:50 +0000 | [diff] [blame] | 2058 | takeKnownDerefBytesMaximum( |
| 2059 | CS.getDereferenceableBytes(ArgNo + AttributeList::FirstArgIndex)); |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 2060 | |
| 2061 | if (CS.paramHasAttr(ArgNo, Attribute::DereferenceableOrNull)) |
| Hideto Ueno | 96bb347 | 2019-08-03 04:10:50 +0000 | [diff] [blame] | 2062 | takeKnownDerefBytesMaximum(CS.getDereferenceableOrNullBytes( |
| 2063 | ArgNo + AttributeList::FirstArgIndex)); |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 2064 | } |
| 2065 | |
| 2066 | /// See AbstractAttribute::updateImpl(Attributor &A). |
| 2067 | ChangeStatus updateImpl(Attributor &A) override; |
| 2068 | |
| 2069 | /// See AbstractAttribute::getManifestPosition(). |
| 2070 | ManifestPosition getManifestPosition() const override { |
| 2071 | return MP_CALL_SITE_ARGUMENT; |
| 2072 | }; |
| 2073 | |
| 2074 | // Return argument index of associated value. |
| 2075 | int getArgNo() const { return ArgNo; } |
| 2076 | |
| 2077 | private: |
| 2078 | unsigned ArgNo; |
| 2079 | }; |
| 2080 | |
| 2081 | ChangeStatus AADereferenceableCallSiteArgument::updateImpl(Attributor &A) { |
| 2082 | // NOTE: Never look at the argument of the callee in this method. |
| 2083 | // If we do this, "dereferenceable" is always deduced because of the |
| 2084 | // assumption. |
| 2085 | |
| 2086 | Value &V = *getAssociatedValue(); |
| 2087 | |
| 2088 | auto BeforeState = static_cast<DerefState>(*this); |
| 2089 | |
| 2090 | syncNonNull(A.getAAFor<AANonNull>(*this, getAnchoredValue(), ArgNo)); |
| 2091 | bool IsNonNull = isAssumedNonNull(); |
| 2092 | bool IsGlobal = isKnownGlobal(); |
| 2093 | |
| 2094 | takeAssumedDerefBytesMinimum( |
| 2095 | computeAssumedDerefenceableBytes(A, V, IsNonNull, IsGlobal)); |
| 2096 | updateAssumedNonNullGlobalState(IsNonNull, IsGlobal); |
| 2097 | |
| 2098 | return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED |
| 2099 | : ChangeStatus::CHANGED; |
| 2100 | } |
| 2101 | |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 2102 | // ------------------------ Align Argument Attribute ------------------------ |
| 2103 | |
| 2104 | struct AAAlignImpl : AAAlign, IntegerState { |
| 2105 | |
| 2106 | // Max alignemnt value allowed in IR |
| 2107 | static const unsigned MAX_ALIGN = 1U << 29; |
| 2108 | |
| 2109 | AAAlignImpl(Value *AssociatedVal, Value &AnchoredValue, |
| 2110 | InformationCache &InfoCache) |
| 2111 | : AAAlign(AssociatedVal, AnchoredValue, InfoCache), |
| 2112 | IntegerState(MAX_ALIGN) {} |
| 2113 | |
| 2114 | AAAlignImpl(Value &V, InformationCache &InfoCache) |
| 2115 | : AAAlignImpl(&V, V, InfoCache) {} |
| 2116 | |
| 2117 | /// See AbstractAttribute::getState() |
| 2118 | /// { |
| 2119 | AbstractState &getState() override { return *this; } |
| 2120 | const AbstractState &getState() const override { return *this; } |
| 2121 | /// } |
| 2122 | |
| 2123 | virtual const std::string getAsStr() const override { |
| 2124 | return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) + |
| 2125 | "-" + std::to_string(getAssumedAlign()) + ">") |
| 2126 | : "unknown-align"; |
| 2127 | } |
| 2128 | |
| 2129 | /// See AAAlign::getAssumedAlign(). |
| 2130 | unsigned getAssumedAlign() const override { return getAssumed(); } |
| 2131 | |
| 2132 | /// See AAAlign::getKnownAlign(). |
| 2133 | unsigned getKnownAlign() const override { return getKnown(); } |
| 2134 | |
| 2135 | /// See AbstractAttriubute::initialize(...). |
| 2136 | void initialize(Attributor &A) override { |
| 2137 | Function &F = getAnchorScope(); |
| 2138 | |
| 2139 | unsigned AttrIdx = |
| 2140 | getAttrIndex(getManifestPosition(), getArgNo(getAnchoredValue())); |
| 2141 | |
| 2142 | // Already the function has align attribute on return value or argument. |
| 2143 | if (F.getAttributes().hasAttribute(AttrIdx, ID)) |
| 2144 | addKnownBits(F.getAttribute(AttrIdx, ID).getAlignment()); |
| 2145 | } |
| 2146 | |
| 2147 | /// See AbstractAttribute::getDeducedAttributes |
| 2148 | virtual void |
| 2149 | getDeducedAttributes(SmallVectorImpl<Attribute> &Attrs) const override { |
| 2150 | LLVMContext &Ctx = AnchoredVal.getContext(); |
| 2151 | |
| 2152 | Attrs.emplace_back(Attribute::getWithAlignment(Ctx, getAssumedAlign())); |
| 2153 | } |
| 2154 | }; |
| 2155 | |
| 2156 | /// Align attribute for function return value. |
| 2157 | struct AAAlignReturned : AAAlignImpl { |
| 2158 | |
| 2159 | AAAlignReturned(Function &F, InformationCache &InfoCache) |
| 2160 | : AAAlignImpl(F, InfoCache) {} |
| 2161 | |
| 2162 | /// See AbstractAttribute::getManifestPosition(). |
| 2163 | virtual ManifestPosition getManifestPosition() const override { |
| 2164 | return MP_RETURNED; |
| 2165 | } |
| 2166 | |
| 2167 | /// See AbstractAttribute::updateImpl(...). |
| 2168 | virtual ChangeStatus updateImpl(Attributor &A) override; |
| 2169 | }; |
| 2170 | |
| 2171 | ChangeStatus AAAlignReturned::updateImpl(Attributor &A) { |
| 2172 | Function &F = getAnchorScope(); |
| 2173 | auto *AARetValImpl = A.getAAFor<AAReturnedValuesImpl>(*this, F); |
| 2174 | if (!AARetValImpl) { |
| 2175 | indicatePessimisticFixpoint(); |
| 2176 | return ChangeStatus::CHANGED; |
| 2177 | } |
| 2178 | |
| 2179 | // Currently, align<n> is deduced if alignments in return values are assumed |
| 2180 | // as greater than n. We reach pessimistic fixpoint if any of the return value |
| 2181 | // wouldn't have align. If no assumed state was used for reasoning, an |
| 2182 | // optimistic fixpoint is reached earlier. |
| 2183 | |
| 2184 | base_t BeforeState = getAssumed(); |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 2185 | std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred = |
| 2186 | [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool { |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 2187 | auto *AlignAA = A.getAAFor<AAAlign>(*this, RV); |
| 2188 | |
| 2189 | if (AlignAA) |
| 2190 | takeAssumedMinimum(AlignAA->getAssumedAlign()); |
| 2191 | else |
| 2192 | // Use IR information. |
| 2193 | takeAssumedMinimum(RV.getPointerAlignment( |
| 2194 | getAnchorScope().getParent()->getDataLayout())); |
| 2195 | |
| 2196 | return isValidState(); |
| 2197 | }; |
| 2198 | |
| 2199 | if (!AARetValImpl->checkForallReturnedValues(Pred)) { |
| 2200 | indicatePessimisticFixpoint(); |
| 2201 | return ChangeStatus::CHANGED; |
| 2202 | } |
| 2203 | |
| 2204 | return (getAssumed() != BeforeState) ? ChangeStatus::CHANGED |
| 2205 | : ChangeStatus::UNCHANGED; |
| 2206 | } |
| 2207 | |
| 2208 | /// Align attribute for function argument. |
| 2209 | struct AAAlignArgument : AAAlignImpl { |
| 2210 | |
| 2211 | AAAlignArgument(Argument &A, InformationCache &InfoCache) |
| 2212 | : AAAlignImpl(A, InfoCache) {} |
| 2213 | |
| 2214 | /// See AbstractAttribute::getManifestPosition(). |
| 2215 | virtual ManifestPosition getManifestPosition() const override { |
| 2216 | return MP_ARGUMENT; |
| 2217 | } |
| 2218 | |
| 2219 | /// See AbstractAttribute::updateImpl(...). |
| 2220 | virtual ChangeStatus updateImpl(Attributor &A) override; |
| 2221 | }; |
| 2222 | |
| 2223 | ChangeStatus AAAlignArgument::updateImpl(Attributor &A) { |
| 2224 | |
| 2225 | Function &F = getAnchorScope(); |
| 2226 | Argument &Arg = cast<Argument>(getAnchoredValue()); |
| 2227 | |
| 2228 | unsigned ArgNo = Arg.getArgNo(); |
| 2229 | const DataLayout &DL = F.getParent()->getDataLayout(); |
| 2230 | |
| 2231 | auto BeforeState = getAssumed(); |
| 2232 | |
| 2233 | // Callback function |
| 2234 | std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) { |
| 2235 | assert(CS && "Sanity check: Call site was not initialized properly!"); |
| 2236 | |
| 2237 | auto *AlignAA = A.getAAFor<AAAlign>(*this, *CS.getInstruction(), ArgNo); |
| 2238 | |
| 2239 | // Check that AlignAA is AAAlignCallSiteArgument. |
| 2240 | if (AlignAA) { |
| 2241 | ImmutableCallSite ICS(&AlignAA->getAnchoredValue()); |
| 2242 | if (ICS && CS.getInstruction() == ICS.getInstruction()) { |
| 2243 | takeAssumedMinimum(AlignAA->getAssumedAlign()); |
| 2244 | return isValidState(); |
| 2245 | } |
| 2246 | } |
| 2247 | |
| 2248 | Value *V = CS.getArgOperand(ArgNo); |
| 2249 | takeAssumedMinimum(V->getPointerAlignment(DL)); |
| 2250 | return isValidState(); |
| 2251 | }; |
| 2252 | |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 2253 | if (!A.checkForAllCallSites(F, CallSiteCheck, true, *this)) |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 2254 | indicatePessimisticFixpoint(); |
| 2255 | |
| 2256 | return BeforeState == getAssumed() ? ChangeStatus::UNCHANGED |
| 2257 | : ChangeStatus ::CHANGED; |
| 2258 | } |
| 2259 | |
| 2260 | struct AAAlignCallSiteArgument : AAAlignImpl { |
| 2261 | |
| 2262 | /// See AANonNullImpl::AANonNullImpl(...). |
| 2263 | AAAlignCallSiteArgument(CallSite CS, unsigned ArgNo, |
| 2264 | InformationCache &InfoCache) |
| 2265 | : AAAlignImpl(CS.getArgOperand(ArgNo), *CS.getInstruction(), InfoCache), |
| 2266 | ArgNo(ArgNo) {} |
| 2267 | |
| 2268 | /// See AbstractAttribute::initialize(...). |
| 2269 | void initialize(Attributor &A) override { |
| 2270 | CallSite CS(&getAnchoredValue()); |
| 2271 | takeKnownMaximum(getAssociatedValue()->getPointerAlignment( |
| 2272 | getAnchorScope().getParent()->getDataLayout())); |
| 2273 | } |
| 2274 | |
| 2275 | /// See AbstractAttribute::updateImpl(Attributor &A). |
| 2276 | ChangeStatus updateImpl(Attributor &A) override; |
| 2277 | |
| 2278 | /// See AbstractAttribute::getManifestPosition(). |
| 2279 | ManifestPosition getManifestPosition() const override { |
| 2280 | return MP_CALL_SITE_ARGUMENT; |
| 2281 | }; |
| 2282 | |
| 2283 | // Return argument index of associated value. |
| 2284 | int getArgNo() const { return ArgNo; } |
| 2285 | |
| 2286 | private: |
| 2287 | unsigned ArgNo; |
| 2288 | }; |
| 2289 | |
| 2290 | ChangeStatus AAAlignCallSiteArgument::updateImpl(Attributor &A) { |
| 2291 | // NOTE: Never look at the argument of the callee in this method. |
| 2292 | // If we do this, "align" is always deduced because of the assumption. |
| 2293 | |
| 2294 | auto BeforeState = getAssumed(); |
| 2295 | |
| 2296 | Value &V = *getAssociatedValue(); |
| 2297 | |
| 2298 | auto *AlignAA = A.getAAFor<AAAlign>(*this, V); |
| 2299 | |
| 2300 | if (AlignAA) |
| 2301 | takeAssumedMinimum(AlignAA->getAssumedAlign()); |
| 2302 | else |
| 2303 | indicatePessimisticFixpoint(); |
| 2304 | |
| 2305 | return BeforeState == getAssumed() ? ChangeStatus::UNCHANGED |
| 2306 | : ChangeStatus::CHANGED; |
| 2307 | } |
| 2308 | |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 2309 | /// ---------------------------------------------------------------------------- |
| 2310 | /// Attributor |
| 2311 | /// ---------------------------------------------------------------------------- |
| 2312 | |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2313 | bool Attributor::checkForAllCallSites(Function &F, |
| 2314 | std::function<bool(CallSite)> &Pred, |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 2315 | bool RequireAllCallSites, |
| 2316 | AbstractAttribute &AA) { |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2317 | // We can try to determine information from |
| 2318 | // the call sites. However, this is only possible all call sites are known, |
| 2319 | // hence the function has internal linkage. |
| 2320 | if (RequireAllCallSites && !F.hasInternalLinkage()) { |
| 2321 | LLVM_DEBUG( |
| 2322 | dbgs() |
| 2323 | << "Attributor: Function " << F.getName() |
| 2324 | << " has no internal linkage, hence not all call sites are known\n"); |
| 2325 | return false; |
| 2326 | } |
| 2327 | |
| 2328 | for (const Use &U : F.uses()) { |
| Stefan Stipanovic | d021617 | 2019-08-02 21:31:22 +0000 | [diff] [blame] | 2329 | Instruction *I = cast<Instruction>(U.getUser()); |
| 2330 | Function *AnchorValue = I->getParent()->getParent(); |
| 2331 | |
| 2332 | auto *LivenessAA = getAAFor<AAIsDead>(AA, *AnchorValue); |
| 2333 | |
| 2334 | // Skip dead calls. |
| 2335 | if (LivenessAA && LivenessAA->isAssumedDead(I)) |
| 2336 | continue; |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2337 | |
| 2338 | CallSite CS(U.getUser()); |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2339 | if (!CS || !CS.isCallee(&U) || !CS.getCaller()->hasExactDefinition()) { |
| 2340 | if (!RequireAllCallSites) |
| 2341 | continue; |
| 2342 | |
| 2343 | LLVM_DEBUG(dbgs() << "Attributor: User " << *U.getUser() |
| 2344 | << " is an invalid use of " << F.getName() << "\n"); |
| 2345 | return false; |
| 2346 | } |
| 2347 | |
| 2348 | if (Pred(CS)) |
| 2349 | continue; |
| 2350 | |
| 2351 | LLVM_DEBUG(dbgs() << "Attributor: Call site callback failed for " |
| 2352 | << *CS.getInstruction() << "\n"); |
| 2353 | return false; |
| 2354 | } |
| 2355 | |
| 2356 | return true; |
| 2357 | } |
| 2358 | |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 2359 | ChangeStatus Attributor::run() { |
| 2360 | // Initialize all abstract attributes. |
| 2361 | for (AbstractAttribute *AA : AllAbstractAttributes) |
| 2362 | AA->initialize(*this); |
| 2363 | |
| 2364 | LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized " |
| 2365 | << AllAbstractAttributes.size() |
| 2366 | << " abstract attributes.\n"); |
| 2367 | |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 2368 | // Now that all abstract attributes are collected and initialized we start |
| 2369 | // the abstract analysis. |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 2370 | |
| 2371 | unsigned IterationCounter = 1; |
| 2372 | |
| 2373 | SmallVector<AbstractAttribute *, 64> ChangedAAs; |
| 2374 | SetVector<AbstractAttribute *> Worklist; |
| 2375 | Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end()); |
| 2376 | |
| 2377 | do { |
| 2378 | LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter |
| 2379 | << ", Worklist size: " << Worklist.size() << "\n"); |
| 2380 | |
| 2381 | // Add all abstract attributes that are potentially dependent on one that |
| 2382 | // changed to the work list. |
| 2383 | for (AbstractAttribute *ChangedAA : ChangedAAs) { |
| 2384 | auto &QuerriedAAs = QueryMap[ChangedAA]; |
| 2385 | Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end()); |
| 2386 | } |
| 2387 | |
| 2388 | // Reset the changed set. |
| 2389 | ChangedAAs.clear(); |
| 2390 | |
| 2391 | // Update all abstract attribute in the work list and record the ones that |
| 2392 | // changed. |
| 2393 | for (AbstractAttribute *AA : Worklist) |
| 2394 | if (AA->update(*this) == ChangeStatus::CHANGED) |
| 2395 | ChangedAAs.push_back(AA); |
| 2396 | |
| 2397 | // Reset the work list and repopulate with the changed abstract attributes. |
| 2398 | // Note that dependent ones are added above. |
| 2399 | Worklist.clear(); |
| 2400 | Worklist.insert(ChangedAAs.begin(), ChangedAAs.end()); |
| 2401 | |
| 2402 | } while (!Worklist.empty() && ++IterationCounter < MaxFixpointIterations); |
| 2403 | |
| 2404 | LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: " |
| 2405 | << IterationCounter << "/" << MaxFixpointIterations |
| 2406 | << " iterations\n"); |
| 2407 | |
| 2408 | bool FinishedAtFixpoint = Worklist.empty(); |
| 2409 | |
| 2410 | // Reset abstract arguments not settled in a sound fixpoint by now. This |
| 2411 | // happens when we stopped the fixpoint iteration early. Note that only the |
| 2412 | // ones marked as "changed" *and* the ones transitively depending on them |
| 2413 | // need to be reverted to a pessimistic state. Others might not be in a |
| 2414 | // fixpoint state but we can use the optimistic results for them anyway. |
| 2415 | SmallPtrSet<AbstractAttribute *, 32> Visited; |
| 2416 | for (unsigned u = 0; u < ChangedAAs.size(); u++) { |
| 2417 | AbstractAttribute *ChangedAA = ChangedAAs[u]; |
| 2418 | if (!Visited.insert(ChangedAA).second) |
| 2419 | continue; |
| 2420 | |
| 2421 | AbstractState &State = ChangedAA->getState(); |
| 2422 | if (!State.isAtFixpoint()) { |
| 2423 | State.indicatePessimisticFixpoint(); |
| 2424 | |
| 2425 | NumAttributesTimedOut++; |
| 2426 | } |
| 2427 | |
| 2428 | auto &QuerriedAAs = QueryMap[ChangedAA]; |
| 2429 | ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end()); |
| 2430 | } |
| 2431 | |
| 2432 | LLVM_DEBUG({ |
| 2433 | if (!Visited.empty()) |
| 2434 | dbgs() << "\n[Attributor] Finalized " << Visited.size() |
| 2435 | << " abstract attributes.\n"; |
| 2436 | }); |
| 2437 | |
| 2438 | unsigned NumManifested = 0; |
| 2439 | unsigned NumAtFixpoint = 0; |
| 2440 | ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; |
| 2441 | for (AbstractAttribute *AA : AllAbstractAttributes) { |
| 2442 | AbstractState &State = AA->getState(); |
| 2443 | |
| 2444 | // If there is not already a fixpoint reached, we can now take the |
| 2445 | // optimistic state. This is correct because we enforced a pessimistic one |
| 2446 | // on abstract attributes that were transitively dependent on a changed one |
| 2447 | // already above. |
| 2448 | if (!State.isAtFixpoint()) |
| 2449 | State.indicateOptimisticFixpoint(); |
| 2450 | |
| 2451 | // If the state is invalid, we do not try to manifest it. |
| 2452 | if (!State.isValidState()) |
| 2453 | continue; |
| 2454 | |
| 2455 | // Manifest the state and record if we changed the IR. |
| 2456 | ChangeStatus LocalChange = AA->manifest(*this); |
| 2457 | ManifestChange = ManifestChange | LocalChange; |
| 2458 | |
| 2459 | NumAtFixpoint++; |
| 2460 | NumManifested += (LocalChange == ChangeStatus::CHANGED); |
| 2461 | } |
| 2462 | |
| 2463 | (void)NumManifested; |
| 2464 | (void)NumAtFixpoint; |
| 2465 | LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested |
| 2466 | << " arguments while " << NumAtFixpoint |
| 2467 | << " were in a valid fixpoint state\n"); |
| 2468 | |
| 2469 | // If verification is requested, we finished this run at a fixpoint, and the |
| 2470 | // IR was changed, we re-run the whole fixpoint analysis, starting at |
| 2471 | // re-initialization of the arguments. This re-run should not result in an IR |
| 2472 | // change. Though, the (virtual) state of attributes at the end of the re-run |
| 2473 | // might be more optimistic than the known state or the IR state if the better |
| 2474 | // state cannot be manifested. |
| 2475 | if (VerifyAttributor && FinishedAtFixpoint && |
| 2476 | ManifestChange == ChangeStatus::CHANGED) { |
| 2477 | VerifyAttributor = false; |
| 2478 | ChangeStatus VerifyStatus = run(); |
| 2479 | if (VerifyStatus != ChangeStatus::UNCHANGED) |
| 2480 | llvm_unreachable( |
| 2481 | "Attributor verification failed, re-run did result in an IR change " |
| 2482 | "even after a fixpoint was reached in the original run. (False " |
| 2483 | "positives possible!)"); |
| 2484 | VerifyAttributor = true; |
| 2485 | } |
| 2486 | |
| 2487 | NumAttributesManifested += NumManifested; |
| 2488 | NumAttributesValidFixpoint += NumAtFixpoint; |
| 2489 | |
| 2490 | return ManifestChange; |
| 2491 | } |
| 2492 | |
| 2493 | void Attributor::identifyDefaultAbstractAttributes( |
| 2494 | Function &F, InformationCache &InfoCache, |
| 2495 | DenseSet</* Attribute::AttrKind */ unsigned> *Whitelist) { |
| 2496 | |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 2497 | // Every function can be nounwind. |
| 2498 | registerAA(*new AANoUnwindFunction(F, InfoCache)); |
| 2499 | |
| Stefan Stipanovic | 0626367 | 2019-07-11 21:37:40 +0000 | [diff] [blame] | 2500 | // Every function might be marked "nosync" |
| 2501 | registerAA(*new AANoSyncFunction(F, InfoCache)); |
| 2502 | |
| Hideto Ueno | 65bbaf9 | 2019-07-12 17:38:51 +0000 | [diff] [blame] | 2503 | // Every function might be "no-free". |
| 2504 | registerAA(*new AANoFreeFunction(F, InfoCache)); |
| 2505 | |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 2506 | // Return attributes are only appropriate if the return type is non void. |
| 2507 | Type *ReturnType = F.getReturnType(); |
| 2508 | if (!ReturnType->isVoidTy()) { |
| 2509 | // Argument attribute "returned" --- Create only one per function even |
| 2510 | // though it is an argument attribute. |
| 2511 | if (!Whitelist || Whitelist->count(AAReturnedValues::ID)) |
| 2512 | registerAA(*new AAReturnedValuesImpl(F, InfoCache)); |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2513 | |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 2514 | if (ReturnType->isPointerTy()) { |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 2515 | // Every function with pointer return type might be marked align. |
| 2516 | if (!Whitelist || Whitelist->count(AAAlignReturned::ID)) |
| 2517 | registerAA(*new AAAlignReturned(F, InfoCache)); |
| 2518 | |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 2519 | // Every function with pointer return type might be marked nonnull. |
| 2520 | if (!Whitelist || Whitelist->count(AANonNullReturned::ID)) |
| 2521 | registerAA(*new AANonNullReturned(F, InfoCache)); |
| 2522 | |
| 2523 | // Every function with pointer return type might be marked noalias. |
| 2524 | if (!Whitelist || Whitelist->count(AANoAliasReturned::ID)) |
| 2525 | registerAA(*new AANoAliasReturned(F, InfoCache)); |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 2526 | |
| 2527 | // Every function with pointer return type might be marked |
| 2528 | // dereferenceable. |
| 2529 | if (ReturnType->isPointerTy() && |
| 2530 | (!Whitelist || Whitelist->count(AADereferenceableReturned::ID))) |
| 2531 | registerAA(*new AADereferenceableReturned(F, InfoCache)); |
| Stefan Stipanovic | 69ebb02 | 2019-07-22 19:36:27 +0000 | [diff] [blame] | 2532 | } |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2533 | } |
| 2534 | |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2535 | for (Argument &Arg : F.args()) { |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 2536 | if (Arg.getType()->isPointerTy()) { |
| 2537 | // Every argument with pointer type might be marked nonnull. |
| 2538 | if (!Whitelist || Whitelist->count(AANonNullArgument::ID)) |
| 2539 | registerAA(*new AANonNullArgument(Arg, InfoCache)); |
| 2540 | |
| 2541 | // Every argument with pointer type might be marked dereferenceable. |
| 2542 | if (!Whitelist || Whitelist->count(AADereferenceableArgument::ID)) |
| 2543 | registerAA(*new AADereferenceableArgument(Arg, InfoCache)); |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 2544 | |
| 2545 | // Every argument with pointer type might be marked align. |
| 2546 | if (!Whitelist || Whitelist->count(AAAlignArgument::ID)) |
| 2547 | registerAA(*new AAAlignArgument(Arg, InfoCache)); |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 2548 | } |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 2549 | } |
| 2550 | |
| Hideto Ueno | 11d3710 | 2019-07-17 15:15:43 +0000 | [diff] [blame] | 2551 | // Every function might be "will-return". |
| 2552 | registerAA(*new AAWillReturnFunction(F, InfoCache)); |
| 2553 | |
| Stefan Stipanovic | 6058b86 | 2019-07-22 23:58:23 +0000 | [diff] [blame] | 2554 | // Check for dead BasicBlocks in every function. |
| 2555 | registerAA(*new AAIsDeadFunction(F, InfoCache)); |
| 2556 | |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 2557 | // Walk all instructions to find more attribute opportunities and also |
| 2558 | // interesting instructions that might be queried by abstract attributes |
| 2559 | // during their initialization or update. |
| 2560 | auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F]; |
| 2561 | auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F]; |
| 2562 | |
| 2563 | for (Instruction &I : instructions(&F)) { |
| 2564 | bool IsInterestingOpcode = false; |
| 2565 | |
| 2566 | // To allow easy access to all instructions in a function with a given |
| 2567 | // opcode we store them in the InfoCache. As not all opcodes are interesting |
| 2568 | // to concrete attributes we only cache the ones that are as identified in |
| 2569 | // the following switch. |
| 2570 | // Note: There are no concrete attributes now so this is initially empty. |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 2571 | switch (I.getOpcode()) { |
| 2572 | default: |
| 2573 | assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) && |
| 2574 | "New call site/base instruction type needs to be known int the " |
| 2575 | "attributor."); |
| 2576 | break; |
| 2577 | case Instruction::Call: |
| 2578 | case Instruction::CallBr: |
| 2579 | case Instruction::Invoke: |
| 2580 | case Instruction::CleanupRet: |
| 2581 | case Instruction::CatchSwitch: |
| 2582 | case Instruction::Resume: |
| Johannes Doerfert | accd3e8 | 2019-07-08 23:27:20 +0000 | [diff] [blame] | 2583 | case Instruction::Ret: |
| Stefan Stipanovic | 5360589 | 2019-06-27 11:27:54 +0000 | [diff] [blame] | 2584 | IsInterestingOpcode = true; |
| 2585 | } |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 2586 | if (IsInterestingOpcode) |
| 2587 | InstOpcodeMap[I.getOpcode()].push_back(&I); |
| 2588 | if (I.mayReadOrWriteMemory()) |
| 2589 | ReadOrWriteInsts.push_back(&I); |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2590 | |
| 2591 | CallSite CS(&I); |
| 2592 | if (CS && CS.getCalledFunction()) { |
| 2593 | for (int i = 0, e = CS.getCalledFunction()->arg_size(); i < e; i++) { |
| 2594 | if (!CS.getArgument(i)->getType()->isPointerTy()) |
| 2595 | continue; |
| 2596 | |
| 2597 | // Call site argument attribute "non-null". |
| Hideto Ueno | 19c07af | 2019-07-23 08:16:17 +0000 | [diff] [blame] | 2598 | if (!Whitelist || Whitelist->count(AANonNullCallSiteArgument::ID)) |
| 2599 | registerAA(*new AANonNullCallSiteArgument(CS, i, InfoCache), i); |
| 2600 | |
| 2601 | // Call site argument attribute "dereferenceable". |
| 2602 | if (!Whitelist || |
| 2603 | Whitelist->count(AADereferenceableCallSiteArgument::ID)) |
| 2604 | registerAA(*new AADereferenceableCallSiteArgument(CS, i, InfoCache), |
| 2605 | i); |
| Hideto Ueno | e7bea9b | 2019-07-28 07:04:01 +0000 | [diff] [blame] | 2606 | |
| 2607 | // Call site argument attribute "align". |
| 2608 | if (!Whitelist || Whitelist->count(AAAlignCallSiteArgument::ID)) |
| 2609 | registerAA(*new AAAlignCallSiteArgument(CS, i, InfoCache), i); |
| Hideto Ueno | 54869ec | 2019-07-15 06:49:04 +0000 | [diff] [blame] | 2610 | } |
| 2611 | } |
| Johannes Doerfert | aade782 | 2019-06-05 03:02:24 +0000 | [diff] [blame] | 2612 | } |
| 2613 | } |
| 2614 | |
| 2615 | /// Helpers to ease debugging through output streams and print calls. |
| 2616 | /// |
| 2617 | ///{ |
| 2618 | raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { |
| 2619 | return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); |
| 2620 | } |
| 2621 | |
| 2622 | raw_ostream &llvm::operator<<(raw_ostream &OS, |
| 2623 | AbstractAttribute::ManifestPosition AP) { |
| 2624 | switch (AP) { |
| 2625 | case AbstractAttribute::MP_ARGUMENT: |
| 2626 | return OS << "arg"; |
| 2627 | case AbstractAttribute::MP_CALL_SITE_ARGUMENT: |
| 2628 | return OS << "cs_arg"; |
| 2629 | case AbstractAttribute::MP_FUNCTION: |
| 2630 | return OS << "fn"; |
| 2631 | case AbstractAttribute::MP_RETURNED: |
| 2632 | return OS << "fn_ret"; |
| 2633 | } |
| 2634 | llvm_unreachable("Unknown attribute position!"); |
| 2635 | } |
| 2636 | |
| 2637 | raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { |
| 2638 | return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); |
| 2639 | } |
| 2640 | |
| 2641 | raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { |
| 2642 | AA.print(OS); |
| 2643 | return OS; |
| 2644 | } |
| 2645 | |
| 2646 | void AbstractAttribute::print(raw_ostream &OS) const { |
| 2647 | OS << "[" << getManifestPosition() << "][" << getAsStr() << "][" |
| 2648 | << AnchoredVal.getName() << "]"; |
| 2649 | } |
| 2650 | ///} |
| 2651 | |
| 2652 | /// ---------------------------------------------------------------------------- |
| 2653 | /// Pass (Manager) Boilerplate |
| 2654 | /// ---------------------------------------------------------------------------- |
| 2655 | |
| 2656 | static bool runAttributorOnModule(Module &M) { |
| 2657 | if (DisableAttributor) |
| 2658 | return false; |
| 2659 | |
| 2660 | LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size() |
| 2661 | << " functions.\n"); |
| 2662 | |
| 2663 | // Create an Attributor and initially empty information cache that is filled |
| 2664 | // while we identify default attribute opportunities. |
| 2665 | Attributor A; |
| 2666 | InformationCache InfoCache; |
| 2667 | |
| 2668 | for (Function &F : M) { |
| 2669 | // TODO: Not all attributes require an exact definition. Find a way to |
| 2670 | // enable deduction for some but not all attributes in case the |
| 2671 | // definition might be changed at runtime, see also |
| 2672 | // http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html. |
| 2673 | // TODO: We could always determine abstract attributes and if sufficient |
| 2674 | // information was found we could duplicate the functions that do not |
| 2675 | // have an exact definition. |
| 2676 | if (!F.hasExactDefinition()) { |
| 2677 | NumFnWithoutExactDefinition++; |
| 2678 | continue; |
| 2679 | } |
| 2680 | |
| 2681 | // For now we ignore naked and optnone functions. |
| 2682 | if (F.hasFnAttribute(Attribute::Naked) || |
| 2683 | F.hasFnAttribute(Attribute::OptimizeNone)) |
| 2684 | continue; |
| 2685 | |
| 2686 | NumFnWithExactDefinition++; |
| 2687 | |
| 2688 | // Populate the Attributor with abstract attribute opportunities in the |
| 2689 | // function and the information cache with IR information. |
| 2690 | A.identifyDefaultAbstractAttributes(F, InfoCache); |
| 2691 | } |
| 2692 | |
| 2693 | return A.run() == ChangeStatus::CHANGED; |
| 2694 | } |
| 2695 | |
| 2696 | PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { |
| 2697 | if (runAttributorOnModule(M)) { |
| 2698 | // FIXME: Think about passes we will preserve and add them here. |
| 2699 | return PreservedAnalyses::none(); |
| 2700 | } |
| 2701 | return PreservedAnalyses::all(); |
| 2702 | } |
| 2703 | |
| 2704 | namespace { |
| 2705 | |
| 2706 | struct AttributorLegacyPass : public ModulePass { |
| 2707 | static char ID; |
| 2708 | |
| 2709 | AttributorLegacyPass() : ModulePass(ID) { |
| 2710 | initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 2711 | } |
| 2712 | |
| 2713 | bool runOnModule(Module &M) override { |
| 2714 | if (skipModule(M)) |
| 2715 | return false; |
| 2716 | return runAttributorOnModule(M); |
| 2717 | } |
| 2718 | |
| 2719 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 2720 | // FIXME: Think about passes we will preserve and add them here. |
| 2721 | AU.setPreservesCFG(); |
| 2722 | } |
| 2723 | }; |
| 2724 | |
| 2725 | } // end anonymous namespace |
| 2726 | |
| 2727 | Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } |
| 2728 | |
| 2729 | char AttributorLegacyPass::ID = 0; |
| 2730 | INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", |
| 2731 | "Deduce and propagate attributes", false, false) |
| 2732 | INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", |
| 2733 | "Deduce and propagate attributes", false, false) |