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