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 |
| 323 | /// pass will clear this vector. If at the end of the pass the vector is |
| 324 | /// non-empty, we will need to add a use of llvm.type.test to each of the |
| 325 | /// function summaries in the vector. |
| 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 | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 332 | }; |
| 333 | |
| 334 | // Call site information collected for a specific VTableSlot. |
| 335 | struct VTableSlotInfo { |
| 336 | // The set of call sites which do not have all constant integer arguments |
| 337 | // (excluding "this"). |
| 338 | CallSiteInfo CSInfo; |
| 339 | |
| 340 | // The set of call sites with all constant integer arguments (excluding |
| 341 | // "this"), grouped by argument list. |
| 342 | std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; |
| 343 | |
| 344 | void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses); |
| 345 | |
| 346 | private: |
| 347 | CallSiteInfo &findCallSiteInfo(CallSite CS); |
| 348 | }; |
| 349 | |
| 350 | CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) { |
| 351 | std::vector<uint64_t> Args; |
| 352 | auto *CI = dyn_cast<IntegerType>(CS.getType()); |
| 353 | if (!CI || CI->getBitWidth() > 64 || CS.arg_empty()) |
| 354 | return CSInfo; |
| 355 | for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) { |
| 356 | auto *CI = dyn_cast<ConstantInt>(Arg); |
| 357 | if (!CI || CI->getBitWidth() > 64) |
| 358 | return CSInfo; |
| 359 | Args.push_back(CI->getZExtValue()); |
| 360 | } |
| 361 | return ConstCSInfo[Args]; |
| 362 | } |
| 363 | |
| 364 | void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS, |
| 365 | unsigned *NumUnsafeUses) { |
| 366 | findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses}); |
| 367 | } |
| 368 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 369 | struct DevirtModule { |
| 370 | Module &M; |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 371 | function_ref<AAResults &(Function &)> AARGetter; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 372 | |
| 373 | PassSummaryAction Action; |
| 374 | ModuleSummaryIndex *Summary; |
| 375 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 376 | IntegerType *Int8Ty; |
| 377 | PointerType *Int8PtrTy; |
| 378 | IntegerType *Int32Ty; |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 379 | IntegerType *Int64Ty; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 380 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 381 | bool RemarksEnabled; |
| 382 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 383 | MapVector<VTableSlot, VTableSlotInfo> CallSlots; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 384 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 385 | // This map keeps track of the number of "unsafe" uses of a loaded function |
| 386 | // pointer. The key is the associated llvm.type.test intrinsic call generated |
| 387 | // by this pass. An unsafe use is one that calls the loaded function pointer |
| 388 | // directly. Every time we eliminate an unsafe use (for example, by |
| 389 | // devirtualizing it or by applying virtual constant propagation), we |
| 390 | // decrement the value stored in this map. If a value reaches zero, we can |
| 391 | // eliminate the type check by RAUWing the associated llvm.type.test call with |
| 392 | // true. |
| 393 | std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; |
| 394 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 395 | DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter, |
| 396 | PassSummaryAction Action, ModuleSummaryIndex *Summary) |
| 397 | : M(M), AARGetter(AARGetter), Action(Action), Summary(Summary), |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 398 | Int8Ty(Type::getInt8Ty(M.getContext())), |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 399 | Int8PtrTy(Type::getInt8PtrTy(M.getContext())), |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 400 | Int32Ty(Type::getInt32Ty(M.getContext())), |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 401 | Int64Ty(Type::getInt64Ty(M.getContext())), |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 402 | RemarksEnabled(areRemarksEnabled()) {} |
| 403 | |
| 404 | bool areRemarksEnabled(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 405 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 406 | void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc); |
| 407 | void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); |
| 408 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 409 | void buildTypeIdentifierMap( |
| 410 | std::vector<VTableBits> &Bits, |
| 411 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 412 | Constant *getPointerAtOffset(Constant *I, uint64_t Offset); |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 413 | bool |
| 414 | tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, |
| 415 | const std::set<TypeMemberInfo> &TypeMemberInfos, |
| 416 | uint64_t ByteOffset); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 417 | |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 418 | void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn, |
| 419 | bool &IsExported); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 420 | bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 421 | VTableSlotInfo &SlotInfo, |
| 422 | WholeProgramDevirtResolution *Res); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 423 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 424 | bool tryEvaluateFunctionsWithArgs( |
| 425 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 426 | ArrayRef<uint64_t> Args); |
| 427 | |
| 428 | void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 429 | uint64_t TheRetVal); |
| 430 | bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 431 | CallSiteInfo &CSInfo, |
| 432 | WholeProgramDevirtResolution::ByArg *Res); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 433 | |
| 434 | void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, |
| 435 | Constant *UniqueMemberAddr); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 436 | bool tryUniqueRetValOpt(unsigned BitWidth, |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 437 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 438 | CallSiteInfo &CSInfo); |
| 439 | |
| 440 | void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 441 | Constant *Byte, Constant *Bit); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 442 | bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 443 | VTableSlotInfo &SlotInfo, |
| 444 | WholeProgramDevirtResolution *Res); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 445 | |
| 446 | void rebuildGlobal(VTableBits &B); |
| 447 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 448 | // Apply the summary resolution for Slot to all virtual calls in SlotInfo. |
| 449 | void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo); |
| 450 | |
| 451 | // If we were able to eliminate all unsafe uses for a type checked load, |
| 452 | // eliminate the associated type tests by replacing them with true. |
| 453 | void removeRedundantTypeTests(); |
| 454 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 455 | bool run(); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 456 | |
| 457 | // Lower the module using the action and summary passed as command line |
| 458 | // arguments. For testing purposes only. |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 459 | static bool runForTesting(Module &M, |
| 460 | function_ref<AAResults &(Function &)> AARGetter); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 461 | }; |
| 462 | |
| 463 | struct WholeProgramDevirt : public ModulePass { |
| 464 | static char ID; |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 465 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 466 | bool UseCommandLine = false; |
| 467 | |
| 468 | PassSummaryAction Action; |
| 469 | ModuleSummaryIndex *Summary; |
| 470 | |
| 471 | WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) { |
| 472 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 473 | } |
| 474 | |
| 475 | WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary) |
| 476 | : ModulePass(ID), Action(Action), Summary(Summary) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 477 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 478 | } |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 479 | |
| 480 | bool runOnModule(Module &M) override { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 481 | if (skipModule(M)) |
| 482 | return false; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 483 | if (UseCommandLine) |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 484 | return DevirtModule::runForTesting(M, LegacyAARGetter(*this)); |
| 485 | return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run(); |
| 486 | } |
| 487 | |
| 488 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 489 | AU.addRequired<AssumptionCacheTracker>(); |
| 490 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 491 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 492 | }; |
| 493 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 494 | } // end anonymous namespace |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 495 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 496 | INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt", |
| 497 | "Whole program devirtualization", false, false) |
| 498 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 499 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 500 | INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt", |
| 501 | "Whole program devirtualization", false, false) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 502 | char WholeProgramDevirt::ID = 0; |
| 503 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 504 | ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action, |
| 505 | ModuleSummaryIndex *Summary) { |
| 506 | return new WholeProgramDevirt(Action, Summary); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 507 | } |
| 508 | |
Chandler Carruth | 164a2aa6 | 2016-06-17 00:11:01 +0000 | [diff] [blame] | 509 | PreservedAnalyses WholeProgramDevirtPass::run(Module &M, |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 510 | ModuleAnalysisManager &AM) { |
| 511 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
| 512 | auto AARGetter = [&](Function &F) -> AAResults & { |
| 513 | return FAM.getResult<AAManager>(F); |
| 514 | }; |
| 515 | if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run()) |
Davide Italiano | d737dd2 | 2016-06-14 21:44:19 +0000 | [diff] [blame] | 516 | return PreservedAnalyses::all(); |
| 517 | return PreservedAnalyses::none(); |
| 518 | } |
| 519 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 520 | bool DevirtModule::runForTesting( |
| 521 | Module &M, function_ref<AAResults &(Function &)> AARGetter) { |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 522 | ModuleSummaryIndex Summary; |
| 523 | |
| 524 | // Handle the command-line summary arguments. This code is for testing |
| 525 | // purposes only, so we handle errors directly. |
| 526 | if (!ClReadSummary.empty()) { |
| 527 | ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + |
| 528 | ": "); |
| 529 | auto ReadSummaryFile = |
| 530 | ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); |
| 531 | |
| 532 | yaml::Input In(ReadSummaryFile->getBuffer()); |
| 533 | In >> Summary; |
| 534 | ExitOnErr(errorCodeToError(In.error())); |
| 535 | } |
| 536 | |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 537 | bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run(); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 538 | |
| 539 | if (!ClWriteSummary.empty()) { |
| 540 | ExitOnError ExitOnErr( |
| 541 | "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); |
| 542 | std::error_code EC; |
| 543 | raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text); |
| 544 | ExitOnErr(errorCodeToError(EC)); |
| 545 | |
| 546 | yaml::Output Out(OS); |
| 547 | Out << Summary; |
| 548 | } |
| 549 | |
| 550 | return Changed; |
| 551 | } |
| 552 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 553 | void DevirtModule::buildTypeIdentifierMap( |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 554 | std::vector<VTableBits> &Bits, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 555 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 556 | DenseMap<GlobalVariable *, VTableBits *> GVToBits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 557 | Bits.reserve(M.getGlobalList().size()); |
| 558 | SmallVector<MDNode *, 2> Types; |
| 559 | for (GlobalVariable &GV : M.globals()) { |
| 560 | Types.clear(); |
| 561 | GV.getMetadata(LLVMContext::MD_type, Types); |
| 562 | if (Types.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 563 | continue; |
| 564 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 565 | VTableBits *&BitsPtr = GVToBits[&GV]; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 566 | if (!BitsPtr) { |
| 567 | Bits.emplace_back(); |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 568 | Bits.back().GV = &GV; |
| 569 | Bits.back().ObjectSize = |
| 570 | M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 571 | BitsPtr = &Bits.back(); |
| 572 | } |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 573 | |
| 574 | for (MDNode *Type : Types) { |
| 575 | auto TypeID = Type->getOperand(1).get(); |
| 576 | |
| 577 | uint64_t Offset = |
| 578 | cast<ConstantInt>( |
| 579 | cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) |
| 580 | ->getZExtValue(); |
| 581 | |
| 582 | TypeIdMap[TypeID].insert({BitsPtr, Offset}); |
| 583 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 584 | } |
| 585 | } |
| 586 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 587 | Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) { |
| 588 | if (I->getType()->isPointerTy()) { |
| 589 | if (Offset == 0) |
| 590 | return I; |
| 591 | return nullptr; |
| 592 | } |
| 593 | |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 594 | const DataLayout &DL = M.getDataLayout(); |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 595 | |
| 596 | if (auto *C = dyn_cast<ConstantStruct>(I)) { |
| 597 | const StructLayout *SL = DL.getStructLayout(C->getType()); |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 598 | if (Offset >= SL->getSizeInBytes()) |
| 599 | return nullptr; |
| 600 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 601 | unsigned Op = SL->getElementContainingOffset(Offset); |
| 602 | return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), |
| 603 | Offset - SL->getElementOffset(Op)); |
| 604 | } |
| 605 | if (auto *C = dyn_cast<ConstantArray>(I)) { |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 606 | ArrayType *VTableTy = C->getType(); |
| 607 | uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType()); |
| 608 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 609 | unsigned Op = Offset / ElemSize; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 610 | if (Op >= C->getNumOperands()) |
| 611 | return nullptr; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 612 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 613 | return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), |
| 614 | Offset % ElemSize); |
| 615 | } |
| 616 | return nullptr; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 617 | } |
| 618 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 619 | bool DevirtModule::tryFindVirtualCallTargets( |
| 620 | std::vector<VirtualCallTarget> &TargetsForSlot, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 621 | const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) { |
| 622 | for (const TypeMemberInfo &TM : TypeMemberInfos) { |
| 623 | if (!TM.Bits->GV->isConstant()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 624 | return false; |
| 625 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 626 | Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), |
| 627 | TM.Offset + ByteOffset); |
| 628 | if (!Ptr) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 629 | return false; |
| 630 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 631 | auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 632 | if (!Fn) |
| 633 | return false; |
| 634 | |
| 635 | // We can disregard __cxa_pure_virtual as a possible call target, as |
| 636 | // calls to pure virtuals are UB. |
| 637 | if (Fn->getName() == "__cxa_pure_virtual") |
| 638 | continue; |
| 639 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 640 | TargetsForSlot.push_back({Fn, &TM}); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 641 | } |
| 642 | |
| 643 | // Give up if we couldn't find any targets. |
| 644 | return !TargetsForSlot.empty(); |
| 645 | } |
| 646 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 647 | void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 648 | Constant *TheFn, bool &IsExported) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 649 | auto Apply = [&](CallSiteInfo &CSInfo) { |
| 650 | for (auto &&VCallSite : CSInfo.CallSites) { |
| 651 | if (RemarksEnabled) |
| 652 | VCallSite.emitRemark("single-impl", TheFn->getName()); |
| 653 | VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast( |
| 654 | TheFn, VCallSite.CS.getCalledValue()->getType())); |
| 655 | // This use is no longer unsafe. |
| 656 | if (VCallSite.NumUnsafeUses) |
| 657 | --*VCallSite.NumUnsafeUses; |
| 658 | } |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 659 | if (CSInfo.isExported()) { |
| 660 | IsExported = true; |
| 661 | CSInfo.SummaryTypeCheckedLoadUsers.clear(); |
| 662 | } |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 663 | }; |
| 664 | Apply(SlotInfo.CSInfo); |
| 665 | for (auto &P : SlotInfo.ConstCSInfo) |
| 666 | Apply(P.second); |
| 667 | } |
| 668 | |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 669 | bool DevirtModule::trySingleImplDevirt( |
| 670 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 671 | VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) { |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 672 | // See if the program contains a single implementation of this virtual |
| 673 | // function. |
| 674 | Function *TheFn = TargetsForSlot[0].Fn; |
| 675 | for (auto &&Target : TargetsForSlot) |
| 676 | if (TheFn != Target.Fn) |
| 677 | return false; |
| 678 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 679 | // If so, update each call site to call that implementation directly. |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 680 | if (RemarksEnabled) |
| 681 | TargetsForSlot[0].WasDevirt = true; |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 682 | |
| 683 | bool IsExported = false; |
| 684 | applySingleImplDevirt(SlotInfo, TheFn, IsExported); |
| 685 | if (!IsExported) |
| 686 | return false; |
| 687 | |
| 688 | // If the only implementation has local linkage, we must promote to external |
| 689 | // to make it visible to thin LTO objects. We can only get here during the |
| 690 | // ThinLTO export phase. |
| 691 | if (TheFn->hasLocalLinkage()) { |
| 692 | TheFn->setLinkage(GlobalValue::ExternalLinkage); |
| 693 | TheFn->setVisibility(GlobalValue::HiddenVisibility); |
| 694 | TheFn->setName(TheFn->getName() + "$merged"); |
| 695 | } |
| 696 | |
| 697 | Res->TheKind = WholeProgramDevirtResolution::SingleImpl; |
| 698 | Res->SingleImplName = TheFn->getName(); |
| 699 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 700 | return true; |
| 701 | } |
| 702 | |
| 703 | bool DevirtModule::tryEvaluateFunctionsWithArgs( |
| 704 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 705 | ArrayRef<uint64_t> Args) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 706 | // Evaluate each function and store the result in each target's RetVal |
| 707 | // field. |
| 708 | for (VirtualCallTarget &Target : TargetsForSlot) { |
| 709 | if (Target.Fn->arg_size() != Args.size() + 1) |
| 710 | return false; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 711 | |
| 712 | Evaluator Eval(M.getDataLayout(), nullptr); |
| 713 | SmallVector<Constant *, 2> EvalArgs; |
| 714 | EvalArgs.push_back( |
| 715 | Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 716 | for (unsigned I = 0; I != Args.size(); ++I) { |
| 717 | auto *ArgTy = dyn_cast<IntegerType>( |
| 718 | Target.Fn->getFunctionType()->getParamType(I + 1)); |
| 719 | if (!ArgTy) |
| 720 | return false; |
| 721 | EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); |
| 722 | } |
| 723 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 724 | Constant *RetVal; |
| 725 | if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || |
| 726 | !isa<ConstantInt>(RetVal)) |
| 727 | return false; |
| 728 | Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); |
| 729 | } |
| 730 | return true; |
| 731 | } |
| 732 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 733 | void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 734 | uint64_t TheRetVal) { |
| 735 | for (auto Call : CSInfo.CallSites) |
| 736 | Call.replaceAndErase( |
| 737 | "uniform-ret-val", FnName, RemarksEnabled, |
| 738 | ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal)); |
Peter Collingbourne | f0bb90b | 2017-03-04 01:38:05 +0000 | [diff] [blame] | 739 | CSInfo.SummaryTypeCheckedLoadUsers.clear(); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 740 | } |
| 741 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 742 | bool DevirtModule::tryUniformRetValOpt( |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 743 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo, |
| 744 | WholeProgramDevirtResolution::ByArg *Res) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 745 | // Uniform return value optimization. If all functions return the same |
| 746 | // constant, replace all calls with that constant. |
| 747 | uint64_t TheRetVal = TargetsForSlot[0].RetVal; |
| 748 | for (const VirtualCallTarget &Target : TargetsForSlot) |
| 749 | if (Target.RetVal != TheRetVal) |
| 750 | return false; |
| 751 | |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 752 | if (CSInfo.isExported()) { |
| 753 | Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; |
| 754 | Res->Info = TheRetVal; |
| 755 | } |
| 756 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 757 | applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 758 | if (RemarksEnabled) |
| 759 | for (auto &&Target : TargetsForSlot) |
| 760 | Target.WasDevirt = true; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 761 | return true; |
| 762 | } |
| 763 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 764 | void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 765 | bool IsOne, |
| 766 | Constant *UniqueMemberAddr) { |
| 767 | for (auto &&Call : CSInfo.CallSites) { |
| 768 | IRBuilder<> B(Call.CS.getInstruction()); |
| 769 | Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, |
| 770 | Call.VTable, UniqueMemberAddr); |
| 771 | Cmp = B.CreateZExt(Cmp, Call.CS->getType()); |
| 772 | Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp); |
| 773 | } |
| 774 | } |
| 775 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 776 | bool DevirtModule::tryUniqueRetValOpt( |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 777 | unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 778 | CallSiteInfo &CSInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 779 | // IsOne controls whether we look for a 0 or a 1. |
| 780 | auto tryUniqueRetValOptFor = [&](bool IsOne) { |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 781 | const TypeMemberInfo *UniqueMember = nullptr; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 782 | for (const VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 3866cc5 | 2016-03-08 03:50:36 +0000 | [diff] [blame] | 783 | if (Target.RetVal == (IsOne ? 1 : 0)) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 784 | if (UniqueMember) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 785 | return false; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 786 | UniqueMember = Target.TM; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 787 | } |
| 788 | } |
| 789 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 790 | // 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] | 791 | // checked for a uniform return value in tryUniformRetValOpt. |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 792 | assert(UniqueMember); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 793 | |
| 794 | // Replace each call with the comparison. |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 795 | Constant *UniqueMemberAddr = |
| 796 | ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy); |
| 797 | UniqueMemberAddr = ConstantExpr::getGetElementPtr( |
| 798 | Int8Ty, UniqueMemberAddr, |
| 799 | ConstantInt::get(Int64Ty, UniqueMember->Offset)); |
| 800 | |
| 801 | applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, |
| 802 | UniqueMemberAddr); |
| 803 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 804 | // Update devirtualization statistics for targets. |
| 805 | if (RemarksEnabled) |
| 806 | for (auto &&Target : TargetsForSlot) |
| 807 | Target.WasDevirt = true; |
| 808 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 809 | return true; |
| 810 | }; |
| 811 | |
| 812 | if (BitWidth == 1) { |
| 813 | if (tryUniqueRetValOptFor(true)) |
| 814 | return true; |
| 815 | if (tryUniqueRetValOptFor(false)) |
| 816 | return true; |
| 817 | } |
| 818 | return false; |
| 819 | } |
| 820 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 821 | void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 822 | Constant *Byte, Constant *Bit) { |
| 823 | for (auto Call : CSInfo.CallSites) { |
| 824 | auto *RetType = cast<IntegerType>(Call.CS.getType()); |
| 825 | IRBuilder<> B(Call.CS.getInstruction()); |
| 826 | Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte); |
| 827 | if (RetType->getBitWidth() == 1) { |
| 828 | Value *Bits = B.CreateLoad(Addr); |
| 829 | Value *BitsAndBit = B.CreateAnd(Bits, Bit); |
| 830 | auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); |
| 831 | Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, |
| 832 | IsBitSet); |
| 833 | } else { |
| 834 | Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); |
| 835 | Value *Val = B.CreateLoad(RetType, ValAddr); |
| 836 | Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val); |
| 837 | } |
| 838 | } |
| 839 | } |
| 840 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 841 | bool DevirtModule::tryVirtualConstProp( |
| 842 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 843 | VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 844 | // This only works if the function returns an integer. |
| 845 | auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); |
| 846 | if (!RetType) |
| 847 | return false; |
| 848 | unsigned BitWidth = RetType->getBitWidth(); |
| 849 | if (BitWidth > 64) |
| 850 | return false; |
| 851 | |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 852 | // Make sure that each function is defined, does not access memory, takes at |
| 853 | // least one argument, does not use its first argument (which we assume is |
| 854 | // 'this'), and has the same return type. |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 855 | // |
| 856 | // Note that we test whether this copy of the function is readnone, rather |
| 857 | // than testing function attributes, which must hold for any copy of the |
| 858 | // function, even a less optimized version substituted at link time. This is |
| 859 | // sound because the virtual constant propagation optimizations effectively |
| 860 | // inline all implementations of the virtual function into each call site, |
| 861 | // rather than using function attributes to perform local optimization. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 862 | for (VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 37317f1 | 2017-02-17 18:17:04 +0000 | [diff] [blame] | 863 | if (Target.Fn->isDeclaration() || |
| 864 | computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) != |
| 865 | MAK_ReadNone || |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 866 | Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() || |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 867 | Target.Fn->getReturnType() != RetType) |
| 868 | return false; |
| 869 | } |
| 870 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 871 | for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 872 | if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) |
| 873 | continue; |
| 874 | |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 875 | WholeProgramDevirtResolution::ByArg *ResByArg = nullptr; |
| 876 | if (Res) |
| 877 | ResByArg = &Res->ResByArg[CSByConstantArg.first]; |
| 878 | |
| 879 | if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg)) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 880 | continue; |
| 881 | |
| 882 | if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second)) |
| 883 | continue; |
| 884 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 885 | // Find an allocation offset in bits in all vtables associated with the |
| 886 | // type. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 887 | uint64_t AllocBefore = |
| 888 | findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); |
| 889 | uint64_t AllocAfter = |
| 890 | findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); |
| 891 | |
| 892 | // Calculate the total amount of padding needed to store a value at both |
| 893 | // ends of the object. |
| 894 | uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; |
| 895 | for (auto &&Target : TargetsForSlot) { |
| 896 | TotalPaddingBefore += std::max<int64_t>( |
| 897 | (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); |
| 898 | TotalPaddingAfter += std::max<int64_t>( |
| 899 | (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); |
| 900 | } |
| 901 | |
| 902 | // If the amount of padding is too large, give up. |
| 903 | // FIXME: do something smarter here. |
| 904 | if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) |
| 905 | continue; |
| 906 | |
| 907 | // Calculate the offset to the value as a (possibly negative) byte offset |
| 908 | // and (if applicable) a bit offset, and store the values in the targets. |
| 909 | int64_t OffsetByte; |
| 910 | uint64_t OffsetBit; |
| 911 | if (TotalPaddingBefore <= TotalPaddingAfter) |
| 912 | setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, |
| 913 | OffsetBit); |
| 914 | else |
| 915 | setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, |
| 916 | OffsetBit); |
| 917 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 918 | if (RemarksEnabled) |
| 919 | for (auto &&Target : TargetsForSlot) |
| 920 | Target.WasDevirt = true; |
| 921 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 922 | // Rewrite each call to a load from OffsetByte/OffsetBit. |
Peter Collingbourne | 184773d | 2017-02-17 19:43:45 +0000 | [diff] [blame] | 923 | Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 924 | Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); |
| 925 | applyVirtualConstProp(CSByConstantArg.second, |
| 926 | TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 927 | } |
| 928 | return true; |
| 929 | } |
| 930 | |
| 931 | void DevirtModule::rebuildGlobal(VTableBits &B) { |
| 932 | if (B.Before.Bytes.empty() && B.After.Bytes.empty()) |
| 933 | return; |
| 934 | |
| 935 | // Align each byte array to pointer width. |
| 936 | unsigned PointerSize = M.getDataLayout().getPointerSize(); |
| 937 | B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize)); |
| 938 | B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize)); |
| 939 | |
| 940 | // Before was stored in reverse order; flip it now. |
| 941 | for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) |
| 942 | std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); |
| 943 | |
| 944 | // Build an anonymous global containing the before bytes, followed by the |
| 945 | // original initializer, followed by the after bytes. |
| 946 | auto NewInit = ConstantStruct::getAnon( |
| 947 | {ConstantDataArray::get(M.getContext(), B.Before.Bytes), |
| 948 | B.GV->getInitializer(), |
| 949 | ConstantDataArray::get(M.getContext(), B.After.Bytes)}); |
| 950 | auto NewGV = |
| 951 | new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), |
| 952 | GlobalVariable::PrivateLinkage, NewInit, "", B.GV); |
| 953 | NewGV->setSection(B.GV->getSection()); |
| 954 | NewGV->setComdat(B.GV->getComdat()); |
| 955 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 956 | // Copy the original vtable's metadata to the anonymous global, adjusting |
| 957 | // offsets as required. |
| 958 | NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); |
| 959 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 960 | // Build an alias named after the original global, pointing at the second |
| 961 | // element (the original initializer). |
| 962 | auto Alias = GlobalAlias::create( |
| 963 | B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", |
| 964 | ConstantExpr::getGetElementPtr( |
| 965 | NewInit->getType(), NewGV, |
| 966 | ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), |
| 967 | ConstantInt::get(Int32Ty, 1)}), |
| 968 | &M); |
| 969 | Alias->setVisibility(B.GV->getVisibility()); |
| 970 | Alias->takeName(B.GV); |
| 971 | |
| 972 | B.GV->replaceAllUsesWith(Alias); |
| 973 | B.GV->eraseFromParent(); |
| 974 | } |
| 975 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 976 | bool DevirtModule::areRemarksEnabled() { |
| 977 | const auto &FL = M.getFunctionList(); |
| 978 | if (FL.empty()) |
| 979 | return false; |
| 980 | const Function &Fn = FL.front(); |
Adam Nemet | de53bfb | 2017-02-23 23:11:11 +0000 | [diff] [blame] | 981 | |
| 982 | const auto &BBL = Fn.getBasicBlockList(); |
| 983 | if (BBL.empty()) |
| 984 | return false; |
| 985 | auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front()); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 986 | return DI.isEnabled(); |
| 987 | } |
| 988 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 989 | void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc, |
| 990 | Function *AssumeFunc) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 991 | // 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] | 992 | // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p |
| 993 | // points to a member of the type identifier %md. Group calls by (type ID, |
| 994 | // offset) pair (effectively the identity of the virtual function) and store |
| 995 | // to CallSlots. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 996 | DenseSet<Value *> SeenPtrs; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 997 | for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 998 | I != E;) { |
| 999 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 1000 | ++I; |
| 1001 | if (!CI) |
| 1002 | continue; |
| 1003 | |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1004 | // Search for virtual calls based on %p and add them to DevirtCalls. |
| 1005 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1006 | SmallVector<CallInst *, 1> Assumes; |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1007 | findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1008 | |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1009 | // If we found any, add them to CallSlots. Only do this if we haven't seen |
| 1010 | // the vtable pointer before, as it may have been CSE'd with pointers from |
| 1011 | // 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] | 1012 | if (!Assumes.empty()) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1013 | Metadata *TypeId = |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1014 | cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); |
| 1015 | Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1016 | if (SeenPtrs.insert(Ptr).second) { |
| 1017 | for (DevirtCallSite Call : DevirtCalls) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1018 | CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0), |
| 1019 | Call.CS, nullptr); |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 1020 | } |
| 1021 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1022 | } |
| 1023 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1024 | // We no longer need the assumes or the type test. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1025 | for (auto Assume : Assumes) |
| 1026 | Assume->eraseFromParent(); |
| 1027 | // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we |
| 1028 | // may use the vtable argument later. |
| 1029 | if (CI->use_empty()) |
| 1030 | CI->eraseFromParent(); |
| 1031 | } |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1032 | } |
| 1033 | |
| 1034 | void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { |
| 1035 | Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); |
| 1036 | |
| 1037 | for (auto I = TypeCheckedLoadFunc->use_begin(), |
| 1038 | E = TypeCheckedLoadFunc->use_end(); |
| 1039 | I != E;) { |
| 1040 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 1041 | ++I; |
| 1042 | if (!CI) |
| 1043 | continue; |
| 1044 | |
| 1045 | Value *Ptr = CI->getArgOperand(0); |
| 1046 | Value *Offset = CI->getArgOperand(1); |
| 1047 | Value *TypeIdValue = CI->getArgOperand(2); |
| 1048 | Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); |
| 1049 | |
| 1050 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
| 1051 | SmallVector<Instruction *, 1> LoadedPtrs; |
| 1052 | SmallVector<Instruction *, 1> Preds; |
| 1053 | bool HasNonCallUses = false; |
| 1054 | findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, |
| 1055 | HasNonCallUses, CI); |
| 1056 | |
| 1057 | // Start by generating "pessimistic" code that explicitly loads the function |
| 1058 | // pointer from the vtable and performs the type check. If possible, we will |
| 1059 | // eliminate the load and the type check later. |
| 1060 | |
| 1061 | // If possible, only generate the load at the point where it is used. |
| 1062 | // This helps avoid unnecessary spills. |
| 1063 | IRBuilder<> LoadB( |
| 1064 | (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); |
| 1065 | Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset); |
| 1066 | Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy)); |
| 1067 | Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr); |
| 1068 | |
| 1069 | for (Instruction *LoadedPtr : LoadedPtrs) { |
| 1070 | LoadedPtr->replaceAllUsesWith(LoadedValue); |
| 1071 | LoadedPtr->eraseFromParent(); |
| 1072 | } |
| 1073 | |
| 1074 | // Likewise for the type test. |
| 1075 | IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); |
| 1076 | CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); |
| 1077 | |
| 1078 | for (Instruction *Pred : Preds) { |
| 1079 | Pred->replaceAllUsesWith(TypeTestCall); |
| 1080 | Pred->eraseFromParent(); |
| 1081 | } |
| 1082 | |
| 1083 | // We have already erased any extractvalue instructions that refer to the |
| 1084 | // intrinsic call, but the intrinsic may have other non-extractvalue uses |
| 1085 | // (although this is unlikely). In that case, explicitly build a pair and |
| 1086 | // RAUW it. |
| 1087 | if (!CI->use_empty()) { |
| 1088 | Value *Pair = UndefValue::get(CI->getType()); |
| 1089 | IRBuilder<> B(CI); |
| 1090 | Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); |
| 1091 | Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); |
| 1092 | CI->replaceAllUsesWith(Pair); |
| 1093 | } |
| 1094 | |
| 1095 | // The number of unsafe uses is initially the number of uses. |
| 1096 | auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; |
| 1097 | NumUnsafeUses = DevirtCalls.size(); |
| 1098 | |
| 1099 | // If the function pointer has a non-call user, we cannot eliminate the type |
| 1100 | // check, as one of those users may eventually call the pointer. Increment |
| 1101 | // the unsafe use count to make sure it cannot reach zero. |
| 1102 | if (HasNonCallUses) |
| 1103 | ++NumUnsafeUses; |
| 1104 | for (DevirtCallSite Call : DevirtCalls) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 1105 | CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, |
| 1106 | &NumUnsafeUses); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1107 | } |
| 1108 | |
| 1109 | CI->eraseFromParent(); |
| 1110 | } |
| 1111 | } |
| 1112 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1113 | void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) { |
| 1114 | const WholeProgramDevirtResolution &Res = |
| 1115 | Summary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString()) |
| 1116 | .WPDRes[Slot.ByteOffset]; |
| 1117 | |
| 1118 | if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) { |
| 1119 | // The type of the function in the declaration is irrelevant because every |
| 1120 | // call site will cast it to the correct type. |
| 1121 | auto *SingleImpl = M.getOrInsertFunction( |
| 1122 | Res.SingleImplName, Type::getVoidTy(M.getContext()), nullptr); |
| 1123 | |
| 1124 | // This is the import phase so we should not be exporting anything. |
| 1125 | bool IsExported = false; |
| 1126 | applySingleImplDevirt(SlotInfo, SingleImpl, IsExported); |
| 1127 | assert(!IsExported); |
| 1128 | } |
| 1129 | } |
| 1130 | |
| 1131 | void DevirtModule::removeRedundantTypeTests() { |
| 1132 | auto True = ConstantInt::getTrue(M.getContext()); |
| 1133 | for (auto &&U : NumUnsafeUsesForTypeTest) { |
| 1134 | if (U.second == 0) { |
| 1135 | U.first->replaceAllUsesWith(True); |
| 1136 | U.first->eraseFromParent(); |
| 1137 | } |
| 1138 | } |
| 1139 | } |
| 1140 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1141 | bool DevirtModule::run() { |
| 1142 | Function *TypeTestFunc = |
| 1143 | M.getFunction(Intrinsic::getName(Intrinsic::type_test)); |
| 1144 | Function *TypeCheckedLoadFunc = |
| 1145 | M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); |
| 1146 | Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); |
| 1147 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1148 | // Normally if there are no users of the devirtualization intrinsics in the |
| 1149 | // module, this pass has nothing to do. But if we are exporting, we also need |
| 1150 | // to handle any users that appear only in the function summaries. |
| 1151 | if (Action != PassSummaryAction::Export && |
| 1152 | (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1153 | AssumeFunc->use_empty()) && |
| 1154 | (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty())) |
| 1155 | return false; |
| 1156 | |
| 1157 | if (TypeTestFunc && AssumeFunc) |
| 1158 | scanTypeTestUsers(TypeTestFunc, AssumeFunc); |
| 1159 | |
| 1160 | if (TypeCheckedLoadFunc) |
| 1161 | scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1162 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1163 | if (Action == PassSummaryAction::Import) { |
| 1164 | for (auto &S : CallSlots) |
| 1165 | importResolution(S.first, S.second); |
| 1166 | |
| 1167 | removeRedundantTypeTests(); |
| 1168 | |
| 1169 | // The rest of the code is only necessary when exporting or during regular |
| 1170 | // LTO, so we are done. |
| 1171 | return true; |
| 1172 | } |
| 1173 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1174 | // Rebuild type metadata into a map for easy lookup. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1175 | std::vector<VTableBits> Bits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1176 | DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; |
| 1177 | buildTypeIdentifierMap(Bits, TypeIdMap); |
| 1178 | if (TypeIdMap.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1179 | return true; |
| 1180 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1181 | // Collect information from summary about which calls to try to devirtualize. |
| 1182 | if (Action == PassSummaryAction::Export) { |
| 1183 | DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID; |
| 1184 | for (auto &P : TypeIdMap) { |
| 1185 | if (auto *TypeId = dyn_cast<MDString>(P.first)) |
| 1186 | MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back( |
| 1187 | TypeId); |
| 1188 | } |
| 1189 | |
| 1190 | for (auto &P : *Summary) { |
| 1191 | for (auto &S : P.second) { |
| 1192 | auto *FS = dyn_cast<FunctionSummary>(S.get()); |
| 1193 | if (!FS) |
| 1194 | continue; |
| 1195 | // FIXME: Only add live functions. |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1196 | for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) |
| 1197 | for (Metadata *MD : MetadataByGUID[VF.GUID]) |
| 1198 | CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers = |
| 1199 | true; |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1200 | for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) |
| 1201 | for (Metadata *MD : MetadataByGUID[VF.GUID]) |
| 1202 | CallSlots[{MD, VF.Offset}] |
| 1203 | .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS); |
| 1204 | for (const FunctionSummary::ConstVCall &VC : |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1205 | FS->type_test_assume_const_vcalls()) |
| 1206 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) |
| 1207 | CallSlots[{MD, VC.VFunc.Offset}] |
| 1208 | .ConstCSInfo[VC.Args].SummaryHasTypeTestAssumeUsers = true; |
| 1209 | for (const FunctionSummary::ConstVCall &VC : |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1210 | FS->type_checked_load_const_vcalls()) |
| 1211 | for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) |
| 1212 | CallSlots[{MD, VC.VFunc.Offset}] |
| 1213 | .ConstCSInfo[VC.Args] |
| 1214 | .SummaryTypeCheckedLoadUsers.push_back(FS); |
| 1215 | } |
| 1216 | } |
| 1217 | } |
| 1218 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1219 | // For each (type, offset) pair: |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1220 | bool DidVirtualConstProp = false; |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1221 | std::map<std::string, Function*> DevirtTargets; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1222 | for (auto &S : CallSlots) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1223 | // Search each of the members of the type identifier for the virtual |
| 1224 | // function implementation at offset S.first.ByteOffset, and add to |
| 1225 | // TargetsForSlot. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1226 | std::vector<VirtualCallTarget> TargetsForSlot; |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1227 | if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID], |
| 1228 | S.first.ByteOffset)) { |
Peter Collingbourne | 2325bb3 | 2017-03-04 01:31:01 +0000 | [diff] [blame] | 1229 | WholeProgramDevirtResolution *Res = nullptr; |
| 1230 | if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) |
| 1231 | Res = |
| 1232 | &Summary |
| 1233 | ->getTypeIdSummary(cast<MDString>(S.first.TypeID)->getString()) |
| 1234 | .WPDRes[S.first.ByteOffset]; |
| 1235 | |
| 1236 | if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) && |
Peter Collingbourne | 77a8d56 | 2017-03-04 01:34:53 +0000 | [diff] [blame] | 1237 | tryVirtualConstProp(TargetsForSlot, S.second, Res)) |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1238 | DidVirtualConstProp = true; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1239 | |
Peter Collingbourne | b406baa | 2017-03-04 01:23:30 +0000 | [diff] [blame] | 1240 | // Collect functions devirtualized at least for one call site for stats. |
| 1241 | if (RemarksEnabled) |
| 1242 | for (const auto &T : TargetsForSlot) |
| 1243 | if (T.WasDevirt) |
| 1244 | DevirtTargets[T.Fn->getName()] = T.Fn; |
| 1245 | } |
| 1246 | |
| 1247 | // CFI-specific: if we are exporting and any llvm.type.checked.load |
| 1248 | // intrinsics were *not* devirtualized, we need to add the resulting |
| 1249 | // llvm.type.test intrinsics to the function summaries so that the |
| 1250 | // LowerTypeTests pass will export them. |
| 1251 | if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) { |
| 1252 | auto GUID = |
| 1253 | GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString()); |
| 1254 | for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers) |
| 1255 | FS->addTypeTest(GUID); |
| 1256 | for (auto &CCS : S.second.ConstCSInfo) |
| 1257 | for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers) |
| 1258 | FS->addTypeTest(GUID); |
| 1259 | } |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1260 | } |
| 1261 | |
| 1262 | if (RemarksEnabled) { |
| 1263 | // Generate remarks for each devirtualized function. |
| 1264 | for (const auto &DT : DevirtTargets) { |
| 1265 | Function *F = DT.second; |
| 1266 | DISubprogram *SP = F->getSubprogram(); |
Justin Bogner | 7bc978b | 2017-02-18 02:00:27 +0000 | [diff] [blame] | 1267 | emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP, |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1268 | Twine("devirtualized ") + F->getName()); |
Ivan Krasin | b05e06e | 2016-08-05 19:45:16 +0000 | [diff] [blame] | 1269 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1270 | } |
| 1271 | |
Peter Collingbourne | 6d284fa | 2017-03-09 00:21:25 +0000 | [diff] [blame] | 1272 | removeRedundantTypeTests(); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1273 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1274 | // Rebuild each global we touched as part of virtual constant propagation to |
| 1275 | // include the before and after bytes. |
| 1276 | if (DidVirtualConstProp) |
| 1277 | for (VTableBits &B : Bits) |
| 1278 | rebuildGlobal(B); |
| 1279 | |
| 1280 | return true; |
| 1281 | } |