Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1 | //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass implements whole program optimization of virtual calls in cases |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 11 | // 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] | 12 | // includes the following: |
| 13 | // - Single implementation devirtualization: if a virtual call has a single |
| 14 | // possible callee, replace all calls with a direct call to that callee. |
| 15 | // - Virtual constant propagation: if the virtual function's return type is an |
| 16 | // integer <=64 bits and all possible callees are readnone, for each class and |
| 17 | // each list of constant arguments: evaluate the function, store the return |
| 18 | // value alongside the virtual table, and rewrite each virtual call as a load |
| 19 | // from the virtual table. |
| 20 | // - Uniform return value optimization: if the conditions for virtual constant |
| 21 | // propagation hold and each function returns the same constant value, replace |
| 22 | // each virtual call with that constant. |
| 23 | // - Unique return value optimization for i1 return values: if the conditions |
| 24 | // for virtual constant propagation hold and a single vtable's function |
| 25 | // returns 0, or a single vtable's function returns 1, replace each virtual |
| 26 | // call with a comparison of the vptr against that vtable's address. |
| 27 | // |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 28 | // This pass is intended to be used during the regular and thin LTO pipelines. |
| 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 |
| 32 | // llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). During |
| 33 | // ThinLTO, the pass operates in two phases: |
| 34 | // - Export phase: this is run during the thin link over a single merged module |
| 35 | // that contains all vtables with !type metadata that participate in the link. |
| 36 | // The pass computes a resolution for each virtual call and stores it in the |
| 37 | // type identifier summary. |
| 38 | // - Import phase: this is run during the thin backends over the individual |
| 39 | // modules. The pass applies the resolutions previously computed during the |
| 40 | // import phase to each eligible virtual call. |
| 41 | // |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 42 | //===----------------------------------------------------------------------===// |
| 43 | |
| 44 | #include "llvm/Transforms/IPO/WholeProgramDevirt.h" |
Mehdi Amini | b550cb1 | 2016-04-18 09:17:29 +0000 | [diff] [blame] | 45 | #include "llvm/ADT/ArrayRef.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 46 | #include "llvm/ADT/DenseMap.h" |
| 47 | #include "llvm/ADT/DenseMapInfo.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 48 | #include "llvm/ADT/DenseSet.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 49 | #include "llvm/ADT/iterator_range.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 50 | #include "llvm/ADT/MapVector.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 51 | #include "llvm/ADT/SmallVector.h" |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 52 | #include "llvm/Analysis/AliasAnalysis.h" |
| 53 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 54 | #include "llvm/Analysis/TypeMetadataUtils.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 55 | #include "llvm/IR/CallSite.h" |
| 56 | #include "llvm/IR/Constants.h" |
| 57 | #include "llvm/IR/DataLayout.h" |
Ivan Krasin | b05e06e | 2016-08-05 19:45:16 +0000 | [diff] [blame] | 58 | #include "llvm/IR/DebugInfoMetadata.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 59 | #include "llvm/IR/DebugLoc.h" |
| 60 | #include "llvm/IR/DerivedTypes.h" |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 61 | #include "llvm/IR/DiagnosticInfo.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 62 | #include "llvm/IR/Function.h" |
| 63 | #include "llvm/IR/GlobalAlias.h" |
| 64 | #include "llvm/IR/GlobalVariable.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 65 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 66 | #include "llvm/IR/InstrTypes.h" |
| 67 | #include "llvm/IR/Instruction.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 68 | #include "llvm/IR/Instructions.h" |
| 69 | #include "llvm/IR/Intrinsics.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 70 | #include "llvm/IR/LLVMContext.h" |
| 71 | #include "llvm/IR/Metadata.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 72 | #include "llvm/IR/Module.h" |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 73 | #include "llvm/IR/ModuleSummaryIndexYAML.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 74 | #include "llvm/Pass.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 75 | #include "llvm/PassRegistry.h" |
| 76 | #include "llvm/PassSupport.h" |
| 77 | #include "llvm/Support/Casting.h" |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 78 | #include "llvm/Support/Error.h" |
| 79 | #include "llvm/Support/FileSystem.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 80 | #include "llvm/Support/MathExtras.h" |
Mehdi Amini | b550cb1 | 2016-04-18 09:17:29 +0000 | [diff] [blame] | 81 | #include "llvm/Transforms/IPO.h" |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 82 | #include "llvm/Transforms/IPO/FunctionAttrs.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 83 | #include "llvm/Transforms/Utils/Evaluator.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 84 | #include <algorithm> |
| 85 | #include <cstddef> |
| 86 | #include <map> |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 87 | #include <set> |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 88 | #include <string> |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 89 | |
| 90 | using namespace llvm; |
| 91 | using namespace wholeprogramdevirt; |
| 92 | |
| 93 | #define DEBUG_TYPE "wholeprogramdevirt" |
| 94 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 95 | static cl::opt<PassSummaryAction> ClSummaryAction( |
| 96 | "wholeprogramdevirt-summary-action", |
| 97 | cl::desc("What to do with the summary when running this pass"), |
| 98 | cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), |
| 99 | clEnumValN(PassSummaryAction::Import, "import", |
| 100 | "Import typeid resolutions from summary and globals"), |
| 101 | clEnumValN(PassSummaryAction::Export, "export", |
| 102 | "Export typeid resolutions to summary and globals")), |
| 103 | cl::Hidden); |
| 104 | |
| 105 | static cl::opt<std::string> ClReadSummary( |
| 106 | "wholeprogramdevirt-read-summary", |
| 107 | cl::desc("Read summary from given YAML file before running pass"), |
| 108 | cl::Hidden); |
| 109 | |
| 110 | static cl::opt<std::string> ClWriteSummary( |
| 111 | "wholeprogramdevirt-write-summary", |
| 112 | cl::desc("Write summary to given YAML file after running pass"), |
| 113 | cl::Hidden); |
| 114 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 115 | // Find the minimum offset that we may store a value of size Size bits at. If |
| 116 | // IsAfter is set, look for an offset before the object, otherwise look for an |
| 117 | // offset after the object. |
| 118 | uint64_t |
| 119 | wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, |
| 120 | bool IsAfter, uint64_t Size) { |
| 121 | // Find a minimum offset taking into account only vtable sizes. |
| 122 | uint64_t MinByte = 0; |
| 123 | for (const VirtualCallTarget &Target : Targets) { |
| 124 | if (IsAfter) |
| 125 | MinByte = std::max(MinByte, Target.minAfterBytes()); |
| 126 | else |
| 127 | MinByte = std::max(MinByte, Target.minBeforeBytes()); |
| 128 | } |
| 129 | |
| 130 | // Build a vector of arrays of bytes covering, for each target, a slice of the |
| 131 | // used region (see AccumBitVector::BytesUsed in |
| 132 | // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, |
| 133 | // this aligns the used regions to start at MinByte. |
| 134 | // |
| 135 | // In this example, A, B and C are vtables, # is a byte already allocated for |
| 136 | // a virtual function pointer, AAAA... (etc.) are the used regions for the |
| 137 | // vtables and Offset(X) is the value computed for the Offset variable below |
| 138 | // for X. |
| 139 | // |
| 140 | // Offset(A) |
| 141 | // | | |
| 142 | // |MinByte |
| 143 | // A: ################AAAAAAAA|AAAAAAAA |
| 144 | // B: ########BBBBBBBBBBBBBBBB|BBBB |
| 145 | // C: ########################|CCCCCCCCCCCCCCCC |
| 146 | // | Offset(B) | |
| 147 | // |
| 148 | // This code produces the slices of A, B and C that appear after the divider |
| 149 | // at MinByte. |
| 150 | std::vector<ArrayRef<uint8_t>> Used; |
| 151 | for (const VirtualCallTarget &Target : Targets) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 152 | ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed |
| 153 | : Target.TM->Bits->Before.BytesUsed; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 154 | uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() |
| 155 | : MinByte - Target.minBeforeBytes(); |
| 156 | |
| 157 | // Disregard used regions that are smaller than Offset. These are |
| 158 | // effectively all-free regions that do not need to be checked. |
| 159 | if (VTUsed.size() > Offset) |
| 160 | Used.push_back(VTUsed.slice(Offset)); |
| 161 | } |
| 162 | |
| 163 | if (Size == 1) { |
| 164 | // Find a free bit in each member of Used. |
| 165 | for (unsigned I = 0;; ++I) { |
| 166 | uint8_t BitsUsed = 0; |
| 167 | for (auto &&B : Used) |
| 168 | if (I < B.size()) |
| 169 | BitsUsed |= B[I]; |
| 170 | if (BitsUsed != 0xff) |
| 171 | return (MinByte + I) * 8 + |
| 172 | countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); |
| 173 | } |
| 174 | } else { |
| 175 | // Find a free (Size/8) byte region in each member of Used. |
| 176 | // FIXME: see if alignment helps. |
| 177 | for (unsigned I = 0;; ++I) { |
| 178 | for (auto &&B : Used) { |
| 179 | unsigned Byte = 0; |
| 180 | while ((I + Byte) < B.size() && Byte < (Size / 8)) { |
| 181 | if (B[I + Byte]) |
| 182 | goto NextI; |
| 183 | ++Byte; |
| 184 | } |
| 185 | } |
| 186 | return (MinByte + I) * 8; |
| 187 | NextI:; |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | void wholeprogramdevirt::setBeforeReturnValues( |
| 193 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, |
| 194 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 195 | if (BitWidth == 1) |
| 196 | OffsetByte = -(AllocBefore / 8 + 1); |
| 197 | else |
| 198 | OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); |
| 199 | OffsetBit = AllocBefore % 8; |
| 200 | |
| 201 | for (VirtualCallTarget &Target : Targets) { |
| 202 | if (BitWidth == 1) |
| 203 | Target.setBeforeBit(AllocBefore); |
| 204 | else |
| 205 | Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | void wholeprogramdevirt::setAfterReturnValues( |
| 210 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, |
| 211 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 212 | if (BitWidth == 1) |
| 213 | OffsetByte = AllocAfter / 8; |
| 214 | else |
| 215 | OffsetByte = (AllocAfter + 7) / 8; |
| 216 | OffsetBit = AllocAfter % 8; |
| 217 | |
| 218 | for (VirtualCallTarget &Target : Targets) { |
| 219 | if (BitWidth == 1) |
| 220 | Target.setAfterBit(AllocAfter); |
| 221 | else |
| 222 | Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); |
| 223 | } |
| 224 | } |
| 225 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 226 | VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM) |
| 227 | : Fn(Fn), TM(TM), |
Ivan Krasin | 89439a7 | 2016-08-12 01:40:10 +0000 | [diff] [blame] | 228 | IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {} |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 229 | |
| 230 | namespace { |
| 231 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 232 | // 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] | 233 | // tables, and the ByteOffset is the offset in bytes from the address point to |
| 234 | // the virtual function pointer. |
| 235 | struct VTableSlot { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 236 | Metadata *TypeID; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 237 | uint64_t ByteOffset; |
| 238 | }; |
| 239 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 240 | } // end anonymous namespace |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 241 | |
Peter Collingbourne | 9b65652 | 2016-02-09 23:01:38 +0000 | [diff] [blame] | 242 | namespace llvm { |
| 243 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 244 | template <> struct DenseMapInfo<VTableSlot> { |
| 245 | static VTableSlot getEmptyKey() { |
| 246 | return {DenseMapInfo<Metadata *>::getEmptyKey(), |
| 247 | DenseMapInfo<uint64_t>::getEmptyKey()}; |
| 248 | } |
| 249 | static VTableSlot getTombstoneKey() { |
| 250 | return {DenseMapInfo<Metadata *>::getTombstoneKey(), |
| 251 | DenseMapInfo<uint64_t>::getTombstoneKey()}; |
| 252 | } |
| 253 | static unsigned getHashValue(const VTableSlot &I) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 254 | return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^ |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 255 | DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); |
| 256 | } |
| 257 | static bool isEqual(const VTableSlot &LHS, |
| 258 | const VTableSlot &RHS) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 259 | return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 260 | } |
| 261 | }; |
| 262 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 263 | } // end namespace llvm |
Peter Collingbourne | 9b65652 | 2016-02-09 23:01:38 +0000 | [diff] [blame] | 264 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 265 | namespace { |
| 266 | |
| 267 | // A virtual call site. VTable is the loaded virtual table pointer, and CS is |
| 268 | // the indirect virtual call. |
| 269 | struct VirtualCallSite { |
| 270 | Value *VTable; |
| 271 | CallSite CS; |
| 272 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 273 | // If non-null, this field points to the associated unsafe use count stored in |
| 274 | // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description |
| 275 | // of that field for details. |
| 276 | unsigned *NumUnsafeUses; |
| 277 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 278 | void emitRemark(const Twine &OptName, const Twine &TargetName) { |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 279 | Function *F = CS.getCaller(); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 280 | emitOptimizationRemark( |
| 281 | F->getContext(), DEBUG_TYPE, *F, |
| 282 | CS.getInstruction()->getDebugLoc(), |
| 283 | OptName + ": devirtualized a call to " + TargetName); |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 284 | } |
| 285 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 286 | void replaceAndErase(const Twine &OptName, const Twine &TargetName, |
| 287 | bool RemarksEnabled, Value *New) { |
| 288 | if (RemarksEnabled) |
| 289 | emitRemark(OptName, TargetName); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 290 | CS->replaceAllUsesWith(New); |
| 291 | if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) { |
| 292 | BranchInst::Create(II->getNormalDest(), CS.getInstruction()); |
| 293 | II->getUnwindDest()->removePredecessor(II->getParent()); |
| 294 | } |
| 295 | CS->eraseFromParent(); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 296 | // This use is no longer unsafe. |
| 297 | if (NumUnsafeUses) |
| 298 | --*NumUnsafeUses; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 299 | } |
| 300 | }; |
| 301 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 302 | // Call site information collected for a specific VTableSlot and possibly a list |
| 303 | // of constant integer arguments. The grouping by arguments is handled by the |
| 304 | // VTableSlotInfo class. |
| 305 | struct CallSiteInfo { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 306 | /// The set of call sites for this slot. Used during regular LTO and the |
| 307 | /// import phase of ThinLTO (as well as the export phase of ThinLTO for any |
| 308 | /// call sites that appear in the merged module itself); in each of these |
| 309 | /// 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] | 310 | std::vector<VirtualCallSite> CallSites; |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 311 | |
| 312 | // These fields are used during the export phase of ThinLTO and reflect |
| 313 | // information collected from function summaries. |
| 314 | |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 315 | /// Whether any function summary contains an llvm.assume(llvm.type.test) for |
| 316 | /// this slot. |
| 317 | bool SummaryHasTypeTestAssumeUsers; |
| 318 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 319 | /// CFI-specific: a vector containing the list of function summaries that use |
| 320 | /// the llvm.type.checked.load intrinsic and therefore will require |
| 321 | /// resolutions for llvm.type.test in order to implement CFI checks if |
| 322 | /// devirtualization was unsuccessful. If devirtualization was successful, the |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 323 | /// pass will clear this vector by calling markDevirt(). If at the end of the |
| 324 | /// pass the vector is non-empty, we will need to add a use of llvm.type.test |
| 325 | /// to each of the function summaries in the vector. |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 326 | std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 327 | |
| 328 | bool isExported() const { |
| 329 | return SummaryHasTypeTestAssumeUsers || |
| 330 | !SummaryTypeCheckedLoadUsers.empty(); |
| 331 | } |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 332 | |
| 333 | /// As explained in the comment for SummaryTypeCheckedLoadUsers. |
| 334 | void markDevirt() { SummaryTypeCheckedLoadUsers.clear(); } |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 335 | }; |
| 336 | |
| 337 | // Call site information collected for a specific VTableSlot. |
| 338 | struct VTableSlotInfo { |
| 339 | // The set of call sites which do not have all constant integer arguments |
| 340 | // (excluding "this"). |
| 341 | CallSiteInfo CSInfo; |
| 342 | |
| 343 | // The set of call sites with all constant integer arguments (excluding |
| 344 | // "this"), grouped by argument list. |
| 345 | std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; |
| 346 | |
| 347 | void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses); |
| 348 | |
| 349 | private: |
| 350 | CallSiteInfo &findCallSiteInfo(CallSite CS); |
| 351 | }; |
| 352 | |
| 353 | CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) { |
| 354 | std::vector<uint64_t> Args; |
| 355 | auto *CI = dyn_cast<IntegerType>(CS.getType()); |
| 356 | if (!CI || CI->getBitWidth() > 64 || CS.arg_empty()) |
| 357 | return CSInfo; |
| 358 | for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) { |
| 359 | auto *CI = dyn_cast<ConstantInt>(Arg); |
| 360 | if (!CI || CI->getBitWidth() > 64) |
| 361 | return CSInfo; |
| 362 | Args.push_back(CI->getZExtValue()); |
| 363 | } |
| 364 | return ConstCSInfo[Args]; |
| 365 | } |
| 366 | |
| 367 | void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS, |
| 368 | unsigned *NumUnsafeUses) { |
| 369 | findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses}); |
| 370 | } |
| 371 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 372 | struct DevirtModule { |
| 373 | Module &M; |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 374 | function_ref<AAResults &(Function &)> AARGetter; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 375 | |
| 376 | PassSummaryAction Action; |
| 377 | ModuleSummaryIndex *Summary; |
| 378 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 379 | IntegerType *Int8Ty; |
| 380 | PointerType *Int8PtrTy; |
| 381 | IntegerType *Int32Ty; |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 382 | IntegerType *Int64Ty; |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 383 | IntegerType *IntPtrTy; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 384 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 385 | bool RemarksEnabled; |
| 386 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 387 | MapVector<VTableSlot, VTableSlotInfo> CallSlots; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 388 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 389 | // This map keeps track of the number of "unsafe" uses of a loaded function |
| 390 | // pointer. The key is the associated llvm.type.test intrinsic call generated |
| 391 | // by this pass. An unsafe use is one that calls the loaded function pointer |
| 392 | // directly. Every time we eliminate an unsafe use (for example, by |
| 393 | // devirtualizing it or by applying virtual constant propagation), we |
| 394 | // decrement the value stored in this map. If a value reaches zero, we can |
| 395 | // eliminate the type check by RAUWing the associated llvm.type.test call with |
| 396 | // true. |
| 397 | std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; |
| 398 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 399 | DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter, |
| 400 | PassSummaryAction Action, ModuleSummaryIndex *Summary) |
| 401 | : M(M), AARGetter(AARGetter), Action(Action), Summary(Summary), |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 402 | Int8Ty(Type::getInt8Ty(M.getContext())), |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 403 | Int8PtrTy(Type::getInt8PtrTy(M.getContext())), |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 404 | Int32Ty(Type::getInt32Ty(M.getContext())), |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 405 | Int64Ty(Type::getInt64Ty(M.getContext())), |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 406 | IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)), |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 407 | RemarksEnabled(areRemarksEnabled()) {} |
| 408 | |
| 409 | bool areRemarksEnabled(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 410 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 411 | void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc); |
| 412 | void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); |
| 413 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 414 | void buildTypeIdentifierMap( |
| 415 | std::vector<VTableBits> &Bits, |
| 416 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 417 | Constant *getPointerAtOffset(Constant *I, uint64_t Offset); |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 418 | bool |
| 419 | tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, |
| 420 | const std::set<TypeMemberInfo> &TypeMemberInfos, |
| 421 | uint64_t ByteOffset); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 422 | |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 423 | void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn, |
| 424 | bool &IsExported); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 425 | bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 426 | VTableSlotInfo &SlotInfo, |
| 427 | WholeProgramDevirtResolution *Res); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 428 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 429 | bool tryEvaluateFunctionsWithArgs( |
| 430 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 431 | ArrayRef<uint64_t> Args); |
| 432 | |
| 433 | void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 434 | uint64_t TheRetVal); |
| 435 | bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 436 | CallSiteInfo &CSInfo, |
| 437 | WholeProgramDevirtResolution::ByArg *Res); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 438 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 439 | // Returns the global symbol name that is used to export information about the |
| 440 | // given vtable slot and list of arguments. |
| 441 | std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args, |
| 442 | StringRef Name); |
| 443 | |
| 444 | // This function is called during the export phase to create a symbol |
| 445 | // definition containing information about the given vtable slot and list of |
| 446 | // arguments. |
| 447 | void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, |
| 448 | Constant *C); |
| 449 | |
| 450 | // This function is called during the import phase to create a reference to |
| 451 | // the symbol definition created during the export phase. |
| 452 | Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 453 | StringRef Name, unsigned AbsWidth = 0); |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 454 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 455 | void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, |
| 456 | Constant *UniqueMemberAddr); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 457 | bool tryUniqueRetValOpt(unsigned BitWidth, |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 458 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 459 | CallSiteInfo &CSInfo, |
| 460 | WholeProgramDevirtResolution::ByArg *Res, |
| 461 | VTableSlot Slot, ArrayRef<uint64_t> Args); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 462 | |
| 463 | void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 464 | Constant *Byte, Constant *Bit); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 465 | bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 466 | VTableSlotInfo &SlotInfo, |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 467 | WholeProgramDevirtResolution *Res, VTableSlot Slot); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 468 | |
| 469 | void rebuildGlobal(VTableBits &B); |
| 470 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 471 | // Apply the summary resolution for Slot to all virtual calls in SlotInfo. |
| 472 | void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo); |
| 473 | |
| 474 | // If we were able to eliminate all unsafe uses for a type checked load, |
| 475 | // eliminate the associated type tests by replacing them with true. |
| 476 | void removeRedundantTypeTests(); |
| 477 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 478 | bool run(); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 479 | |
| 480 | // Lower the module using the action and summary passed as command line |
| 481 | // arguments. For testing purposes only. |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 482 | static bool runForTesting(Module &M, |
| 483 | function_ref<AAResults &(Function &)> AARGetter); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 484 | }; |
| 485 | |
| 486 | struct WholeProgramDevirt : public ModulePass { |
| 487 | static char ID; |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 488 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 489 | bool UseCommandLine = false; |
| 490 | |
| 491 | PassSummaryAction Action; |
| 492 | ModuleSummaryIndex *Summary; |
| 493 | |
| 494 | WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) { |
| 495 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 496 | } |
| 497 | |
| 498 | WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary) |
| 499 | : ModulePass(ID), Action(Action), Summary(Summary) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 500 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 501 | } |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 502 | |
| 503 | bool runOnModule(Module &M) override { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 504 | if (skipModule(M)) |
| 505 | return false; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 506 | if (UseCommandLine) |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 507 | return DevirtModule::runForTesting(M, LegacyAARGetter(*this)); |
| 508 | return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run(); |
| 509 | } |
| 510 | |
| 511 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 512 | AU.addRequired<AssumptionCacheTracker>(); |
| 513 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 514 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 515 | }; |
| 516 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 517 | } // end anonymous namespace |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 518 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 519 | INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt", |
| 520 | "Whole program devirtualization", false, false) |
| 521 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 522 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 523 | INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt", |
| 524 | "Whole program devirtualization", false, false) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 525 | char WholeProgramDevirt::ID = 0; |
| 526 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 527 | ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action, |
| 528 | ModuleSummaryIndex *Summary) { |
| 529 | return new WholeProgramDevirt(Action, Summary); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 530 | } |
| 531 | |
Chandler Carruth | 164a2aa6 | 2016-06-17 00:11:01 +0000 | [diff] [blame] | 532 | PreservedAnalyses WholeProgramDevirtPass::run(Module &M, |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 533 | ModuleAnalysisManager &AM) { |
| 534 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
| 535 | auto AARGetter = [&](Function &F) -> AAResults & { |
| 536 | return FAM.getResult<AAManager>(F); |
| 537 | }; |
| 538 | if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run()) |
Davide Italiano | d737dd2 | 2016-06-14 21:44:19 +0000 | [diff] [blame] | 539 | return PreservedAnalyses::all(); |
| 540 | return PreservedAnalyses::none(); |
| 541 | } |
| 542 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 543 | bool DevirtModule::runForTesting( |
| 544 | Module &M, function_ref<AAResults &(Function &)> AARGetter) { |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 545 | ModuleSummaryIndex Summary; |
| 546 | |
| 547 | // Handle the command-line summary arguments. This code is for testing |
| 548 | // purposes only, so we handle errors directly. |
| 549 | if (!ClReadSummary.empty()) { |
| 550 | ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + |
| 551 | ": "); |
| 552 | auto ReadSummaryFile = |
| 553 | ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); |
| 554 | |
| 555 | yaml::Input In(ReadSummaryFile->getBuffer()); |
| 556 | In >> Summary; |
| 557 | ExitOnErr(errorCodeToError(In.error())); |
| 558 | } |
| 559 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 560 | bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run(); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 561 | |
| 562 | if (!ClWriteSummary.empty()) { |
| 563 | ExitOnError ExitOnErr( |
| 564 | "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); |
| 565 | std::error_code EC; |
| 566 | raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text); |
| 567 | ExitOnErr(errorCodeToError(EC)); |
| 568 | |
| 569 | yaml::Output Out(OS); |
| 570 | Out << Summary; |
| 571 | } |
| 572 | |
| 573 | return Changed; |
| 574 | } |
| 575 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 576 | void DevirtModule::buildTypeIdentifierMap( |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 577 | std::vector<VTableBits> &Bits, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 578 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 579 | DenseMap<GlobalVariable *, VTableBits *> GVToBits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 580 | Bits.reserve(M.getGlobalList().size()); |
| 581 | SmallVector<MDNode *, 2> Types; |
| 582 | for (GlobalVariable &GV : M.globals()) { |
| 583 | Types.clear(); |
| 584 | GV.getMetadata(LLVMContext::MD_type, Types); |
| 585 | if (Types.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 586 | continue; |
| 587 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 588 | VTableBits *&BitsPtr = GVToBits[&GV]; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 589 | if (!BitsPtr) { |
| 590 | Bits.emplace_back(); |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 591 | Bits.back().GV = &GV; |
| 592 | Bits.back().ObjectSize = |
| 593 | M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 594 | BitsPtr = &Bits.back(); |
| 595 | } |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 596 | |
| 597 | for (MDNode *Type : Types) { |
| 598 | auto TypeID = Type->getOperand(1).get(); |
| 599 | |
| 600 | uint64_t Offset = |
| 601 | cast<ConstantInt>( |
| 602 | cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) |
| 603 | ->getZExtValue(); |
| 604 | |
| 605 | TypeIdMap[TypeID].insert({BitsPtr, Offset}); |
| 606 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 607 | } |
| 608 | } |
| 609 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 610 | Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) { |
| 611 | if (I->getType()->isPointerTy()) { |
| 612 | if (Offset == 0) |
| 613 | return I; |
| 614 | return nullptr; |
| 615 | } |
| 616 | |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 617 | const DataLayout &DL = M.getDataLayout(); |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 618 | |
| 619 | if (auto *C = dyn_cast<ConstantStruct>(I)) { |
| 620 | const StructLayout *SL = DL.getStructLayout(C->getType()); |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 621 | if (Offset >= SL->getSizeInBytes()) |
| 622 | return nullptr; |
| 623 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 624 | unsigned Op = SL->getElementContainingOffset(Offset); |
| 625 | return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), |
| 626 | Offset - SL->getElementOffset(Op)); |
| 627 | } |
| 628 | if (auto *C = dyn_cast<ConstantArray>(I)) { |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 629 | ArrayType *VTableTy = C->getType(); |
| 630 | uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType()); |
| 631 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 632 | unsigned Op = Offset / ElemSize; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 633 | if (Op >= C->getNumOperands()) |
| 634 | return nullptr; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 635 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 636 | return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), |
| 637 | Offset % ElemSize); |
| 638 | } |
| 639 | return nullptr; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 640 | } |
| 641 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 642 | bool DevirtModule::tryFindVirtualCallTargets( |
| 643 | std::vector<VirtualCallTarget> &TargetsForSlot, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 644 | const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) { |
| 645 | for (const TypeMemberInfo &TM : TypeMemberInfos) { |
| 646 | if (!TM.Bits->GV->isConstant()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 647 | return false; |
| 648 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 649 | Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), |
| 650 | TM.Offset + ByteOffset); |
| 651 | if (!Ptr) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 652 | return false; |
| 653 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 654 | auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 655 | if (!Fn) |
| 656 | return false; |
| 657 | |
| 658 | // We can disregard __cxa_pure_virtual as a possible call target, as |
| 659 | // calls to pure virtuals are UB. |
| 660 | if (Fn->getName() == "__cxa_pure_virtual") |
| 661 | continue; |
| 662 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 663 | TargetsForSlot.push_back({Fn, &TM}); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 664 | } |
| 665 | |
| 666 | // Give up if we couldn't find any targets. |
| 667 | return !TargetsForSlot.empty(); |
| 668 | } |
| 669 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 670 | void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 671 | Constant *TheFn, bool &IsExported) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 672 | auto Apply = [&](CallSiteInfo &CSInfo) { |
| 673 | for (auto &&VCallSite : CSInfo.CallSites) { |
| 674 | if (RemarksEnabled) |
| 675 | VCallSite.emitRemark("single-impl", TheFn->getName()); |
| 676 | VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast( |
| 677 | TheFn, VCallSite.CS.getCalledValue()->getType())); |
| 678 | // This use is no longer unsafe. |
| 679 | if (VCallSite.NumUnsafeUses) |
| 680 | --*VCallSite.NumUnsafeUses; |
| 681 | } |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 682 | if (CSInfo.isExported()) { |
| 683 | IsExported = true; |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 684 | CSInfo.markDevirt(); |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 685 | } |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 686 | }; |
| 687 | Apply(SlotInfo.CSInfo); |
| 688 | for (auto &P : SlotInfo.ConstCSInfo) |
| 689 | Apply(P.second); |
| 690 | } |
| 691 | |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 692 | bool DevirtModule::trySingleImplDevirt( |
| 693 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 694 | VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) { |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 695 | // See if the program contains a single implementation of this virtual |
| 696 | // function. |
| 697 | Function *TheFn = TargetsForSlot[0].Fn; |
| 698 | for (auto &&Target : TargetsForSlot) |
| 699 | if (TheFn != Target.Fn) |
| 700 | return false; |
| 701 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 702 | // If so, update each call site to call that implementation directly. |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 703 | if (RemarksEnabled) |
| 704 | TargetsForSlot[0].WasDevirt = true; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 705 | |
| 706 | bool IsExported = false; |
| 707 | applySingleImplDevirt(SlotInfo, TheFn, IsExported); |
| 708 | if (!IsExported) |
| 709 | return false; |
| 710 | |
| 711 | // If the only implementation has local linkage, we must promote to external |
| 712 | // to make it visible to thin LTO objects. We can only get here during the |
| 713 | // ThinLTO export phase. |
| 714 | if (TheFn->hasLocalLinkage()) { |
| 715 | TheFn->setLinkage(GlobalValue::ExternalLinkage); |
| 716 | TheFn->setVisibility(GlobalValue::HiddenVisibility); |
| 717 | TheFn->setName(TheFn->getName() + "$merged"); |
| 718 | } |
| 719 | |
| 720 | Res->TheKind = WholeProgramDevirtResolution::SingleImpl; |
| 721 | Res->SingleImplName = TheFn->getName(); |
| 722 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 723 | return true; |
| 724 | } |
| 725 | |
| 726 | bool DevirtModule::tryEvaluateFunctionsWithArgs( |
| 727 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 728 | ArrayRef<uint64_t> Args) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 729 | // Evaluate each function and store the result in each target's RetVal |
| 730 | // field. |
| 731 | for (VirtualCallTarget &Target : TargetsForSlot) { |
| 732 | if (Target.Fn->arg_size() != Args.size() + 1) |
| 733 | return false; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 734 | |
| 735 | Evaluator Eval(M.getDataLayout(), nullptr); |
| 736 | SmallVector<Constant *, 2> EvalArgs; |
| 737 | EvalArgs.push_back( |
| 738 | Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 739 | for (unsigned I = 0; I != Args.size(); ++I) { |
| 740 | auto *ArgTy = dyn_cast<IntegerType>( |
| 741 | Target.Fn->getFunctionType()->getParamType(I + 1)); |
| 742 | if (!ArgTy) |
| 743 | return false; |
| 744 | EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); |
| 745 | } |
| 746 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 747 | Constant *RetVal; |
| 748 | if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || |
| 749 | !isa<ConstantInt>(RetVal)) |
| 750 | return false; |
| 751 | Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); |
| 752 | } |
| 753 | return true; |
| 754 | } |
| 755 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 756 | void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 757 | uint64_t TheRetVal) { |
| 758 | for (auto Call : CSInfo.CallSites) |
| 759 | Call.replaceAndErase( |
| 760 | "uniform-ret-val", FnName, RemarksEnabled, |
| 761 | ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal)); |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 762 | CSInfo.markDevirt(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 763 | } |
| 764 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 765 | bool DevirtModule::tryUniformRetValOpt( |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 766 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo, |
| 767 | WholeProgramDevirtResolution::ByArg *Res) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 768 | // Uniform return value optimization. If all functions return the same |
| 769 | // constant, replace all calls with that constant. |
| 770 | uint64_t TheRetVal = TargetsForSlot[0].RetVal; |
| 771 | for (const VirtualCallTarget &Target : TargetsForSlot) |
| 772 | if (Target.RetVal != TheRetVal) |
| 773 | return false; |
| 774 | |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 775 | if (CSInfo.isExported()) { |
| 776 | Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; |
| 777 | Res->Info = TheRetVal; |
| 778 | } |
| 779 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 780 | applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 781 | if (RemarksEnabled) |
| 782 | for (auto &&Target : TargetsForSlot) |
| 783 | Target.WasDevirt = true; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 784 | return true; |
| 785 | } |
| 786 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 787 | std::string DevirtModule::getGlobalName(VTableSlot Slot, |
| 788 | ArrayRef<uint64_t> Args, |
| 789 | StringRef Name) { |
| 790 | std::string FullName = "__typeid_"; |
| 791 | raw_string_ostream OS(FullName); |
| 792 | OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset; |
| 793 | for (uint64_t Arg : Args) |
| 794 | OS << '_' << Arg; |
| 795 | OS << '_' << Name; |
| 796 | return OS.str(); |
| 797 | } |
| 798 | |
| 799 | void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, |
| 800 | StringRef Name, Constant *C) { |
| 801 | GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage, |
| 802 | getGlobalName(Slot, Args, Name), C, &M); |
| 803 | GA->setVisibility(GlobalValue::HiddenVisibility); |
| 804 | } |
| 805 | |
| 806 | Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 807 | StringRef Name, unsigned AbsWidth) { |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 808 | Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty); |
| 809 | auto *GV = dyn_cast<GlobalVariable>(C); |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 810 | // We only need to set metadata if the global is newly created, in which |
| 811 | // case it would not have hidden visibility. |
| 812 | if (!GV || GV->getVisibility() == GlobalValue::HiddenVisibility) |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 813 | return C; |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 814 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 815 | GV->setVisibility(GlobalValue::HiddenVisibility); |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 816 | auto SetAbsRange = [&](uint64_t Min, uint64_t Max) { |
| 817 | auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min)); |
| 818 | auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max)); |
| 819 | GV->setMetadata(LLVMContext::MD_absolute_symbol, |
| 820 | MDNode::get(M.getContext(), {MinC, MaxC})); |
| 821 | }; |
| 822 | if (AbsWidth == IntPtrTy->getBitWidth()) |
| 823 | SetAbsRange(~0ull, ~0ull); // Full set. |
| 824 | else if (AbsWidth) |
| 825 | SetAbsRange(0, 1ull << AbsWidth); |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 826 | return GV; |
| 827 | } |
| 828 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 829 | void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 830 | bool IsOne, |
| 831 | Constant *UniqueMemberAddr) { |
| 832 | for (auto &&Call : CSInfo.CallSites) { |
| 833 | IRBuilder<> B(Call.CS.getInstruction()); |
| 834 | Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, |
| 835 | Call.VTable, UniqueMemberAddr); |
| 836 | Cmp = B.CreateZExt(Cmp, Call.CS->getType()); |
| 837 | Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp); |
| 838 | } |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 839 | CSInfo.markDevirt(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 840 | } |
| 841 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 842 | bool DevirtModule::tryUniqueRetValOpt( |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 843 | unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 844 | CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res, |
| 845 | VTableSlot Slot, ArrayRef<uint64_t> Args) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 846 | // IsOne controls whether we look for a 0 or a 1. |
| 847 | auto tryUniqueRetValOptFor = [&](bool IsOne) { |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 848 | const TypeMemberInfo *UniqueMember = nullptr; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 849 | for (const VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 3866cc5 | 2016-03-08 03:50:36 +0000 | [diff] [blame] | 850 | if (Target.RetVal == (IsOne ? 1 : 0)) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 851 | if (UniqueMember) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 852 | return false; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 853 | UniqueMember = Target.TM; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 854 | } |
| 855 | } |
| 856 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 857 | // 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] | 858 | // checked for a uniform return value in tryUniformRetValOpt. |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 859 | assert(UniqueMember); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 860 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 861 | Constant *UniqueMemberAddr = |
| 862 | ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy); |
| 863 | UniqueMemberAddr = ConstantExpr::getGetElementPtr( |
| 864 | Int8Ty, UniqueMemberAddr, |
| 865 | ConstantInt::get(Int64Ty, UniqueMember->Offset)); |
| 866 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 867 | if (CSInfo.isExported()) { |
| 868 | Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; |
| 869 | Res->Info = IsOne; |
| 870 | |
| 871 | exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr); |
| 872 | } |
| 873 | |
| 874 | // Replace each call with the comparison. |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 875 | applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, |
| 876 | UniqueMemberAddr); |
| 877 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 878 | // Update devirtualization statistics for targets. |
| 879 | if (RemarksEnabled) |
| 880 | for (auto &&Target : TargetsForSlot) |
| 881 | Target.WasDevirt = true; |
| 882 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 883 | return true; |
| 884 | }; |
| 885 | |
| 886 | if (BitWidth == 1) { |
| 887 | if (tryUniqueRetValOptFor(true)) |
| 888 | return true; |
| 889 | if (tryUniqueRetValOptFor(false)) |
| 890 | return true; |
| 891 | } |
| 892 | return false; |
| 893 | } |
| 894 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 895 | void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 896 | Constant *Byte, Constant *Bit) { |
| 897 | for (auto Call : CSInfo.CallSites) { |
| 898 | auto *RetType = cast<IntegerType>(Call.CS.getType()); |
| 899 | IRBuilder<> B(Call.CS.getInstruction()); |
| 900 | Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte); |
| 901 | if (RetType->getBitWidth() == 1) { |
| 902 | Value *Bits = B.CreateLoad(Addr); |
| 903 | Value *BitsAndBit = B.CreateAnd(Bits, Bit); |
| 904 | auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); |
| 905 | Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, |
| 906 | IsBitSet); |
| 907 | } else { |
| 908 | Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); |
| 909 | Value *Val = B.CreateLoad(RetType, ValAddr); |
| 910 | Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val); |
| 911 | } |
| 912 | } |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 913 | CSInfo.markDevirt(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 914 | } |
| 915 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 916 | bool DevirtModule::tryVirtualConstProp( |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 917 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, |
| 918 | WholeProgramDevirtResolution *Res, VTableSlot Slot) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 919 | // This only works if the function returns an integer. |
| 920 | auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); |
| 921 | if (!RetType) |
| 922 | return false; |
| 923 | unsigned BitWidth = RetType->getBitWidth(); |
| 924 | if (BitWidth > 64) |
| 925 | return false; |
| 926 | |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 927 | // Make sure that each function is defined, does not access memory, takes at |
| 928 | // least one argument, does not use its first argument (which we assume is |
| 929 | // 'this'), and has the same return type. |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 930 | // |
| 931 | // Note that we test whether this copy of the function is readnone, rather |
| 932 | // than testing function attributes, which must hold for any copy of the |
| 933 | // function, even a less optimized version substituted at link time. This is |
| 934 | // sound because the virtual constant propagation optimizations effectively |
| 935 | // inline all implementations of the virtual function into each call site, |
| 936 | // rather than using function attributes to perform local optimization. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 937 | for (VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 938 | if (Target.Fn->isDeclaration() || |
| 939 | computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) != |
| 940 | MAK_ReadNone || |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 941 | Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() || |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 942 | Target.Fn->getReturnType() != RetType) |
| 943 | return false; |
| 944 | } |
| 945 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 946 | for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 947 | if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) |
| 948 | continue; |
| 949 | |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 950 | WholeProgramDevirtResolution::ByArg *ResByArg = nullptr; |
| 951 | if (Res) |
| 952 | ResByArg = &Res->ResByArg[CSByConstantArg.first]; |
| 953 | |
| 954 | if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg)) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 955 | continue; |
| 956 | |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 957 | if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second, |
| 958 | ResByArg, Slot, CSByConstantArg.first)) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 959 | continue; |
| 960 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 961 | // Find an allocation offset in bits in all vtables associated with the |
| 962 | // type. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 963 | uint64_t AllocBefore = |
| 964 | findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); |
| 965 | uint64_t AllocAfter = |
| 966 | findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); |
| 967 | |
| 968 | // Calculate the total amount of padding needed to store a value at both |
| 969 | // ends of the object. |
| 970 | uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; |
| 971 | for (auto &&Target : TargetsForSlot) { |
| 972 | TotalPaddingBefore += std::max<int64_t>( |
| 973 | (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); |
| 974 | TotalPaddingAfter += std::max<int64_t>( |
| 975 | (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); |
| 976 | } |
| 977 | |
| 978 | // If the amount of padding is too large, give up. |
| 979 | // FIXME: do something smarter here. |
| 980 | if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) |
| 981 | continue; |
| 982 | |
| 983 | // Calculate the offset to the value as a (possibly negative) byte offset |
| 984 | // and (if applicable) a bit offset, and store the values in the targets. |
| 985 | int64_t OffsetByte; |
| 986 | uint64_t OffsetBit; |
| 987 | if (TotalPaddingBefore <= TotalPaddingAfter) |
| 988 | setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, |
| 989 | OffsetBit); |
| 990 | else |
| 991 | setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, |
| 992 | OffsetBit); |
| 993 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 994 | if (RemarksEnabled) |
| 995 | for (auto &&Target : TargetsForSlot) |
| 996 | Target.WasDevirt = true; |
| 997 | |
Peter Collingbourne | 184773d | 2017-02-17 19:43:45 +0000 | [diff] [blame] | 998 | Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 999 | Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1000 | |
| 1001 | if (CSByConstantArg.second.isExported()) { |
| 1002 | ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; |
| 1003 | exportGlobal(Slot, CSByConstantArg.first, "byte", |
| 1004 | ConstantExpr::getIntToPtr(ByteConst, Int8PtrTy)); |
| 1005 | exportGlobal(Slot, CSByConstantArg.first, "bit", |
| 1006 | ConstantExpr::getIntToPtr(BitConst, Int8PtrTy)); |
| 1007 | } |
| 1008 | |
| 1009 | // Rewrite each call to a load from OffsetByte/OffsetBit. |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1010 | applyVirtualConstProp(CSByConstantArg.second, |
| 1011 | TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1012 | } |
| 1013 | return true; |
| 1014 | } |
| 1015 | |
| 1016 | void DevirtModule::rebuildGlobal(VTableBits &B) { |
| 1017 | if (B.Before.Bytes.empty() && B.After.Bytes.empty()) |
| 1018 | return; |
| 1019 | |
| 1020 | // Align each byte array to pointer width. |
| 1021 | unsigned PointerSize = M.getDataLayout().getPointerSize(); |
| 1022 | B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize)); |
| 1023 | B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize)); |
| 1024 | |
| 1025 | // Before was stored in reverse order; flip it now. |
| 1026 | for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) |
| 1027 | std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); |
| 1028 | |
| 1029 | // Build an anonymous global containing the before bytes, followed by the |
| 1030 | // original initializer, followed by the after bytes. |
| 1031 | auto NewInit = ConstantStruct::getAnon( |
| 1032 | {ConstantDataArray::get(M.getContext(), B.Before.Bytes), |
| 1033 | B.GV->getInitializer(), |
| 1034 | ConstantDataArray::get(M.getContext(), B.After.Bytes)}); |
| 1035 | auto NewGV = |
| 1036 | new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), |
| 1037 | GlobalVariable::PrivateLinkage, NewInit, "", B.GV); |
| 1038 | NewGV->setSection(B.GV->getSection()); |
| 1039 | NewGV->setComdat(B.GV->getComdat()); |
| 1040 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1041 | // Copy the original vtable's metadata to the anonymous global, adjusting |
| 1042 | // offsets as required. |
| 1043 | NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); |
| 1044 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1045 | // Build an alias named after the original global, pointing at the second |
| 1046 | // element (the original initializer). |
| 1047 | auto Alias = GlobalAlias::create( |
| 1048 | B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", |
| 1049 | ConstantExpr::getGetElementPtr( |
| 1050 | NewInit->getType(), NewGV, |
| 1051 | ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), |
| 1052 | ConstantInt::get(Int32Ty, 1)}), |
| 1053 | &M); |
| 1054 | Alias->setVisibility(B.GV->getVisibility()); |
| 1055 | Alias->takeName(B.GV); |
| 1056 | |
| 1057 | B.GV->replaceAllUsesWith(Alias); |
| 1058 | B.GV->eraseFromParent(); |
| 1059 | } |
| 1060 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1061 | bool DevirtModule::areRemarksEnabled() { |
| 1062 | const auto &FL = M.getFunctionList(); |
| 1063 | if (FL.empty()) |
| 1064 | return false; |
| 1065 | const Function &Fn = FL.front(); |
Adam Nemet | de53bfb | 2017-02-23 23:11:11 +0000 | [diff] [blame] | 1066 | |
| 1067 | const auto &BBL = Fn.getBasicBlockList(); |
| 1068 | if (BBL.empty()) |
| 1069 | return false; |
| 1070 | auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front()); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1071 | return DI.isEnabled(); |
| 1072 | } |
| 1073 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1074 | void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc, |
| 1075 | Function *AssumeFunc) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1076 | // 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] | 1077 | // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p |
| 1078 | // points to a member of the type identifier %md. Group calls by (type ID, |
| 1079 | // offset) pair (effectively the identity of the virtual function) and store |
| 1080 | // to CallSlots. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1081 | DenseSet<Value *> SeenPtrs; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1082 | for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1083 | I != E;) { |
| 1084 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 1085 | ++I; |
| 1086 | if (!CI) |
| 1087 | continue; |
| 1088 | |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1089 | // Search for virtual calls based on %p and add them to DevirtCalls. |
| 1090 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1091 | SmallVector<CallInst *, 1> Assumes; |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1092 | findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1093 | |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1094 | // If we found any, add them to CallSlots. Only do this if we haven't seen |
| 1095 | // the vtable pointer before, as it may have been CSE'd with pointers from |
| 1096 | // other call sites, and we don't want to process call sites multiple times. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1097 | if (!Assumes.empty()) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1098 | Metadata *TypeId = |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1099 | cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); |
| 1100 | Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1101 | if (SeenPtrs.insert(Ptr).second) { |
| 1102 | for (DevirtCallSite Call : DevirtCalls) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1103 | CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0), |
| 1104 | Call.CS, nullptr); |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1105 | } |
| 1106 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1107 | } |
| 1108 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1109 | // We no longer need the assumes or the type test. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1110 | for (auto Assume : Assumes) |
| 1111 | Assume->eraseFromParent(); |
| 1112 | // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we |
| 1113 | // may use the vtable argument later. |
| 1114 | if (CI->use_empty()) |
| 1115 | CI->eraseFromParent(); |
| 1116 | } |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1117 | } |
| 1118 | |
| 1119 | void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { |
| 1120 | Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); |
| 1121 | |
| 1122 | for (auto I = TypeCheckedLoadFunc->use_begin(), |
| 1123 | E = TypeCheckedLoadFunc->use_end(); |
| 1124 | I != E;) { |
| 1125 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 1126 | ++I; |
| 1127 | if (!CI) |
| 1128 | continue; |
| 1129 | |
| 1130 | Value *Ptr = CI->getArgOperand(0); |
| 1131 | Value *Offset = CI->getArgOperand(1); |
| 1132 | Value *TypeIdValue = CI->getArgOperand(2); |
| 1133 | Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); |
| 1134 | |
| 1135 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
| 1136 | SmallVector<Instruction *, 1> LoadedPtrs; |
| 1137 | SmallVector<Instruction *, 1> Preds; |
| 1138 | bool HasNonCallUses = false; |
| 1139 | findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, |
| 1140 | HasNonCallUses, CI); |
| 1141 | |
| 1142 | // Start by generating "pessimistic" code that explicitly loads the function |
| 1143 | // pointer from the vtable and performs the type check. If possible, we will |
| 1144 | // eliminate the load and the type check later. |
| 1145 | |
| 1146 | // If possible, only generate the load at the point where it is used. |
| 1147 | // This helps avoid unnecessary spills. |
| 1148 | IRBuilder<> LoadB( |
| 1149 | (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); |
| 1150 | Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset); |
| 1151 | Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy)); |
| 1152 | Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr); |
| 1153 | |
| 1154 | for (Instruction *LoadedPtr : LoadedPtrs) { |
| 1155 | LoadedPtr->replaceAllUsesWith(LoadedValue); |
| 1156 | LoadedPtr->eraseFromParent(); |
| 1157 | } |
| 1158 | |
| 1159 | // Likewise for the type test. |
| 1160 | IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); |
| 1161 | CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); |
| 1162 | |
| 1163 | for (Instruction *Pred : Preds) { |
| 1164 | Pred->replaceAllUsesWith(TypeTestCall); |
| 1165 | Pred->eraseFromParent(); |
| 1166 | } |
| 1167 | |
| 1168 | // We have already erased any extractvalue instructions that refer to the |
| 1169 | // intrinsic call, but the intrinsic may have other non-extractvalue uses |
| 1170 | // (although this is unlikely). In that case, explicitly build a pair and |
| 1171 | // RAUW it. |
| 1172 | if (!CI->use_empty()) { |
| 1173 | Value *Pair = UndefValue::get(CI->getType()); |
| 1174 | IRBuilder<> B(CI); |
| 1175 | Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); |
| 1176 | Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); |
| 1177 | CI->replaceAllUsesWith(Pair); |
| 1178 | } |
| 1179 | |
| 1180 | // The number of unsafe uses is initially the number of uses. |
| 1181 | auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; |
| 1182 | NumUnsafeUses = DevirtCalls.size(); |
| 1183 | |
| 1184 | // If the function pointer has a non-call user, we cannot eliminate the type |
| 1185 | // check, as one of those users may eventually call the pointer. Increment |
| 1186 | // the unsafe use count to make sure it cannot reach zero. |
| 1187 | if (HasNonCallUses) |
| 1188 | ++NumUnsafeUses; |
| 1189 | for (DevirtCallSite Call : DevirtCalls) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1190 | CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, |
| 1191 | &NumUnsafeUses); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1192 | } |
| 1193 | |
| 1194 | CI->eraseFromParent(); |
| 1195 | } |
| 1196 | } |
| 1197 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1198 | void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) { |
Peter Collingbourne | 9a3f979 | 2017-03-22 18:04:39 +0000 | [diff] [blame^] | 1199 | const TypeIdSummary *TidSummary = |
| 1200 | Summary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString()); |
| 1201 | if (!TidSummary) |
| 1202 | return; |
| 1203 | auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset); |
| 1204 | if (ResI == TidSummary->WPDRes.end()) |
| 1205 | return; |
| 1206 | const WholeProgramDevirtResolution &Res = ResI->second; |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1207 | |
| 1208 | if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) { |
| 1209 | // The type of the function in the declaration is irrelevant because every |
| 1210 | // call site will cast it to the correct type. |
| 1211 | auto *SingleImpl = M.getOrInsertFunction( |
| 1212 | Res.SingleImplName, Type::getVoidTy(M.getContext()), nullptr); |
| 1213 | |
| 1214 | // This is the import phase so we should not be exporting anything. |
| 1215 | bool IsExported = false; |
| 1216 | applySingleImplDevirt(SlotInfo, SingleImpl, IsExported); |
| 1217 | assert(!IsExported); |
| 1218 | } |
Peter Collingbourne | 0152c81 | 2017-03-09 01:11:15 +0000 | [diff] [blame] | 1219 | |
| 1220 | for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) { |
| 1221 | auto I = Res.ResByArg.find(CSByConstantArg.first); |
| 1222 | if (I == Res.ResByArg.end()) |
| 1223 | continue; |
| 1224 | auto &ResByArg = I->second; |
| 1225 | // FIXME: We should figure out what to do about the "function name" argument |
| 1226 | // to the apply* functions, as the function names are unavailable during the |
| 1227 | // importing phase. For now we just pass the empty string. This does not |
| 1228 | // impact correctness because the function names are just used for remarks. |
| 1229 | switch (ResByArg.TheKind) { |
| 1230 | case WholeProgramDevirtResolution::ByArg::UniformRetVal: |
| 1231 | applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info); |
| 1232 | break; |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1233 | case WholeProgramDevirtResolution::ByArg::UniqueRetVal: { |
| 1234 | Constant *UniqueMemberAddr = |
| 1235 | importGlobal(Slot, CSByConstantArg.first, "unique_member"); |
| 1236 | applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info, |
| 1237 | UniqueMemberAddr); |
| 1238 | break; |
| 1239 | } |
Peter Collingbourne | 14dcf02 | 2017-03-10 20:13:58 +0000 | [diff] [blame] | 1240 | case WholeProgramDevirtResolution::ByArg::VirtualConstProp: { |
| 1241 | Constant *Byte = importGlobal(Slot, CSByConstantArg.first, "byte", 32); |
| 1242 | Byte = ConstantExpr::getPtrToInt(Byte, Int32Ty); |
| 1243 | Constant *Bit = importGlobal(Slot, CSByConstantArg.first, "bit", 8); |
| 1244 | Bit = ConstantExpr::getPtrToInt(Bit, Int8Ty); |
| 1245 | applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit); |
| 1246 | } |
Peter Collingbourne | 0152c81 | 2017-03-09 01:11:15 +0000 | [diff] [blame] | 1247 | default: |
| 1248 | break; |
| 1249 | } |
| 1250 | } |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1251 | } |
| 1252 | |
| 1253 | void DevirtModule::removeRedundantTypeTests() { |
| 1254 | auto True = ConstantInt::getTrue(M.getContext()); |
| 1255 | for (auto &&U : NumUnsafeUsesForTypeTest) { |
| 1256 | if (U.second == 0) { |
| 1257 | U.first->replaceAllUsesWith(True); |
| 1258 | U.first->eraseFromParent(); |
| 1259 | } |
| 1260 | } |
| 1261 | } |
| 1262 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1263 | bool DevirtModule::run() { |
| 1264 | Function *TypeTestFunc = |
| 1265 | M.getFunction(Intrinsic::getName(Intrinsic::type_test)); |
| 1266 | Function *TypeCheckedLoadFunc = |
| 1267 | M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); |
| 1268 | Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); |
| 1269 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1270 | // Normally if there are no users of the devirtualization intrinsics in the |
| 1271 | // module, this pass has nothing to do. But if we are exporting, we also need |
| 1272 | // to handle any users that appear only in the function summaries. |
| 1273 | if (Action != PassSummaryAction::Export && |
| 1274 | (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1275 | AssumeFunc->use_empty()) && |
| 1276 | (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty())) |
| 1277 | return false; |
| 1278 | |
| 1279 | if (TypeTestFunc && AssumeFunc) |
| 1280 | scanTypeTestUsers(TypeTestFunc, AssumeFunc); |
| 1281 | |
| 1282 | if (TypeCheckedLoadFunc) |
| 1283 | scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1284 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1285 | if (Action == PassSummaryAction::Import) { |
| 1286 | for (auto &S : CallSlots) |
| 1287 | importResolution(S.first, S.second); |
| 1288 | |
| 1289 | removeRedundantTypeTests(); |
| 1290 | |
| 1291 | // The rest of the code is only necessary when exporting or during regular |
| 1292 | // LTO, so we are done. |
| 1293 | return true; |
| 1294 | } |
| 1295 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1296 | // Rebuild type metadata into a map for easy lookup. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1297 | std::vector<VTableBits> Bits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1298 | DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; |
| 1299 | buildTypeIdentifierMap(Bits, TypeIdMap); |
| 1300 | if (TypeIdMap.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1301 | return true; |
| 1302 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1303 | // Collect information from summary about which calls to try to devirtualize. |
| 1304 | if (Action == PassSummaryAction::Export) { |
| 1305 | DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID; |
| 1306 | for (auto &P : TypeIdMap) { |
| 1307 | if (auto *TypeId = dyn_cast<MDString>(P.first)) |
| 1308 | MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back( |
| 1309 | TypeId); |
| 1310 | } |
| 1311 | |
| 1312 | for (auto &P : *Summary) { |
| 1313 | for (auto &S : P.second) { |
| 1314 | auto *FS = dyn_cast<FunctionSummary>(S.get()); |
| 1315 | if (!FS) |
| 1316 | continue; |
| 1317 | // FIXME: Only add live functions. |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1318 | for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { |
| 1319 | for (Metadata *MD : MetadataByGUID[VF.GUID]) { |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1320 | CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers = |
| 1321 | true; |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1322 | } |
| 1323 | } |
| 1324 | for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { |
| 1325 | for (Metadata *MD : MetadataByGUID[VF.GUID]) { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1326 | CallSlots[{MD, VF.Offset}] |
| 1327 | .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS); |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1328 | } |
| 1329 | } |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1330 | for (const FunctionSummary::ConstVCall &VC : |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1331 | FS->type_test_assume_const_vcalls()) { |
| 1332 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1333 | CallSlots[{MD, VC.VFunc.Offset}] |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1334 | .ConstCSInfo[VC.Args] |
| 1335 | .SummaryHasTypeTestAssumeUsers = true; |
| 1336 | } |
| 1337 | } |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1338 | for (const FunctionSummary::ConstVCall &VC : |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1339 | FS->type_checked_load_const_vcalls()) { |
| 1340 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1341 | CallSlots[{MD, VC.VFunc.Offset}] |
| 1342 | .ConstCSInfo[VC.Args] |
| 1343 | .SummaryTypeCheckedLoadUsers.push_back(FS); |
George Rimar | 5d8aea1 | 2017-03-10 10:31:56 +0000 | [diff] [blame] | 1344 | } |
| 1345 | } |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1346 | } |
| 1347 | } |
| 1348 | } |
| 1349 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1350 | // For each (type, offset) pair: |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1351 | bool DidVirtualConstProp = false; |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1352 | std::map<std::string, Function*> DevirtTargets; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1353 | for (auto &S : CallSlots) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1354 | // Search each of the members of the type identifier for the virtual |
| 1355 | // function implementation at offset S.first.ByteOffset, and add to |
| 1356 | // TargetsForSlot. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1357 | std::vector<VirtualCallTarget> TargetsForSlot; |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1358 | if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID], |
| 1359 | S.first.ByteOffset)) { |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1360 | WholeProgramDevirtResolution *Res = nullptr; |
| 1361 | if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) |
Peter Collingbourne | 9a3f979 | 2017-03-22 18:04:39 +0000 | [diff] [blame^] | 1362 | Res = &Summary |
| 1363 | ->getOrInsertTypeIdSummary( |
| 1364 | cast<MDString>(S.first.TypeID)->getString()) |
| 1365 | .WPDRes[S.first.ByteOffset]; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1366 | |
| 1367 | if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) && |
Peter Collingbourne | 59675ba | 2017-03-10 20:09:11 +0000 | [diff] [blame] | 1368 | tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first)) |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1369 | DidVirtualConstProp = true; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1370 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1371 | // Collect functions devirtualized at least for one call site for stats. |
| 1372 | if (RemarksEnabled) |
| 1373 | for (const auto &T : TargetsForSlot) |
| 1374 | if (T.WasDevirt) |
| 1375 | DevirtTargets[T.Fn->getName()] = T.Fn; |
| 1376 | } |
| 1377 | |
| 1378 | // CFI-specific: if we are exporting and any llvm.type.checked.load |
| 1379 | // intrinsics were *not* devirtualized, we need to add the resulting |
| 1380 | // llvm.type.test intrinsics to the function summaries so that the |
| 1381 | // LowerTypeTests pass will export them. |
| 1382 | if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) { |
| 1383 | auto GUID = |
| 1384 | GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString()); |
| 1385 | for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers) |
| 1386 | FS->addTypeTest(GUID); |
| 1387 | for (auto &CCS : S.second.ConstCSInfo) |
| 1388 | for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers) |
| 1389 | FS->addTypeTest(GUID); |
| 1390 | } |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1391 | } |
| 1392 | |
| 1393 | if (RemarksEnabled) { |
| 1394 | // Generate remarks for each devirtualized function. |
| 1395 | for (const auto &DT : DevirtTargets) { |
| 1396 | Function *F = DT.second; |
| 1397 | DISubprogram *SP = F->getSubprogram(); |
Justin Bogner | 7bc978b | 2017-02-18 02:00:27 +0000 | [diff] [blame] | 1398 | emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP, |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1399 | Twine("devirtualized ") + F->getName()); |
Ivan Krasin | b05e06e | 2016-08-05 19:45:16 +0000 | [diff] [blame] | 1400 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1401 | } |
| 1402 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1403 | removeRedundantTypeTests(); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1404 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1405 | // Rebuild each global we touched as part of virtual constant propagation to |
| 1406 | // include the before and after bytes. |
| 1407 | if (DidVirtualConstProp) |
| 1408 | for (VTableBits &B : Bits) |
| 1409 | rebuildGlobal(B); |
| 1410 | |
| 1411 | return true; |
| 1412 | } |