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