blob: 73ea5c19267438145e235f48b988f159a77722c5 [file] [log] [blame]
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001//===- 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 Collingbourne7efd7502016-06-24 21:21:32 +000011// where we know (via !type metadata) that the list of callees is fixed. This
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000012// includes the following:
13// - Single implementation devirtualization: if a virtual call has a single
14// possible callee, replace all calls with a direct call to that callee.
15// - Virtual constant propagation: if the virtual function's return type is an
16// integer <=64 bits and all possible callees are readnone, for each class and
17// each list of constant arguments: evaluate the function, store the return
18// value alongside the virtual table, and rewrite each virtual call as a load
19// from the virtual table.
20// - Uniform return value optimization: if the conditions for virtual constant
21// propagation hold and each function returns the same constant value, replace
22// each virtual call with that constant.
23// - Unique return value optimization for i1 return values: if the conditions
24// for virtual constant propagation hold and a single vtable's function
25// returns 0, or a single vtable's function returns 1, replace each virtual
26// call with a comparison of the vptr against that vtable's address.
27//
28//===----------------------------------------------------------------------===//
29
30#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000031#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/DenseMapInfo.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000034#include "llvm/ADT/DenseSet.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000035#include "llvm/ADT/iterator_range.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000036#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000037#include "llvm/ADT/SmallVector.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000038#include "llvm/Analysis/TypeMetadataUtils.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000039#include "llvm/IR/CallSite.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
Ivan Krasinb05e06e2016-08-05 19:45:16 +000042#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000043#include "llvm/IR/DebugLoc.h"
44#include "llvm/IR/DerivedTypes.h"
Ivan Krasin54746452016-07-12 02:38:37 +000045#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include "llvm/IR/Function.h"
47#include "llvm/IR/GlobalAlias.h"
48#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000049#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000052#include "llvm/IR/Instructions.h"
53#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000054#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000056#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000057#include "llvm/IR/ModuleSummaryIndexYAML.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000058#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/PassRegistry.h"
60#include "llvm/PassSupport.h"
61#include "llvm/Support/Casting.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000062#include "llvm/Support/Error.h"
63#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000064#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000065#include "llvm/Transforms/IPO.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000066#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000067#include <algorithm>
68#include <cstddef>
69#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000070#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000071#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000072
73using namespace llvm;
74using namespace wholeprogramdevirt;
75
76#define DEBUG_TYPE "wholeprogramdevirt"
77
Peter Collingbourne2b33f652017-02-13 19:26:18 +000078static cl::opt<PassSummaryAction> ClSummaryAction(
79 "wholeprogramdevirt-summary-action",
80 cl::desc("What to do with the summary when running this pass"),
81 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
82 clEnumValN(PassSummaryAction::Import, "import",
83 "Import typeid resolutions from summary and globals"),
84 clEnumValN(PassSummaryAction::Export, "export",
85 "Export typeid resolutions to summary and globals")),
86 cl::Hidden);
87
88static cl::opt<std::string> ClReadSummary(
89 "wholeprogramdevirt-read-summary",
90 cl::desc("Read summary from given YAML file before running pass"),
91 cl::Hidden);
92
93static cl::opt<std::string> ClWriteSummary(
94 "wholeprogramdevirt-write-summary",
95 cl::desc("Write summary to given YAML file after running pass"),
96 cl::Hidden);
97
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000098// Find the minimum offset that we may store a value of size Size bits at. If
99// IsAfter is set, look for an offset before the object, otherwise look for an
100// offset after the object.
101uint64_t
102wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
103 bool IsAfter, uint64_t Size) {
104 // Find a minimum offset taking into account only vtable sizes.
105 uint64_t MinByte = 0;
106 for (const VirtualCallTarget &Target : Targets) {
107 if (IsAfter)
108 MinByte = std::max(MinByte, Target.minAfterBytes());
109 else
110 MinByte = std::max(MinByte, Target.minBeforeBytes());
111 }
112
113 // Build a vector of arrays of bytes covering, for each target, a slice of the
114 // used region (see AccumBitVector::BytesUsed in
115 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
116 // this aligns the used regions to start at MinByte.
117 //
118 // In this example, A, B and C are vtables, # is a byte already allocated for
119 // a virtual function pointer, AAAA... (etc.) are the used regions for the
120 // vtables and Offset(X) is the value computed for the Offset variable below
121 // for X.
122 //
123 // Offset(A)
124 // | |
125 // |MinByte
126 // A: ################AAAAAAAA|AAAAAAAA
127 // B: ########BBBBBBBBBBBBBBBB|BBBB
128 // C: ########################|CCCCCCCCCCCCCCCC
129 // | Offset(B) |
130 //
131 // This code produces the slices of A, B and C that appear after the divider
132 // at MinByte.
133 std::vector<ArrayRef<uint8_t>> Used;
134 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000135 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
136 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000137 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
138 : MinByte - Target.minBeforeBytes();
139
140 // Disregard used regions that are smaller than Offset. These are
141 // effectively all-free regions that do not need to be checked.
142 if (VTUsed.size() > Offset)
143 Used.push_back(VTUsed.slice(Offset));
144 }
145
146 if (Size == 1) {
147 // Find a free bit in each member of Used.
148 for (unsigned I = 0;; ++I) {
149 uint8_t BitsUsed = 0;
150 for (auto &&B : Used)
151 if (I < B.size())
152 BitsUsed |= B[I];
153 if (BitsUsed != 0xff)
154 return (MinByte + I) * 8 +
155 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
156 }
157 } else {
158 // Find a free (Size/8) byte region in each member of Used.
159 // FIXME: see if alignment helps.
160 for (unsigned I = 0;; ++I) {
161 for (auto &&B : Used) {
162 unsigned Byte = 0;
163 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
164 if (B[I + Byte])
165 goto NextI;
166 ++Byte;
167 }
168 }
169 return (MinByte + I) * 8;
170 NextI:;
171 }
172 }
173}
174
175void wholeprogramdevirt::setBeforeReturnValues(
176 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
177 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
178 if (BitWidth == 1)
179 OffsetByte = -(AllocBefore / 8 + 1);
180 else
181 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
182 OffsetBit = AllocBefore % 8;
183
184 for (VirtualCallTarget &Target : Targets) {
185 if (BitWidth == 1)
186 Target.setBeforeBit(AllocBefore);
187 else
188 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
189 }
190}
191
192void wholeprogramdevirt::setAfterReturnValues(
193 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
194 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
195 if (BitWidth == 1)
196 OffsetByte = AllocAfter / 8;
197 else
198 OffsetByte = (AllocAfter + 7) / 8;
199 OffsetBit = AllocAfter % 8;
200
201 for (VirtualCallTarget &Target : Targets) {
202 if (BitWidth == 1)
203 Target.setAfterBit(AllocAfter);
204 else
205 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
206 }
207}
208
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000209VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
210 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000211 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000212
213namespace {
214
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000215// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000216// tables, and the ByteOffset is the offset in bytes from the address point to
217// the virtual function pointer.
218struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000219 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000220 uint64_t ByteOffset;
221};
222
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000223} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000224
Peter Collingbourne9b656522016-02-09 23:01:38 +0000225namespace llvm {
226
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000227template <> struct DenseMapInfo<VTableSlot> {
228 static VTableSlot getEmptyKey() {
229 return {DenseMapInfo<Metadata *>::getEmptyKey(),
230 DenseMapInfo<uint64_t>::getEmptyKey()};
231 }
232 static VTableSlot getTombstoneKey() {
233 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
234 DenseMapInfo<uint64_t>::getTombstoneKey()};
235 }
236 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000237 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000238 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
239 }
240 static bool isEqual(const VTableSlot &LHS,
241 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000242 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000243 }
244};
245
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000246} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000247
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000248namespace {
249
250// A virtual call site. VTable is the loaded virtual table pointer, and CS is
251// the indirect virtual call.
252struct VirtualCallSite {
253 Value *VTable;
254 CallSite CS;
255
Peter Collingbourne0312f612016-06-25 00:23:04 +0000256 // If non-null, this field points to the associated unsafe use count stored in
257 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
258 // of that field for details.
259 unsigned *NumUnsafeUses;
260
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000261 void emitRemark(const Twine &OptName, const Twine &TargetName) {
Ivan Krasin54746452016-07-12 02:38:37 +0000262 Function *F = CS.getCaller();
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000263 emitOptimizationRemark(
264 F->getContext(), DEBUG_TYPE, *F,
265 CS.getInstruction()->getDebugLoc(),
266 OptName + ": devirtualized a call to " + TargetName);
Ivan Krasin54746452016-07-12 02:38:37 +0000267 }
268
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000269 void replaceAndErase(const Twine &OptName, const Twine &TargetName,
270 bool RemarksEnabled, Value *New) {
271 if (RemarksEnabled)
272 emitRemark(OptName, TargetName);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000273 CS->replaceAllUsesWith(New);
274 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
275 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
276 II->getUnwindDest()->removePredecessor(II->getParent());
277 }
278 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000279 // This use is no longer unsafe.
280 if (NumUnsafeUses)
281 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000282 }
283};
284
285struct DevirtModule {
286 Module &M;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000287
288 PassSummaryAction Action;
289 ModuleSummaryIndex *Summary;
290
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000291 IntegerType *Int8Ty;
292 PointerType *Int8PtrTy;
293 IntegerType *Int32Ty;
294
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000295 bool RemarksEnabled;
296
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000297 MapVector<VTableSlot, std::vector<VirtualCallSite>> CallSlots;
298
Peter Collingbourne0312f612016-06-25 00:23:04 +0000299 // This map keeps track of the number of "unsafe" uses of a loaded function
300 // pointer. The key is the associated llvm.type.test intrinsic call generated
301 // by this pass. An unsafe use is one that calls the loaded function pointer
302 // directly. Every time we eliminate an unsafe use (for example, by
303 // devirtualizing it or by applying virtual constant propagation), we
304 // decrement the value stored in this map. If a value reaches zero, we can
305 // eliminate the type check by RAUWing the associated llvm.type.test call with
306 // true.
307 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
308
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000309 DevirtModule(Module &M, PassSummaryAction Action, ModuleSummaryIndex *Summary)
310 : M(M), Action(Action), Summary(Summary),
311 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000312 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000313 Int32Ty(Type::getInt32Ty(M.getContext())),
314 RemarksEnabled(areRemarksEnabled()) {}
315
316 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000317
Peter Collingbourne0312f612016-06-25 00:23:04 +0000318 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
319 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
320
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000321 void buildTypeIdentifierMap(
322 std::vector<VTableBits> &Bits,
323 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000324 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000325 bool
326 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
327 const std::set<TypeMemberInfo> &TypeMemberInfos,
328 uint64_t ByteOffset);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000329 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000330 MutableArrayRef<VirtualCallSite> CallSites);
331 bool tryEvaluateFunctionsWithArgs(
332 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
333 ArrayRef<ConstantInt *> Args);
334 bool tryUniformRetValOpt(IntegerType *RetType,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000335 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000336 MutableArrayRef<VirtualCallSite> CallSites);
337 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000338 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000339 MutableArrayRef<VirtualCallSite> CallSites);
340 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
341 ArrayRef<VirtualCallSite> CallSites);
342
343 void rebuildGlobal(VTableBits &B);
344
345 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000346
347 // Lower the module using the action and summary passed as command line
348 // arguments. For testing purposes only.
349 static bool runForTesting(Module &M);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000350};
351
352struct WholeProgramDevirt : public ModulePass {
353 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000354
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000355 bool UseCommandLine = false;
356
357 PassSummaryAction Action;
358 ModuleSummaryIndex *Summary;
359
360 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
361 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
362 }
363
364 WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary)
365 : ModulePass(ID), Action(Action), Summary(Summary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000366 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
367 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000368
369 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000370 if (skipModule(M))
371 return false;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000372 if (UseCommandLine)
373 return DevirtModule::runForTesting(M);
374 return DevirtModule(M, Action, Summary).run();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000375 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000376};
377
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000378} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000379
380INITIALIZE_PASS(WholeProgramDevirt, "wholeprogramdevirt",
381 "Whole program devirtualization", false, false)
382char WholeProgramDevirt::ID = 0;
383
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000384ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action,
385 ModuleSummaryIndex *Summary) {
386 return new WholeProgramDevirt(Action, Summary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000387}
388
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000389PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
390 ModuleAnalysisManager &) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000391 if (!DevirtModule(M, PassSummaryAction::None, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000392 return PreservedAnalyses::all();
393 return PreservedAnalyses::none();
394}
395
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000396bool DevirtModule::runForTesting(Module &M) {
397 ModuleSummaryIndex Summary;
398
399 // Handle the command-line summary arguments. This code is for testing
400 // purposes only, so we handle errors directly.
401 if (!ClReadSummary.empty()) {
402 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
403 ": ");
404 auto ReadSummaryFile =
405 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
406
407 yaml::Input In(ReadSummaryFile->getBuffer());
408 In >> Summary;
409 ExitOnErr(errorCodeToError(In.error()));
410 }
411
412 bool Changed = DevirtModule(M, ClSummaryAction, &Summary).run();
413
414 if (!ClWriteSummary.empty()) {
415 ExitOnError ExitOnErr(
416 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
417 std::error_code EC;
418 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
419 ExitOnErr(errorCodeToError(EC));
420
421 yaml::Output Out(OS);
422 Out << Summary;
423 }
424
425 return Changed;
426}
427
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000428void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000429 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000430 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000431 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000432 Bits.reserve(M.getGlobalList().size());
433 SmallVector<MDNode *, 2> Types;
434 for (GlobalVariable &GV : M.globals()) {
435 Types.clear();
436 GV.getMetadata(LLVMContext::MD_type, Types);
437 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000438 continue;
439
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000440 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000441 if (!BitsPtr) {
442 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000443 Bits.back().GV = &GV;
444 Bits.back().ObjectSize =
445 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000446 BitsPtr = &Bits.back();
447 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000448
449 for (MDNode *Type : Types) {
450 auto TypeID = Type->getOperand(1).get();
451
452 uint64_t Offset =
453 cast<ConstantInt>(
454 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
455 ->getZExtValue();
456
457 TypeIdMap[TypeID].insert({BitsPtr, Offset});
458 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000459 }
460}
461
Peter Collingbourne87867542016-12-09 01:10:11 +0000462Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
463 if (I->getType()->isPointerTy()) {
464 if (Offset == 0)
465 return I;
466 return nullptr;
467 }
468
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000469 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000470
471 if (auto *C = dyn_cast<ConstantStruct>(I)) {
472 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000473 if (Offset >= SL->getSizeInBytes())
474 return nullptr;
475
Peter Collingbourne87867542016-12-09 01:10:11 +0000476 unsigned Op = SL->getElementContainingOffset(Offset);
477 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
478 Offset - SL->getElementOffset(Op));
479 }
480 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000481 ArrayType *VTableTy = C->getType();
482 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
483
Peter Collingbourne87867542016-12-09 01:10:11 +0000484 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000485 if (Op >= C->getNumOperands())
486 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000487
Peter Collingbourne87867542016-12-09 01:10:11 +0000488 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
489 Offset % ElemSize);
490 }
491 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000492}
493
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000494bool DevirtModule::tryFindVirtualCallTargets(
495 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000496 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
497 for (const TypeMemberInfo &TM : TypeMemberInfos) {
498 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000499 return false;
500
Peter Collingbourne87867542016-12-09 01:10:11 +0000501 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
502 TM.Offset + ByteOffset);
503 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000504 return false;
505
Peter Collingbourne87867542016-12-09 01:10:11 +0000506 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000507 if (!Fn)
508 return false;
509
510 // We can disregard __cxa_pure_virtual as a possible call target, as
511 // calls to pure virtuals are UB.
512 if (Fn->getName() == "__cxa_pure_virtual")
513 continue;
514
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000515 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000516 }
517
518 // Give up if we couldn't find any targets.
519 return !TargetsForSlot.empty();
520}
521
522bool DevirtModule::trySingleImplDevirt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000523 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000524 MutableArrayRef<VirtualCallSite> CallSites) {
525 // See if the program contains a single implementation of this virtual
526 // function.
527 Function *TheFn = TargetsForSlot[0].Fn;
528 for (auto &&Target : TargetsForSlot)
529 if (TheFn != Target.Fn)
530 return false;
531
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000532 if (RemarksEnabled)
533 TargetsForSlot[0].WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000534 // If so, update each call site to call that implementation directly.
535 for (auto &&VCallSite : CallSites) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000536 if (RemarksEnabled)
537 VCallSite.emitRemark("single-impl", TheFn->getName());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000538 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
539 TheFn, VCallSite.CS.getCalledValue()->getType()));
Peter Collingbourne0312f612016-06-25 00:23:04 +0000540 // This use is no longer unsafe.
541 if (VCallSite.NumUnsafeUses)
542 --*VCallSite.NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000543 }
544 return true;
545}
546
547bool DevirtModule::tryEvaluateFunctionsWithArgs(
548 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
549 ArrayRef<ConstantInt *> Args) {
550 // Evaluate each function and store the result in each target's RetVal
551 // field.
552 for (VirtualCallTarget &Target : TargetsForSlot) {
553 if (Target.Fn->arg_size() != Args.size() + 1)
554 return false;
555 for (unsigned I = 0; I != Args.size(); ++I)
556 if (Target.Fn->getFunctionType()->getParamType(I + 1) !=
557 Args[I]->getType())
558 return false;
559
560 Evaluator Eval(M.getDataLayout(), nullptr);
561 SmallVector<Constant *, 2> EvalArgs;
562 EvalArgs.push_back(
563 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
564 EvalArgs.insert(EvalArgs.end(), Args.begin(), Args.end());
565 Constant *RetVal;
566 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
567 !isa<ConstantInt>(RetVal))
568 return false;
569 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
570 }
571 return true;
572}
573
574bool DevirtModule::tryUniformRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000575 IntegerType *RetType, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000576 MutableArrayRef<VirtualCallSite> CallSites) {
577 // Uniform return value optimization. If all functions return the same
578 // constant, replace all calls with that constant.
579 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
580 for (const VirtualCallTarget &Target : TargetsForSlot)
581 if (Target.RetVal != TheRetVal)
582 return false;
583
584 auto TheRetValConst = ConstantInt::get(RetType, TheRetVal);
585 for (auto Call : CallSites)
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000586 Call.replaceAndErase("uniform-ret-val", TargetsForSlot[0].Fn->getName(),
587 RemarksEnabled, TheRetValConst);
588 if (RemarksEnabled)
589 for (auto &&Target : TargetsForSlot)
590 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000591 return true;
592}
593
594bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000595 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000596 MutableArrayRef<VirtualCallSite> CallSites) {
597 // IsOne controls whether we look for a 0 or a 1.
598 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000599 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000600 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000601 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000602 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000603 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000604 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000605 }
606 }
607
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000608 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000609 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000610 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000611
612 // Replace each call with the comparison.
613 for (auto &&Call : CallSites) {
614 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000615 Value *OneAddr = B.CreateBitCast(UniqueMember->Bits->GV, Int8PtrTy);
616 OneAddr = B.CreateConstGEP1_64(OneAddr, UniqueMember->Offset);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000617 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
618 Call.VTable, OneAddr);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000619 Call.replaceAndErase("unique-ret-val", TargetsForSlot[0].Fn->getName(),
620 RemarksEnabled, Cmp);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000621 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000622 // Update devirtualization statistics for targets.
623 if (RemarksEnabled)
624 for (auto &&Target : TargetsForSlot)
625 Target.WasDevirt = true;
626
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000627 return true;
628 };
629
630 if (BitWidth == 1) {
631 if (tryUniqueRetValOptFor(true))
632 return true;
633 if (tryUniqueRetValOptFor(false))
634 return true;
635 }
636 return false;
637}
638
639bool DevirtModule::tryVirtualConstProp(
640 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
641 ArrayRef<VirtualCallSite> CallSites) {
642 // This only works if the function returns an integer.
643 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
644 if (!RetType)
645 return false;
646 unsigned BitWidth = RetType->getBitWidth();
647 if (BitWidth > 64)
648 return false;
649
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000650 // Make sure that each function is defined, does not access memory, takes at
651 // least one argument, does not use its first argument (which we assume is
652 // 'this'), and has the same return type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000653 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000654 if (Target.Fn->isDeclaration() || !Target.Fn->doesNotAccessMemory() ||
655 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000656 Target.Fn->getReturnType() != RetType)
657 return false;
658 }
659
660 // Group call sites by the list of constant arguments they pass.
661 // The comparator ensures deterministic ordering.
662 struct ByAPIntValue {
663 bool operator()(const std::vector<ConstantInt *> &A,
664 const std::vector<ConstantInt *> &B) const {
665 return std::lexicographical_compare(
666 A.begin(), A.end(), B.begin(), B.end(),
667 [](ConstantInt *AI, ConstantInt *BI) {
668 return AI->getValue().ult(BI->getValue());
669 });
670 }
671 };
672 std::map<std::vector<ConstantInt *>, std::vector<VirtualCallSite>,
673 ByAPIntValue>
674 VCallSitesByConstantArg;
675 for (auto &&VCallSite : CallSites) {
676 std::vector<ConstantInt *> Args;
677 if (VCallSite.CS.getType() != RetType)
678 continue;
679 for (auto &&Arg :
680 make_range(VCallSite.CS.arg_begin() + 1, VCallSite.CS.arg_end())) {
681 if (!isa<ConstantInt>(Arg))
682 break;
683 Args.push_back(cast<ConstantInt>(&Arg));
684 }
685 if (Args.size() + 1 != VCallSite.CS.arg_size())
686 continue;
687
688 VCallSitesByConstantArg[Args].push_back(VCallSite);
689 }
690
691 for (auto &&CSByConstantArg : VCallSitesByConstantArg) {
692 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
693 continue;
694
695 if (tryUniformRetValOpt(RetType, TargetsForSlot, CSByConstantArg.second))
696 continue;
697
698 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
699 continue;
700
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000701 // Find an allocation offset in bits in all vtables associated with the
702 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000703 uint64_t AllocBefore =
704 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
705 uint64_t AllocAfter =
706 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
707
708 // Calculate the total amount of padding needed to store a value at both
709 // ends of the object.
710 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
711 for (auto &&Target : TargetsForSlot) {
712 TotalPaddingBefore += std::max<int64_t>(
713 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
714 TotalPaddingAfter += std::max<int64_t>(
715 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
716 }
717
718 // If the amount of padding is too large, give up.
719 // FIXME: do something smarter here.
720 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
721 continue;
722
723 // Calculate the offset to the value as a (possibly negative) byte offset
724 // and (if applicable) a bit offset, and store the values in the targets.
725 int64_t OffsetByte;
726 uint64_t OffsetBit;
727 if (TotalPaddingBefore <= TotalPaddingAfter)
728 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
729 OffsetBit);
730 else
731 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
732 OffsetBit);
733
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000734 if (RemarksEnabled)
735 for (auto &&Target : TargetsForSlot)
736 Target.WasDevirt = true;
737
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000738 // Rewrite each call to a load from OffsetByte/OffsetBit.
739 for (auto Call : CSByConstantArg.second) {
740 IRBuilder<> B(Call.CS.getInstruction());
741 Value *Addr = B.CreateConstGEP1_64(Call.VTable, OffsetByte);
742 if (BitWidth == 1) {
743 Value *Bits = B.CreateLoad(Addr);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +0000744 Value *Bit = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000745 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
746 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000747 Call.replaceAndErase("virtual-const-prop-1-bit",
748 TargetsForSlot[0].Fn->getName(),
749 RemarksEnabled, IsBitSet);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000750 } else {
751 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
752 Value *Val = B.CreateLoad(RetType, ValAddr);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000753 Call.replaceAndErase("virtual-const-prop",
754 TargetsForSlot[0].Fn->getName(),
755 RemarksEnabled, Val);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000756 }
757 }
758 }
759 return true;
760}
761
762void DevirtModule::rebuildGlobal(VTableBits &B) {
763 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
764 return;
765
766 // Align each byte array to pointer width.
767 unsigned PointerSize = M.getDataLayout().getPointerSize();
768 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
769 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
770
771 // Before was stored in reverse order; flip it now.
772 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
773 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
774
775 // Build an anonymous global containing the before bytes, followed by the
776 // original initializer, followed by the after bytes.
777 auto NewInit = ConstantStruct::getAnon(
778 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
779 B.GV->getInitializer(),
780 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
781 auto NewGV =
782 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
783 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
784 NewGV->setSection(B.GV->getSection());
785 NewGV->setComdat(B.GV->getComdat());
786
Peter Collingbourne0312f612016-06-25 00:23:04 +0000787 // Copy the original vtable's metadata to the anonymous global, adjusting
788 // offsets as required.
789 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
790
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000791 // Build an alias named after the original global, pointing at the second
792 // element (the original initializer).
793 auto Alias = GlobalAlias::create(
794 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
795 ConstantExpr::getGetElementPtr(
796 NewInit->getType(), NewGV,
797 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
798 ConstantInt::get(Int32Ty, 1)}),
799 &M);
800 Alias->setVisibility(B.GV->getVisibility());
801 Alias->takeName(B.GV);
802
803 B.GV->replaceAllUsesWith(Alias);
804 B.GV->eraseFromParent();
805}
806
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000807bool DevirtModule::areRemarksEnabled() {
808 const auto &FL = M.getFunctionList();
809 if (FL.empty())
810 return false;
811 const Function &Fn = FL.front();
Adam Nemet04758ba2016-09-27 22:19:23 +0000812 auto DI = OptimizationRemark(DEBUG_TYPE, Fn, DebugLoc(), "");
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000813 return DI.isEnabled();
814}
815
Peter Collingbourne0312f612016-06-25 00:23:04 +0000816void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
817 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000818 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000819 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
820 // points to a member of the type identifier %md. Group calls by (type ID,
821 // offset) pair (effectively the identity of the virtual function) and store
822 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000823 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000824 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000825 I != E;) {
826 auto CI = dyn_cast<CallInst>(I->getUser());
827 ++I;
828 if (!CI)
829 continue;
830
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000831 // Search for virtual calls based on %p and add them to DevirtCalls.
832 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000833 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +0000834 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000835
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000836 // If we found any, add them to CallSlots. Only do this if we haven't seen
837 // the vtable pointer before, as it may have been CSE'd with pointers from
838 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000839 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000840 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000841 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
842 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000843 if (SeenPtrs.insert(Ptr).second) {
844 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000845 CallSlots[{TypeId, Call.Offset}].push_back(
Peter Collingbourne0312f612016-06-25 00:23:04 +0000846 {CI->getArgOperand(0), Call.CS, nullptr});
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000847 }
848 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000849 }
850
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000851 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000852 for (auto Assume : Assumes)
853 Assume->eraseFromParent();
854 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
855 // may use the vtable argument later.
856 if (CI->use_empty())
857 CI->eraseFromParent();
858 }
Peter Collingbourne0312f612016-06-25 00:23:04 +0000859}
860
861void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
862 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
863
864 for (auto I = TypeCheckedLoadFunc->use_begin(),
865 E = TypeCheckedLoadFunc->use_end();
866 I != E;) {
867 auto CI = dyn_cast<CallInst>(I->getUser());
868 ++I;
869 if (!CI)
870 continue;
871
872 Value *Ptr = CI->getArgOperand(0);
873 Value *Offset = CI->getArgOperand(1);
874 Value *TypeIdValue = CI->getArgOperand(2);
875 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
876
877 SmallVector<DevirtCallSite, 1> DevirtCalls;
878 SmallVector<Instruction *, 1> LoadedPtrs;
879 SmallVector<Instruction *, 1> Preds;
880 bool HasNonCallUses = false;
881 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
882 HasNonCallUses, CI);
883
884 // Start by generating "pessimistic" code that explicitly loads the function
885 // pointer from the vtable and performs the type check. If possible, we will
886 // eliminate the load and the type check later.
887
888 // If possible, only generate the load at the point where it is used.
889 // This helps avoid unnecessary spills.
890 IRBuilder<> LoadB(
891 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
892 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
893 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
894 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
895
896 for (Instruction *LoadedPtr : LoadedPtrs) {
897 LoadedPtr->replaceAllUsesWith(LoadedValue);
898 LoadedPtr->eraseFromParent();
899 }
900
901 // Likewise for the type test.
902 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
903 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
904
905 for (Instruction *Pred : Preds) {
906 Pred->replaceAllUsesWith(TypeTestCall);
907 Pred->eraseFromParent();
908 }
909
910 // We have already erased any extractvalue instructions that refer to the
911 // intrinsic call, but the intrinsic may have other non-extractvalue uses
912 // (although this is unlikely). In that case, explicitly build a pair and
913 // RAUW it.
914 if (!CI->use_empty()) {
915 Value *Pair = UndefValue::get(CI->getType());
916 IRBuilder<> B(CI);
917 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
918 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
919 CI->replaceAllUsesWith(Pair);
920 }
921
922 // The number of unsafe uses is initially the number of uses.
923 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
924 NumUnsafeUses = DevirtCalls.size();
925
926 // If the function pointer has a non-call user, we cannot eliminate the type
927 // check, as one of those users may eventually call the pointer. Increment
928 // the unsafe use count to make sure it cannot reach zero.
929 if (HasNonCallUses)
930 ++NumUnsafeUses;
931 for (DevirtCallSite Call : DevirtCalls) {
932 CallSlots[{TypeId, Call.Offset}].push_back(
933 {Ptr, Call.CS, &NumUnsafeUses});
934 }
935
936 CI->eraseFromParent();
937 }
938}
939
940bool DevirtModule::run() {
941 Function *TypeTestFunc =
942 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
943 Function *TypeCheckedLoadFunc =
944 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
945 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
946
947 if ((!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
948 AssumeFunc->use_empty()) &&
949 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
950 return false;
951
952 if (TypeTestFunc && AssumeFunc)
953 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
954
955 if (TypeCheckedLoadFunc)
956 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000957
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000958 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000959 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000960 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
961 buildTypeIdentifierMap(Bits, TypeIdMap);
962 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000963 return true;
964
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000965 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000966 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000967 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000968 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000969 // Search each of the members of the type identifier for the virtual
970 // function implementation at offset S.first.ByteOffset, and add to
971 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000972 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000973 if (!tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000974 S.first.ByteOffset))
975 continue;
976
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000977 if (!trySingleImplDevirt(TargetsForSlot, S.second) &&
978 tryVirtualConstProp(TargetsForSlot, S.second))
979 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000980
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000981 // Collect functions devirtualized at least for one call site for stats.
982 if (RemarksEnabled)
983 for (const auto &T : TargetsForSlot)
984 if (T.WasDevirt)
985 DevirtTargets[T.Fn->getName()] = T.Fn;
986 }
987
988 if (RemarksEnabled) {
989 // Generate remarks for each devirtualized function.
990 for (const auto &DT : DevirtTargets) {
991 Function *F = DT.second;
992 DISubprogram *SP = F->getSubprogram();
993 DebugLoc DL = SP ? DebugLoc::get(SP->getScopeLine(), 0, SP) : DebugLoc();
994 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, DL,
995 Twine("devirtualized ") + F->getName());
Ivan Krasinb05e06e2016-08-05 19:45:16 +0000996 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000997 }
998
Peter Collingbourne0312f612016-06-25 00:23:04 +0000999 // If we were able to eliminate all unsafe uses for a type checked load,
1000 // eliminate the type test by replacing it with true.
1001 if (TypeCheckedLoadFunc) {
1002 auto True = ConstantInt::getTrue(M.getContext());
1003 for (auto &&U : NumUnsafeUsesForTypeTest) {
1004 if (U.second == 0) {
1005 U.first->replaceAllUsesWith(True);
1006 U.first->eraseFromParent();
1007 }
1008 }
1009 }
1010
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001011 // Rebuild each global we touched as part of virtual constant propagation to
1012 // include the before and after bytes.
1013 if (DidVirtualConstProp)
1014 for (VTableBits &B : Bits)
1015 rebuildGlobal(B);
1016
1017 return true;
1018}