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 | // |
| 28 | //===----------------------------------------------------------------------===// |
| 29 | |
| 30 | #include "llvm/Transforms/IPO/WholeProgramDevirt.h" |
Mehdi Amini | b550cb1 | 2016-04-18 09:17:29 +0000 | [diff] [blame] | 31 | #include "llvm/ADT/ArrayRef.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 32 | #include "llvm/ADT/DenseMap.h" |
| 33 | #include "llvm/ADT/DenseMapInfo.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 34 | #include "llvm/ADT/DenseSet.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 35 | #include "llvm/ADT/iterator_range.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 36 | #include "llvm/ADT/MapVector.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 37 | #include "llvm/ADT/SmallVector.h" |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 38 | #include "llvm/Analysis/TypeMetadataUtils.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 39 | #include "llvm/IR/CallSite.h" |
| 40 | #include "llvm/IR/Constants.h" |
| 41 | #include "llvm/IR/DataLayout.h" |
Ivan Krasin | b05e06e | 2016-08-05 19:45:16 +0000 | [diff] [blame] | 42 | #include "llvm/IR/DebugInfoMetadata.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 43 | #include "llvm/IR/DebugLoc.h" |
| 44 | #include "llvm/IR/DerivedTypes.h" |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 45 | #include "llvm/IR/DiagnosticInfo.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 46 | #include "llvm/IR/Function.h" |
| 47 | #include "llvm/IR/GlobalAlias.h" |
| 48 | #include "llvm/IR/GlobalVariable.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 49 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 50 | #include "llvm/IR/InstrTypes.h" |
| 51 | #include "llvm/IR/Instruction.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 52 | #include "llvm/IR/Instructions.h" |
| 53 | #include "llvm/IR/Intrinsics.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 54 | #include "llvm/IR/LLVMContext.h" |
| 55 | #include "llvm/IR/Metadata.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 56 | #include "llvm/IR/Module.h" |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 57 | #include "llvm/IR/ModuleSummaryIndexYAML.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 58 | #include "llvm/Pass.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 59 | #include "llvm/PassRegistry.h" |
| 60 | #include "llvm/PassSupport.h" |
| 61 | #include "llvm/Support/Casting.h" |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 62 | #include "llvm/Support/Error.h" |
| 63 | #include "llvm/Support/FileSystem.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 64 | #include "llvm/Support/MathExtras.h" |
Mehdi Amini | b550cb1 | 2016-04-18 09:17:29 +0000 | [diff] [blame] | 65 | #include "llvm/Transforms/IPO.h" |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 66 | #include "llvm/Transforms/Utils/Evaluator.h" |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 67 | #include <algorithm> |
| 68 | #include <cstddef> |
| 69 | #include <map> |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 70 | #include <set> |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 71 | #include <string> |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 72 | |
| 73 | using namespace llvm; |
| 74 | using namespace wholeprogramdevirt; |
| 75 | |
| 76 | #define DEBUG_TYPE "wholeprogramdevirt" |
| 77 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 78 | static cl::opt<PassSummaryAction> ClSummaryAction( |
| 79 | "wholeprogramdevirt-summary-action", |
| 80 | cl::desc("What to do with the summary when running this pass"), |
| 81 | cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), |
| 82 | clEnumValN(PassSummaryAction::Import, "import", |
| 83 | "Import typeid resolutions from summary and globals"), |
| 84 | clEnumValN(PassSummaryAction::Export, "export", |
| 85 | "Export typeid resolutions to summary and globals")), |
| 86 | cl::Hidden); |
| 87 | |
| 88 | static cl::opt<std::string> ClReadSummary( |
| 89 | "wholeprogramdevirt-read-summary", |
| 90 | cl::desc("Read summary from given YAML file before running pass"), |
| 91 | cl::Hidden); |
| 92 | |
| 93 | static cl::opt<std::string> ClWriteSummary( |
| 94 | "wholeprogramdevirt-write-summary", |
| 95 | cl::desc("Write summary to given YAML file after running pass"), |
| 96 | cl::Hidden); |
| 97 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 98 | // Find the minimum offset that we may store a value of size Size bits at. If |
| 99 | // IsAfter is set, look for an offset before the object, otherwise look for an |
| 100 | // offset after the object. |
| 101 | uint64_t |
| 102 | wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, |
| 103 | bool IsAfter, uint64_t Size) { |
| 104 | // Find a minimum offset taking into account only vtable sizes. |
| 105 | uint64_t MinByte = 0; |
| 106 | for (const VirtualCallTarget &Target : Targets) { |
| 107 | if (IsAfter) |
| 108 | MinByte = std::max(MinByte, Target.minAfterBytes()); |
| 109 | else |
| 110 | MinByte = std::max(MinByte, Target.minBeforeBytes()); |
| 111 | } |
| 112 | |
| 113 | // Build a vector of arrays of bytes covering, for each target, a slice of the |
| 114 | // used region (see AccumBitVector::BytesUsed in |
| 115 | // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, |
| 116 | // this aligns the used regions to start at MinByte. |
| 117 | // |
| 118 | // In this example, A, B and C are vtables, # is a byte already allocated for |
| 119 | // a virtual function pointer, AAAA... (etc.) are the used regions for the |
| 120 | // vtables and Offset(X) is the value computed for the Offset variable below |
| 121 | // for X. |
| 122 | // |
| 123 | // Offset(A) |
| 124 | // | | |
| 125 | // |MinByte |
| 126 | // A: ################AAAAAAAA|AAAAAAAA |
| 127 | // B: ########BBBBBBBBBBBBBBBB|BBBB |
| 128 | // C: ########################|CCCCCCCCCCCCCCCC |
| 129 | // | Offset(B) | |
| 130 | // |
| 131 | // This code produces the slices of A, B and C that appear after the divider |
| 132 | // at MinByte. |
| 133 | std::vector<ArrayRef<uint8_t>> Used; |
| 134 | for (const VirtualCallTarget &Target : Targets) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 135 | ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed |
| 136 | : Target.TM->Bits->Before.BytesUsed; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 137 | uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() |
| 138 | : MinByte - Target.minBeforeBytes(); |
| 139 | |
| 140 | // Disregard used regions that are smaller than Offset. These are |
| 141 | // effectively all-free regions that do not need to be checked. |
| 142 | if (VTUsed.size() > Offset) |
| 143 | Used.push_back(VTUsed.slice(Offset)); |
| 144 | } |
| 145 | |
| 146 | if (Size == 1) { |
| 147 | // Find a free bit in each member of Used. |
| 148 | for (unsigned I = 0;; ++I) { |
| 149 | uint8_t BitsUsed = 0; |
| 150 | for (auto &&B : Used) |
| 151 | if (I < B.size()) |
| 152 | BitsUsed |= B[I]; |
| 153 | if (BitsUsed != 0xff) |
| 154 | return (MinByte + I) * 8 + |
| 155 | countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); |
| 156 | } |
| 157 | } else { |
| 158 | // Find a free (Size/8) byte region in each member of Used. |
| 159 | // FIXME: see if alignment helps. |
| 160 | for (unsigned I = 0;; ++I) { |
| 161 | for (auto &&B : Used) { |
| 162 | unsigned Byte = 0; |
| 163 | while ((I + Byte) < B.size() && Byte < (Size / 8)) { |
| 164 | if (B[I + Byte]) |
| 165 | goto NextI; |
| 166 | ++Byte; |
| 167 | } |
| 168 | } |
| 169 | return (MinByte + I) * 8; |
| 170 | NextI:; |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | void wholeprogramdevirt::setBeforeReturnValues( |
| 176 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, |
| 177 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 178 | if (BitWidth == 1) |
| 179 | OffsetByte = -(AllocBefore / 8 + 1); |
| 180 | else |
| 181 | OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); |
| 182 | OffsetBit = AllocBefore % 8; |
| 183 | |
| 184 | for (VirtualCallTarget &Target : Targets) { |
| 185 | if (BitWidth == 1) |
| 186 | Target.setBeforeBit(AllocBefore); |
| 187 | else |
| 188 | Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | void wholeprogramdevirt::setAfterReturnValues( |
| 193 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, |
| 194 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 195 | if (BitWidth == 1) |
| 196 | OffsetByte = AllocAfter / 8; |
| 197 | else |
| 198 | OffsetByte = (AllocAfter + 7) / 8; |
| 199 | OffsetBit = AllocAfter % 8; |
| 200 | |
| 201 | for (VirtualCallTarget &Target : Targets) { |
| 202 | if (BitWidth == 1) |
| 203 | Target.setAfterBit(AllocAfter); |
| 204 | else |
| 205 | Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); |
| 206 | } |
| 207 | } |
| 208 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 209 | VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM) |
| 210 | : Fn(Fn), TM(TM), |
Ivan Krasin | 89439a7 | 2016-08-12 01:40:10 +0000 | [diff] [blame] | 211 | IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {} |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 212 | |
| 213 | namespace { |
| 214 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 215 | // 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] | 216 | // tables, and the ByteOffset is the offset in bytes from the address point to |
| 217 | // the virtual function pointer. |
| 218 | struct VTableSlot { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 219 | Metadata *TypeID; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 220 | uint64_t ByteOffset; |
| 221 | }; |
| 222 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 223 | } // end anonymous namespace |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 224 | |
Peter Collingbourne | 9b65652 | 2016-02-09 23:01:38 +0000 | [diff] [blame] | 225 | namespace llvm { |
| 226 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 227 | template <> struct DenseMapInfo<VTableSlot> { |
| 228 | static VTableSlot getEmptyKey() { |
| 229 | return {DenseMapInfo<Metadata *>::getEmptyKey(), |
| 230 | DenseMapInfo<uint64_t>::getEmptyKey()}; |
| 231 | } |
| 232 | static VTableSlot getTombstoneKey() { |
| 233 | return {DenseMapInfo<Metadata *>::getTombstoneKey(), |
| 234 | DenseMapInfo<uint64_t>::getTombstoneKey()}; |
| 235 | } |
| 236 | static unsigned getHashValue(const VTableSlot &I) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 237 | return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^ |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 238 | DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); |
| 239 | } |
| 240 | static bool isEqual(const VTableSlot &LHS, |
| 241 | const VTableSlot &RHS) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 242 | return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 243 | } |
| 244 | }; |
| 245 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 246 | } // end namespace llvm |
Peter Collingbourne | 9b65652 | 2016-02-09 23:01:38 +0000 | [diff] [blame] | 247 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 248 | namespace { |
| 249 | |
| 250 | // A virtual call site. VTable is the loaded virtual table pointer, and CS is |
| 251 | // the indirect virtual call. |
| 252 | struct VirtualCallSite { |
| 253 | Value *VTable; |
| 254 | CallSite CS; |
| 255 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 256 | // If non-null, this field points to the associated unsafe use count stored in |
| 257 | // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description |
| 258 | // of that field for details. |
| 259 | unsigned *NumUnsafeUses; |
| 260 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 261 | void emitRemark(const Twine &OptName, const Twine &TargetName) { |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 262 | Function *F = CS.getCaller(); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 263 | emitOptimizationRemark( |
| 264 | F->getContext(), DEBUG_TYPE, *F, |
| 265 | CS.getInstruction()->getDebugLoc(), |
| 266 | OptName + ": devirtualized a call to " + TargetName); |
Ivan Krasin | 5474645 | 2016-07-12 02:38:37 +0000 | [diff] [blame] | 267 | } |
| 268 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 269 | void replaceAndErase(const Twine &OptName, const Twine &TargetName, |
| 270 | bool RemarksEnabled, Value *New) { |
| 271 | if (RemarksEnabled) |
| 272 | emitRemark(OptName, TargetName); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 273 | CS->replaceAllUsesWith(New); |
| 274 | if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) { |
| 275 | BranchInst::Create(II->getNormalDest(), CS.getInstruction()); |
| 276 | II->getUnwindDest()->removePredecessor(II->getParent()); |
| 277 | } |
| 278 | CS->eraseFromParent(); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 279 | // This use is no longer unsafe. |
| 280 | if (NumUnsafeUses) |
| 281 | --*NumUnsafeUses; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 282 | } |
| 283 | }; |
| 284 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 285 | // Call site information collected for a specific VTableSlot and possibly a list |
| 286 | // of constant integer arguments. The grouping by arguments is handled by the |
| 287 | // VTableSlotInfo class. |
| 288 | struct CallSiteInfo { |
| 289 | std::vector<VirtualCallSite> CallSites; |
| 290 | }; |
| 291 | |
| 292 | // Call site information collected for a specific VTableSlot. |
| 293 | struct VTableSlotInfo { |
| 294 | // The set of call sites which do not have all constant integer arguments |
| 295 | // (excluding "this"). |
| 296 | CallSiteInfo CSInfo; |
| 297 | |
| 298 | // The set of call sites with all constant integer arguments (excluding |
| 299 | // "this"), grouped by argument list. |
| 300 | std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; |
| 301 | |
| 302 | void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses); |
| 303 | |
| 304 | private: |
| 305 | CallSiteInfo &findCallSiteInfo(CallSite CS); |
| 306 | }; |
| 307 | |
| 308 | CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) { |
| 309 | std::vector<uint64_t> Args; |
| 310 | auto *CI = dyn_cast<IntegerType>(CS.getType()); |
| 311 | if (!CI || CI->getBitWidth() > 64 || CS.arg_empty()) |
| 312 | return CSInfo; |
| 313 | for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) { |
| 314 | auto *CI = dyn_cast<ConstantInt>(Arg); |
| 315 | if (!CI || CI->getBitWidth() > 64) |
| 316 | return CSInfo; |
| 317 | Args.push_back(CI->getZExtValue()); |
| 318 | } |
| 319 | return ConstCSInfo[Args]; |
| 320 | } |
| 321 | |
| 322 | void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS, |
| 323 | unsigned *NumUnsafeUses) { |
| 324 | findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses}); |
| 325 | } |
| 326 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 327 | struct DevirtModule { |
| 328 | Module &M; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 329 | |
| 330 | PassSummaryAction Action; |
| 331 | ModuleSummaryIndex *Summary; |
| 332 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 333 | IntegerType *Int8Ty; |
| 334 | PointerType *Int8PtrTy; |
| 335 | IntegerType *Int32Ty; |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 336 | IntegerType *Int64Ty; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 337 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 338 | bool RemarksEnabled; |
| 339 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 340 | MapVector<VTableSlot, VTableSlotInfo> CallSlots; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 341 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 342 | // This map keeps track of the number of "unsafe" uses of a loaded function |
| 343 | // pointer. The key is the associated llvm.type.test intrinsic call generated |
| 344 | // by this pass. An unsafe use is one that calls the loaded function pointer |
| 345 | // directly. Every time we eliminate an unsafe use (for example, by |
| 346 | // devirtualizing it or by applying virtual constant propagation), we |
| 347 | // decrement the value stored in this map. If a value reaches zero, we can |
| 348 | // eliminate the type check by RAUWing the associated llvm.type.test call with |
| 349 | // true. |
| 350 | std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; |
| 351 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 352 | DevirtModule(Module &M, PassSummaryAction Action, ModuleSummaryIndex *Summary) |
| 353 | : M(M), Action(Action), Summary(Summary), |
| 354 | Int8Ty(Type::getInt8Ty(M.getContext())), |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 355 | Int8PtrTy(Type::getInt8PtrTy(M.getContext())), |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 356 | Int32Ty(Type::getInt32Ty(M.getContext())), |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 357 | Int64Ty(Type::getInt64Ty(M.getContext())), |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 358 | RemarksEnabled(areRemarksEnabled()) {} |
| 359 | |
| 360 | bool areRemarksEnabled(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 361 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 362 | void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc); |
| 363 | void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); |
| 364 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 365 | void buildTypeIdentifierMap( |
| 366 | std::vector<VTableBits> &Bits, |
| 367 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 368 | Constant *getPointerAtOffset(Constant *I, uint64_t Offset); |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 369 | bool |
| 370 | tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, |
| 371 | const std::set<TypeMemberInfo> &TypeMemberInfos, |
| 372 | uint64_t ByteOffset); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 373 | |
| 374 | void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 375 | bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 376 | VTableSlotInfo &SlotInfo); |
| 377 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 378 | bool tryEvaluateFunctionsWithArgs( |
| 379 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 380 | ArrayRef<uint64_t> Args); |
| 381 | |
| 382 | void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 383 | uint64_t TheRetVal); |
| 384 | bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
| 385 | CallSiteInfo &CSInfo); |
| 386 | |
| 387 | void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, |
| 388 | Constant *UniqueMemberAddr); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 389 | bool tryUniqueRetValOpt(unsigned BitWidth, |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 390 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 391 | CallSiteInfo &CSInfo); |
| 392 | |
| 393 | void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 394 | Constant *Byte, Constant *Bit); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 395 | bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 396 | VTableSlotInfo &SlotInfo); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 397 | |
| 398 | void rebuildGlobal(VTableBits &B); |
| 399 | |
| 400 | bool run(); |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 401 | |
| 402 | // Lower the module using the action and summary passed as command line |
| 403 | // arguments. For testing purposes only. |
| 404 | static bool runForTesting(Module &M); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 405 | }; |
| 406 | |
| 407 | struct WholeProgramDevirt : public ModulePass { |
| 408 | static char ID; |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 409 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 410 | bool UseCommandLine = false; |
| 411 | |
| 412 | PassSummaryAction Action; |
| 413 | ModuleSummaryIndex *Summary; |
| 414 | |
| 415 | WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) { |
| 416 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 417 | } |
| 418 | |
| 419 | WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary) |
| 420 | : ModulePass(ID), Action(Action), Summary(Summary) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 421 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 422 | } |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 423 | |
| 424 | bool runOnModule(Module &M) override { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 425 | if (skipModule(M)) |
| 426 | return false; |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 427 | if (UseCommandLine) |
| 428 | return DevirtModule::runForTesting(M); |
| 429 | return DevirtModule(M, Action, Summary).run(); |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 430 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 431 | }; |
| 432 | |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 433 | } // end anonymous namespace |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 434 | |
| 435 | INITIALIZE_PASS(WholeProgramDevirt, "wholeprogramdevirt", |
| 436 | "Whole program devirtualization", false, false) |
| 437 | char WholeProgramDevirt::ID = 0; |
| 438 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 439 | ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action, |
| 440 | ModuleSummaryIndex *Summary) { |
| 441 | return new WholeProgramDevirt(Action, Summary); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 442 | } |
| 443 | |
Chandler Carruth | 164a2aa6 | 2016-06-17 00:11:01 +0000 | [diff] [blame] | 444 | PreservedAnalyses WholeProgramDevirtPass::run(Module &M, |
| 445 | ModuleAnalysisManager &) { |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 446 | if (!DevirtModule(M, PassSummaryAction::None, nullptr).run()) |
Davide Italiano | d737dd2 | 2016-06-14 21:44:19 +0000 | [diff] [blame] | 447 | return PreservedAnalyses::all(); |
| 448 | return PreservedAnalyses::none(); |
| 449 | } |
| 450 | |
Peter Collingbourne | 2b33f65 | 2017-02-13 19:26:18 +0000 | [diff] [blame] | 451 | bool DevirtModule::runForTesting(Module &M) { |
| 452 | ModuleSummaryIndex Summary; |
| 453 | |
| 454 | // Handle the command-line summary arguments. This code is for testing |
| 455 | // purposes only, so we handle errors directly. |
| 456 | if (!ClReadSummary.empty()) { |
| 457 | ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + |
| 458 | ": "); |
| 459 | auto ReadSummaryFile = |
| 460 | ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); |
| 461 | |
| 462 | yaml::Input In(ReadSummaryFile->getBuffer()); |
| 463 | In >> Summary; |
| 464 | ExitOnErr(errorCodeToError(In.error())); |
| 465 | } |
| 466 | |
| 467 | bool Changed = DevirtModule(M, ClSummaryAction, &Summary).run(); |
| 468 | |
| 469 | if (!ClWriteSummary.empty()) { |
| 470 | ExitOnError ExitOnErr( |
| 471 | "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); |
| 472 | std::error_code EC; |
| 473 | raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text); |
| 474 | ExitOnErr(errorCodeToError(EC)); |
| 475 | |
| 476 | yaml::Output Out(OS); |
| 477 | Out << Summary; |
| 478 | } |
| 479 | |
| 480 | return Changed; |
| 481 | } |
| 482 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 483 | void DevirtModule::buildTypeIdentifierMap( |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 484 | std::vector<VTableBits> &Bits, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 485 | DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 486 | DenseMap<GlobalVariable *, VTableBits *> GVToBits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 487 | Bits.reserve(M.getGlobalList().size()); |
| 488 | SmallVector<MDNode *, 2> Types; |
| 489 | for (GlobalVariable &GV : M.globals()) { |
| 490 | Types.clear(); |
| 491 | GV.getMetadata(LLVMContext::MD_type, Types); |
| 492 | if (Types.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 493 | continue; |
| 494 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 495 | VTableBits *&BitsPtr = GVToBits[&GV]; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 496 | if (!BitsPtr) { |
| 497 | Bits.emplace_back(); |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 498 | Bits.back().GV = &GV; |
| 499 | Bits.back().ObjectSize = |
| 500 | M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 501 | BitsPtr = &Bits.back(); |
| 502 | } |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 503 | |
| 504 | for (MDNode *Type : Types) { |
| 505 | auto TypeID = Type->getOperand(1).get(); |
| 506 | |
| 507 | uint64_t Offset = |
| 508 | cast<ConstantInt>( |
| 509 | cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) |
| 510 | ->getZExtValue(); |
| 511 | |
| 512 | TypeIdMap[TypeID].insert({BitsPtr, Offset}); |
| 513 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 514 | } |
| 515 | } |
| 516 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 517 | Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) { |
| 518 | if (I->getType()->isPointerTy()) { |
| 519 | if (Offset == 0) |
| 520 | return I; |
| 521 | return nullptr; |
| 522 | } |
| 523 | |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 524 | const DataLayout &DL = M.getDataLayout(); |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 525 | |
| 526 | if (auto *C = dyn_cast<ConstantStruct>(I)) { |
| 527 | const StructLayout *SL = DL.getStructLayout(C->getType()); |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 528 | if (Offset >= SL->getSizeInBytes()) |
| 529 | return nullptr; |
| 530 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 531 | unsigned Op = SL->getElementContainingOffset(Offset); |
| 532 | return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), |
| 533 | Offset - SL->getElementOffset(Op)); |
| 534 | } |
| 535 | if (auto *C = dyn_cast<ConstantArray>(I)) { |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 536 | ArrayType *VTableTy = C->getType(); |
| 537 | uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType()); |
| 538 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 539 | unsigned Op = Offset / ElemSize; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 540 | if (Op >= C->getNumOperands()) |
| 541 | return nullptr; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 542 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 543 | return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), |
| 544 | Offset % ElemSize); |
| 545 | } |
| 546 | return nullptr; |
Peter Collingbourne | 7a1e5bb | 2016-12-09 00:33:27 +0000 | [diff] [blame] | 547 | } |
| 548 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 549 | bool DevirtModule::tryFindVirtualCallTargets( |
| 550 | std::vector<VirtualCallTarget> &TargetsForSlot, |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 551 | const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) { |
| 552 | for (const TypeMemberInfo &TM : TypeMemberInfos) { |
| 553 | if (!TM.Bits->GV->isConstant()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 554 | return false; |
| 555 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 556 | Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), |
| 557 | TM.Offset + ByteOffset); |
| 558 | if (!Ptr) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 559 | return false; |
| 560 | |
Peter Collingbourne | 8786754 | 2016-12-09 01:10:11 +0000 | [diff] [blame] | 561 | auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts()); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 562 | if (!Fn) |
| 563 | return false; |
| 564 | |
| 565 | // We can disregard __cxa_pure_virtual as a possible call target, as |
| 566 | // calls to pure virtuals are UB. |
| 567 | if (Fn->getName() == "__cxa_pure_virtual") |
| 568 | continue; |
| 569 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 570 | TargetsForSlot.push_back({Fn, &TM}); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 571 | } |
| 572 | |
| 573 | // Give up if we couldn't find any targets. |
| 574 | return !TargetsForSlot.empty(); |
| 575 | } |
| 576 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 577 | void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, |
| 578 | Constant *TheFn) { |
| 579 | auto Apply = [&](CallSiteInfo &CSInfo) { |
| 580 | for (auto &&VCallSite : CSInfo.CallSites) { |
| 581 | if (RemarksEnabled) |
| 582 | VCallSite.emitRemark("single-impl", TheFn->getName()); |
| 583 | VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast( |
| 584 | TheFn, VCallSite.CS.getCalledValue()->getType())); |
| 585 | // This use is no longer unsafe. |
| 586 | if (VCallSite.NumUnsafeUses) |
| 587 | --*VCallSite.NumUnsafeUses; |
| 588 | } |
| 589 | }; |
| 590 | Apply(SlotInfo.CSInfo); |
| 591 | for (auto &P : SlotInfo.ConstCSInfo) |
| 592 | Apply(P.second); |
| 593 | } |
| 594 | |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 595 | bool DevirtModule::trySingleImplDevirt( |
| 596 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 597 | VTableSlotInfo &SlotInfo) { |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 598 | // See if the program contains a single implementation of this virtual |
| 599 | // function. |
| 600 | Function *TheFn = TargetsForSlot[0].Fn; |
| 601 | for (auto &&Target : TargetsForSlot) |
| 602 | if (TheFn != Target.Fn) |
| 603 | return false; |
| 604 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 605 | // If so, update each call site to call that implementation directly. |
Peter Collingbourne | e236741 | 2017-02-15 02:13:08 +0000 | [diff] [blame] | 606 | if (RemarksEnabled) |
| 607 | TargetsForSlot[0].WasDevirt = true; |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 608 | applySingleImplDevirt(SlotInfo, TheFn); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 609 | return true; |
| 610 | } |
| 611 | |
| 612 | bool DevirtModule::tryEvaluateFunctionsWithArgs( |
| 613 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 614 | ArrayRef<uint64_t> Args) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 615 | // Evaluate each function and store the result in each target's RetVal |
| 616 | // field. |
| 617 | for (VirtualCallTarget &Target : TargetsForSlot) { |
| 618 | if (Target.Fn->arg_size() != Args.size() + 1) |
| 619 | return false; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 620 | |
| 621 | Evaluator Eval(M.getDataLayout(), nullptr); |
| 622 | SmallVector<Constant *, 2> EvalArgs; |
| 623 | EvalArgs.push_back( |
| 624 | Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 625 | for (unsigned I = 0; I != Args.size(); ++I) { |
| 626 | auto *ArgTy = dyn_cast<IntegerType>( |
| 627 | Target.Fn->getFunctionType()->getParamType(I + 1)); |
| 628 | if (!ArgTy) |
| 629 | return false; |
| 630 | EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); |
| 631 | } |
| 632 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 633 | Constant *RetVal; |
| 634 | if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || |
| 635 | !isa<ConstantInt>(RetVal)) |
| 636 | return false; |
| 637 | Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); |
| 638 | } |
| 639 | return true; |
| 640 | } |
| 641 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 642 | void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 643 | uint64_t TheRetVal) { |
| 644 | for (auto Call : CSInfo.CallSites) |
| 645 | Call.replaceAndErase( |
| 646 | "uniform-ret-val", FnName, RemarksEnabled, |
| 647 | ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal)); |
| 648 | } |
| 649 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 650 | bool DevirtModule::tryUniformRetValOpt( |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 651 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 652 | // Uniform return value optimization. If all functions return the same |
| 653 | // constant, replace all calls with that constant. |
| 654 | uint64_t TheRetVal = TargetsForSlot[0].RetVal; |
| 655 | for (const VirtualCallTarget &Target : TargetsForSlot) |
| 656 | if (Target.RetVal != TheRetVal) |
| 657 | return false; |
| 658 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 659 | applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 660 | if (RemarksEnabled) |
| 661 | for (auto &&Target : TargetsForSlot) |
| 662 | Target.WasDevirt = true; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 663 | return true; |
| 664 | } |
| 665 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 666 | void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, |
| 667 | bool IsOne, |
| 668 | Constant *UniqueMemberAddr) { |
| 669 | for (auto &&Call : CSInfo.CallSites) { |
| 670 | IRBuilder<> B(Call.CS.getInstruction()); |
| 671 | Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, |
| 672 | Call.VTable, UniqueMemberAddr); |
| 673 | Cmp = B.CreateZExt(Cmp, Call.CS->getType()); |
| 674 | Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp); |
| 675 | } |
| 676 | } |
| 677 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 678 | bool DevirtModule::tryUniqueRetValOpt( |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 679 | unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 680 | CallSiteInfo &CSInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 681 | // IsOne controls whether we look for a 0 or a 1. |
| 682 | auto tryUniqueRetValOptFor = [&](bool IsOne) { |
Eugene Zelenko | cdc7161 | 2016-08-11 17:20:18 +0000 | [diff] [blame] | 683 | const TypeMemberInfo *UniqueMember = nullptr; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 684 | for (const VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 3866cc5 | 2016-03-08 03:50:36 +0000 | [diff] [blame] | 685 | if (Target.RetVal == (IsOne ? 1 : 0)) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 686 | if (UniqueMember) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 687 | return false; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 688 | UniqueMember = Target.TM; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 689 | } |
| 690 | } |
| 691 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 692 | // 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] | 693 | // checked for a uniform return value in tryUniformRetValOpt. |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 694 | assert(UniqueMember); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 695 | |
| 696 | // Replace each call with the comparison. |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 697 | Constant *UniqueMemberAddr = |
| 698 | ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy); |
| 699 | UniqueMemberAddr = ConstantExpr::getGetElementPtr( |
| 700 | Int8Ty, UniqueMemberAddr, |
| 701 | ConstantInt::get(Int64Ty, UniqueMember->Offset)); |
| 702 | |
| 703 | applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, |
| 704 | UniqueMemberAddr); |
| 705 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 706 | // Update devirtualization statistics for targets. |
| 707 | if (RemarksEnabled) |
| 708 | for (auto &&Target : TargetsForSlot) |
| 709 | Target.WasDevirt = true; |
| 710 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 711 | return true; |
| 712 | }; |
| 713 | |
| 714 | if (BitWidth == 1) { |
| 715 | if (tryUniqueRetValOptFor(true)) |
| 716 | return true; |
| 717 | if (tryUniqueRetValOptFor(false)) |
| 718 | return true; |
| 719 | } |
| 720 | return false; |
| 721 | } |
| 722 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 723 | void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, |
| 724 | Constant *Byte, Constant *Bit) { |
| 725 | for (auto Call : CSInfo.CallSites) { |
| 726 | auto *RetType = cast<IntegerType>(Call.CS.getType()); |
| 727 | IRBuilder<> B(Call.CS.getInstruction()); |
| 728 | Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte); |
| 729 | if (RetType->getBitWidth() == 1) { |
| 730 | Value *Bits = B.CreateLoad(Addr); |
| 731 | Value *BitsAndBit = B.CreateAnd(Bits, Bit); |
| 732 | auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); |
| 733 | Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, |
| 734 | IsBitSet); |
| 735 | } else { |
| 736 | Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); |
| 737 | Value *Val = B.CreateLoad(RetType, ValAddr); |
| 738 | Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val); |
| 739 | } |
| 740 | } |
| 741 | } |
| 742 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 743 | bool DevirtModule::tryVirtualConstProp( |
| 744 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 745 | VTableSlotInfo &SlotInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 746 | // This only works if the function returns an integer. |
| 747 | auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); |
| 748 | if (!RetType) |
| 749 | return false; |
| 750 | unsigned BitWidth = RetType->getBitWidth(); |
| 751 | if (BitWidth > 64) |
| 752 | return false; |
| 753 | |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 754 | // Make sure that each function is defined, does not access memory, takes at |
| 755 | // least one argument, does not use its first argument (which we assume is |
| 756 | // 'this'), and has the same return type. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 757 | for (VirtualCallTarget &Target : TargetsForSlot) { |
Peter Collingbourne | 17febdb | 2017-02-09 23:46:26 +0000 | [diff] [blame] | 758 | if (Target.Fn->isDeclaration() || !Target.Fn->doesNotAccessMemory() || |
| 759 | Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() || |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 760 | Target.Fn->getReturnType() != RetType) |
| 761 | return false; |
| 762 | } |
| 763 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 764 | for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 765 | if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) |
| 766 | continue; |
| 767 | |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 768 | if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second)) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 769 | continue; |
| 770 | |
| 771 | if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second)) |
| 772 | continue; |
| 773 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 774 | // Find an allocation offset in bits in all vtables associated with the |
| 775 | // type. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 776 | uint64_t AllocBefore = |
| 777 | findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); |
| 778 | uint64_t AllocAfter = |
| 779 | findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); |
| 780 | |
| 781 | // Calculate the total amount of padding needed to store a value at both |
| 782 | // ends of the object. |
| 783 | uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; |
| 784 | for (auto &&Target : TargetsForSlot) { |
| 785 | TotalPaddingBefore += std::max<int64_t>( |
| 786 | (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); |
| 787 | TotalPaddingAfter += std::max<int64_t>( |
| 788 | (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); |
| 789 | } |
| 790 | |
| 791 | // If the amount of padding is too large, give up. |
| 792 | // FIXME: do something smarter here. |
| 793 | if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) |
| 794 | continue; |
| 795 | |
| 796 | // Calculate the offset to the value as a (possibly negative) byte offset |
| 797 | // and (if applicable) a bit offset, and store the values in the targets. |
| 798 | int64_t OffsetByte; |
| 799 | uint64_t OffsetBit; |
| 800 | if (TotalPaddingBefore <= TotalPaddingAfter) |
| 801 | setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, |
| 802 | OffsetBit); |
| 803 | else |
| 804 | setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, |
| 805 | OffsetBit); |
| 806 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 807 | if (RemarksEnabled) |
| 808 | for (auto &&Target : TargetsForSlot) |
| 809 | Target.WasDevirt = true; |
| 810 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 811 | // Rewrite each call to a load from OffsetByte/OffsetBit. |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 812 | Constant *ByteConst = ConstantInt::get(Int64Ty, OffsetByte); |
| 813 | Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); |
| 814 | applyVirtualConstProp(CSByConstantArg.second, |
| 815 | TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 816 | } |
| 817 | return true; |
| 818 | } |
| 819 | |
| 820 | void DevirtModule::rebuildGlobal(VTableBits &B) { |
| 821 | if (B.Before.Bytes.empty() && B.After.Bytes.empty()) |
| 822 | return; |
| 823 | |
| 824 | // Align each byte array to pointer width. |
| 825 | unsigned PointerSize = M.getDataLayout().getPointerSize(); |
| 826 | B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize)); |
| 827 | B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize)); |
| 828 | |
| 829 | // Before was stored in reverse order; flip it now. |
| 830 | for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) |
| 831 | std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); |
| 832 | |
| 833 | // Build an anonymous global containing the before bytes, followed by the |
| 834 | // original initializer, followed by the after bytes. |
| 835 | auto NewInit = ConstantStruct::getAnon( |
| 836 | {ConstantDataArray::get(M.getContext(), B.Before.Bytes), |
| 837 | B.GV->getInitializer(), |
| 838 | ConstantDataArray::get(M.getContext(), B.After.Bytes)}); |
| 839 | auto NewGV = |
| 840 | new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), |
| 841 | GlobalVariable::PrivateLinkage, NewInit, "", B.GV); |
| 842 | NewGV->setSection(B.GV->getSection()); |
| 843 | NewGV->setComdat(B.GV->getComdat()); |
| 844 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 845 | // Copy the original vtable's metadata to the anonymous global, adjusting |
| 846 | // offsets as required. |
| 847 | NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); |
| 848 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 849 | // Build an alias named after the original global, pointing at the second |
| 850 | // element (the original initializer). |
| 851 | auto Alias = GlobalAlias::create( |
| 852 | B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", |
| 853 | ConstantExpr::getGetElementPtr( |
| 854 | NewInit->getType(), NewGV, |
| 855 | ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), |
| 856 | ConstantInt::get(Int32Ty, 1)}), |
| 857 | &M); |
| 858 | Alias->setVisibility(B.GV->getVisibility()); |
| 859 | Alias->takeName(B.GV); |
| 860 | |
| 861 | B.GV->replaceAllUsesWith(Alias); |
| 862 | B.GV->eraseFromParent(); |
| 863 | } |
| 864 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 865 | bool DevirtModule::areRemarksEnabled() { |
| 866 | const auto &FL = M.getFunctionList(); |
| 867 | if (FL.empty()) |
| 868 | return false; |
| 869 | const Function &Fn = FL.front(); |
Adam Nemet | 04758ba | 2016-09-27 22:19:23 +0000 | [diff] [blame] | 870 | auto DI = OptimizationRemark(DEBUG_TYPE, Fn, DebugLoc(), ""); |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 871 | return DI.isEnabled(); |
| 872 | } |
| 873 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 874 | void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc, |
| 875 | Function *AssumeFunc) { |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 876 | // 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] | 877 | // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p |
| 878 | // points to a member of the type identifier %md. Group calls by (type ID, |
| 879 | // offset) pair (effectively the identity of the virtual function) and store |
| 880 | // to CallSlots. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 881 | DenseSet<Value *> SeenPtrs; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 882 | for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end(); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 883 | I != E;) { |
| 884 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 885 | ++I; |
| 886 | if (!CI) |
| 887 | continue; |
| 888 | |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 889 | // Search for virtual calls based on %p and add them to DevirtCalls. |
| 890 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 891 | SmallVector<CallInst *, 1> Assumes; |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 892 | findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 893 | |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 894 | // If we found any, add them to CallSlots. Only do this if we haven't seen |
| 895 | // the vtable pointer before, as it may have been CSE'd with pointers from |
| 896 | // 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] | 897 | if (!Assumes.empty()) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 898 | Metadata *TypeId = |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 899 | cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); |
| 900 | Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 901 | if (SeenPtrs.insert(Ptr).second) { |
| 902 | for (DevirtCallSite Call : DevirtCalls) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 903 | CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0), |
| 904 | Call.CS, nullptr); |
Peter Collingbourne | ccdc225 | 2016-05-10 18:07:21 +0000 | [diff] [blame] | 905 | } |
| 906 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 907 | } |
| 908 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 909 | // We no longer need the assumes or the type test. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 910 | for (auto Assume : Assumes) |
| 911 | Assume->eraseFromParent(); |
| 912 | // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we |
| 913 | // may use the vtable argument later. |
| 914 | if (CI->use_empty()) |
| 915 | CI->eraseFromParent(); |
| 916 | } |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 917 | } |
| 918 | |
| 919 | void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { |
| 920 | Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); |
| 921 | |
| 922 | for (auto I = TypeCheckedLoadFunc->use_begin(), |
| 923 | E = TypeCheckedLoadFunc->use_end(); |
| 924 | I != E;) { |
| 925 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 926 | ++I; |
| 927 | if (!CI) |
| 928 | continue; |
| 929 | |
| 930 | Value *Ptr = CI->getArgOperand(0); |
| 931 | Value *Offset = CI->getArgOperand(1); |
| 932 | Value *TypeIdValue = CI->getArgOperand(2); |
| 933 | Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); |
| 934 | |
| 935 | SmallVector<DevirtCallSite, 1> DevirtCalls; |
| 936 | SmallVector<Instruction *, 1> LoadedPtrs; |
| 937 | SmallVector<Instruction *, 1> Preds; |
| 938 | bool HasNonCallUses = false; |
| 939 | findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, |
| 940 | HasNonCallUses, CI); |
| 941 | |
| 942 | // Start by generating "pessimistic" code that explicitly loads the function |
| 943 | // pointer from the vtable and performs the type check. If possible, we will |
| 944 | // eliminate the load and the type check later. |
| 945 | |
| 946 | // If possible, only generate the load at the point where it is used. |
| 947 | // This helps avoid unnecessary spills. |
| 948 | IRBuilder<> LoadB( |
| 949 | (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); |
| 950 | Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset); |
| 951 | Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy)); |
| 952 | Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr); |
| 953 | |
| 954 | for (Instruction *LoadedPtr : LoadedPtrs) { |
| 955 | LoadedPtr->replaceAllUsesWith(LoadedValue); |
| 956 | LoadedPtr->eraseFromParent(); |
| 957 | } |
| 958 | |
| 959 | // Likewise for the type test. |
| 960 | IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); |
| 961 | CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); |
| 962 | |
| 963 | for (Instruction *Pred : Preds) { |
| 964 | Pred->replaceAllUsesWith(TypeTestCall); |
| 965 | Pred->eraseFromParent(); |
| 966 | } |
| 967 | |
| 968 | // We have already erased any extractvalue instructions that refer to the |
| 969 | // intrinsic call, but the intrinsic may have other non-extractvalue uses |
| 970 | // (although this is unlikely). In that case, explicitly build a pair and |
| 971 | // RAUW it. |
| 972 | if (!CI->use_empty()) { |
| 973 | Value *Pair = UndefValue::get(CI->getType()); |
| 974 | IRBuilder<> B(CI); |
| 975 | Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); |
| 976 | Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); |
| 977 | CI->replaceAllUsesWith(Pair); |
| 978 | } |
| 979 | |
| 980 | // The number of unsafe uses is initially the number of uses. |
| 981 | auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; |
| 982 | NumUnsafeUses = DevirtCalls.size(); |
| 983 | |
| 984 | // If the function pointer has a non-call user, we cannot eliminate the type |
| 985 | // check, as one of those users may eventually call the pointer. Increment |
| 986 | // the unsafe use count to make sure it cannot reach zero. |
| 987 | if (HasNonCallUses) |
| 988 | ++NumUnsafeUses; |
| 989 | for (DevirtCallSite Call : DevirtCalls) { |
Peter Collingbourne | 50cbd7c | 2017-02-15 21:56:51 +0000 | [diff] [blame] | 990 | CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, |
| 991 | &NumUnsafeUses); |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 992 | } |
| 993 | |
| 994 | CI->eraseFromParent(); |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | bool DevirtModule::run() { |
| 999 | Function *TypeTestFunc = |
| 1000 | M.getFunction(Intrinsic::getName(Intrinsic::type_test)); |
| 1001 | Function *TypeCheckedLoadFunc = |
| 1002 | M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); |
| 1003 | Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); |
| 1004 | |
| 1005 | if ((!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || |
| 1006 | AssumeFunc->use_empty()) && |
| 1007 | (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty())) |
| 1008 | return false; |
| 1009 | |
| 1010 | if (TypeTestFunc && AssumeFunc) |
| 1011 | scanTypeTestUsers(TypeTestFunc, AssumeFunc); |
| 1012 | |
| 1013 | if (TypeCheckedLoadFunc) |
| 1014 | scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1015 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1016 | // Rebuild type metadata into a map for easy lookup. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1017 | std::vector<VTableBits> Bits; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1018 | DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; |
| 1019 | buildTypeIdentifierMap(Bits, TypeIdMap); |
| 1020 | if (TypeIdMap.empty()) |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1021 | return true; |
| 1022 | |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1023 | // For each (type, offset) pair: |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1024 | bool DidVirtualConstProp = false; |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1025 | std::map<std::string, Function*> DevirtTargets; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1026 | for (auto &S : CallSlots) { |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1027 | // Search each of the members of the type identifier for the virtual |
| 1028 | // function implementation at offset S.first.ByteOffset, and add to |
| 1029 | // TargetsForSlot. |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1030 | std::vector<VirtualCallTarget> TargetsForSlot; |
Peter Collingbourne | 7efd750 | 2016-06-24 21:21:32 +0000 | [diff] [blame] | 1031 | if (!tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID], |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1032 | S.first.ByteOffset)) |
| 1033 | continue; |
| 1034 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1035 | if (!trySingleImplDevirt(TargetsForSlot, S.second) && |
| 1036 | tryVirtualConstProp(TargetsForSlot, S.second)) |
| 1037 | DidVirtualConstProp = true; |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1038 | |
Ivan Krasin | f3403fd | 2016-08-11 19:09:02 +0000 | [diff] [blame] | 1039 | // Collect functions devirtualized at least for one call site for stats. |
| 1040 | if (RemarksEnabled) |
| 1041 | for (const auto &T : TargetsForSlot) |
| 1042 | if (T.WasDevirt) |
| 1043 | DevirtTargets[T.Fn->getName()] = T.Fn; |
| 1044 | } |
| 1045 | |
| 1046 | if (RemarksEnabled) { |
| 1047 | // Generate remarks for each devirtualized function. |
| 1048 | for (const auto &DT : DevirtTargets) { |
| 1049 | Function *F = DT.second; |
| 1050 | DISubprogram *SP = F->getSubprogram(); |
| 1051 | DebugLoc DL = SP ? DebugLoc::get(SP->getScopeLine(), 0, SP) : DebugLoc(); |
| 1052 | emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, DL, |
| 1053 | Twine("devirtualized ") + F->getName()); |
Ivan Krasin | b05e06e | 2016-08-05 19:45:16 +0000 | [diff] [blame] | 1054 | } |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1055 | } |
| 1056 | |
Peter Collingbourne | 0312f61 | 2016-06-25 00:23:04 +0000 | [diff] [blame] | 1057 | // If we were able to eliminate all unsafe uses for a type checked load, |
| 1058 | // eliminate the type test by replacing it with true. |
| 1059 | if (TypeCheckedLoadFunc) { |
| 1060 | auto True = ConstantInt::getTrue(M.getContext()); |
| 1061 | for (auto &&U : NumUnsafeUsesForTypeTest) { |
| 1062 | if (U.second == 0) { |
| 1063 | U.first->replaceAllUsesWith(True); |
| 1064 | U.first->eraseFromParent(); |
| 1065 | } |
| 1066 | } |
| 1067 | } |
| 1068 | |
Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame] | 1069 | // Rebuild each global we touched as part of virtual constant propagation to |
| 1070 | // include the before and after bytes. |
| 1071 | if (DidVirtualConstProp) |
| 1072 | for (VTableBits &B : Bits) |
| 1073 | rebuildGlobal(B); |
| 1074 | |
| 1075 | return true; |
| 1076 | } |