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