Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1 | //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This pass implements whole program optimization of virtual calls in cases |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 10 | // where we know (via !type metadata) that the list of callees is fixed. This |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 11 | // includes the following: |
| 12 | // - Single implementation devirtualization: if a virtual call has a single |
| 13 | // possible callee, replace all calls with a direct call to that callee. |
| 14 | // - Virtual constant propagation: if the virtual function's return type is an |
| 15 | // integer <=64 bits and all possible callees are readnone, for each class and |
| 16 | // each list of constant arguments: evaluate the function, store the return |
| 17 | // value alongside the virtual table, and rewrite each virtual call as a load |
| 18 | // from the virtual table. |
| 19 | // - Uniform return value optimization: if the conditions for virtual constant |
| 20 | // propagation hold and each function returns the same constant value, replace |
| 21 | // each virtual call with that constant. |
| 22 | // - Unique return value optimization for i1 return values: if the conditions |
| 23 | // for virtual constant propagation hold and a single vtable's function |
| 24 | // returns 0, or a single vtable's function returns 1, replace each virtual |
| 25 | // call with a comparison of the vptr against that vtable's address. |
| 26 | // |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 27 | // This pass is intended to be used during the regular and thin LTO pipelines: |
| 28 | // |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 29 | // During regular LTO, the pass determines the best optimization for each |
| 30 | // virtual call and applies the resolutions directly to virtual calls that are |
| 31 | // eligible for virtual call optimization (i.e. calls that use either of the |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 32 | // llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). |
| 33 | // |
| 34 | // During hybrid Regular/ThinLTO, the pass operates in two phases: |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 35 | // - Export phase: this is run during the thin link over a single merged module |
| 36 | // that contains all vtables with !type metadata that participate in the link. |
| 37 | // The pass computes a resolution for each virtual call and stores it in the |
| 38 | // type identifier summary. |
| 39 | // - Import phase: this is run during the thin backends over the individual |
| 40 | // modules. The pass applies the resolutions previously computed during the |
| 41 | // import phase to each eligible virtual call. |
| 42 | // |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 43 | // During ThinLTO, the pass operates in two phases: |
| 44 | // - Export phase: this is run during the thin link over the index which |
| 45 | // contains a summary of all vtables with !type metadata that participate in |
| 46 | // the link. It computes a resolution for each virtual call and stores it in |
| 47 | // the type identifier summary. Only single implementation devirtualization |
| 48 | // is supported. |
| 49 | // - Import phase: (same as with hybrid case above). |
| 50 | // |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 51 | //===----------------------------------------------------------------------===// |
| 52 | |
| 53 | #include "llvm/Transforms/IPO/WholeProgramDevirt.h" |
Mehdi Amini | b550cb1 | 2016-04-18 09:17:29 +0000 | [diff] [blame] | 54 | #include "llvm/ADT/ArrayRef.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 55 | #include "llvm/ADT/DenseMap.h" |
| 56 | #include "llvm/ADT/DenseMapInfo.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 57 | #include "llvm/ADT/DenseSet.h" |
| 58 | #include "llvm/ADT/MapVector.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 59 | #include "llvm/ADT/SmallVector.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 60 | #include "llvm/ADT/iterator_range.h" |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 61 | #include "llvm/Analysis/AliasAnalysis.h" |
| 62 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
Adam Nemet | 0965da2 | 2017-10-09 23:19:02 +0000 | [diff] [blame] | 63 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 64 | #include "llvm/Analysis/TypeMetadataUtils.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 65 | #include "llvm/IR/CallSite.h" |
| 66 | #include "llvm/IR/Constants.h" |
| 67 | #include "llvm/IR/DataLayout.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 68 | #include "llvm/IR/DebugLoc.h" |
| 69 | #include "llvm/IR/DerivedTypes.h" |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 70 | #include "llvm/IR/Dominators.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 71 | #include "llvm/IR/Function.h" |
| 72 | #include "llvm/IR/GlobalAlias.h" |
| 73 | #include "llvm/IR/GlobalVariable.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 74 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 75 | #include "llvm/IR/InstrTypes.h" |
| 76 | #include "llvm/IR/Instruction.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 77 | #include "llvm/IR/Instructions.h" |
| 78 | #include "llvm/IR/Intrinsics.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 79 | #include "llvm/IR/LLVMContext.h" |
| 80 | #include "llvm/IR/Metadata.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 81 | #include "llvm/IR/Module.h" |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 82 | #include "llvm/IR/ModuleSummaryIndexYAML.h" |
Reid Kleckner | 05da2fe | 2019-11-13 13:15:01 -0800 | [diff] [blame] | 83 | #include "llvm/InitializePasses.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 84 | #include "llvm/Pass.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 85 | #include "llvm/PassRegistry.h" |
| 86 | #include "llvm/PassSupport.h" |
| 87 | #include "llvm/Support/Casting.h" |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 88 | #include "llvm/Support/Error.h" |
| 89 | #include "llvm/Support/FileSystem.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 90 | #include "llvm/Support/MathExtras.h" |
Mehdi Amini | b550cb1 | 2016-04-18 09:17:29 +0000 | [diff] [blame] | 91 | #include "llvm/Transforms/IPO.h" |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 92 | #include "llvm/Transforms/IPO/FunctionAttrs.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 93 | #include "llvm/Transforms/Utils/Evaluator.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 94 | #include <algorithm> |
| 95 | #include <cstddef> |
| 96 | #include <map> |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 97 | #include <set> |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 98 | #include <string> |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 99 | |
| 100 | using namespace llvm; |
| 101 | using namespace wholeprogramdevirt; |
| 102 | |
| 103 | #define DEBUG_TYPE "wholeprogramdevirt" |
| 104 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 105 | static cl::opt<PassSummaryAction> ClSummaryAction( |
| 106 | "wholeprogramdevirt-summary-action", |
| 107 | cl::desc("What to do with the summary when running this pass"), |
| 108 | cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), |
| 109 | clEnumValN(PassSummaryAction::Import, "import", |
| 110 | "Import typeid resolutions from summary and globals"), |
| 111 | clEnumValN(PassSummaryAction::Export, "export", |
| 112 | "Export typeid resolutions to summary and globals")), |
| 113 | cl::Hidden); |
| 114 | |
| 115 | static cl::opt<std::string> ClReadSummary( |
| 116 | "wholeprogramdevirt-read-summary", |
| 117 | cl::desc("Read summary from given YAML file before running pass"), |
| 118 | cl::Hidden); |
| 119 | |
| 120 | static cl::opt<std::string> ClWriteSummary( |
| 121 | "wholeprogramdevirt-write-summary", |
| 122 | cl::desc("Write summary to given YAML file after running pass"), |
| 123 | cl::Hidden); |
| 124 | |
Vitaly Buka | 9cb59b9 | 2018-04-06 21:41:17 +0000 | [diff] [blame] | 125 | static cl::opt<unsigned> |
| 126 | ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden, |
| 127 | cl::init(10), cl::ZeroOrMore, |
| 128 | cl::desc("Maximum number of call targets per " |
| 129 | "call site to enable branch funnels")); |
Vitaly Buka | 66f53d7 | 2018-04-06 21:32:36 +0000 | [diff] [blame] | 130 | |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 131 | static cl::opt<bool> |
| 132 | PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden, |
| 133 | cl::init(false), cl::ZeroOrMore, |
| 134 | cl::desc("Print index-based devirtualization messages")); |
| 135 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 136 | // Find the minimum offset that we may store a value of size Size bits at. If |
| 137 | // IsAfter is set, look for an offset before the object, otherwise look for an |
| 138 | // offset after the object. |
| 139 | uint64_t |
| 140 | wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, |
| 141 | bool IsAfter, uint64_t Size) { |
| 142 | // Find a minimum offset taking into account only vtable sizes. |
| 143 | uint64_t MinByte = 0; |
| 144 | for (const VirtualCallTarget &Target : Targets) { |
| 145 | if (IsAfter) |
| 146 | MinByte = std::max(MinByte, Target.minAfterBytes()); |
| 147 | else |
| 148 | MinByte = std::max(MinByte, Target.minBeforeBytes()); |
| 149 | } |
| 150 | |
| 151 | // Build a vector of arrays of bytes covering, for each target, a slice of the |
| 152 | // used region (see AccumBitVector::BytesUsed in |
| 153 | // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, |
| 154 | // this aligns the used regions to start at MinByte. |
| 155 | // |
| 156 | // In this example, A, B and C are vtables, # is a byte already allocated for |
| 157 | // a virtual function pointer, AAAA... (etc.) are the used regions for the |
| 158 | // vtables and Offset(X) is the value computed for the Offset variable below |
| 159 | // for X. |
| 160 | // |
| 161 | // Offset(A) |
| 162 | // | | |
| 163 | // |MinByte |
| 164 | // A: ################AAAAAAAA|AAAAAAAA |
| 165 | // B: ########BBBBBBBBBBBBBBBB|BBBB |
| 166 | // C: ########################|CCCCCCCCCCCCCCCC |
| 167 | // | Offset(B) | |
| 168 | // |
| 169 | // This code produces the slices of A, B and C that appear after the divider |
| 170 | // at MinByte. |
| 171 | std::vector<ArrayRef<uint8_t>> Used; |
| 172 | for (const VirtualCallTarget &Target : Targets) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 173 | ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed |
| 174 | : Target.TM->Bits->Before.BytesUsed; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 175 | uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() |
| 176 | : MinByte - Target.minBeforeBytes(); |
| 177 | |
| 178 | // Disregard used regions that are smaller than Offset. These are |
| 179 | // effectively all-free regions that do not need to be checked. |
| 180 | if (VTUsed.size() > Offset) |
| 181 | Used.push_back(VTUsed.slice(Offset)); |
| 182 | } |
| 183 | |
| 184 | if (Size == 1) { |
| 185 | // Find a free bit in each member of Used. |
| 186 | for (unsigned I = 0;; ++I) { |
| 187 | uint8_t BitsUsed = 0; |
| 188 | for (auto &&B : Used) |
| 189 | if (I < B.size()) |
| 190 | BitsUsed |= B[I]; |
| 191 | if (BitsUsed != 0xff) |
| 192 | return (MinByte + I) * 8 + |
| 193 | countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); |
| 194 | } |
| 195 | } else { |
| 196 | // Find a free (Size/8) byte region in each member of Used. |
| 197 | // FIXME: see if alignment helps. |
| 198 | for (unsigned I = 0;; ++I) { |
| 199 | for (auto &&B : Used) { |
| 200 | unsigned Byte = 0; |
| 201 | while ((I + Byte) < B.size() && Byte < (Size / 8)) { |
| 202 | if (B[I + Byte]) |
| 203 | goto NextI; |
| 204 | ++Byte; |
| 205 | } |
| 206 | } |
| 207 | return (MinByte + I) * 8; |
| 208 | NextI:; |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | void wholeprogramdevirt::setBeforeReturnValues( |
| 214 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, |
| 215 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 216 | if (BitWidth == 1) |
| 217 | OffsetByte = -(AllocBefore / 8 + 1); |
| 218 | else |
| 219 | OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); |
| 220 | OffsetBit = AllocBefore % 8; |
| 221 | |
| 222 | for (VirtualCallTarget &Target : Targets) { |
| 223 | if (BitWidth == 1) |
| 224 | Target.setBeforeBit(AllocBefore); |
| 225 | else |
| 226 | Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | void wholeprogramdevirt::setAfterReturnValues( |
| 231 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, |
| 232 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 233 | if (BitWidth == 1) |
| 234 | OffsetByte = AllocAfter / 8; |
| 235 | else |
| 236 | OffsetByte = (AllocAfter + 7) / 8; |
| 237 | OffsetBit = AllocAfter % 8; |
| 238 | |
| 239 | for (VirtualCallTarget &Target : Targets) { |
| 240 | if (BitWidth == 1) |
| 241 | Target.setAfterBit(AllocAfter); |
| 242 | else |
| 243 | Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); |
| 244 | } |
| 245 | } |
| 246 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 247 | VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM) |
| 248 | : Fn(Fn), TM(TM), |
Ivan Krasin | 89439a7 | 2016-08-12 01:40:10 +0000 | [diff] [blame] | 249 | IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {} |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 250 | |
| 251 | namespace { |
| 252 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 253 | // A slot in a set of virtual tables. The TypeID identifies the set of virtual |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 254 | // tables, and the ByteOffset is the offset in bytes from the address point to |
| 255 | // the virtual function pointer. |
| 256 | struct VTableSlot { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 257 | Metadata *TypeID; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 258 | uint64_t ByteOffset; |
| 259 | }; |
| 260 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 261 | } // end anonymous namespace |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 262 | |
Peter Collingbourne | 9b65652 | 2016-02-09 23:01:38 +0000 | [diff] [blame] | 263 | namespace llvm { |
| 264 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 265 | template <> struct DenseMapInfo<VTableSlot> { |
| 266 | static VTableSlot getEmptyKey() { |
| 267 | return {DenseMapInfo<Metadata *>::getEmptyKey(), |
| 268 | DenseMapInfo<uint64_t>::getEmptyKey()}; |
| 269 | } |
| 270 | static VTableSlot getTombstoneKey() { |
| 271 | return {DenseMapInfo<Metadata *>::getTombstoneKey(), |
| 272 | DenseMapInfo<uint64_t>::getTombstoneKey()}; |
| 273 | } |
| 274 | static unsigned getHashValue(const VTableSlot &I) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 275 | return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^ |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 276 | DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); |
| 277 | } |
| 278 | static bool isEqual(const VTableSlot &LHS, |
| 279 | const VTableSlot &RHS) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 280 | return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 281 | } |
| 282 | }; |
| 283 | |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 284 | template <> struct DenseMapInfo<VTableSlotSummary> { |
| 285 | static VTableSlotSummary getEmptyKey() { |
| 286 | return {DenseMapInfo<StringRef>::getEmptyKey(), |
| 287 | DenseMapInfo<uint64_t>::getEmptyKey()}; |
| 288 | } |
| 289 | static VTableSlotSummary getTombstoneKey() { |
| 290 | return {DenseMapInfo<StringRef>::getTombstoneKey(), |
| 291 | DenseMapInfo<uint64_t>::getTombstoneKey()}; |
| 292 | } |
| 293 | static unsigned getHashValue(const VTableSlotSummary &I) { |
| 294 | return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^ |
| 295 | DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); |
| 296 | } |
| 297 | static bool isEqual(const VTableSlotSummary &LHS, |
| 298 | const VTableSlotSummary &RHS) { |
| 299 | return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; |
| 300 | } |
| 301 | }; |
| 302 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 303 | } // end namespace llvm |
Peter Collingbourne | 9b65652 | 2016-02-09 23:01:38 +0000 | [diff] [blame] | 304 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 305 | namespace { |
| 306 | |
| 307 | // A virtual call site. VTable is the loaded virtual table pointer, and CS is |
| 308 | // the indirect virtual call. |
| 309 | struct VirtualCallSite { |
| 310 | Value *VTable; |
| 311 | CallSite CS; |
| 312 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 313 | // If non-null, this field points to the associated unsafe use count stored in |
| 314 | // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description |
| 315 | // of that field for details. |
| 316 | unsigned *NumUnsafeUses; |
| 317 | |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 318 | void |
| 319 | emitRemark(const StringRef OptName, const StringRef TargetName, |
| 320 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) { |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 321 | Function *F = CS.getCaller(); |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 322 | DebugLoc DLoc = CS->getDebugLoc(); |
| 323 | BasicBlock *Block = CS.getParent(); |
| 324 | |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 325 | using namespace ore; |
Peter Collingbourne | 9110cb4 | 2018-01-05 00:27:51 +0000 | [diff] [blame] | 326 | OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block) |
| 327 | << NV("Optimization", OptName) |
| 328 | << ": devirtualized a call to " |
| 329 | << NV("FunctionName", TargetName)); |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 330 | } |
| 331 | |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 332 | void replaceAndErase( |
| 333 | const StringRef OptName, const StringRef TargetName, bool RemarksEnabled, |
| 334 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, |
| 335 | Value *New) { |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 336 | if (RemarksEnabled) |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 337 | emitRemark(OptName, TargetName, OREGetter); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 338 | CS->replaceAllUsesWith(New); |
| 339 | if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) { |
| 340 | BranchInst::Create(II->getNormalDest(), CS.getInstruction()); |
| 341 | II->getUnwindDest()->removePredecessor(II->getParent()); |
| 342 | } |
| 343 | CS->eraseFromParent(); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 344 | // This use is no longer unsafe. |
| 345 | if (NumUnsafeUses) |
| 346 | --*NumUnsafeUses; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 347 | } |
| 348 | }; |
| 349 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 350 | // Call site information collected for a specific VTableSlot and possibly a list |
| 351 | // of constant integer arguments. The grouping by arguments is handled by the |
| 352 | // VTableSlotInfo class. |
| 353 | struct CallSiteInfo { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 354 | /// The set of call sites for this slot. Used during regular LTO and the |
| 355 | /// import phase of ThinLTO (as well as the export phase of ThinLTO for any |
| 356 | /// call sites that appear in the merged module itself); in each of these |
| 357 | /// cases we are directly operating on the call sites at the IR level. |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 358 | std::vector<VirtualCallSite> CallSites; |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 359 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 360 | /// Whether all call sites represented by this CallSiteInfo, including those |
| 361 | /// in summaries, have been devirtualized. This starts off as true because a |
| 362 | /// default constructed CallSiteInfo represents no call sites. |
| 363 | bool AllCallSitesDevirted = true; |
| 364 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 365 | // These fields are used during the export phase of ThinLTO and reflect |
| 366 | // information collected from function summaries. |
| 367 | |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 368 | /// Whether any function summary contains an llvm.assume(llvm.type.test) for |
| 369 | /// this slot. |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 370 | bool SummaryHasTypeTestAssumeUsers = false; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 371 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 372 | /// CFI-specific: a vector containing the list of function summaries that use |
| 373 | /// the llvm.type.checked.load intrinsic and therefore will require |
| 374 | /// resolutions for llvm.type.test in order to implement CFI checks if |
| 375 | /// devirtualization was unsuccessful. If devirtualization was successful, the |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 376 | /// pass will clear this vector by calling markDevirt(). If at the end of the |
| 377 | /// pass the vector is non-empty, we will need to add a use of llvm.type.test |
| 378 | /// to each of the function summaries in the vector. |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 379 | std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers; |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 380 | std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 381 | |
| 382 | bool isExported() const { |
| 383 | return SummaryHasTypeTestAssumeUsers || |
| 384 | !SummaryTypeCheckedLoadUsers.empty(); |
| 385 | } |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 386 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 387 | void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) { |
| 388 | SummaryTypeCheckedLoadUsers.push_back(FS); |
| 389 | AllCallSitesDevirted = false; |
| 390 | } |
| 391 | |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 392 | void addSummaryTypeTestAssumeUser(FunctionSummary *FS) { |
| 393 | SummaryTypeTestAssumeUsers.push_back(FS); |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 394 | SummaryHasTypeTestAssumeUsers = true; |
| 395 | AllCallSitesDevirted = false; |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 396 | } |
| 397 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 398 | void markDevirt() { |
| 399 | AllCallSitesDevirted = true; |
| 400 | |
| 401 | // As explained in the comment for SummaryTypeCheckedLoadUsers. |
| 402 | SummaryTypeCheckedLoadUsers.clear(); |
| 403 | } |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 404 | }; |
| 405 | |
| 406 | // Call site information collected for a specific VTableSlot. |
| 407 | struct VTableSlotInfo { |
| 408 | // The set of call sites which do not have all constant integer arguments |
| 409 | // (excluding "this"). |
| 410 | CallSiteInfo CSInfo; |
| 411 | |
| 412 | // The set of call sites with all constant integer arguments (excluding |
| 413 | // "this"), grouped by argument list. |
| 414 | std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; |
| 415 | |
| 416 | void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses); |
| 417 | |
| 418 | private: |
| 419 | CallSiteInfo &findCallSiteInfo(CallSite CS); |
| 420 | }; |
| 421 | |
| 422 | CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) { |
| 423 | std::vector<uint64_t> Args; |
| 424 | auto *CI = dyn_cast<IntegerType>(CS.getType()); |
| 425 | if (!CI || CI->getBitWidth() > 64 || CS.arg_empty()) |
| 426 | return CSInfo; |
| 427 | for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) { |
| 428 | auto *CI = dyn_cast<ConstantInt>(Arg); |
| 429 | if (!CI || CI->getBitWidth() > 64) |
| 430 | return CSInfo; |
| 431 | Args.push_back(CI->getZExtValue()); |
| 432 | } |
| 433 | return ConstCSInfo[Args]; |
| 434 | } |
| 435 | |
| 436 | void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS, |
| 437 | unsigned *NumUnsafeUses) { |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 438 | auto &CSI = findCallSiteInfo(CS); |
| 439 | CSI.AllCallSitesDevirted = false; |
| 440 | CSI.CallSites.push_back({VTable, CS, NumUnsafeUses}); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 441 | } |
| 442 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 443 | struct DevirtModule { |
| 444 | Module &M; |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 445 | function_ref<AAResults &(Function &)> AARGetter; |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 446 | function_ref<DominatorTree &(Function &)> LookupDomTree; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 447 | |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 448 | ModuleSummaryIndex *ExportSummary; |
| 449 | const ModuleSummaryIndex *ImportSummary; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 450 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 451 | IntegerType *Int8Ty; |
| 452 | PointerType *Int8PtrTy; |
| 453 | IntegerType *Int32Ty; |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 454 | IntegerType *Int64Ty; |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 455 | IntegerType *IntPtrTy; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 456 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 457 | bool RemarksEnabled; |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 458 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter; |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 459 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 460 | MapVector<VTableSlot, VTableSlotInfo> CallSlots; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 461 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 462 | // This map keeps track of the number of "unsafe" uses of a loaded function |
| 463 | // pointer. The key is the associated llvm.type.test intrinsic call generated |
| 464 | // by this pass. An unsafe use is one that calls the loaded function pointer |
| 465 | // directly. Every time we eliminate an unsafe use (for example, by |
| 466 | // devirtualizing it or by applying virtual constant propagation), we |
| 467 | // decrement the value stored in this map. If a value reaches zero, we can |
| 468 | // eliminate the type check by RAUWing the associated llvm.type.test call with |
| 469 | // true. |
| 470 | std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; |
| 471 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 472 | DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter, |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 473 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 474 | function_ref<DominatorTree &(Function &)> LookupDomTree, |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 475 | ModuleSummaryIndex *ExportSummary, |
| 476 | const ModuleSummaryIndex *ImportSummary) |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 477 | : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree), |
| 478 | ExportSummary(ExportSummary), ImportSummary(ImportSummary), |
| 479 | Int8Ty(Type::getInt8Ty(M.getContext())), |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 480 | Int8PtrTy(Type::getInt8PtrTy(M.getContext())), |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 481 | Int32Ty(Type::getInt32Ty(M.getContext())), |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 482 | Int64Ty(Type::getInt64Ty(M.getContext())), |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 483 | IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)), |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 484 | RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) { |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 485 | assert(!(ExportSummary && ImportSummary)); |
| 486 | } |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 487 | |
| 488 | bool areRemarksEnabled(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 489 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 490 | void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc); |
| 491 | void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); |
| 492 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 493 | void buildTypeIdentifierMap( |
| 494 | std::vector<VTableBits> &Bits, |
| 495 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); |
| 496 | bool |
| 497 | tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, |
| 498 | const std::set<TypeMemberInfo> &TypeMemberInfos, |
| 499 | uint64_t ByteOffset); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 500 | |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 501 | void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn, |
| 502 | bool &IsExported); |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 503 | bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary, |
| 504 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 505 | VTableSlotInfo &SlotInfo, |
| 506 | WholeProgramDevirtResolution *Res); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 507 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 508 | void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT, |
| 509 | bool &IsExported); |
| 510 | void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
| 511 | VTableSlotInfo &SlotInfo, |
| 512 | WholeProgramDevirtResolution *Res, VTableSlot Slot); |
| 513 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 514 | bool tryEvaluateFunctionsWithArgs( |
| 515 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 516 | ArrayRef<uint64_t> Args); |
| 517 | |
| 518 | void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 519 | uint64_t TheRetVal); |
| 520 | bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 521 | CallSiteInfo &CSInfo, |
| 522 | WholeProgramDevirtResolution::ByArg *Res); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 523 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 524 | // Returns the global symbol name that is used to export information about the |
| 525 | // given vtable slot and list of arguments. |
| 526 | std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args, |
| 527 | StringRef Name); |
| 528 | |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 529 | bool shouldExportConstantsAsAbsoluteSymbols(); |
| 530 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 531 | // This function is called during the export phase to create a symbol |
| 532 | // definition containing information about the given vtable slot and list of |
| 533 | // arguments. |
| 534 | void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, |
| 535 | Constant *C); |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 536 | void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, |
| 537 | uint32_t Const, uint32_t &Storage); |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 538 | |
| 539 | // This function is called during the import phase to create a reference to |
| 540 | // the symbol definition created during the export phase. |
| 541 | Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 542 | StringRef Name); |
| 543 | Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, |
| 544 | StringRef Name, IntegerType *IntTy, |
| 545 | uint32_t Storage); |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 546 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 547 | Constant *getMemberAddr(const TypeMemberInfo *M); |
| 548 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 549 | void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, |
| 550 | Constant *UniqueMemberAddr); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 551 | bool tryUniqueRetValOpt(unsigned BitWidth, |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 552 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 553 | CallSiteInfo &CSInfo, |
| 554 | WholeProgramDevirtResolution::ByArg *Res, |
| 555 | VTableSlot Slot, ArrayRef<uint64_t> Args); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 556 | |
| 557 | void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 558 | Constant *Byte, Constant *Bit); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 559 | bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 560 | VTableSlotInfo &SlotInfo, |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 561 | WholeProgramDevirtResolution *Res, VTableSlot Slot); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 562 | |
| 563 | void rebuildGlobal(VTableBits &B); |
| 564 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 565 | // Apply the summary resolution for Slot to all virtual calls in SlotInfo. |
| 566 | void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo); |
| 567 | |
| 568 | // If we were able to eliminate all unsafe uses for a type checked load, |
| 569 | // eliminate the associated type tests by replacing them with true. |
| 570 | void removeRedundantTypeTests(); |
| 571 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 572 | bool run(); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 573 | |
| 574 | // Lower the module using the action and summary passed as command line |
| 575 | // arguments. For testing purposes only. |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 576 | static bool |
| 577 | runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter, |
| 578 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, |
| 579 | function_ref<DominatorTree &(Function &)> LookupDomTree); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 580 | }; |
| 581 | |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 582 | struct DevirtIndex { |
| 583 | ModuleSummaryIndex &ExportSummary; |
| 584 | // The set in which to record GUIDs exported from their module by |
| 585 | // devirtualization, used by client to ensure they are not internalized. |
| 586 | std::set<GlobalValue::GUID> &ExportedGUIDs; |
| 587 | // A map in which to record the information necessary to locate the WPD |
| 588 | // resolution for local targets in case they are exported by cross module |
| 589 | // importing. |
| 590 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap; |
| 591 | |
| 592 | MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots; |
| 593 | |
| 594 | DevirtIndex( |
| 595 | ModuleSummaryIndex &ExportSummary, |
| 596 | std::set<GlobalValue::GUID> &ExportedGUIDs, |
| 597 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) |
| 598 | : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs), |
| 599 | LocalWPDTargetsMap(LocalWPDTargetsMap) {} |
| 600 | |
| 601 | bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot, |
| 602 | const TypeIdCompatibleVtableInfo TIdInfo, |
| 603 | uint64_t ByteOffset); |
| 604 | |
| 605 | bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, |
| 606 | VTableSlotSummary &SlotSummary, |
| 607 | VTableSlotInfo &SlotInfo, |
| 608 | WholeProgramDevirtResolution *Res, |
| 609 | std::set<ValueInfo> &DevirtTargets); |
| 610 | |
| 611 | void run(); |
| 612 | }; |
| 613 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 614 | struct WholeProgramDevirt : public ModulePass { |
| 615 | static char ID; |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 616 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 617 | bool UseCommandLine = false; |
| 618 | |
Simon Pilgrim | 39c0829 | 2019-11-14 13:54:29 +0000 | [diff] [blame] | 619 | ModuleSummaryIndex *ExportSummary = nullptr; |
| 620 | const ModuleSummaryIndex *ImportSummary = nullptr; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 621 | |
| 622 | WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) { |
| 623 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 624 | } |
| 625 | |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 626 | WholeProgramDevirt(ModuleSummaryIndex *ExportSummary, |
| 627 | const ModuleSummaryIndex *ImportSummary) |
| 628 | : ModulePass(ID), ExportSummary(ExportSummary), |
| 629 | ImportSummary(ImportSummary) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 630 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 631 | } |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 632 | |
| 633 | bool runOnModule(Module &M) override { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 634 | if (skipModule(M)) |
| 635 | return false; |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 636 | |
Peter Collingbourne | 9110cb4 | 2018-01-05 00:27:51 +0000 | [diff] [blame] | 637 | // In the new pass manager, we can request the optimization |
| 638 | // remark emitter pass on a per-function-basis, which the |
| 639 | // OREGetter will do for us. |
| 640 | // In the old pass manager, this is harder, so we just build |
| 641 | // an optimization remark emitter on the fly, when we need it. |
| 642 | std::unique_ptr<OptimizationRemarkEmitter> ORE; |
| 643 | auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & { |
Jonas Devlieghere | 0eaee54 | 2019-08-15 15:54:37 +0000 | [diff] [blame] | 644 | ORE = std::make_unique<OptimizationRemarkEmitter>(F); |
Peter Collingbourne | 9110cb4 | 2018-01-05 00:27:51 +0000 | [diff] [blame] | 645 | return *ORE; |
| 646 | }; |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 647 | |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 648 | auto LookupDomTree = [this](Function &F) -> DominatorTree & { |
| 649 | return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); |
| 650 | }; |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 651 | |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 652 | if (UseCommandLine) |
| 653 | return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter, |
| 654 | LookupDomTree); |
| 655 | |
| 656 | return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree, |
| 657 | ExportSummary, ImportSummary) |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 658 | .run(); |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 659 | } |
| 660 | |
| 661 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 662 | AU.addRequired<AssumptionCacheTracker>(); |
| 663 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 664 | AU.addRequired<DominatorTreeWrapperPass>(); |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 665 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 666 | }; |
| 667 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 668 | } // end anonymous namespace |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 669 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 670 | INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt", |
| 671 | "Whole program devirtualization", false, false) |
| 672 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 673 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 674 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 675 | INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt", |
| 676 | "Whole program devirtualization", false, false) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 677 | char WholeProgramDevirt::ID = 0; |
| 678 | |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 679 | ModulePass * |
| 680 | llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary, |
| 681 | const ModuleSummaryIndex *ImportSummary) { |
| 682 | return new WholeProgramDevirt(ExportSummary, ImportSummary); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 683 | } |
| 684 | |
Chandler Carruth | 164a2aa6 | 2016-06-17 00:11:01 +0000 | [diff] [blame] | 685 | PreservedAnalyses WholeProgramDevirtPass::run(Module &M, |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 686 | ModuleAnalysisManager &AM) { |
| 687 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
| 688 | auto AARGetter = [&](Function &F) -> AAResults & { |
| 689 | return FAM.getResult<AAManager>(F); |
| 690 | }; |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 691 | auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & { |
| 692 | return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); |
| 693 | }; |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 694 | auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & { |
| 695 | return FAM.getResult<DominatorTreeAnalysis>(F); |
| 696 | }; |
| 697 | if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary, |
| 698 | ImportSummary) |
Teresa Johnson | 28023db | 2018-07-19 14:51:32 +0000 | [diff] [blame] | 699 | .run()) |
Davide Italiano | d737dd2 | 2016-06-14 21:44:19 +0000 | [diff] [blame] | 700 | return PreservedAnalyses::all(); |
| 701 | return PreservedAnalyses::none(); |
| 702 | } |
| 703 | |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 704 | namespace llvm { |
| 705 | void runWholeProgramDevirtOnIndex( |
| 706 | ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs, |
| 707 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { |
| 708 | DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run(); |
| 709 | } |
| 710 | |
| 711 | void updateIndexWPDForExports( |
| 712 | ModuleSummaryIndex &Summary, |
Benjamin Kramer | 360f661 | 2019-11-14 16:07:13 +0100 | [diff] [blame] | 713 | function_ref<bool(StringRef, GlobalValue::GUID)> isExported, |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 714 | std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { |
| 715 | for (auto &T : LocalWPDTargetsMap) { |
| 716 | auto &VI = T.first; |
| 717 | // This was enforced earlier during trySingleImplDevirt. |
| 718 | assert(VI.getSummaryList().size() == 1 && |
| 719 | "Devirt of local target has more than one copy"); |
| 720 | auto &S = VI.getSummaryList()[0]; |
Benjamin Kramer | 360f661 | 2019-11-14 16:07:13 +0100 | [diff] [blame] | 721 | if (!isExported(S->modulePath(), VI.getGUID())) |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 722 | continue; |
| 723 | |
| 724 | // It's been exported by a cross module import. |
| 725 | for (auto &SlotSummary : T.second) { |
| 726 | auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID); |
| 727 | assert(TIdSum); |
| 728 | auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset); |
| 729 | assert(WPDRes != TIdSum->WPDRes.end()); |
| 730 | WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( |
| 731 | WPDRes->second.SingleImplName, |
| 732 | Summary.getModuleHash(S->modulePath())); |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | } // end namespace llvm |
| 738 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 739 | bool DevirtModule::runForTesting( |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 740 | Module &M, function_ref<AAResults &(Function &)> AARGetter, |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 741 | function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, |
| 742 | function_ref<DominatorTree &(Function &)> LookupDomTree) { |
Teresa Johnson | 4ffc3e7 | 2018-06-06 22:22:01 +0000 | [diff] [blame] | 743 | ModuleSummaryIndex Summary(/*HaveGVs=*/false); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 744 | |
| 745 | // Handle the command-line summary arguments. This code is for testing |
| 746 | // purposes only, so we handle errors directly. |
| 747 | if (!ClReadSummary.empty()) { |
| 748 | ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + |
| 749 | ": "); |
| 750 | auto ReadSummaryFile = |
| 751 | ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); |
| 752 | |
| 753 | yaml::Input In(ReadSummaryFile->getBuffer()); |
| 754 | In >> Summary; |
| 755 | ExitOnErr(errorCodeToError(In.error())); |
| 756 | } |
| 757 | |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 758 | bool Changed = |
| 759 | DevirtModule( |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 760 | M, AARGetter, OREGetter, LookupDomTree, |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 761 | ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr, |
| 762 | ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr) |
| 763 | .run(); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 764 | |
| 765 | if (!ClWriteSummary.empty()) { |
| 766 | ExitOnError ExitOnErr( |
| 767 | "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); |
| 768 | std::error_code EC; |
Fangrui Song | d9b948b | 2019-08-05 05:43:48 +0000 | [diff] [blame] | 769 | raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_Text); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 770 | ExitOnErr(errorCodeToError(EC)); |
| 771 | |
| 772 | yaml::Output Out(OS); |
| 773 | Out << Summary; |
| 774 | } |
| 775 | |
| 776 | return Changed; |
| 777 | } |
| 778 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 779 | void DevirtModule::buildTypeIdentifierMap( |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 780 | std::vector<VTableBits> &Bits, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 781 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 782 | DenseMap<GlobalVariable *, VTableBits *> GVToBits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 783 | Bits.reserve(M.getGlobalList().size()); |
| 784 | SmallVector<MDNode *, 2> Types; |
| 785 | for (GlobalVariable &GV : M.globals()) { |
| 786 | Types.clear(); |
| 787 | GV.getMetadata(LLVMContext::MD_type, Types); |
Eugene Leviant | 2b70d61 | 2018-09-23 13:27:47 +0000 | [diff] [blame] | 788 | if (GV.isDeclaration() || Types.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 789 | continue; |
| 790 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 791 | VTableBits *&BitsPtr = GVToBits[&GV]; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 792 | if (!BitsPtr) { |
| 793 | Bits.emplace_back(); |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 794 | Bits.back().GV = &GV; |
| 795 | Bits.back().ObjectSize = |
| 796 | M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 797 | BitsPtr = &Bits.back(); |
| 798 | } |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 799 | |
| 800 | for (MDNode *Type : Types) { |
| 801 | auto TypeID = Type->getOperand(1).get(); |
| 802 | |
| 803 | uint64_t Offset = |
| 804 | cast<ConstantInt>( |
| 805 | cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) |
| 806 | ->getZExtValue(); |
| 807 | |
| 808 | TypeIdMap[TypeID].insert({BitsPtr, Offset}); |
| 809 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 810 | } |
| 811 | } |
| 812 | |
| 813 | bool DevirtModule::tryFindVirtualCallTargets( |
| 814 | std::vector<VirtualCallTarget> &TargetsForSlot, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 815 | const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) { |
| 816 | for (const TypeMemberInfo &TM : TypeMemberInfos) { |
| 817 | if (!TM.Bits->GV->isConstant()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 818 | return false; |
| 819 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 820 | Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), |
Oliver Stannard | 3b598b9 | 2019-10-17 09:58:57 +0000 | [diff] [blame] | 821 | TM.Offset + ByteOffset, M); |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 822 | if (!Ptr) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 823 | return false; |
| 824 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 825 | auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 826 | if (!Fn) |
| 827 | return false; |
| 828 | |
| 829 | // We can disregard __cxa_pure_virtual as a possible call target, as |
| 830 | // calls to pure virtuals are UB. |
| 831 | if (Fn->getName() == "__cxa_pure_virtual") |
| 832 | continue; |
| 833 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 834 | TargetsForSlot.push_back({Fn, &TM}); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 835 | } |
| 836 | |
| 837 | // Give up if we couldn't find any targets. |
| 838 | return !TargetsForSlot.empty(); |
| 839 | } |
| 840 | |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 841 | bool DevirtIndex::tryFindVirtualCallTargets( |
| 842 | std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo, |
| 843 | uint64_t ByteOffset) { |
| 844 | for (const TypeIdOffsetVtableInfo P : TIdInfo) { |
Teresa Johnson | c844f88 | 2019-10-25 14:56:12 -0700 | [diff] [blame] | 845 | // Ensure that we have at most one external linkage vtable initializer. |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 846 | assert(P.VTableVI.getSummaryList().size() == 1 || |
Teresa Johnson | c844f88 | 2019-10-25 14:56:12 -0700 | [diff] [blame] | 847 | llvm::count_if( |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 848 | P.VTableVI.getSummaryList(), |
| 849 | [&](const std::unique_ptr<GlobalValueSummary> &Summary) { |
Teresa Johnson | c844f88 | 2019-10-25 14:56:12 -0700 | [diff] [blame] | 850 | return GlobalValue::isExternalLinkage(Summary->linkage()); |
| 851 | }) <= 1); |
| 852 | // Find the first non-available_externally linkage vtable initializer. |
| 853 | // We can have multiple available_externally, linkonce_odr and weak_odr |
| 854 | // vtable initializers, however we want to skip available_externally as they |
| 855 | // do not have type metadata attached, and therefore the summary will not |
| 856 | // contain any vtable functions. |
| 857 | // |
| 858 | // Also, handle the case of same-named local Vtables with the same path |
| 859 | // and therefore the same GUID. This can happen if there isn't enough |
| 860 | // distinguishing path when compiling the source file. In that case we |
| 861 | // conservatively return false early. |
| 862 | const GlobalVarSummary *VS = nullptr; |
| 863 | bool LocalFound = false; |
| 864 | for (auto &S : P.VTableVI.getSummaryList()) { |
| 865 | if (GlobalValue::isLocalLinkage(S->linkage())) { |
| 866 | if (LocalFound) |
| 867 | return false; |
| 868 | LocalFound = true; |
| 869 | } |
| 870 | if (!GlobalValue::isAvailableExternallyLinkage(S->linkage())) |
| 871 | VS = cast<GlobalVarSummary>(S.get()); |
| 872 | } |
| 873 | if (!VS->isLive()) |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 874 | continue; |
| 875 | for (auto VTP : VS->vTableFuncs()) { |
| 876 | if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset) |
| 877 | continue; |
| 878 | |
| 879 | TargetsForSlot.push_back(VTP.FuncVI); |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | // Give up if we couldn't find any targets. |
| 884 | return !TargetsForSlot.empty(); |
| 885 | } |
| 886 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 887 | void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 888 | Constant *TheFn, bool &IsExported) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 889 | auto Apply = [&](CallSiteInfo &CSInfo) { |
| 890 | for (auto &&VCallSite : CSInfo.CallSites) { |
| 891 | if (RemarksEnabled) |
Teresa Johnson | b0a1d3b | 2018-08-14 03:00:16 +0000 | [diff] [blame] | 892 | VCallSite.emitRemark("single-impl", |
| 893 | TheFn->stripPointerCasts()->getName(), OREGetter); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 894 | VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast( |
| 895 | TheFn, VCallSite.CS.getCalledValue()->getType())); |
| 896 | // This use is no longer unsafe. |
| 897 | if (VCallSite.NumUnsafeUses) |
| 898 | --*VCallSite.NumUnsafeUses; |
| 899 | } |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 900 | if (CSInfo.isExported()) |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 901 | IsExported = true; |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 902 | CSInfo.markDevirt(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 903 | }; |
| 904 | Apply(SlotInfo.CSInfo); |
| 905 | for (auto &P : SlotInfo.ConstCSInfo) |
| 906 | Apply(P.second); |
| 907 | } |
| 908 | |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 909 | static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) { |
| 910 | // We can't add calls if we haven't seen a definition |
| 911 | if (Callee.getSummaryList().empty()) |
| 912 | return false; |
| 913 | |
| 914 | // Insert calls into the summary index so that the devirtualized targets |
| 915 | // are eligible for import. |
| 916 | // FIXME: Annotate type tests with hotness. For now, mark these as hot |
| 917 | // to better ensure we have the opportunity to inline them. |
| 918 | bool IsExported = false; |
| 919 | auto &S = Callee.getSummaryList()[0]; |
| 920 | CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0); |
| 921 | auto AddCalls = [&](CallSiteInfo &CSInfo) { |
| 922 | for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) { |
| 923 | FS->addCall({Callee, CI}); |
| 924 | IsExported |= S->modulePath() != FS->modulePath(); |
| 925 | } |
| 926 | for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) { |
| 927 | FS->addCall({Callee, CI}); |
| 928 | IsExported |= S->modulePath() != FS->modulePath(); |
| 929 | } |
| 930 | }; |
| 931 | AddCalls(SlotInfo.CSInfo); |
| 932 | for (auto &P : SlotInfo.ConstCSInfo) |
| 933 | AddCalls(P.second); |
| 934 | return IsExported; |
| 935 | } |
| 936 | |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 937 | bool DevirtModule::trySingleImplDevirt( |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 938 | ModuleSummaryIndex *ExportSummary, |
| 939 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, |
| 940 | WholeProgramDevirtResolution *Res) { |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 941 | // See if the program contains a single implementation of this virtual |
| 942 | // function. |
| 943 | Function *TheFn = TargetsForSlot[0].Fn; |
| 944 | for (auto &&Target : TargetsForSlot) |
| 945 | if (TheFn != Target.Fn) |
| 946 | return false; |
| 947 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 948 | // If so, update each call site to call that implementation directly. |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 949 | if (RemarksEnabled) |
| 950 | TargetsForSlot[0].WasDevirt = true; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 951 | |
| 952 | bool IsExported = false; |
| 953 | applySingleImplDevirt(SlotInfo, TheFn, IsExported); |
| 954 | if (!IsExported) |
| 955 | return false; |
| 956 | |
| 957 | // If the only implementation has local linkage, we must promote to external |
| 958 | // to make it visible to thin LTO objects. We can only get here during the |
| 959 | // ThinLTO export phase. |
| 960 | if (TheFn->hasLocalLinkage()) { |
Peter Collingbourne | 88a58cf | 2017-09-08 00:10:53 +0000 | [diff] [blame] | 961 | std::string NewName = (TheFn->getName() + "$merged").str(); |
| 962 | |
| 963 | // Since we are renaming the function, any comdats with the same name must |
| 964 | // also be renamed. This is required when targeting COFF, as the comdat name |
| 965 | // must match one of the names of the symbols in the comdat. |
| 966 | if (Comdat *C = TheFn->getComdat()) { |
| 967 | if (C->getName() == TheFn->getName()) { |
| 968 | Comdat *NewC = M.getOrInsertComdat(NewName); |
| 969 | NewC->setSelectionKind(C->getSelectionKind()); |
| 970 | for (GlobalObject &GO : M.global_objects()) |
| 971 | if (GO.getComdat() == C) |
| 972 | GO.setComdat(NewC); |
| 973 | } |
| 974 | } |
| 975 | |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 976 | TheFn->setLinkage(GlobalValue::ExternalLinkage); |
| 977 | TheFn->setVisibility(GlobalValue::HiddenVisibility); |
Peter Collingbourne | 88a58cf | 2017-09-08 00:10:53 +0000 | [diff] [blame] | 978 | TheFn->setName(NewName); |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 979 | } |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 980 | if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID())) |
| 981 | // Any needed promotion of 'TheFn' has already been done during |
| 982 | // LTO unit split, so we can ignore return value of AddCalls. |
| 983 | AddCalls(SlotInfo, TheFnVI); |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 984 | |
| 985 | Res->TheKind = WholeProgramDevirtResolution::SingleImpl; |
| 986 | Res->SingleImplName = TheFn->getName(); |
| 987 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 988 | return true; |
| 989 | } |
| 990 | |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 991 | bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, |
| 992 | VTableSlotSummary &SlotSummary, |
| 993 | VTableSlotInfo &SlotInfo, |
| 994 | WholeProgramDevirtResolution *Res, |
| 995 | std::set<ValueInfo> &DevirtTargets) { |
| 996 | // See if the program contains a single implementation of this virtual |
| 997 | // function. |
| 998 | auto TheFn = TargetsForSlot[0]; |
| 999 | for (auto &&Target : TargetsForSlot) |
| 1000 | if (TheFn != Target) |
| 1001 | return false; |
| 1002 | |
| 1003 | // Don't devirtualize if we don't have target definition. |
| 1004 | auto Size = TheFn.getSummaryList().size(); |
| 1005 | if (!Size) |
| 1006 | return false; |
| 1007 | |
| 1008 | // If the summary list contains multiple summaries where at least one is |
| 1009 | // a local, give up, as we won't know which (possibly promoted) name to use. |
| 1010 | for (auto &S : TheFn.getSummaryList()) |
| 1011 | if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1) |
| 1012 | return false; |
| 1013 | |
| 1014 | // Collect functions devirtualized at least for one call site for stats. |
| 1015 | if (PrintSummaryDevirt) |
| 1016 | DevirtTargets.insert(TheFn); |
| 1017 | |
| 1018 | auto &S = TheFn.getSummaryList()[0]; |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 1019 | bool IsExported = AddCalls(SlotInfo, TheFn); |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 1020 | if (IsExported) |
| 1021 | ExportedGUIDs.insert(TheFn.getGUID()); |
| 1022 | |
| 1023 | // Record in summary for use in devirtualization during the ThinLTO import |
| 1024 | // step. |
| 1025 | Res->TheKind = WholeProgramDevirtResolution::SingleImpl; |
| 1026 | if (GlobalValue::isLocalLinkage(S->linkage())) { |
| 1027 | if (IsExported) |
| 1028 | // If target is a local function and we are exporting it by |
| 1029 | // devirtualizing a call in another module, we need to record the |
| 1030 | // promoted name. |
| 1031 | Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( |
| 1032 | TheFn.name(), ExportSummary.getModuleHash(S->modulePath())); |
| 1033 | else { |
| 1034 | LocalWPDTargetsMap[TheFn].push_back(SlotSummary); |
| 1035 | Res->SingleImplName = TheFn.name(); |
| 1036 | } |
| 1037 | } else |
| 1038 | Res->SingleImplName = TheFn.name(); |
| 1039 | |
| 1040 | // Name will be empty if this thin link driven off of serialized combined |
| 1041 | // index (e.g. llvm-lto). However, WPD is not supported/invoked for the |
| 1042 | // legacy LTO API anyway. |
| 1043 | assert(!Res->SingleImplName.empty()); |
| 1044 | |
| 1045 | return true; |
| 1046 | } |
| 1047 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1048 | void DevirtModule::tryICallBranchFunnel( |
| 1049 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, |
| 1050 | WholeProgramDevirtResolution *Res, VTableSlot Slot) { |
| 1051 | Triple T(M.getTargetTriple()); |
| 1052 | if (T.getArch() != Triple::x86_64) |
| 1053 | return; |
| 1054 | |
Vitaly Buka | 66f53d7 | 2018-04-06 21:32:36 +0000 | [diff] [blame] | 1055 | if (TargetsForSlot.size() > ClThreshold) |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1056 | return; |
| 1057 | |
| 1058 | bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted; |
| 1059 | if (!HasNonDevirt) |
| 1060 | for (auto &P : SlotInfo.ConstCSInfo) |
| 1061 | if (!P.second.AllCallSitesDevirted) { |
| 1062 | HasNonDevirt = true; |
| 1063 | break; |
| 1064 | } |
| 1065 | |
| 1066 | if (!HasNonDevirt) |
| 1067 | return; |
| 1068 | |
| 1069 | FunctionType *FT = |
| 1070 | FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true); |
| 1071 | Function *JT; |
| 1072 | if (isa<MDString>(Slot.TypeID)) { |
| 1073 | JT = Function::Create(FT, Function::ExternalLinkage, |
Dylan McKay | f920da0 | 2018-12-18 09:52:52 +0000 | [diff] [blame] | 1074 | M.getDataLayout().getProgramAddressSpace(), |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1075 | getGlobalName(Slot, {}, "branch_funnel"), &M); |
| 1076 | JT->setVisibility(GlobalValue::HiddenVisibility); |
| 1077 | } else { |
Dylan McKay | f920da0 | 2018-12-18 09:52:52 +0000 | [diff] [blame] | 1078 | JT = Function::Create(FT, Function::InternalLinkage, |
| 1079 | M.getDataLayout().getProgramAddressSpace(), |
| 1080 | "branch_funnel", &M); |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1081 | } |
| 1082 | JT->addAttribute(1, Attribute::Nest); |
| 1083 | |
| 1084 | std::vector<Value *> JTArgs; |
| 1085 | JTArgs.push_back(JT->arg_begin()); |
| 1086 | for (auto &T : TargetsForSlot) { |
| 1087 | JTArgs.push_back(getMemberAddr(T.TM)); |
| 1088 | JTArgs.push_back(T.Fn); |
| 1089 | } |
| 1090 | |
| 1091 | BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr); |
James Y Knight | 7976eb5 | 2019-02-01 20:43:25 +0000 | [diff] [blame] | 1092 | Function *Intr = |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1093 | Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {}); |
| 1094 | |
| 1095 | auto *CI = CallInst::Create(Intr, JTArgs, "", BB); |
| 1096 | CI->setTailCallKind(CallInst::TCK_MustTail); |
| 1097 | ReturnInst::Create(M.getContext(), nullptr, BB); |
| 1098 | |
| 1099 | bool IsExported = false; |
| 1100 | applyICallBranchFunnel(SlotInfo, JT, IsExported); |
| 1101 | if (IsExported) |
| 1102 | Res->TheKind = WholeProgramDevirtResolution::BranchFunnel; |
| 1103 | } |
| 1104 | |
| 1105 | void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo, |
| 1106 | Constant *JT, bool &IsExported) { |
| 1107 | auto Apply = [&](CallSiteInfo &CSInfo) { |
| 1108 | if (CSInfo.isExported()) |
| 1109 | IsExported = true; |
| 1110 | if (CSInfo.AllCallSitesDevirted) |
| 1111 | return; |
| 1112 | for (auto &&VCallSite : CSInfo.CallSites) { |
| 1113 | CallSite CS = VCallSite.CS; |
| 1114 | |
| 1115 | // Jump tables are only profitable if the retpoline mitigation is enabled. |
| 1116 | Attribute FSAttr = CS.getCaller()->getFnAttribute("target-features"); |
| 1117 | if (FSAttr.hasAttribute(Attribute::None) || |
| 1118 | !FSAttr.getValueAsString().contains("+retpoline")) |
| 1119 | continue; |
| 1120 | |
| 1121 | if (RemarksEnabled) |
Teresa Johnson | b0a1d3b | 2018-08-14 03:00:16 +0000 | [diff] [blame] | 1122 | VCallSite.emitRemark("branch-funnel", |
| 1123 | JT->stripPointerCasts()->getName(), OREGetter); |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1124 | |
| 1125 | // Pass the address of the vtable in the nest register, which is r10 on |
| 1126 | // x86_64. |
| 1127 | std::vector<Type *> NewArgs; |
| 1128 | NewArgs.push_back(Int8PtrTy); |
| 1129 | for (Type *T : CS.getFunctionType()->params()) |
| 1130 | NewArgs.push_back(T); |
James Y Knight | 7976eb5 | 2019-02-01 20:43:25 +0000 | [diff] [blame] | 1131 | FunctionType *NewFT = |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1132 | FunctionType::get(CS.getFunctionType()->getReturnType(), NewArgs, |
James Y Knight | 7976eb5 | 2019-02-01 20:43:25 +0000 | [diff] [blame] | 1133 | CS.getFunctionType()->isVarArg()); |
| 1134 | PointerType *NewFTPtr = PointerType::getUnqual(NewFT); |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1135 | |
| 1136 | IRBuilder<> IRB(CS.getInstruction()); |
| 1137 | std::vector<Value *> Args; |
| 1138 | Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy)); |
| 1139 | for (unsigned I = 0; I != CS.getNumArgOperands(); ++I) |
| 1140 | Args.push_back(CS.getArgOperand(I)); |
| 1141 | |
| 1142 | CallSite NewCS; |
| 1143 | if (CS.isCall()) |
James Y Knight | 7976eb5 | 2019-02-01 20:43:25 +0000 | [diff] [blame] | 1144 | NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args); |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1145 | else |
| 1146 | NewCS = IRB.CreateInvoke( |
James Y Knight | d9e85a0 | 2019-02-01 20:43:34 +0000 | [diff] [blame] | 1147 | NewFT, IRB.CreateBitCast(JT, NewFTPtr), |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1148 | cast<InvokeInst>(CS.getInstruction())->getNormalDest(), |
| 1149 | cast<InvokeInst>(CS.getInstruction())->getUnwindDest(), Args); |
| 1150 | NewCS.setCallingConv(CS.getCallingConv()); |
| 1151 | |
| 1152 | AttributeList Attrs = CS.getAttributes(); |
| 1153 | std::vector<AttributeSet> NewArgAttrs; |
| 1154 | NewArgAttrs.push_back(AttributeSet::get( |
| 1155 | M.getContext(), ArrayRef<Attribute>{Attribute::get( |
| 1156 | M.getContext(), Attribute::Nest)})); |
| 1157 | for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I) |
| 1158 | NewArgAttrs.push_back(Attrs.getParamAttributes(I)); |
| 1159 | NewCS.setAttributes( |
| 1160 | AttributeList::get(M.getContext(), Attrs.getFnAttributes(), |
| 1161 | Attrs.getRetAttributes(), NewArgAttrs)); |
| 1162 | |
| 1163 | CS->replaceAllUsesWith(NewCS.getInstruction()); |
| 1164 | CS->eraseFromParent(); |
| 1165 | |
| 1166 | // This use is no longer unsafe. |
| 1167 | if (VCallSite.NumUnsafeUses) |
| 1168 | --*VCallSite.NumUnsafeUses; |
| 1169 | } |
| 1170 | // Don't mark as devirtualized because there may be callers compiled without |
| 1171 | // retpoline mitigation, which would mean that they are lowered to |
| 1172 | // llvm.type.test and therefore require an llvm.type.test resolution for the |
| 1173 | // type identifier. |
| 1174 | }; |
| 1175 | Apply(SlotInfo.CSInfo); |
| 1176 | for (auto &P : SlotInfo.ConstCSInfo) |
| 1177 | Apply(P.second); |
| 1178 | } |
| 1179 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1180 | bool DevirtModule::tryEvaluateFunctionsWithArgs( |
| 1181 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1182 | ArrayRef<uint64_t> Args) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1183 | // Evaluate each function and store the result in each target's RetVal |
| 1184 | // field. |
| 1185 | for (VirtualCallTarget &Target : TargetsForSlot) { |
| 1186 | if (Target.Fn->arg_size() != Args.size() + 1) |
| 1187 | return false; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1188 | |
| 1189 | Evaluator Eval(M.getDataLayout(), nullptr); |
| 1190 | SmallVector<Constant *, 2> EvalArgs; |
| 1191 | EvalArgs.push_back( |
| 1192 | Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1193 | for (unsigned I = 0; I != Args.size(); ++I) { |
| 1194 | auto *ArgTy = dyn_cast<IntegerType>( |
| 1195 | Target.Fn->getFunctionType()->getParamType(I + 1)); |
| 1196 | if (!ArgTy) |
| 1197 | return false; |
| 1198 | EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); |
| 1199 | } |
| 1200 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1201 | Constant *RetVal; |
| 1202 | if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || |
| 1203 | !isa<ConstantInt>(RetVal)) |
| 1204 | return false; |
| 1205 | Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); |
| 1206 | } |
| 1207 | return true; |
| 1208 | } |
| 1209 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1210 | void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 1211 | uint64_t TheRetVal) { |
| 1212 | for (auto Call : CSInfo.CallSites) |
| 1213 | Call.replaceAndErase( |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 1214 | "uniform-ret-val", FnName, RemarksEnabled, OREGetter, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1215 | ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal)); |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1216 | CSInfo.markDevirt(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1217 | } |
| 1218 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1219 | bool DevirtModule::tryUniformRetValOpt( |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 1220 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo, |
| 1221 | WholeProgramDevirtResolution::ByArg *Res) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1222 | // Uniform return value optimization. If all functions return the same |
| 1223 | // constant, replace all calls with that constant. |
| 1224 | uint64_t TheRetVal = TargetsForSlot[0].RetVal; |
| 1225 | for (const VirtualCallTarget &Target : TargetsForSlot) |
| 1226 | if (Target.RetVal != TheRetVal) |
| 1227 | return false; |
| 1228 | |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 1229 | if (CSInfo.isExported()) { |
| 1230 | Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; |
| 1231 | Res->Info = TheRetVal; |
| 1232 | } |
| 1233 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1234 | applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1235 | if (RemarksEnabled) |
| 1236 | for (auto &&Target : TargetsForSlot) |
| 1237 | Target.WasDevirt = true; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1238 | return true; |
| 1239 | } |
| 1240 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1241 | std::string DevirtModule::getGlobalName(VTableSlot Slot, |
| 1242 | ArrayRef<uint64_t> Args, |
| 1243 | StringRef Name) { |
| 1244 | std::string FullName = "__typeid_"; |
| 1245 | raw_string_ostream OS(FullName); |
| 1246 | OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset; |
| 1247 | for (uint64_t Arg : Args) |
| 1248 | OS << '_' << Arg; |
| 1249 | OS << '_' << Name; |
| 1250 | return OS.str(); |
| 1251 | } |
| 1252 | |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1253 | bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() { |
| 1254 | Triple T(M.getTargetTriple()); |
| 1255 | return (T.getArch() == Triple::x86 || T.getArch() == Triple::x86_64) && |
| 1256 | T.getObjectFormat() == Triple::ELF; |
| 1257 | } |
| 1258 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1259 | void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, |
| 1260 | StringRef Name, Constant *C) { |
| 1261 | GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage, |
| 1262 | getGlobalName(Slot, Args, Name), C, &M); |
| 1263 | GA->setVisibility(GlobalValue::HiddenVisibility); |
| 1264 | } |
| 1265 | |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1266 | void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, |
| 1267 | StringRef Name, uint32_t Const, |
| 1268 | uint32_t &Storage) { |
| 1269 | if (shouldExportConstantsAsAbsoluteSymbols()) { |
| 1270 | exportGlobal( |
| 1271 | Slot, Args, Name, |
| 1272 | ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy)); |
| 1273 | return; |
| 1274 | } |
| 1275 | |
| 1276 | Storage = Const; |
| 1277 | } |
| 1278 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1279 | Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1280 | StringRef Name) { |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1281 | Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty); |
| 1282 | auto *GV = dyn_cast<GlobalVariable>(C); |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1283 | if (GV) |
| 1284 | GV->setVisibility(GlobalValue::HiddenVisibility); |
| 1285 | return C; |
| 1286 | } |
| 1287 | |
| 1288 | Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, |
| 1289 | StringRef Name, IntegerType *IntTy, |
| 1290 | uint32_t Storage) { |
| 1291 | if (!shouldExportConstantsAsAbsoluteSymbols()) |
| 1292 | return ConstantInt::get(IntTy, Storage); |
| 1293 | |
| 1294 | Constant *C = importGlobal(Slot, Args, Name); |
| 1295 | auto *GV = cast<GlobalVariable>(C->stripPointerCasts()); |
| 1296 | C = ConstantExpr::getPtrToInt(C, IntTy); |
| 1297 | |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1298 | // We only need to set metadata if the global is newly created, in which |
| 1299 | // case it would not have hidden visibility. |
Benjamin Kramer | 0deb9a9 | 2018-05-31 13:29:58 +0000 | [diff] [blame] | 1300 | if (GV->hasMetadata(LLVMContext::MD_absolute_symbol)) |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1301 | return C; |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1302 | |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1303 | auto SetAbsRange = [&](uint64_t Min, uint64_t Max) { |
| 1304 | auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min)); |
| 1305 | auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max)); |
| 1306 | GV->setMetadata(LLVMContext::MD_absolute_symbol, |
| 1307 | MDNode::get(M.getContext(), {MinC, MaxC})); |
| 1308 | }; |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1309 | unsigned AbsWidth = IntTy->getBitWidth(); |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1310 | if (AbsWidth == IntPtrTy->getBitWidth()) |
| 1311 | SetAbsRange(~0ull, ~0ull); // Full set. |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1312 | else |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1313 | SetAbsRange(0, 1ull << AbsWidth); |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1314 | return C; |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1315 | } |
| 1316 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1317 | void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 1318 | bool IsOne, |
| 1319 | Constant *UniqueMemberAddr) { |
| 1320 | for (auto &&Call : CSInfo.CallSites) { |
| 1321 | IRBuilder<> B(Call.CS.getInstruction()); |
Peter Collingbourne | 001052a | 2017-08-22 21:41:19 +0000 | [diff] [blame] | 1322 | Value *Cmp = |
| 1323 | B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, |
| 1324 | B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1325 | Cmp = B.CreateZExt(Cmp, Call.CS->getType()); |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 1326 | Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter, |
| 1327 | Cmp); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1328 | } |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1329 | CSInfo.markDevirt(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1330 | } |
| 1331 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1332 | Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) { |
| 1333 | Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy); |
| 1334 | return ConstantExpr::getGetElementPtr(Int8Ty, C, |
| 1335 | ConstantInt::get(Int64Ty, M->Offset)); |
| 1336 | } |
| 1337 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1338 | bool DevirtModule::tryUniqueRetValOpt( |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1339 | unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1340 | CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res, |
| 1341 | VTableSlot Slot, ArrayRef<uint64_t> Args) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1342 | // IsOne controls whether we look for a 0 or a 1. |
| 1343 | auto tryUniqueRetValOptFor = [&](bool IsOne) { |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 1344 | const TypeMemberInfo *UniqueMember = nullptr; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1345 | for (const VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 3866cc5 | 2016-03-08 03:50:36 +0000 | [diff] [blame] | 1346 | if (Target.RetVal == (IsOne ? 1 : 0)) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1347 | if (UniqueMember) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1348 | return false; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1349 | UniqueMember = Target.TM; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1350 | } |
| 1351 | } |
| 1352 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1353 | // We should have found a unique member or bailed out by now. We already |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1354 | // checked for a uniform return value in tryUniformRetValOpt. |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1355 | assert(UniqueMember); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1356 | |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1357 | Constant *UniqueMemberAddr = getMemberAddr(UniqueMember); |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1358 | if (CSInfo.isExported()) { |
| 1359 | Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; |
| 1360 | Res->Info = IsOne; |
| 1361 | |
| 1362 | exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr); |
| 1363 | } |
| 1364 | |
| 1365 | // Replace each call with the comparison. |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1366 | applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, |
| 1367 | UniqueMemberAddr); |
| 1368 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1369 | // Update devirtualization statistics for targets. |
| 1370 | if (RemarksEnabled) |
| 1371 | for (auto &&Target : TargetsForSlot) |
| 1372 | Target.WasDevirt = true; |
| 1373 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1374 | return true; |
| 1375 | }; |
| 1376 | |
| 1377 | if (BitWidth == 1) { |
| 1378 | if (tryUniqueRetValOptFor(true)) |
| 1379 | return true; |
| 1380 | if (tryUniqueRetValOptFor(false)) |
| 1381 | return true; |
| 1382 | } |
| 1383 | return false; |
| 1384 | } |
| 1385 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1386 | void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 1387 | Constant *Byte, Constant *Bit) { |
| 1388 | for (auto Call : CSInfo.CallSites) { |
| 1389 | auto *RetType = cast<IntegerType>(Call.CS.getType()); |
| 1390 | IRBuilder<> B(Call.CS.getInstruction()); |
Peter Collingbourne | 001052a | 2017-08-22 21:41:19 +0000 | [diff] [blame] | 1391 | Value *Addr = |
| 1392 | B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1393 | if (RetType->getBitWidth() == 1) { |
James Y Knight | 14359ef | 2019-02-01 20:44:24 +0000 | [diff] [blame] | 1394 | Value *Bits = B.CreateLoad(Int8Ty, Addr); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1395 | Value *BitsAndBit = B.CreateAnd(Bits, Bit); |
| 1396 | auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); |
| 1397 | Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 1398 | OREGetter, IsBitSet); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1399 | } else { |
| 1400 | Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); |
| 1401 | Value *Val = B.CreateLoad(RetType, ValAddr); |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 1402 | Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, |
| 1403 | OREGetter, Val); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1404 | } |
| 1405 | } |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1406 | CSInfo.markDevirt(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1407 | } |
| 1408 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1409 | bool DevirtModule::tryVirtualConstProp( |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1410 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, |
| 1411 | WholeProgramDevirtResolution *Res, VTableSlot Slot) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1412 | // This only works if the function returns an integer. |
| 1413 | auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); |
| 1414 | if (!RetType) |
| 1415 | return false; |
| 1416 | unsigned BitWidth = RetType->getBitWidth(); |
| 1417 | if (BitWidth > 64) |
| 1418 | return false; |
| 1419 | |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 1420 | // Make sure that each function is defined, does not access memory, takes at |
| 1421 | // least one argument, does not use its first argument (which we assume is |
| 1422 | // 'this'), and has the same return type. |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 1423 | // |
| 1424 | // Note that we test whether this copy of the function is readnone, rather |
| 1425 | // than testing function attributes, which must hold for any copy of the |
| 1426 | // function, even a less optimized version substituted at link time. This is |
| 1427 | // sound because the virtual constant propagation optimizations effectively |
| 1428 | // inline all implementations of the virtual function into each call site, |
| 1429 | // rather than using function attributes to perform local optimization. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1430 | for (VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 1431 | if (Target.Fn->isDeclaration() || |
| 1432 | computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) != |
| 1433 | MAK_ReadNone || |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 1434 | Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() || |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1435 | Target.Fn->getReturnType() != RetType) |
| 1436 | return false; |
| 1437 | } |
| 1438 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1439 | for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1440 | if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) |
| 1441 | continue; |
| 1442 | |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 1443 | WholeProgramDevirtResolution::ByArg *ResByArg = nullptr; |
| 1444 | if (Res) |
| 1445 | ResByArg = &Res->ResByArg[CSByConstantArg.first]; |
| 1446 | |
| 1447 | if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg)) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1448 | continue; |
| 1449 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1450 | if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second, |
| 1451 | ResByArg, Slot, CSByConstantArg.first)) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1452 | continue; |
| 1453 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1454 | // Find an allocation offset in bits in all vtables associated with the |
| 1455 | // type. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1456 | uint64_t AllocBefore = |
| 1457 | findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); |
| 1458 | uint64_t AllocAfter = |
| 1459 | findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); |
| 1460 | |
| 1461 | // Calculate the total amount of padding needed to store a value at both |
| 1462 | // ends of the object. |
| 1463 | uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; |
| 1464 | for (auto &&Target : TargetsForSlot) { |
| 1465 | TotalPaddingBefore += std::max<int64_t>( |
| 1466 | (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); |
| 1467 | TotalPaddingAfter += std::max<int64_t>( |
| 1468 | (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); |
| 1469 | } |
| 1470 | |
| 1471 | // If the amount of padding is too large, give up. |
| 1472 | // FIXME: do something smarter here. |
| 1473 | if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) |
| 1474 | continue; |
| 1475 | |
| 1476 | // Calculate the offset to the value as a (possibly negative) byte offset |
| 1477 | // and (if applicable) a bit offset, and store the values in the targets. |
| 1478 | int64_t OffsetByte; |
| 1479 | uint64_t OffsetBit; |
| 1480 | if (TotalPaddingBefore <= TotalPaddingAfter) |
| 1481 | setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, |
| 1482 | OffsetBit); |
| 1483 | else |
| 1484 | setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, |
| 1485 | OffsetBit); |
| 1486 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1487 | if (RemarksEnabled) |
| 1488 | for (auto &&Target : TargetsForSlot) |
| 1489 | Target.WasDevirt = true; |
| 1490 | |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1491 | |
| 1492 | if (CSByConstantArg.second.isExported()) { |
| 1493 | ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1494 | exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte, |
| 1495 | ResByArg->Byte); |
| 1496 | exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit, |
| 1497 | ResByArg->Bit); |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1498 | } |
| 1499 | |
| 1500 | // Rewrite each call to a load from OffsetByte/OffsetBit. |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1501 | Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte); |
| 1502 | Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1503 | applyVirtualConstProp(CSByConstantArg.second, |
| 1504 | TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1505 | } |
| 1506 | return true; |
| 1507 | } |
| 1508 | |
| 1509 | void DevirtModule::rebuildGlobal(VTableBits &B) { |
| 1510 | if (B.Before.Bytes.empty() && B.After.Bytes.empty()) |
| 1511 | return; |
| 1512 | |
Peter Collingbourne | ef5cfc2 | 2019-07-22 18:50:45 +0000 | [diff] [blame] | 1513 | // Align the before byte array to the global's minimum alignment so that we |
| 1514 | // don't break any alignment requirements on the global. |
Guillaume Chatelet | 0e62011 | 2019-10-15 11:24:36 +0000 | [diff] [blame] | 1515 | MaybeAlign Alignment(B.GV->getAlignment()); |
| 1516 | if (!Alignment) |
| 1517 | Alignment = |
| 1518 | Align(M.getDataLayout().getABITypeAlignment(B.GV->getValueType())); |
| 1519 | B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment)); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1520 | |
| 1521 | // Before was stored in reverse order; flip it now. |
| 1522 | for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) |
| 1523 | std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); |
| 1524 | |
| 1525 | // Build an anonymous global containing the before bytes, followed by the |
| 1526 | // original initializer, followed by the after bytes. |
| 1527 | auto NewInit = ConstantStruct::getAnon( |
| 1528 | {ConstantDataArray::get(M.getContext(), B.Before.Bytes), |
| 1529 | B.GV->getInitializer(), |
| 1530 | ConstantDataArray::get(M.getContext(), B.After.Bytes)}); |
| 1531 | auto NewGV = |
| 1532 | new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), |
| 1533 | GlobalVariable::PrivateLinkage, NewInit, "", B.GV); |
| 1534 | NewGV->setSection(B.GV->getSection()); |
| 1535 | NewGV->setComdat(B.GV->getComdat()); |
Guillaume Chatelet | 0e62011 | 2019-10-15 11:24:36 +0000 | [diff] [blame] | 1536 | NewGV->setAlignment(MaybeAlign(B.GV->getAlignment())); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1537 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1538 | // Copy the original vtable's metadata to the anonymous global, adjusting |
| 1539 | // offsets as required. |
| 1540 | NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); |
| 1541 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1542 | // Build an alias named after the original global, pointing at the second |
| 1543 | // element (the original initializer). |
| 1544 | auto Alias = GlobalAlias::create( |
| 1545 | B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", |
| 1546 | ConstantExpr::getGetElementPtr( |
| 1547 | NewInit->getType(), NewGV, |
| 1548 | ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), |
| 1549 | ConstantInt::get(Int32Ty, 1)}), |
| 1550 | &M); |
| 1551 | Alias->setVisibility(B.GV->getVisibility()); |
| 1552 | Alias->takeName(B.GV); |
| 1553 | |
| 1554 | B.GV->replaceAllUsesWith(Alias); |
| 1555 | B.GV->eraseFromParent(); |
| 1556 | } |
| 1557 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1558 | bool DevirtModule::areRemarksEnabled() { |
| 1559 | const auto &FL = M.getFunctionList(); |
Teresa Johnson | 5e1c0e7 | 2018-09-18 13:42:24 +0000 | [diff] [blame] | 1560 | for (const Function &Fn : FL) { |
| 1561 | const auto &BBL = Fn.getBasicBlockList(); |
| 1562 | if (BBL.empty()) |
| 1563 | continue; |
| 1564 | auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front()); |
| 1565 | return DI.isEnabled(); |
| 1566 | } |
| 1567 | return false; |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1568 | } |
| 1569 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1570 | void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc, |
| 1571 | Function *AssumeFunc) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1572 | // Find all virtual calls via a virtual table pointer %p under an assumption |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1573 | // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p |
| 1574 | // points to a member of the type identifier %md. Group calls by (type ID, |
| 1575 | // offset) pair (effectively the identity of the virtual function) and store |
| 1576 | // to CallSlots. |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 1577 | DenseSet<CallSite> SeenCallSites; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1578 | for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1579 | I != E;) { |
| 1580 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 1581 | ++I; |
| 1582 | if (!CI) |
| 1583 | continue; |
| 1584 | |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1585 | // Search for virtual calls based on %p and add them to DevirtCalls. |
| 1586 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1587 | SmallVector<CallInst *, 1> Assumes; |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 1588 | auto &DT = LookupDomTree(*CI->getFunction()); |
| 1589 | findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1590 | |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 1591 | // If we found any, add them to CallSlots. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1592 | if (!Assumes.empty()) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1593 | Metadata *TypeId = |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1594 | cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); |
| 1595 | Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 1596 | for (DevirtCallSite Call : DevirtCalls) { |
| 1597 | // Only add this CallSite if we haven't seen it before. The vtable |
| 1598 | // pointer may have been CSE'd with pointers from other call sites, |
| 1599 | // and we don't want to process call sites multiple times. We can't |
| 1600 | // just skip the vtable Ptr if it has been seen before, however, since |
| 1601 | // it may be shared by type tests that dominate different calls. |
| 1602 | if (SeenCallSites.insert(Call.CS).second) |
Peter Collingbourne | 001052a | 2017-08-22 21:41:19 +0000 | [diff] [blame] | 1603 | CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr); |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1604 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1605 | } |
| 1606 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1607 | // We no longer need the assumes or the type test. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1608 | for (auto Assume : Assumes) |
| 1609 | Assume->eraseFromParent(); |
| 1610 | // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we |
| 1611 | // may use the vtable argument later. |
| 1612 | if (CI->use_empty()) |
| 1613 | CI->eraseFromParent(); |
| 1614 | } |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1615 | } |
| 1616 | |
| 1617 | void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { |
| 1618 | Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); |
| 1619 | |
| 1620 | for (auto I = TypeCheckedLoadFunc->use_begin(), |
| 1621 | E = TypeCheckedLoadFunc->use_end(); |
| 1622 | I != E;) { |
| 1623 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 1624 | ++I; |
| 1625 | if (!CI) |
| 1626 | continue; |
| 1627 | |
| 1628 | Value *Ptr = CI->getArgOperand(0); |
| 1629 | Value *Offset = CI->getArgOperand(1); |
| 1630 | Value *TypeIdValue = CI->getArgOperand(2); |
| 1631 | Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); |
| 1632 | |
| 1633 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
| 1634 | SmallVector<Instruction *, 1> LoadedPtrs; |
| 1635 | SmallVector<Instruction *, 1> Preds; |
| 1636 | bool HasNonCallUses = false; |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 1637 | auto &DT = LookupDomTree(*CI->getFunction()); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1638 | findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, |
Teresa Johnson | f24136f | 2018-09-27 14:55:32 +0000 | [diff] [blame] | 1639 | HasNonCallUses, CI, DT); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1640 | |
| 1641 | // Start by generating "pessimistic" code that explicitly loads the function |
| 1642 | // pointer from the vtable and performs the type check. If possible, we will |
| 1643 | // eliminate the load and the type check later. |
| 1644 | |
| 1645 | // If possible, only generate the load at the point where it is used. |
| 1646 | // This helps avoid unnecessary spills. |
| 1647 | IRBuilder<> LoadB( |
| 1648 | (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); |
| 1649 | Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset); |
| 1650 | Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy)); |
| 1651 | Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr); |
| 1652 | |
| 1653 | for (Instruction *LoadedPtr : LoadedPtrs) { |
| 1654 | LoadedPtr->replaceAllUsesWith(LoadedValue); |
| 1655 | LoadedPtr->eraseFromParent(); |
| 1656 | } |
| 1657 | |
| 1658 | // Likewise for the type test. |
| 1659 | IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); |
| 1660 | CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); |
| 1661 | |
| 1662 | for (Instruction *Pred : Preds) { |
| 1663 | Pred->replaceAllUsesWith(TypeTestCall); |
| 1664 | Pred->eraseFromParent(); |
| 1665 | } |
| 1666 | |
| 1667 | // We have already erased any extractvalue instructions that refer to the |
| 1668 | // intrinsic call, but the intrinsic may have other non-extractvalue uses |
| 1669 | // (although this is unlikely). In that case, explicitly build a pair and |
| 1670 | // RAUW it. |
| 1671 | if (!CI->use_empty()) { |
| 1672 | Value *Pair = UndefValue::get(CI->getType()); |
| 1673 | IRBuilder<> B(CI); |
| 1674 | Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); |
| 1675 | Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); |
| 1676 | CI->replaceAllUsesWith(Pair); |
| 1677 | } |
| 1678 | |
| 1679 | // The number of unsafe uses is initially the number of uses. |
| 1680 | auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; |
| 1681 | NumUnsafeUses = DevirtCalls.size(); |
| 1682 | |
| 1683 | // If the function pointer has a non-call user, we cannot eliminate the type |
| 1684 | // check, as one of those users may eventually call the pointer. Increment |
| 1685 | // the unsafe use count to make sure it cannot reach zero. |
| 1686 | if (HasNonCallUses) |
| 1687 | ++NumUnsafeUses; |
| 1688 | for (DevirtCallSite Call : DevirtCalls) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1689 | CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, |
| 1690 | &NumUnsafeUses); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1691 | } |
| 1692 | |
| 1693 | CI->eraseFromParent(); |
| 1694 | } |
| 1695 | } |
| 1696 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1697 | void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) { |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 1698 | auto *TypeId = dyn_cast<MDString>(Slot.TypeID); |
| 1699 | if (!TypeId) |
| 1700 | return; |
Peter Collingbourne | 9a3f979 | 2017-03-22 18:04:39 +0000 | [diff] [blame] | 1701 | const TypeIdSummary *TidSummary = |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 1702 | ImportSummary->getTypeIdSummary(TypeId->getString()); |
Peter Collingbourne | 9a3f979 | 2017-03-22 18:04:39 +0000 | [diff] [blame] | 1703 | if (!TidSummary) |
| 1704 | return; |
| 1705 | auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset); |
| 1706 | if (ResI == TidSummary->WPDRes.end()) |
| 1707 | return; |
| 1708 | const WholeProgramDevirtResolution &Res = ResI->second; |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1709 | |
| 1710 | if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) { |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 1711 | assert(!Res.SingleImplName.empty()); |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1712 | // The type of the function in the declaration is irrelevant because every |
| 1713 | // call site will cast it to the correct type. |
James Y Knight | 1368022 | 2019-02-01 02:28:03 +0000 | [diff] [blame] | 1714 | Constant *SingleImpl = |
| 1715 | cast<Constant>(M.getOrInsertFunction(Res.SingleImplName, |
| 1716 | Type::getVoidTy(M.getContext())) |
| 1717 | .getCallee()); |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1718 | |
| 1719 | // This is the import phase so we should not be exporting anything. |
| 1720 | bool IsExported = false; |
| 1721 | applySingleImplDevirt(SlotInfo, SingleImpl, IsExported); |
| 1722 | assert(!IsExported); |
| 1723 | } |
Peter Collingbourne | 0152c81 | 2017-03-09 01:11:15 +0000 | [diff] [blame] | 1724 | |
| 1725 | for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) { |
| 1726 | auto I = Res.ResByArg.find(CSByConstantArg.first); |
| 1727 | if (I == Res.ResByArg.end()) |
| 1728 | continue; |
| 1729 | auto &ResByArg = I->second; |
| 1730 | // FIXME: We should figure out what to do about the "function name" argument |
| 1731 | // to the apply* functions, as the function names are unavailable during the |
| 1732 | // importing phase. For now we just pass the empty string. This does not |
| 1733 | // impact correctness because the function names are just used for remarks. |
| 1734 | switch (ResByArg.TheKind) { |
| 1735 | case WholeProgramDevirtResolution::ByArg::UniformRetVal: |
| 1736 | applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info); |
| 1737 | break; |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1738 | case WholeProgramDevirtResolution::ByArg::UniqueRetVal: { |
| 1739 | Constant *UniqueMemberAddr = |
| 1740 | importGlobal(Slot, CSByConstantArg.first, "unique_member"); |
| 1741 | applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info, |
| 1742 | UniqueMemberAddr); |
| 1743 | break; |
| 1744 | } |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1745 | case WholeProgramDevirtResolution::ByArg::VirtualConstProp: { |
Peter Collingbourne | b15a35e | 2017-09-11 22:34:42 +0000 | [diff] [blame] | 1746 | Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte", |
| 1747 | Int32Ty, ResByArg.Byte); |
| 1748 | Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty, |
| 1749 | ResByArg.Bit); |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1750 | applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit); |
Adrian Prantl | 0e6694d | 2017-12-19 22:05:25 +0000 | [diff] [blame] | 1751 | break; |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1752 | } |
Peter Collingbourne | 0152c81 | 2017-03-09 01:11:15 +0000 | [diff] [blame] | 1753 | default: |
| 1754 | break; |
| 1755 | } |
| 1756 | } |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1757 | |
| 1758 | if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) { |
James Y Knight | 1368022 | 2019-02-01 02:28:03 +0000 | [diff] [blame] | 1759 | // The type of the function is irrelevant, because it's bitcast at calls |
| 1760 | // anyhow. |
| 1761 | Constant *JT = cast<Constant>( |
| 1762 | M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"), |
| 1763 | Type::getVoidTy(M.getContext())) |
| 1764 | .getCallee()); |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1765 | bool IsExported = false; |
| 1766 | applyICallBranchFunnel(SlotInfo, JT, IsExported); |
| 1767 | assert(!IsExported); |
| 1768 | } |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1769 | } |
| 1770 | |
| 1771 | void DevirtModule::removeRedundantTypeTests() { |
| 1772 | auto True = ConstantInt::getTrue(M.getContext()); |
| 1773 | for (auto &&U : NumUnsafeUsesForTypeTest) { |
| 1774 | if (U.second == 0) { |
| 1775 | U.first->replaceAllUsesWith(True); |
| 1776 | U.first->eraseFromParent(); |
| 1777 | } |
| 1778 | } |
| 1779 | } |
| 1780 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1781 | bool DevirtModule::run() { |
Teresa Johnson | d0b1f30 | 2019-02-14 21:22:50 +0000 | [diff] [blame] | 1782 | // If only some of the modules were split, we cannot correctly perform |
| 1783 | // this transformation. We already checked for the presense of type tests |
| 1784 | // with partially split modules during the thin link, and would have emitted |
| 1785 | // an error if any were found, so here we can simply return. |
| 1786 | if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) || |
| 1787 | (ImportSummary && ImportSummary->partiallySplitLTOUnits())) |
| 1788 | return false; |
| 1789 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1790 | Function *TypeTestFunc = |
| 1791 | M.getFunction(Intrinsic::getName(Intrinsic::type_test)); |
| 1792 | Function *TypeCheckedLoadFunc = |
| 1793 | M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); |
| 1794 | Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); |
| 1795 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1796 | // Normally if there are no users of the devirtualization intrinsics in the |
| 1797 | // module, this pass has nothing to do. But if we are exporting, we also need |
| 1798 | // to handle any users that appear only in the function summaries. |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 1799 | if (!ExportSummary && |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1800 | (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1801 | AssumeFunc->use_empty()) && |
| 1802 | (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty())) |
| 1803 | return false; |
| 1804 | |
| 1805 | if (TypeTestFunc && AssumeFunc) |
| 1806 | scanTypeTestUsers(TypeTestFunc, AssumeFunc); |
| 1807 | |
| 1808 | if (TypeCheckedLoadFunc) |
| 1809 | scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1810 | |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 1811 | if (ImportSummary) { |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1812 | for (auto &S : CallSlots) |
| 1813 | importResolution(S.first, S.second); |
| 1814 | |
| 1815 | removeRedundantTypeTests(); |
| 1816 | |
| 1817 | // The rest of the code is only necessary when exporting or during regular |
| 1818 | // LTO, so we are done. |
| 1819 | return true; |
| 1820 | } |
| 1821 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1822 | // Rebuild type metadata into a map for easy lookup. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1823 | std::vector<VTableBits> Bits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1824 | DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; |
| 1825 | buildTypeIdentifierMap(Bits, TypeIdMap); |
| 1826 | if (TypeIdMap.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1827 | return true; |
| 1828 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1829 | // Collect information from summary about which calls to try to devirtualize. |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 1830 | if (ExportSummary) { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1831 | DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID; |
| 1832 | for (auto &P : TypeIdMap) { |
| 1833 | if (auto *TypeId = dyn_cast<MDString>(P.first)) |
| 1834 | MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back( |
| 1835 | TypeId); |
| 1836 | } |
| 1837 | |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 1838 | for (auto &P : *ExportSummary) { |
Peter Collingbourne | 9667b91 | 2017-05-04 18:03:25 +0000 | [diff] [blame] | 1839 | for (auto &S : P.second.SummaryList) { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1840 | auto *FS = dyn_cast<FunctionSummary>(S.get()); |
| 1841 | if (!FS) |
| 1842 | continue; |
| 1843 | // FIXME: Only add live functions. |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1844 | for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { |
| 1845 | for (Metadata *MD : MetadataByGUID[VF.GUID]) { |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 1846 | CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1847 | } |
| 1848 | } |
| 1849 | for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { |
| 1850 | for (Metadata *MD : MetadataByGUID[VF.GUID]) { |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1851 | CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1852 | } |
| 1853 | } |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1854 | for (const FunctionSummary::ConstVCall &VC : |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1855 | FS->type_test_assume_const_vcalls()) { |
| 1856 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1857 | CallSlots[{MD, VC.VFunc.Offset}] |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1858 | .ConstCSInfo[VC.Args] |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 1859 | .addSummaryTypeTestAssumeUser(FS); |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1860 | } |
| 1861 | } |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1862 | for (const FunctionSummary::ConstVCall &VC : |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1863 | FS->type_checked_load_const_vcalls()) { |
| 1864 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1865 | CallSlots[{MD, VC.VFunc.Offset}] |
| 1866 | .ConstCSInfo[VC.Args] |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1867 | .addSummaryTypeCheckedLoadUser(FS); |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1868 | } |
| 1869 | } |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1870 | } |
| 1871 | } |
| 1872 | } |
| 1873 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1874 | // For each (type, offset) pair: |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1875 | bool DidVirtualConstProp = false; |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1876 | std::map<std::string, Function*> DevirtTargets; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1877 | for (auto &S : CallSlots) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1878 | // Search each of the members of the type identifier for the virtual |
| 1879 | // function implementation at offset S.first.ByteOffset, and add to |
| 1880 | // TargetsForSlot. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1881 | std::vector<VirtualCallTarget> TargetsForSlot; |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1882 | if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID], |
| 1883 | S.first.ByteOffset)) { |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1884 | WholeProgramDevirtResolution *Res = nullptr; |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 1885 | if (ExportSummary && isa<MDString>(S.first.TypeID)) |
| 1886 | Res = &ExportSummary |
Peter Collingbourne | 9a3f979 | 2017-03-22 18:04:39 +0000 | [diff] [blame] | 1887 | ->getOrInsertTypeIdSummary( |
| 1888 | cast<MDString>(S.first.TypeID)->getString()) |
| 1889 | .WPDRes[S.first.ByteOffset]; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1890 | |
Eugene Leviant | 943afb5 | 2019-10-17 07:46:18 +0000 | [diff] [blame] | 1891 | if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) { |
Peter Collingbourne | 2974856 | 2018-03-09 19:11:44 +0000 | [diff] [blame] | 1892 | DidVirtualConstProp |= |
| 1893 | tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first); |
| 1894 | |
| 1895 | tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first); |
| 1896 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1897 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1898 | // Collect functions devirtualized at least for one call site for stats. |
| 1899 | if (RemarksEnabled) |
| 1900 | for (const auto &T : TargetsForSlot) |
| 1901 | if (T.WasDevirt) |
| 1902 | DevirtTargets[T.Fn->getName()] = T.Fn; |
| 1903 | } |
| 1904 | |
| 1905 | // CFI-specific: if we are exporting and any llvm.type.checked.load |
| 1906 | // intrinsics were *not* devirtualized, we need to add the resulting |
| 1907 | // llvm.type.test intrinsics to the function summaries so that the |
| 1908 | // LowerTypeTests pass will export them. |
Peter Collingbourne | f7691d8 | 2017-03-22 18:22:59 +0000 | [diff] [blame] | 1909 | if (ExportSummary && isa<MDString>(S.first.TypeID)) { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1910 | auto GUID = |
| 1911 | GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString()); |
| 1912 | for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers) |
| 1913 | FS->addTypeTest(GUID); |
| 1914 | for (auto &CCS : S.second.ConstCSInfo) |
| 1915 | for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers) |
| 1916 | FS->addTypeTest(GUID); |
| 1917 | } |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1918 | } |
| 1919 | |
| 1920 | if (RemarksEnabled) { |
| 1921 | // Generate remarks for each devirtualized function. |
| 1922 | for (const auto &DT : DevirtTargets) { |
| 1923 | Function *F = DT.second; |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 1924 | |
Sam Elliott | e963c89 | 2017-08-21 16:57:21 +0000 | [diff] [blame] | 1925 | using namespace ore; |
Peter Collingbourne | 9110cb4 | 2018-01-05 00:27:51 +0000 | [diff] [blame] | 1926 | OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F) |
| 1927 | << "devirtualized " |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 1928 | << NV("FunctionName", DT.first)); |
Ivan Krasin | b05e06e | 2016-08-05 19:45:16 +0000 | [diff] [blame] | 1929 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1930 | } |
| 1931 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1932 | removeRedundantTypeTests(); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1933 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1934 | // Rebuild each global we touched as part of virtual constant propagation to |
| 1935 | // include the before and after bytes. |
| 1936 | if (DidVirtualConstProp) |
| 1937 | for (VTableBits &B : Bits) |
| 1938 | rebuildGlobal(B); |
| 1939 | |
Oliver Stannard | 3b598b9 | 2019-10-17 09:58:57 +0000 | [diff] [blame] | 1940 | // We have lowered or deleted the type checked load intrinsics, so we no |
| 1941 | // longer have enough information to reason about the liveness of virtual |
| 1942 | // function pointers in GlobalDCE. |
| 1943 | for (GlobalVariable &GV : M.globals()) |
| 1944 | GV.eraseMetadata(LLVMContext::MD_vcall_visibility); |
| 1945 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1946 | return true; |
| 1947 | } |
Teresa Johnson | d2df54e | 2019-08-02 13:10:52 +0000 | [diff] [blame] | 1948 | |
| 1949 | void DevirtIndex::run() { |
| 1950 | if (ExportSummary.typeIdCompatibleVtableMap().empty()) |
| 1951 | return; |
| 1952 | |
| 1953 | DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID; |
| 1954 | for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) { |
| 1955 | NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first); |
| 1956 | } |
| 1957 | |
| 1958 | // Collect information from summary about which calls to try to devirtualize. |
| 1959 | for (auto &P : ExportSummary) { |
| 1960 | for (auto &S : P.second.SummaryList) { |
| 1961 | auto *FS = dyn_cast<FunctionSummary>(S.get()); |
| 1962 | if (!FS) |
| 1963 | continue; |
| 1964 | // FIXME: Only add live functions. |
| 1965 | for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { |
| 1966 | for (StringRef Name : NameByGUID[VF.GUID]) { |
| 1967 | CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); |
| 1968 | } |
| 1969 | } |
| 1970 | for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { |
| 1971 | for (StringRef Name : NameByGUID[VF.GUID]) { |
| 1972 | CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); |
| 1973 | } |
| 1974 | } |
| 1975 | for (const FunctionSummary::ConstVCall &VC : |
| 1976 | FS->type_test_assume_const_vcalls()) { |
| 1977 | for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { |
| 1978 | CallSlots[{Name, VC.VFunc.Offset}] |
| 1979 | .ConstCSInfo[VC.Args] |
| 1980 | .addSummaryTypeTestAssumeUser(FS); |
| 1981 | } |
| 1982 | } |
| 1983 | for (const FunctionSummary::ConstVCall &VC : |
| 1984 | FS->type_checked_load_const_vcalls()) { |
| 1985 | for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { |
| 1986 | CallSlots[{Name, VC.VFunc.Offset}] |
| 1987 | .ConstCSInfo[VC.Args] |
| 1988 | .addSummaryTypeCheckedLoadUser(FS); |
| 1989 | } |
| 1990 | } |
| 1991 | } |
| 1992 | } |
| 1993 | |
| 1994 | std::set<ValueInfo> DevirtTargets; |
| 1995 | // For each (type, offset) pair: |
| 1996 | for (auto &S : CallSlots) { |
| 1997 | // Search each of the members of the type identifier for the virtual |
| 1998 | // function implementation at offset S.first.ByteOffset, and add to |
| 1999 | // TargetsForSlot. |
| 2000 | std::vector<ValueInfo> TargetsForSlot; |
| 2001 | auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID); |
| 2002 | assert(TidSummary); |
| 2003 | if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary, |
| 2004 | S.first.ByteOffset)) { |
| 2005 | WholeProgramDevirtResolution *Res = |
| 2006 | &ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID) |
| 2007 | .WPDRes[S.first.ByteOffset]; |
| 2008 | |
| 2009 | if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res, |
| 2010 | DevirtTargets)) |
| 2011 | continue; |
| 2012 | } |
| 2013 | } |
| 2014 | |
| 2015 | // Optionally have the thin link print message for each devirtualized |
| 2016 | // function. |
| 2017 | if (PrintSummaryDevirt) |
| 2018 | for (const auto &DT : DevirtTargets) |
| 2019 | errs() << "Devirtualized call to " << DT << "\n"; |
| 2020 | |
| 2021 | return; |
| 2022 | } |