blob: 5c5ddf4a38c8393bcd8883a7d7caaddb808630f9 [file] [log] [blame]
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001//===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements whole program optimization of virtual calls in cases
Peter Collingbourne7efd7502016-06-24 21:21:32 +000010// where we know (via !type metadata) that the list of callees is fixed. This
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000011// includes the following:
12// - Single implementation devirtualization: if a virtual call has a single
13// possible callee, replace all calls with a direct call to that callee.
14// - Virtual constant propagation: if the virtual function's return type is an
15// integer <=64 bits and all possible callees are readnone, for each class and
16// each list of constant arguments: evaluate the function, store the return
17// value alongside the virtual table, and rewrite each virtual call as a load
18// from the virtual table.
19// - Uniform return value optimization: if the conditions for virtual constant
20// propagation hold and each function returns the same constant value, replace
21// each virtual call with that constant.
22// - Unique return value optimization for i1 return values: if the conditions
23// for virtual constant propagation hold and a single vtable's function
24// returns 0, or a single vtable's function returns 1, replace each virtual
25// call with a comparison of the vptr against that vtable's address.
26//
Teresa Johnsond2df54e2019-08-02 13:10:52 +000027// This pass is intended to be used during the regular and thin LTO pipelines:
28//
Peter Collingbourneb406baa2017-03-04 01:23:30 +000029// 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
Teresa Johnsond2df54e2019-08-02 13:10:52 +000032// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics).
33//
34// During hybrid Regular/ThinLTO, the pass operates in two phases:
Peter Collingbourneb406baa2017-03-04 01:23:30 +000035// - Export phase: this is run during the thin link over a single merged module
36// that contains all vtables with !type metadata that participate in the link.
37// The pass computes a resolution for each virtual call and stores it in the
38// type identifier summary.
39// - Import phase: this is run during the thin backends over the individual
40// modules. The pass applies the resolutions previously computed during the
41// import phase to each eligible virtual call.
42//
Teresa Johnsond2df54e2019-08-02 13:10:52 +000043// During ThinLTO, the pass operates in two phases:
44// - Export phase: this is run during the thin link over the index which
45// contains a summary of all vtables with !type metadata that participate in
46// the link. It computes a resolution for each virtual call and stores it in
47// the type identifier summary. Only single implementation devirtualization
48// is supported.
49// - Import phase: (same as with hybrid case above).
50//
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000051//===----------------------------------------------------------------------===//
52
53#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000054#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000055#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/DenseMapInfo.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000057#include "llvm/ADT/DenseSet.h"
58#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000060#include "llvm/ADT/iterator_range.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000061#include "llvm/Analysis/AliasAnalysis.h"
62#include "llvm/Analysis/BasicAliasAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000063#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000064#include "llvm/Analysis/TypeMetadataUtils.h"
Evgeny Leviant8973fae2020-01-24 00:31:39 -080065#include "llvm/Bitcode/BitcodeReader.h"
66#include "llvm/Bitcode/BitcodeWriter.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000067#include "llvm/IR/CallSite.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DataLayout.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000070#include "llvm/IR/DebugLoc.h"
71#include "llvm/IR/DerivedTypes.h"
Teresa Johnsonf24136f2018-09-27 14:55:32 +000072#include "llvm/IR/Dominators.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000073#include "llvm/IR/Function.h"
74#include "llvm/IR/GlobalAlias.h"
75#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000076#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000077#include "llvm/IR/InstrTypes.h"
78#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000079#include "llvm/IR/Instructions.h"
80#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000081#include "llvm/IR/LLVMContext.h"
82#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000083#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000084#include "llvm/IR/ModuleSummaryIndexYAML.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080085#include "llvm/InitializePasses.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000086#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000087#include "llvm/PassRegistry.h"
88#include "llvm/PassSupport.h"
89#include "llvm/Support/Casting.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080090#include "llvm/Support/CommandLine.h"
Evgeny Leviant8973fae2020-01-24 00:31:39 -080091#include "llvm/Support/Errc.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000092#include "llvm/Support/Error.h"
93#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000094#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000095#include "llvm/Transforms/IPO.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000096#include "llvm/Transforms/IPO/FunctionAttrs.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000097#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000098#include <algorithm>
99#include <cstddef>
100#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000101#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000102#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000103
104using namespace llvm;
105using namespace wholeprogramdevirt;
106
107#define DEBUG_TYPE "wholeprogramdevirt"
108
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000109static cl::opt<PassSummaryAction> ClSummaryAction(
110 "wholeprogramdevirt-summary-action",
111 cl::desc("What to do with the summary when running this pass"),
112 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
113 clEnumValN(PassSummaryAction::Import, "import",
114 "Import typeid resolutions from summary and globals"),
115 clEnumValN(PassSummaryAction::Export, "export",
116 "Export typeid resolutions to summary and globals")),
117 cl::Hidden);
118
119static cl::opt<std::string> ClReadSummary(
120 "wholeprogramdevirt-read-summary",
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800121 cl::desc(
122 "Read summary from given bitcode or YAML file before running pass"),
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000123 cl::Hidden);
124
125static cl::opt<std::string> ClWriteSummary(
126 "wholeprogramdevirt-write-summary",
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800127 cl::desc("Write summary to given bitcode or YAML file after running pass. "
128 "Output file format is deduced from extension: *.bc means writing "
129 "bitcode, otherwise YAML"),
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000130 cl::Hidden);
131
Vitaly Buka9cb59b92018-04-06 21:41:17 +0000132static cl::opt<unsigned>
133 ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
134 cl::init(10), cl::ZeroOrMore,
135 cl::desc("Maximum number of call targets per "
136 "call site to enable branch funnels"));
Vitaly Buka66f53d72018-04-06 21:32:36 +0000137
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000138static cl::opt<bool>
139 PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden,
140 cl::init(false), cl::ZeroOrMore,
141 cl::desc("Print index-based devirtualization messages"));
142
Teresa Johnson2f63d542020-01-24 12:24:18 -0800143/// Provide a way to force enable whole program visibility in tests.
144/// This is needed to support legacy tests that don't contain
145/// !vcall_visibility metadata (the mere presense of type tests
146/// previously implied hidden visibility).
147cl::opt<bool>
148 WholeProgramVisibility("whole-program-visibility", cl::init(false),
149 cl::Hidden, cl::ZeroOrMore,
150 cl::desc("Enable whole program visibility"));
151
152/// Provide a way to force disable whole program for debugging or workarounds,
153/// when enabled via the linker.
154cl::opt<bool> DisableWholeProgramVisibility(
155 "disable-whole-program-visibility", cl::init(false), cl::Hidden,
156 cl::ZeroOrMore,
157 cl::desc("Disable whole program visibility (overrides enabling options)"));
158
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000159// Find the minimum offset that we may store a value of size Size bits at. If
160// IsAfter is set, look for an offset before the object, otherwise look for an
161// offset after the object.
162uint64_t
163wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
164 bool IsAfter, uint64_t Size) {
165 // Find a minimum offset taking into account only vtable sizes.
166 uint64_t MinByte = 0;
167 for (const VirtualCallTarget &Target : Targets) {
168 if (IsAfter)
169 MinByte = std::max(MinByte, Target.minAfterBytes());
170 else
171 MinByte = std::max(MinByte, Target.minBeforeBytes());
172 }
173
174 // Build a vector of arrays of bytes covering, for each target, a slice of the
175 // used region (see AccumBitVector::BytesUsed in
176 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
177 // this aligns the used regions to start at MinByte.
178 //
179 // In this example, A, B and C are vtables, # is a byte already allocated for
180 // a virtual function pointer, AAAA... (etc.) are the used regions for the
181 // vtables and Offset(X) is the value computed for the Offset variable below
182 // for X.
183 //
184 // Offset(A)
185 // | |
186 // |MinByte
187 // A: ################AAAAAAAA|AAAAAAAA
188 // B: ########BBBBBBBBBBBBBBBB|BBBB
189 // C: ########################|CCCCCCCCCCCCCCCC
190 // | Offset(B) |
191 //
192 // This code produces the slices of A, B and C that appear after the divider
193 // at MinByte.
194 std::vector<ArrayRef<uint8_t>> Used;
195 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000196 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
197 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000198 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
199 : MinByte - Target.minBeforeBytes();
200
201 // Disregard used regions that are smaller than Offset. These are
202 // effectively all-free regions that do not need to be checked.
203 if (VTUsed.size() > Offset)
204 Used.push_back(VTUsed.slice(Offset));
205 }
206
207 if (Size == 1) {
208 // Find a free bit in each member of Used.
209 for (unsigned I = 0;; ++I) {
210 uint8_t BitsUsed = 0;
211 for (auto &&B : Used)
212 if (I < B.size())
213 BitsUsed |= B[I];
214 if (BitsUsed != 0xff)
215 return (MinByte + I) * 8 +
216 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
217 }
218 } else {
219 // Find a free (Size/8) byte region in each member of Used.
220 // FIXME: see if alignment helps.
221 for (unsigned I = 0;; ++I) {
222 for (auto &&B : Used) {
223 unsigned Byte = 0;
224 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
225 if (B[I + Byte])
226 goto NextI;
227 ++Byte;
228 }
229 }
230 return (MinByte + I) * 8;
231 NextI:;
232 }
233 }
234}
235
236void wholeprogramdevirt::setBeforeReturnValues(
237 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
238 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
239 if (BitWidth == 1)
240 OffsetByte = -(AllocBefore / 8 + 1);
241 else
242 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
243 OffsetBit = AllocBefore % 8;
244
245 for (VirtualCallTarget &Target : Targets) {
246 if (BitWidth == 1)
247 Target.setBeforeBit(AllocBefore);
248 else
249 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
250 }
251}
252
253void wholeprogramdevirt::setAfterReturnValues(
254 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
255 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
256 if (BitWidth == 1)
257 OffsetByte = AllocAfter / 8;
258 else
259 OffsetByte = (AllocAfter + 7) / 8;
260 OffsetBit = AllocAfter % 8;
261
262 for (VirtualCallTarget &Target : Targets) {
263 if (BitWidth == 1)
264 Target.setAfterBit(AllocAfter);
265 else
266 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
267 }
268}
269
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000270VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
271 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000272 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000273
274namespace {
275
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000276// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000277// tables, and the ByteOffset is the offset in bytes from the address point to
278// the virtual function pointer.
279struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000280 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000281 uint64_t ByteOffset;
282};
283
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000284} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000285
Peter Collingbourne9b656522016-02-09 23:01:38 +0000286namespace llvm {
287
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000288template <> struct DenseMapInfo<VTableSlot> {
289 static VTableSlot getEmptyKey() {
290 return {DenseMapInfo<Metadata *>::getEmptyKey(),
291 DenseMapInfo<uint64_t>::getEmptyKey()};
292 }
293 static VTableSlot getTombstoneKey() {
294 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
295 DenseMapInfo<uint64_t>::getTombstoneKey()};
296 }
297 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000298 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000299 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
300 }
301 static bool isEqual(const VTableSlot &LHS,
302 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000303 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000304 }
305};
306
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000307template <> struct DenseMapInfo<VTableSlotSummary> {
308 static VTableSlotSummary getEmptyKey() {
309 return {DenseMapInfo<StringRef>::getEmptyKey(),
310 DenseMapInfo<uint64_t>::getEmptyKey()};
311 }
312 static VTableSlotSummary getTombstoneKey() {
313 return {DenseMapInfo<StringRef>::getTombstoneKey(),
314 DenseMapInfo<uint64_t>::getTombstoneKey()};
315 }
316 static unsigned getHashValue(const VTableSlotSummary &I) {
317 return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^
318 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
319 }
320 static bool isEqual(const VTableSlotSummary &LHS,
321 const VTableSlotSummary &RHS) {
322 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
323 }
324};
325
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000326} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000327
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000328namespace {
329
330// A virtual call site. VTable is the loaded virtual table pointer, and CS is
331// the indirect virtual call.
332struct VirtualCallSite {
333 Value *VTable;
334 CallSite CS;
335
Peter Collingbourne0312f612016-06-25 00:23:04 +0000336 // If non-null, this field points to the associated unsafe use count stored in
337 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
338 // of that field for details.
339 unsigned *NumUnsafeUses;
340
Sam Elliotte963c892017-08-21 16:57:21 +0000341 void
342 emitRemark(const StringRef OptName, const StringRef TargetName,
343 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Ivan Krasin54746452016-07-12 02:38:37 +0000344 Function *F = CS.getCaller();
Sam Elliotte963c892017-08-21 16:57:21 +0000345 DebugLoc DLoc = CS->getDebugLoc();
346 BasicBlock *Block = CS.getParent();
347
Sam Elliotte963c892017-08-21 16:57:21 +0000348 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000349 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
350 << NV("Optimization", OptName)
351 << ": devirtualized a call to "
352 << NV("FunctionName", TargetName));
Ivan Krasin54746452016-07-12 02:38:37 +0000353 }
354
Sam Elliotte963c892017-08-21 16:57:21 +0000355 void replaceAndErase(
356 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
357 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
358 Value *New) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000359 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000360 emitRemark(OptName, TargetName, OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000361 CS->replaceAllUsesWith(New);
362 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
363 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
364 II->getUnwindDest()->removePredecessor(II->getParent());
365 }
366 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000367 // This use is no longer unsafe.
368 if (NumUnsafeUses)
369 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000370 }
371};
372
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000373// Call site information collected for a specific VTableSlot and possibly a list
374// of constant integer arguments. The grouping by arguments is handled by the
375// VTableSlotInfo class.
376struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000377 /// The set of call sites for this slot. Used during regular LTO and the
378 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
379 /// call sites that appear in the merged module itself); in each of these
380 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000381 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000382
Peter Collingbourne29748562018-03-09 19:11:44 +0000383 /// Whether all call sites represented by this CallSiteInfo, including those
384 /// in summaries, have been devirtualized. This starts off as true because a
385 /// default constructed CallSiteInfo represents no call sites.
386 bool AllCallSitesDevirted = true;
387
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000388 // These fields are used during the export phase of ThinLTO and reflect
389 // information collected from function summaries.
390
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000391 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
392 /// this slot.
Peter Collingbourne29748562018-03-09 19:11:44 +0000393 bool SummaryHasTypeTestAssumeUsers = false;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000394
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000395 /// CFI-specific: a vector containing the list of function summaries that use
396 /// the llvm.type.checked.load intrinsic and therefore will require
397 /// resolutions for llvm.type.test in order to implement CFI checks if
398 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000399 /// pass will clear this vector by calling markDevirt(). If at the end of the
400 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
401 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000402 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000403 std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000404
405 bool isExported() const {
406 return SummaryHasTypeTestAssumeUsers ||
407 !SummaryTypeCheckedLoadUsers.empty();
408 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000409
Peter Collingbourne29748562018-03-09 19:11:44 +0000410 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
411 SummaryTypeCheckedLoadUsers.push_back(FS);
412 AllCallSitesDevirted = false;
413 }
414
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000415 void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
416 SummaryTypeTestAssumeUsers.push_back(FS);
Eugene Leviant943afb52019-10-17 07:46:18 +0000417 SummaryHasTypeTestAssumeUsers = true;
418 AllCallSitesDevirted = false;
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000419 }
420
Peter Collingbourne29748562018-03-09 19:11:44 +0000421 void markDevirt() {
422 AllCallSitesDevirted = true;
423
424 // As explained in the comment for SummaryTypeCheckedLoadUsers.
425 SummaryTypeCheckedLoadUsers.clear();
426 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000427};
428
429// Call site information collected for a specific VTableSlot.
430struct VTableSlotInfo {
431 // The set of call sites which do not have all constant integer arguments
432 // (excluding "this").
433 CallSiteInfo CSInfo;
434
435 // The set of call sites with all constant integer arguments (excluding
436 // "this"), grouped by argument list.
437 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
438
439 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
440
441private:
442 CallSiteInfo &findCallSiteInfo(CallSite CS);
443};
444
445CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
446 std::vector<uint64_t> Args;
447 auto *CI = dyn_cast<IntegerType>(CS.getType());
448 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
449 return CSInfo;
450 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
451 auto *CI = dyn_cast<ConstantInt>(Arg);
452 if (!CI || CI->getBitWidth() > 64)
453 return CSInfo;
454 Args.push_back(CI->getZExtValue());
455 }
456 return ConstCSInfo[Args];
457}
458
459void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
460 unsigned *NumUnsafeUses) {
Peter Collingbourne29748562018-03-09 19:11:44 +0000461 auto &CSI = findCallSiteInfo(CS);
462 CSI.AllCallSitesDevirted = false;
463 CSI.CallSites.push_back({VTable, CS, NumUnsafeUses});
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000464}
465
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000466struct DevirtModule {
467 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000468 function_ref<AAResults &(Function &)> AARGetter;
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000469 function_ref<DominatorTree &(Function &)> LookupDomTree;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000470
Peter Collingbournef7691d82017-03-22 18:22:59 +0000471 ModuleSummaryIndex *ExportSummary;
472 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000473
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000474 IntegerType *Int8Ty;
475 PointerType *Int8PtrTy;
476 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000477 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000478 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000479
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000480 bool RemarksEnabled;
Sam Elliotte963c892017-08-21 16:57:21 +0000481 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000482
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000483 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000484
Peter Collingbourne0312f612016-06-25 00:23:04 +0000485 // This map keeps track of the number of "unsafe" uses of a loaded function
486 // pointer. The key is the associated llvm.type.test intrinsic call generated
487 // by this pass. An unsafe use is one that calls the loaded function pointer
488 // directly. Every time we eliminate an unsafe use (for example, by
489 // devirtualizing it or by applying virtual constant propagation), we
490 // decrement the value stored in this map. If a value reaches zero, we can
491 // eliminate the type check by RAUWing the associated llvm.type.test call with
492 // true.
493 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
494
Peter Collingbourne37317f12017-02-17 18:17:04 +0000495 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Sam Elliotte963c892017-08-21 16:57:21 +0000496 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000497 function_ref<DominatorTree &(Function &)> LookupDomTree,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000498 ModuleSummaryIndex *ExportSummary,
499 const ModuleSummaryIndex *ImportSummary)
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000500 : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree),
501 ExportSummary(ExportSummary), ImportSummary(ImportSummary),
502 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000503 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000504 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000505 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000506 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Sam Elliotte963c892017-08-21 16:57:21 +0000507 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000508 assert(!(ExportSummary && ImportSummary));
509 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000510
511 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000512
Teresa Johnsonc8e36862019-12-06 12:13:34 -0800513 void scanTypeTestUsers(Function *TypeTestFunc);
Peter Collingbourne0312f612016-06-25 00:23:04 +0000514 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
515
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000516 void buildTypeIdentifierMap(
517 std::vector<VTableBits> &Bits,
518 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
519 bool
520 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
521 const std::set<TypeMemberInfo> &TypeMemberInfos,
522 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000523
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000524 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
525 bool &IsExported);
Eugene Leviant943afb52019-10-17 07:46:18 +0000526 bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
527 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000528 VTableSlotInfo &SlotInfo,
529 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000530
Peter Collingbourne29748562018-03-09 19:11:44 +0000531 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
532 bool &IsExported);
533 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
534 VTableSlotInfo &SlotInfo,
535 WholeProgramDevirtResolution *Res, VTableSlot Slot);
536
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000537 bool tryEvaluateFunctionsWithArgs(
538 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000539 ArrayRef<uint64_t> Args);
540
541 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
542 uint64_t TheRetVal);
543 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000544 CallSiteInfo &CSInfo,
545 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000546
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000547 // Returns the global symbol name that is used to export information about the
548 // given vtable slot and list of arguments.
549 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
550 StringRef Name);
551
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000552 bool shouldExportConstantsAsAbsoluteSymbols();
553
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000554 // This function is called during the export phase to create a symbol
555 // definition containing information about the given vtable slot and list of
556 // arguments.
557 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
558 Constant *C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000559 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
560 uint32_t Const, uint32_t &Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000561
562 // This function is called during the import phase to create a reference to
563 // the symbol definition created during the export phase.
564 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000565 StringRef Name);
566 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
567 StringRef Name, IntegerType *IntTy,
568 uint32_t Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000569
Peter Collingbourne29748562018-03-09 19:11:44 +0000570 Constant *getMemberAddr(const TypeMemberInfo *M);
571
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000572 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
573 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000574 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000575 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000576 CallSiteInfo &CSInfo,
577 WholeProgramDevirtResolution::ByArg *Res,
578 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000579
580 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
581 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000582 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000583 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000584 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000585
586 void rebuildGlobal(VTableBits &B);
587
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000588 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
589 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
590
591 // If we were able to eliminate all unsafe uses for a type checked load,
592 // eliminate the associated type tests by replacing them with true.
593 void removeRedundantTypeTests();
594
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000595 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000596
597 // Lower the module using the action and summary passed as command line
598 // arguments. For testing purposes only.
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000599 static bool
600 runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter,
601 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
602 function_ref<DominatorTree &(Function &)> LookupDomTree);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000603};
604
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000605struct DevirtIndex {
606 ModuleSummaryIndex &ExportSummary;
607 // The set in which to record GUIDs exported from their module by
608 // devirtualization, used by client to ensure they are not internalized.
609 std::set<GlobalValue::GUID> &ExportedGUIDs;
610 // A map in which to record the information necessary to locate the WPD
611 // resolution for local targets in case they are exported by cross module
612 // importing.
613 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
614
615 MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
616
617 DevirtIndex(
618 ModuleSummaryIndex &ExportSummary,
619 std::set<GlobalValue::GUID> &ExportedGUIDs,
620 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap)
621 : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
622 LocalWPDTargetsMap(LocalWPDTargetsMap) {}
623
624 bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
625 const TypeIdCompatibleVtableInfo TIdInfo,
626 uint64_t ByteOffset);
627
628 bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
629 VTableSlotSummary &SlotSummary,
630 VTableSlotInfo &SlotInfo,
631 WholeProgramDevirtResolution *Res,
632 std::set<ValueInfo> &DevirtTargets);
633
634 void run();
635};
636
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000637struct WholeProgramDevirt : public ModulePass {
638 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000639
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000640 bool UseCommandLine = false;
641
Simon Pilgrim39c08292019-11-14 13:54:29 +0000642 ModuleSummaryIndex *ExportSummary = nullptr;
643 const ModuleSummaryIndex *ImportSummary = nullptr;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000644
645 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
646 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
647 }
648
Peter Collingbournef7691d82017-03-22 18:22:59 +0000649 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
650 const ModuleSummaryIndex *ImportSummary)
651 : ModulePass(ID), ExportSummary(ExportSummary),
652 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000653 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
654 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000655
656 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000657 if (skipModule(M))
658 return false;
Sam Elliotte963c892017-08-21 16:57:21 +0000659
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000660 // In the new pass manager, we can request the optimization
661 // remark emitter pass on a per-function-basis, which the
662 // OREGetter will do for us.
663 // In the old pass manager, this is harder, so we just build
664 // an optimization remark emitter on the fly, when we need it.
665 std::unique_ptr<OptimizationRemarkEmitter> ORE;
666 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000667 ORE = std::make_unique<OptimizationRemarkEmitter>(F);
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000668 return *ORE;
669 };
Sam Elliotte963c892017-08-21 16:57:21 +0000670
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000671 auto LookupDomTree = [this](Function &F) -> DominatorTree & {
672 return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
673 };
Sam Elliotte963c892017-08-21 16:57:21 +0000674
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000675 if (UseCommandLine)
676 return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter,
677 LookupDomTree);
678
679 return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree,
680 ExportSummary, ImportSummary)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000681 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000682 }
683
684 void getAnalysisUsage(AnalysisUsage &AU) const override {
685 AU.addRequired<AssumptionCacheTracker>();
686 AU.addRequired<TargetLibraryInfoWrapperPass>();
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000687 AU.addRequired<DominatorTreeWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000688 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000689};
690
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000691} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000692
Peter Collingbourne37317f12017-02-17 18:17:04 +0000693INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
694 "Whole program devirtualization", false, false)
695INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
696INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000697INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000698INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
699 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000700char WholeProgramDevirt::ID = 0;
701
Peter Collingbournef7691d82017-03-22 18:22:59 +0000702ModulePass *
703llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
704 const ModuleSummaryIndex *ImportSummary) {
705 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000706}
707
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000708PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000709 ModuleAnalysisManager &AM) {
710 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
711 auto AARGetter = [&](Function &F) -> AAResults & {
712 return FAM.getResult<AAManager>(F);
713 };
Sam Elliotte963c892017-08-21 16:57:21 +0000714 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
715 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
716 };
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000717 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {
718 return FAM.getResult<DominatorTreeAnalysis>(F);
719 };
720 if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary,
721 ImportSummary)
Teresa Johnson28023db2018-07-19 14:51:32 +0000722 .run())
Davide Italianod737dd22016-06-14 21:44:19 +0000723 return PreservedAnalyses::all();
724 return PreservedAnalyses::none();
725}
726
Teresa Johnson2f63d542020-01-24 12:24:18 -0800727// Enable whole program visibility if enabled by client (e.g. linker) or
728// internal option, and not force disabled.
729static bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) {
730 return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) &&
731 !DisableWholeProgramVisibility;
732}
733
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000734namespace llvm {
Teresa Johnson2f63d542020-01-24 12:24:18 -0800735
736/// If whole program visibility asserted, then upgrade all public vcall
737/// visibility metadata on vtable definitions to linkage unit visibility in
738/// Module IR (for regular or hybrid LTO).
739void updateVCallVisibilityInModule(Module &M,
740 bool WholeProgramVisibilityEnabledInLTO) {
741 if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
742 return;
743 for (GlobalVariable &GV : M.globals())
744 // Add linkage unit visibility to any variable with type metadata, which are
745 // the vtable definitions. We won't have an existing vcall_visibility
746 // metadata on vtable definitions with public visibility.
747 if (GV.hasMetadata(LLVMContext::MD_type) &&
748 GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
749 GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit);
750}
751
752/// If whole program visibility asserted, then upgrade all public vcall
753/// visibility metadata on vtable definition summaries to linkage unit
754/// visibility in Module summary index (for ThinLTO).
755void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index,
756 bool WholeProgramVisibilityEnabledInLTO) {
757 if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
758 return;
759 for (auto &P : Index) {
760 for (auto &S : P.second.SummaryList) {
761 auto *GVar = dyn_cast<GlobalVarSummary>(S.get());
762 if (!GVar || GVar->vTableFuncs().empty() ||
763 GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic)
764 continue;
765 GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit);
766 }
767 }
768}
769
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000770void runWholeProgramDevirtOnIndex(
771 ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
772 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
773 DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run();
774}
775
776void updateIndexWPDForExports(
777 ModuleSummaryIndex &Summary,
evgeny3d708bf2019-11-15 16:13:19 +0300778 function_ref<bool(StringRef, ValueInfo)> isExported,
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000779 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
780 for (auto &T : LocalWPDTargetsMap) {
781 auto &VI = T.first;
782 // This was enforced earlier during trySingleImplDevirt.
783 assert(VI.getSummaryList().size() == 1 &&
784 "Devirt of local target has more than one copy");
785 auto &S = VI.getSummaryList()[0];
evgeny3d708bf2019-11-15 16:13:19 +0300786 if (!isExported(S->modulePath(), VI))
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000787 continue;
788
789 // It's been exported by a cross module import.
790 for (auto &SlotSummary : T.second) {
791 auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
792 assert(TIdSum);
793 auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
794 assert(WPDRes != TIdSum->WPDRes.end());
795 WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
796 WPDRes->second.SingleImplName,
797 Summary.getModuleHash(S->modulePath()));
798 }
799 }
800}
801
802} // end namespace llvm
803
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800804static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) {
805 // Check that summary index contains regular LTO module when performing
806 // export to prevent occasional use of index from pure ThinLTO compilation
807 // (-fno-split-lto-module). This kind of summary index is passed to
808 // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting.
809 const auto &ModPaths = Summary->modulePaths();
810 if (ClSummaryAction != PassSummaryAction::Import &&
811 ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) ==
812 ModPaths.end())
813 return createStringError(
814 errc::invalid_argument,
815 "combined summary should contain Regular LTO module");
816 return ErrorSuccess();
817}
818
Peter Collingbourne37317f12017-02-17 18:17:04 +0000819bool DevirtModule::runForTesting(
Sam Elliotte963c892017-08-21 16:57:21 +0000820 Module &M, function_ref<AAResults &(Function &)> AARGetter,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000821 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
822 function_ref<DominatorTree &(Function &)> LookupDomTree) {
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800823 std::unique_ptr<ModuleSummaryIndex> Summary =
824 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000825
826 // Handle the command-line summary arguments. This code is for testing
827 // purposes only, so we handle errors directly.
828 if (!ClReadSummary.empty()) {
829 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
830 ": ");
831 auto ReadSummaryFile =
832 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800833 if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
834 getModuleSummaryIndex(*ReadSummaryFile)) {
835 Summary = std::move(*SummaryOrErr);
836 ExitOnErr(checkCombinedSummaryForTesting(Summary.get()));
837 } else {
838 // Try YAML if we've failed with bitcode.
839 consumeError(SummaryOrErr.takeError());
840 yaml::Input In(ReadSummaryFile->getBuffer());
841 In >> *Summary;
842 ExitOnErr(errorCodeToError(In.error()));
843 }
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000844 }
845
Peter Collingbournef7691d82017-03-22 18:22:59 +0000846 bool Changed =
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800847 DevirtModule(M, AARGetter, OREGetter, LookupDomTree,
848 ClSummaryAction == PassSummaryAction::Export ? Summary.get()
849 : nullptr,
850 ClSummaryAction == PassSummaryAction::Import ? Summary.get()
851 : nullptr)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000852 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000853
854 if (!ClWriteSummary.empty()) {
855 ExitOnError ExitOnErr(
856 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
857 std::error_code EC;
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800858 if (StringRef(ClWriteSummary).endswith(".bc")) {
859 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None);
860 ExitOnErr(errorCodeToError(EC));
861 WriteIndexToFile(*Summary, OS);
862 } else {
863 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_Text);
864 ExitOnErr(errorCodeToError(EC));
865 yaml::Output Out(OS);
866 Out << *Summary;
867 }
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000868 }
869
870 return Changed;
871}
872
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000873void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000874 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000875 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000876 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000877 Bits.reserve(M.getGlobalList().size());
878 SmallVector<MDNode *, 2> Types;
879 for (GlobalVariable &GV : M.globals()) {
880 Types.clear();
881 GV.getMetadata(LLVMContext::MD_type, Types);
Eugene Leviant2b70d612018-09-23 13:27:47 +0000882 if (GV.isDeclaration() || Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000883 continue;
884
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000885 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000886 if (!BitsPtr) {
887 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000888 Bits.back().GV = &GV;
889 Bits.back().ObjectSize =
890 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000891 BitsPtr = &Bits.back();
892 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000893
894 for (MDNode *Type : Types) {
895 auto TypeID = Type->getOperand(1).get();
896
897 uint64_t Offset =
898 cast<ConstantInt>(
899 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
900 ->getZExtValue();
901
902 TypeIdMap[TypeID].insert({BitsPtr, Offset});
903 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000904 }
905}
906
907bool DevirtModule::tryFindVirtualCallTargets(
908 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000909 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
910 for (const TypeMemberInfo &TM : TypeMemberInfos) {
911 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000912 return false;
913
Teresa Johnson2f63d542020-01-24 12:24:18 -0800914 // We cannot perform whole program devirtualization analysis on a vtable
915 // with public LTO visibility.
916 if (TM.Bits->GV->getVCallVisibility() ==
917 GlobalObject::VCallVisibilityPublic)
918 return false;
919
Peter Collingbourne87867542016-12-09 01:10:11 +0000920 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
Oliver Stannard3b598b92019-10-17 09:58:57 +0000921 TM.Offset + ByteOffset, M);
Peter Collingbourne87867542016-12-09 01:10:11 +0000922 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000923 return false;
924
Peter Collingbourne87867542016-12-09 01:10:11 +0000925 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000926 if (!Fn)
927 return false;
928
929 // We can disregard __cxa_pure_virtual as a possible call target, as
930 // calls to pure virtuals are UB.
931 if (Fn->getName() == "__cxa_pure_virtual")
932 continue;
933
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000934 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000935 }
936
937 // Give up if we couldn't find any targets.
938 return !TargetsForSlot.empty();
939}
940
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000941bool DevirtIndex::tryFindVirtualCallTargets(
942 std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo,
943 uint64_t ByteOffset) {
Mark de Wever098d3342019-12-22 19:20:17 +0100944 for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
Teresa Johnsonc844f882019-10-25 14:56:12 -0700945 // Find the first non-available_externally linkage vtable initializer.
946 // We can have multiple available_externally, linkonce_odr and weak_odr
947 // vtable initializers, however we want to skip available_externally as they
948 // do not have type metadata attached, and therefore the summary will not
Teresa Johnson2cefb932020-01-13 13:50:41 -0800949 // contain any vtable functions. We can also have multiple external
950 // vtable initializers in the case of comdats, which we cannot check here.
951 // The linker should give an error in this case.
Teresa Johnsonc844f882019-10-25 14:56:12 -0700952 //
953 // Also, handle the case of same-named local Vtables with the same path
954 // and therefore the same GUID. This can happen if there isn't enough
955 // distinguishing path when compiling the source file. In that case we
956 // conservatively return false early.
957 const GlobalVarSummary *VS = nullptr;
958 bool LocalFound = false;
959 for (auto &S : P.VTableVI.getSummaryList()) {
960 if (GlobalValue::isLocalLinkage(S->linkage())) {
961 if (LocalFound)
962 return false;
963 LocalFound = true;
964 }
Teresa Johnson2f63d542020-01-24 12:24:18 -0800965 if (!GlobalValue::isAvailableExternallyLinkage(S->linkage())) {
Teresa Johnson31441a32019-12-04 17:15:10 -0800966 VS = cast<GlobalVarSummary>(S->getBaseObject());
Teresa Johnson2f63d542020-01-24 12:24:18 -0800967 // We cannot perform whole program devirtualization analysis on a vtable
968 // with public LTO visibility.
969 if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
970 return false;
971 }
Teresa Johnsonc844f882019-10-25 14:56:12 -0700972 }
973 if (!VS->isLive())
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000974 continue;
975 for (auto VTP : VS->vTableFuncs()) {
976 if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
977 continue;
978
979 TargetsForSlot.push_back(VTP.FuncVI);
980 }
981 }
982
983 // Give up if we couldn't find any targets.
984 return !TargetsForSlot.empty();
985}
986
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000987void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000988 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000989 auto Apply = [&](CallSiteInfo &CSInfo) {
990 for (auto &&VCallSite : CSInfo.CallSites) {
991 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +0000992 VCallSite.emitRemark("single-impl",
993 TheFn->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000994 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
995 TheFn, VCallSite.CS.getCalledValue()->getType()));
996 // This use is no longer unsafe.
997 if (VCallSite.NumUnsafeUses)
998 --*VCallSite.NumUnsafeUses;
999 }
Peter Collingbourne29748562018-03-09 19:11:44 +00001000 if (CSInfo.isExported())
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001001 IsExported = true;
Peter Collingbourne29748562018-03-09 19:11:44 +00001002 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001003 };
1004 Apply(SlotInfo.CSInfo);
1005 for (auto &P : SlotInfo.ConstCSInfo)
1006 Apply(P.second);
1007}
1008
Eugene Leviant943afb52019-10-17 07:46:18 +00001009static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
1010 // We can't add calls if we haven't seen a definition
1011 if (Callee.getSummaryList().empty())
1012 return false;
1013
1014 // Insert calls into the summary index so that the devirtualized targets
1015 // are eligible for import.
1016 // FIXME: Annotate type tests with hotness. For now, mark these as hot
1017 // to better ensure we have the opportunity to inline them.
1018 bool IsExported = false;
1019 auto &S = Callee.getSummaryList()[0];
1020 CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0);
1021 auto AddCalls = [&](CallSiteInfo &CSInfo) {
1022 for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
1023 FS->addCall({Callee, CI});
1024 IsExported |= S->modulePath() != FS->modulePath();
1025 }
1026 for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
1027 FS->addCall({Callee, CI});
1028 IsExported |= S->modulePath() != FS->modulePath();
1029 }
1030 };
1031 AddCalls(SlotInfo.CSInfo);
1032 for (auto &P : SlotInfo.ConstCSInfo)
1033 AddCalls(P.second);
1034 return IsExported;
1035}
1036
Peter Collingbournee2367412017-02-15 02:13:08 +00001037bool DevirtModule::trySingleImplDevirt(
Eugene Leviant943afb52019-10-17 07:46:18 +00001038 ModuleSummaryIndex *ExportSummary,
1039 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1040 WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +00001041 // See if the program contains a single implementation of this virtual
1042 // function.
1043 Function *TheFn = TargetsForSlot[0].Fn;
1044 for (auto &&Target : TargetsForSlot)
1045 if (TheFn != Target.Fn)
1046 return false;
1047
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001048 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +00001049 if (RemarksEnabled)
1050 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001051
1052 bool IsExported = false;
1053 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
1054 if (!IsExported)
1055 return false;
1056
1057 // If the only implementation has local linkage, we must promote to external
1058 // to make it visible to thin LTO objects. We can only get here during the
1059 // ThinLTO export phase.
1060 if (TheFn->hasLocalLinkage()) {
Peter Collingbourne88a58cf2017-09-08 00:10:53 +00001061 std::string NewName = (TheFn->getName() + "$merged").str();
1062
1063 // Since we are renaming the function, any comdats with the same name must
1064 // also be renamed. This is required when targeting COFF, as the comdat name
1065 // must match one of the names of the symbols in the comdat.
1066 if (Comdat *C = TheFn->getComdat()) {
1067 if (C->getName() == TheFn->getName()) {
1068 Comdat *NewC = M.getOrInsertComdat(NewName);
1069 NewC->setSelectionKind(C->getSelectionKind());
1070 for (GlobalObject &GO : M.global_objects())
1071 if (GO.getComdat() == C)
1072 GO.setComdat(NewC);
1073 }
1074 }
1075
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001076 TheFn->setLinkage(GlobalValue::ExternalLinkage);
1077 TheFn->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne88a58cf2017-09-08 00:10:53 +00001078 TheFn->setName(NewName);
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001079 }
Eugene Leviant943afb52019-10-17 07:46:18 +00001080 if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
1081 // Any needed promotion of 'TheFn' has already been done during
1082 // LTO unit split, so we can ignore return value of AddCalls.
1083 AddCalls(SlotInfo, TheFnVI);
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001084
1085 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1086 Res->SingleImplName = TheFn->getName();
1087
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001088 return true;
1089}
1090
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001091bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
1092 VTableSlotSummary &SlotSummary,
1093 VTableSlotInfo &SlotInfo,
1094 WholeProgramDevirtResolution *Res,
1095 std::set<ValueInfo> &DevirtTargets) {
1096 // See if the program contains a single implementation of this virtual
1097 // function.
1098 auto TheFn = TargetsForSlot[0];
1099 for (auto &&Target : TargetsForSlot)
1100 if (TheFn != Target)
1101 return false;
1102
1103 // Don't devirtualize if we don't have target definition.
1104 auto Size = TheFn.getSummaryList().size();
1105 if (!Size)
1106 return false;
1107
1108 // If the summary list contains multiple summaries where at least one is
1109 // a local, give up, as we won't know which (possibly promoted) name to use.
1110 for (auto &S : TheFn.getSummaryList())
1111 if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1)
1112 return false;
1113
1114 // Collect functions devirtualized at least for one call site for stats.
1115 if (PrintSummaryDevirt)
1116 DevirtTargets.insert(TheFn);
1117
1118 auto &S = TheFn.getSummaryList()[0];
Eugene Leviant943afb52019-10-17 07:46:18 +00001119 bool IsExported = AddCalls(SlotInfo, TheFn);
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001120 if (IsExported)
1121 ExportedGUIDs.insert(TheFn.getGUID());
1122
1123 // Record in summary for use in devirtualization during the ThinLTO import
1124 // step.
1125 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1126 if (GlobalValue::isLocalLinkage(S->linkage())) {
1127 if (IsExported)
1128 // If target is a local function and we are exporting it by
1129 // devirtualizing a call in another module, we need to record the
1130 // promoted name.
1131 Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
1132 TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
1133 else {
1134 LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
1135 Res->SingleImplName = TheFn.name();
1136 }
1137 } else
1138 Res->SingleImplName = TheFn.name();
1139
1140 // Name will be empty if this thin link driven off of serialized combined
1141 // index (e.g. llvm-lto). However, WPD is not supported/invoked for the
1142 // legacy LTO API anyway.
1143 assert(!Res->SingleImplName.empty());
1144
1145 return true;
1146}
1147
Peter Collingbourne29748562018-03-09 19:11:44 +00001148void DevirtModule::tryICallBranchFunnel(
1149 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1150 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1151 Triple T(M.getTargetTriple());
1152 if (T.getArch() != Triple::x86_64)
1153 return;
1154
Vitaly Buka66f53d72018-04-06 21:32:36 +00001155 if (TargetsForSlot.size() > ClThreshold)
Peter Collingbourne29748562018-03-09 19:11:44 +00001156 return;
1157
1158 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
1159 if (!HasNonDevirt)
1160 for (auto &P : SlotInfo.ConstCSInfo)
1161 if (!P.second.AllCallSitesDevirted) {
1162 HasNonDevirt = true;
1163 break;
1164 }
1165
1166 if (!HasNonDevirt)
1167 return;
1168
1169 FunctionType *FT =
1170 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
1171 Function *JT;
1172 if (isa<MDString>(Slot.TypeID)) {
1173 JT = Function::Create(FT, Function::ExternalLinkage,
Dylan McKayf920da02018-12-18 09:52:52 +00001174 M.getDataLayout().getProgramAddressSpace(),
Peter Collingbourne29748562018-03-09 19:11:44 +00001175 getGlobalName(Slot, {}, "branch_funnel"), &M);
1176 JT->setVisibility(GlobalValue::HiddenVisibility);
1177 } else {
Dylan McKayf920da02018-12-18 09:52:52 +00001178 JT = Function::Create(FT, Function::InternalLinkage,
1179 M.getDataLayout().getProgramAddressSpace(),
1180 "branch_funnel", &M);
Peter Collingbourne29748562018-03-09 19:11:44 +00001181 }
1182 JT->addAttribute(1, Attribute::Nest);
1183
1184 std::vector<Value *> JTArgs;
1185 JTArgs.push_back(JT->arg_begin());
1186 for (auto &T : TargetsForSlot) {
1187 JTArgs.push_back(getMemberAddr(T.TM));
1188 JTArgs.push_back(T.Fn);
1189 }
1190
1191 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
James Y Knight7976eb52019-02-01 20:43:25 +00001192 Function *Intr =
Peter Collingbourne29748562018-03-09 19:11:44 +00001193 Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
1194
1195 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
1196 CI->setTailCallKind(CallInst::TCK_MustTail);
1197 ReturnInst::Create(M.getContext(), nullptr, BB);
1198
1199 bool IsExported = false;
1200 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1201 if (IsExported)
1202 Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
1203}
1204
1205void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
1206 Constant *JT, bool &IsExported) {
1207 auto Apply = [&](CallSiteInfo &CSInfo) {
1208 if (CSInfo.isExported())
1209 IsExported = true;
1210 if (CSInfo.AllCallSitesDevirted)
1211 return;
1212 for (auto &&VCallSite : CSInfo.CallSites) {
1213 CallSite CS = VCallSite.CS;
1214
1215 // Jump tables are only profitable if the retpoline mitigation is enabled.
1216 Attribute FSAttr = CS.getCaller()->getFnAttribute("target-features");
1217 if (FSAttr.hasAttribute(Attribute::None) ||
1218 !FSAttr.getValueAsString().contains("+retpoline"))
1219 continue;
1220
1221 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +00001222 VCallSite.emitRemark("branch-funnel",
1223 JT->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne29748562018-03-09 19:11:44 +00001224
1225 // Pass the address of the vtable in the nest register, which is r10 on
1226 // x86_64.
1227 std::vector<Type *> NewArgs;
1228 NewArgs.push_back(Int8PtrTy);
1229 for (Type *T : CS.getFunctionType()->params())
1230 NewArgs.push_back(T);
James Y Knight7976eb52019-02-01 20:43:25 +00001231 FunctionType *NewFT =
Peter Collingbourne29748562018-03-09 19:11:44 +00001232 FunctionType::get(CS.getFunctionType()->getReturnType(), NewArgs,
James Y Knight7976eb52019-02-01 20:43:25 +00001233 CS.getFunctionType()->isVarArg());
1234 PointerType *NewFTPtr = PointerType::getUnqual(NewFT);
Peter Collingbourne29748562018-03-09 19:11:44 +00001235
1236 IRBuilder<> IRB(CS.getInstruction());
1237 std::vector<Value *> Args;
1238 Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
1239 for (unsigned I = 0; I != CS.getNumArgOperands(); ++I)
1240 Args.push_back(CS.getArgOperand(I));
1241
1242 CallSite NewCS;
1243 if (CS.isCall())
James Y Knight7976eb52019-02-01 20:43:25 +00001244 NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args);
Peter Collingbourne29748562018-03-09 19:11:44 +00001245 else
1246 NewCS = IRB.CreateInvoke(
James Y Knightd9e85a02019-02-01 20:43:34 +00001247 NewFT, IRB.CreateBitCast(JT, NewFTPtr),
Peter Collingbourne29748562018-03-09 19:11:44 +00001248 cast<InvokeInst>(CS.getInstruction())->getNormalDest(),
1249 cast<InvokeInst>(CS.getInstruction())->getUnwindDest(), Args);
1250 NewCS.setCallingConv(CS.getCallingConv());
1251
1252 AttributeList Attrs = CS.getAttributes();
1253 std::vector<AttributeSet> NewArgAttrs;
1254 NewArgAttrs.push_back(AttributeSet::get(
1255 M.getContext(), ArrayRef<Attribute>{Attribute::get(
1256 M.getContext(), Attribute::Nest)}));
1257 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
1258 NewArgAttrs.push_back(Attrs.getParamAttributes(I));
1259 NewCS.setAttributes(
1260 AttributeList::get(M.getContext(), Attrs.getFnAttributes(),
1261 Attrs.getRetAttributes(), NewArgAttrs));
1262
1263 CS->replaceAllUsesWith(NewCS.getInstruction());
1264 CS->eraseFromParent();
1265
1266 // This use is no longer unsafe.
1267 if (VCallSite.NumUnsafeUses)
1268 --*VCallSite.NumUnsafeUses;
1269 }
1270 // Don't mark as devirtualized because there may be callers compiled without
1271 // retpoline mitigation, which would mean that they are lowered to
1272 // llvm.type.test and therefore require an llvm.type.test resolution for the
1273 // type identifier.
1274 };
1275 Apply(SlotInfo.CSInfo);
1276 for (auto &P : SlotInfo.ConstCSInfo)
1277 Apply(P.second);
1278}
1279
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001280bool DevirtModule::tryEvaluateFunctionsWithArgs(
1281 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001282 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001283 // Evaluate each function and store the result in each target's RetVal
1284 // field.
1285 for (VirtualCallTarget &Target : TargetsForSlot) {
1286 if (Target.Fn->arg_size() != Args.size() + 1)
1287 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001288
1289 Evaluator Eval(M.getDataLayout(), nullptr);
1290 SmallVector<Constant *, 2> EvalArgs;
1291 EvalArgs.push_back(
1292 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001293 for (unsigned I = 0; I != Args.size(); ++I) {
1294 auto *ArgTy = dyn_cast<IntegerType>(
1295 Target.Fn->getFunctionType()->getParamType(I + 1));
1296 if (!ArgTy)
1297 return false;
1298 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
1299 }
1300
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001301 Constant *RetVal;
1302 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
1303 !isa<ConstantInt>(RetVal))
1304 return false;
1305 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
1306 }
1307 return true;
1308}
1309
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001310void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1311 uint64_t TheRetVal) {
1312 for (auto Call : CSInfo.CallSites)
1313 Call.replaceAndErase(
Sam Elliotte963c892017-08-21 16:57:21 +00001314 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001315 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001316 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001317}
1318
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001319bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001320 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
1321 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001322 // Uniform return value optimization. If all functions return the same
1323 // constant, replace all calls with that constant.
1324 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1325 for (const VirtualCallTarget &Target : TargetsForSlot)
1326 if (Target.RetVal != TheRetVal)
1327 return false;
1328
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001329 if (CSInfo.isExported()) {
1330 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
1331 Res->Info = TheRetVal;
1332 }
1333
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001334 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001335 if (RemarksEnabled)
1336 for (auto &&Target : TargetsForSlot)
1337 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001338 return true;
1339}
1340
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001341std::string DevirtModule::getGlobalName(VTableSlot Slot,
1342 ArrayRef<uint64_t> Args,
1343 StringRef Name) {
1344 std::string FullName = "__typeid_";
1345 raw_string_ostream OS(FullName);
1346 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1347 for (uint64_t Arg : Args)
1348 OS << '_' << Arg;
1349 OS << '_' << Name;
1350 return OS.str();
1351}
1352
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001353bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1354 Triple T(M.getTargetTriple());
Fangrui Song6904cd92020-01-06 10:16:28 -08001355 return T.isX86() && T.getObjectFormat() == Triple::ELF;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001356}
1357
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001358void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1359 StringRef Name, Constant *C) {
1360 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1361 getGlobalName(Slot, Args, Name), C, &M);
1362 GA->setVisibility(GlobalValue::HiddenVisibility);
1363}
1364
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001365void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1366 StringRef Name, uint32_t Const,
1367 uint32_t &Storage) {
1368 if (shouldExportConstantsAsAbsoluteSymbols()) {
1369 exportGlobal(
1370 Slot, Args, Name,
1371 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1372 return;
1373 }
1374
1375 Storage = Const;
1376}
1377
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001378Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001379 StringRef Name) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001380 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
1381 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001382 if (GV)
1383 GV->setVisibility(GlobalValue::HiddenVisibility);
1384 return C;
1385}
1386
1387Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1388 StringRef Name, IntegerType *IntTy,
1389 uint32_t Storage) {
1390 if (!shouldExportConstantsAsAbsoluteSymbols())
1391 return ConstantInt::get(IntTy, Storage);
1392
1393 Constant *C = importGlobal(Slot, Args, Name);
1394 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1395 C = ConstantExpr::getPtrToInt(C, IntTy);
1396
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001397 // We only need to set metadata if the global is newly created, in which
1398 // case it would not have hidden visibility.
Benjamin Kramer0deb9a92018-05-31 13:29:58 +00001399 if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001400 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001401
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001402 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1403 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1404 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1405 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1406 MDNode::get(M.getContext(), {MinC, MaxC}));
1407 };
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001408 unsigned AbsWidth = IntTy->getBitWidth();
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001409 if (AbsWidth == IntPtrTy->getBitWidth())
1410 SetAbsRange(~0ull, ~0ull); // Full set.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001411 else
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001412 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001413 return C;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001414}
1415
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001416void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1417 bool IsOne,
1418 Constant *UniqueMemberAddr) {
1419 for (auto &&Call : CSInfo.CallSites) {
1420 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001421 Value *Cmp =
1422 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
1423 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001424 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
Sam Elliotte963c892017-08-21 16:57:21 +00001425 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1426 Cmp);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001427 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001428 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001429}
1430
Peter Collingbourne29748562018-03-09 19:11:44 +00001431Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1432 Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1433 return ConstantExpr::getGetElementPtr(Int8Ty, C,
1434 ConstantInt::get(Int64Ty, M->Offset));
1435}
1436
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001437bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001438 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001439 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1440 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001441 // IsOne controls whether we look for a 0 or a 1.
1442 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001443 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001444 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +00001445 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001446 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001447 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001448 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001449 }
1450 }
1451
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001452 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001453 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001454 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001455
Peter Collingbourne29748562018-03-09 19:11:44 +00001456 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001457 if (CSInfo.isExported()) {
1458 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1459 Res->Info = IsOne;
1460
1461 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1462 }
1463
1464 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001465 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1466 UniqueMemberAddr);
1467
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001468 // Update devirtualization statistics for targets.
1469 if (RemarksEnabled)
1470 for (auto &&Target : TargetsForSlot)
1471 Target.WasDevirt = true;
1472
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001473 return true;
1474 };
1475
1476 if (BitWidth == 1) {
1477 if (tryUniqueRetValOptFor(true))
1478 return true;
1479 if (tryUniqueRetValOptFor(false))
1480 return true;
1481 }
1482 return false;
1483}
1484
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001485void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1486 Constant *Byte, Constant *Bit) {
1487 for (auto Call : CSInfo.CallSites) {
1488 auto *RetType = cast<IntegerType>(Call.CS.getType());
1489 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001490 Value *Addr =
1491 B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001492 if (RetType->getBitWidth() == 1) {
James Y Knight14359ef2019-02-01 20:44:24 +00001493 Value *Bits = B.CreateLoad(Int8Ty, Addr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001494 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1495 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1496 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
Sam Elliotte963c892017-08-21 16:57:21 +00001497 OREGetter, IsBitSet);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001498 } else {
1499 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1500 Value *Val = B.CreateLoad(RetType, ValAddr);
Sam Elliotte963c892017-08-21 16:57:21 +00001501 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1502 OREGetter, Val);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001503 }
1504 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001505 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001506}
1507
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001508bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001509 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1510 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001511 // This only works if the function returns an integer.
1512 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1513 if (!RetType)
1514 return false;
1515 unsigned BitWidth = RetType->getBitWidth();
1516 if (BitWidth > 64)
1517 return false;
1518
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001519 // Make sure that each function is defined, does not access memory, takes at
1520 // least one argument, does not use its first argument (which we assume is
1521 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +00001522 //
1523 // Note that we test whether this copy of the function is readnone, rather
1524 // than testing function attributes, which must hold for any copy of the
1525 // function, even a less optimized version substituted at link time. This is
1526 // sound because the virtual constant propagation optimizations effectively
1527 // inline all implementations of the virtual function into each call site,
1528 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001529 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +00001530 if (Target.Fn->isDeclaration() ||
1531 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1532 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001533 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001534 Target.Fn->getReturnType() != RetType)
1535 return false;
1536 }
1537
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001538 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001539 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1540 continue;
1541
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001542 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1543 if (Res)
1544 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1545
1546 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001547 continue;
1548
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001549 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1550 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001551 continue;
1552
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001553 // Find an allocation offset in bits in all vtables associated with the
1554 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001555 uint64_t AllocBefore =
1556 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1557 uint64_t AllocAfter =
1558 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1559
1560 // Calculate the total amount of padding needed to store a value at both
1561 // ends of the object.
1562 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1563 for (auto &&Target : TargetsForSlot) {
1564 TotalPaddingBefore += std::max<int64_t>(
1565 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1566 TotalPaddingAfter += std::max<int64_t>(
1567 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1568 }
1569
1570 // If the amount of padding is too large, give up.
1571 // FIXME: do something smarter here.
1572 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1573 continue;
1574
1575 // Calculate the offset to the value as a (possibly negative) byte offset
1576 // and (if applicable) a bit offset, and store the values in the targets.
1577 int64_t OffsetByte;
1578 uint64_t OffsetBit;
1579 if (TotalPaddingBefore <= TotalPaddingAfter)
1580 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1581 OffsetBit);
1582 else
1583 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1584 OffsetBit);
1585
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001586 if (RemarksEnabled)
1587 for (auto &&Target : TargetsForSlot)
1588 Target.WasDevirt = true;
1589
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001590
1591 if (CSByConstantArg.second.isExported()) {
1592 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001593 exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1594 ResByArg->Byte);
1595 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1596 ResByArg->Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001597 }
1598
1599 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001600 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1601 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001602 applyVirtualConstProp(CSByConstantArg.second,
1603 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001604 }
1605 return true;
1606}
1607
1608void DevirtModule::rebuildGlobal(VTableBits &B) {
1609 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1610 return;
1611
Peter Collingbourneef5cfc22019-07-22 18:50:45 +00001612 // Align the before byte array to the global's minimum alignment so that we
1613 // don't break any alignment requirements on the global.
Guillaume Chatelet0e620112019-10-15 11:24:36 +00001614 MaybeAlign Alignment(B.GV->getAlignment());
1615 if (!Alignment)
1616 Alignment =
1617 Align(M.getDataLayout().getABITypeAlignment(B.GV->getValueType()));
1618 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001619
1620 // Before was stored in reverse order; flip it now.
1621 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1622 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1623
1624 // Build an anonymous global containing the before bytes, followed by the
1625 // original initializer, followed by the after bytes.
1626 auto NewInit = ConstantStruct::getAnon(
1627 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1628 B.GV->getInitializer(),
1629 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1630 auto NewGV =
1631 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1632 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1633 NewGV->setSection(B.GV->getSection());
1634 NewGV->setComdat(B.GV->getComdat());
Guillaume Chatelet0e620112019-10-15 11:24:36 +00001635 NewGV->setAlignment(MaybeAlign(B.GV->getAlignment()));
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001636
Peter Collingbourne0312f612016-06-25 00:23:04 +00001637 // Copy the original vtable's metadata to the anonymous global, adjusting
1638 // offsets as required.
1639 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1640
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001641 // Build an alias named after the original global, pointing at the second
1642 // element (the original initializer).
1643 auto Alias = GlobalAlias::create(
1644 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1645 ConstantExpr::getGetElementPtr(
1646 NewInit->getType(), NewGV,
1647 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1648 ConstantInt::get(Int32Ty, 1)}),
1649 &M);
1650 Alias->setVisibility(B.GV->getVisibility());
1651 Alias->takeName(B.GV);
1652
1653 B.GV->replaceAllUsesWith(Alias);
1654 B.GV->eraseFromParent();
1655}
1656
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001657bool DevirtModule::areRemarksEnabled() {
1658 const auto &FL = M.getFunctionList();
Teresa Johnson5e1c0e72018-09-18 13:42:24 +00001659 for (const Function &Fn : FL) {
1660 const auto &BBL = Fn.getBasicBlockList();
1661 if (BBL.empty())
1662 continue;
1663 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
1664 return DI.isEnabled();
1665 }
1666 return false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001667}
1668
Teresa Johnsonc8e36862019-12-06 12:13:34 -08001669void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001670 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001671 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1672 // points to a member of the type identifier %md. Group calls by (type ID,
1673 // offset) pair (effectively the identity of the virtual function) and store
1674 // to CallSlots.
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001675 DenseSet<CallSite> SeenCallSites;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001676 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001677 I != E;) {
1678 auto CI = dyn_cast<CallInst>(I->getUser());
1679 ++I;
1680 if (!CI)
1681 continue;
1682
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001683 // Search for virtual calls based on %p and add them to DevirtCalls.
1684 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001685 SmallVector<CallInst *, 1> Assumes;
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001686 auto &DT = LookupDomTree(*CI->getFunction());
1687 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001688
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001689 // If we found any, add them to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001690 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001691 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001692 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1693 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001694 for (DevirtCallSite Call : DevirtCalls) {
1695 // Only add this CallSite if we haven't seen it before. The vtable
1696 // pointer may have been CSE'd with pointers from other call sites,
1697 // and we don't want to process call sites multiple times. We can't
1698 // just skip the vtable Ptr if it has been seen before, however, since
1699 // it may be shared by type tests that dominate different calls.
1700 if (SeenCallSites.insert(Call.CS).second)
Peter Collingbourne001052a2017-08-22 21:41:19 +00001701 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001702 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001703 }
1704
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001705 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001706 for (auto Assume : Assumes)
1707 Assume->eraseFromParent();
1708 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1709 // may use the vtable argument later.
1710 if (CI->use_empty())
1711 CI->eraseFromParent();
1712 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001713}
1714
1715void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1716 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1717
1718 for (auto I = TypeCheckedLoadFunc->use_begin(),
1719 E = TypeCheckedLoadFunc->use_end();
1720 I != E;) {
1721 auto CI = dyn_cast<CallInst>(I->getUser());
1722 ++I;
1723 if (!CI)
1724 continue;
1725
1726 Value *Ptr = CI->getArgOperand(0);
1727 Value *Offset = CI->getArgOperand(1);
1728 Value *TypeIdValue = CI->getArgOperand(2);
1729 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1730
1731 SmallVector<DevirtCallSite, 1> DevirtCalls;
1732 SmallVector<Instruction *, 1> LoadedPtrs;
1733 SmallVector<Instruction *, 1> Preds;
1734 bool HasNonCallUses = false;
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001735 auto &DT = LookupDomTree(*CI->getFunction());
Peter Collingbourne0312f612016-06-25 00:23:04 +00001736 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001737 HasNonCallUses, CI, DT);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001738
1739 // Start by generating "pessimistic" code that explicitly loads the function
1740 // pointer from the vtable and performs the type check. If possible, we will
1741 // eliminate the load and the type check later.
1742
1743 // If possible, only generate the load at the point where it is used.
1744 // This helps avoid unnecessary spills.
1745 IRBuilder<> LoadB(
1746 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1747 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1748 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1749 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1750
1751 for (Instruction *LoadedPtr : LoadedPtrs) {
1752 LoadedPtr->replaceAllUsesWith(LoadedValue);
1753 LoadedPtr->eraseFromParent();
1754 }
1755
1756 // Likewise for the type test.
1757 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1758 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1759
1760 for (Instruction *Pred : Preds) {
1761 Pred->replaceAllUsesWith(TypeTestCall);
1762 Pred->eraseFromParent();
1763 }
1764
1765 // We have already erased any extractvalue instructions that refer to the
1766 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1767 // (although this is unlikely). In that case, explicitly build a pair and
1768 // RAUW it.
1769 if (!CI->use_empty()) {
1770 Value *Pair = UndefValue::get(CI->getType());
1771 IRBuilder<> B(CI);
1772 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1773 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1774 CI->replaceAllUsesWith(Pair);
1775 }
1776
1777 // The number of unsafe uses is initially the number of uses.
1778 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1779 NumUnsafeUses = DevirtCalls.size();
1780
1781 // If the function pointer has a non-call user, we cannot eliminate the type
1782 // check, as one of those users may eventually call the pointer. Increment
1783 // the unsafe use count to make sure it cannot reach zero.
1784 if (HasNonCallUses)
1785 ++NumUnsafeUses;
1786 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001787 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1788 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001789 }
1790
1791 CI->eraseFromParent();
1792 }
1793}
1794
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001795void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001796 auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
1797 if (!TypeId)
1798 return;
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001799 const TypeIdSummary *TidSummary =
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001800 ImportSummary->getTypeIdSummary(TypeId->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001801 if (!TidSummary)
1802 return;
1803 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1804 if (ResI == TidSummary->WPDRes.end())
1805 return;
1806 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001807
1808 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001809 assert(!Res.SingleImplName.empty());
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001810 // The type of the function in the declaration is irrelevant because every
1811 // call site will cast it to the correct type.
James Y Knight13680222019-02-01 02:28:03 +00001812 Constant *SingleImpl =
1813 cast<Constant>(M.getOrInsertFunction(Res.SingleImplName,
1814 Type::getVoidTy(M.getContext()))
1815 .getCallee());
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001816
1817 // This is the import phase so we should not be exporting anything.
1818 bool IsExported = false;
1819 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1820 assert(!IsExported);
1821 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001822
1823 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1824 auto I = Res.ResByArg.find(CSByConstantArg.first);
1825 if (I == Res.ResByArg.end())
1826 continue;
1827 auto &ResByArg = I->second;
1828 // FIXME: We should figure out what to do about the "function name" argument
1829 // to the apply* functions, as the function names are unavailable during the
1830 // importing phase. For now we just pass the empty string. This does not
1831 // impact correctness because the function names are just used for remarks.
1832 switch (ResByArg.TheKind) {
1833 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1834 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1835 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001836 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1837 Constant *UniqueMemberAddr =
1838 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1839 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1840 UniqueMemberAddr);
1841 break;
1842 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001843 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001844 Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
1845 Int32Ty, ResByArg.Byte);
1846 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
1847 ResByArg.Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001848 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
Adrian Prantl0e6694d2017-12-19 22:05:25 +00001849 break;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001850 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001851 default:
1852 break;
1853 }
1854 }
Peter Collingbourne29748562018-03-09 19:11:44 +00001855
1856 if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
James Y Knight13680222019-02-01 02:28:03 +00001857 // The type of the function is irrelevant, because it's bitcast at calls
1858 // anyhow.
1859 Constant *JT = cast<Constant>(
1860 M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
1861 Type::getVoidTy(M.getContext()))
1862 .getCallee());
Peter Collingbourne29748562018-03-09 19:11:44 +00001863 bool IsExported = false;
1864 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1865 assert(!IsExported);
1866 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001867}
1868
1869void DevirtModule::removeRedundantTypeTests() {
1870 auto True = ConstantInt::getTrue(M.getContext());
1871 for (auto &&U : NumUnsafeUsesForTypeTest) {
1872 if (U.second == 0) {
1873 U.first->replaceAllUsesWith(True);
1874 U.first->eraseFromParent();
1875 }
1876 }
1877}
1878
Peter Collingbourne0312f612016-06-25 00:23:04 +00001879bool DevirtModule::run() {
Teresa Johnsond0b1f302019-02-14 21:22:50 +00001880 // If only some of the modules were split, we cannot correctly perform
1881 // this transformation. We already checked for the presense of type tests
1882 // with partially split modules during the thin link, and would have emitted
1883 // an error if any were found, so here we can simply return.
1884 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
1885 (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
1886 return false;
1887
Peter Collingbourne0312f612016-06-25 00:23:04 +00001888 Function *TypeTestFunc =
1889 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1890 Function *TypeCheckedLoadFunc =
1891 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1892 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1893
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001894 // Normally if there are no users of the devirtualization intrinsics in the
1895 // module, this pass has nothing to do. But if we are exporting, we also need
1896 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001897 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001898 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001899 AssumeFunc->use_empty()) &&
1900 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1901 return false;
1902
1903 if (TypeTestFunc && AssumeFunc)
Teresa Johnsonc8e36862019-12-06 12:13:34 -08001904 scanTypeTestUsers(TypeTestFunc);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001905
1906 if (TypeCheckedLoadFunc)
1907 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001908
Peter Collingbournef7691d82017-03-22 18:22:59 +00001909 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001910 for (auto &S : CallSlots)
1911 importResolution(S.first, S.second);
1912
1913 removeRedundantTypeTests();
1914
Teresa Johnson2f63d542020-01-24 12:24:18 -08001915 // We have lowered or deleted the type instrinsics, so we will no
1916 // longer have enough information to reason about the liveness of virtual
1917 // function pointers in GlobalDCE.
1918 for (GlobalVariable &GV : M.globals())
1919 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
1920
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001921 // The rest of the code is only necessary when exporting or during regular
1922 // LTO, so we are done.
1923 return true;
1924 }
1925
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001926 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001927 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001928 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1929 buildTypeIdentifierMap(Bits, TypeIdMap);
1930 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001931 return true;
1932
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001933 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001934 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001935 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1936 for (auto &P : TypeIdMap) {
1937 if (auto *TypeId = dyn_cast<MDString>(P.first))
1938 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1939 TypeId);
1940 }
1941
Peter Collingbournef7691d82017-03-22 18:22:59 +00001942 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001943 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001944 auto *FS = dyn_cast<FunctionSummary>(S.get());
1945 if (!FS)
1946 continue;
1947 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001948 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1949 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Eugene Leviant943afb52019-10-17 07:46:18 +00001950 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001951 }
1952 }
1953 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1954 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001955 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001956 }
1957 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001958 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001959 FS->type_test_assume_const_vcalls()) {
1960 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001961 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001962 .ConstCSInfo[VC.Args]
Eugene Leviant943afb52019-10-17 07:46:18 +00001963 .addSummaryTypeTestAssumeUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001964 }
1965 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001966 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001967 FS->type_checked_load_const_vcalls()) {
1968 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001969 CallSlots[{MD, VC.VFunc.Offset}]
1970 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001971 .addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001972 }
1973 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001974 }
1975 }
1976 }
1977
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001978 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001979 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001980 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001981 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001982 // Search each of the members of the type identifier for the virtual
1983 // function implementation at offset S.first.ByteOffset, and add to
1984 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001985 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001986 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1987 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001988 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001989 if (ExportSummary && isa<MDString>(S.first.TypeID))
1990 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001991 ->getOrInsertTypeIdSummary(
1992 cast<MDString>(S.first.TypeID)->getString())
1993 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001994
Eugene Leviant943afb52019-10-17 07:46:18 +00001995 if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001996 DidVirtualConstProp |=
1997 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
1998
1999 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
2000 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00002001
Peter Collingbourneb406baa2017-03-04 01:23:30 +00002002 // Collect functions devirtualized at least for one call site for stats.
2003 if (RemarksEnabled)
2004 for (const auto &T : TargetsForSlot)
2005 if (T.WasDevirt)
2006 DevirtTargets[T.Fn->getName()] = T.Fn;
2007 }
2008
2009 // CFI-specific: if we are exporting and any llvm.type.checked.load
2010 // intrinsics were *not* devirtualized, we need to add the resulting
2011 // llvm.type.test intrinsics to the function summaries so that the
2012 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00002013 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00002014 auto GUID =
2015 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
2016 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
2017 FS->addTypeTest(GUID);
2018 for (auto &CCS : S.second.ConstCSInfo)
2019 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
2020 FS->addTypeTest(GUID);
2021 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00002022 }
2023
2024 if (RemarksEnabled) {
2025 // Generate remarks for each devirtualized function.
2026 for (const auto &DT : DevirtTargets) {
2027 Function *F = DT.second;
Sam Elliotte963c892017-08-21 16:57:21 +00002028
Sam Elliotte963c892017-08-21 16:57:21 +00002029 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +00002030 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
2031 << "devirtualized "
Teresa Johnsond2df54e2019-08-02 13:10:52 +00002032 << NV("FunctionName", DT.first));
Ivan Krasinb05e06e2016-08-05 19:45:16 +00002033 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00002034 }
2035
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00002036 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00002037
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00002038 // Rebuild each global we touched as part of virtual constant propagation to
2039 // include the before and after bytes.
2040 if (DidVirtualConstProp)
2041 for (VTableBits &B : Bits)
2042 rebuildGlobal(B);
2043
Teresa Johnson2f63d542020-01-24 12:24:18 -08002044 // We have lowered or deleted the type instrinsics, so we will no
Oliver Stannard3b598b92019-10-17 09:58:57 +00002045 // longer have enough information to reason about the liveness of virtual
2046 // function pointers in GlobalDCE.
2047 for (GlobalVariable &GV : M.globals())
2048 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2049
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00002050 return true;
2051}
Teresa Johnsond2df54e2019-08-02 13:10:52 +00002052
2053void DevirtIndex::run() {
2054 if (ExportSummary.typeIdCompatibleVtableMap().empty())
2055 return;
2056
2057 DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
2058 for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
2059 NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first);
2060 }
2061
2062 // Collect information from summary about which calls to try to devirtualize.
2063 for (auto &P : ExportSummary) {
2064 for (auto &S : P.second.SummaryList) {
2065 auto *FS = dyn_cast<FunctionSummary>(S.get());
2066 if (!FS)
2067 continue;
2068 // FIXME: Only add live functions.
2069 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2070 for (StringRef Name : NameByGUID[VF.GUID]) {
2071 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2072 }
2073 }
2074 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2075 for (StringRef Name : NameByGUID[VF.GUID]) {
2076 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2077 }
2078 }
2079 for (const FunctionSummary::ConstVCall &VC :
2080 FS->type_test_assume_const_vcalls()) {
2081 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2082 CallSlots[{Name, VC.VFunc.Offset}]
2083 .ConstCSInfo[VC.Args]
2084 .addSummaryTypeTestAssumeUser(FS);
2085 }
2086 }
2087 for (const FunctionSummary::ConstVCall &VC :
2088 FS->type_checked_load_const_vcalls()) {
2089 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2090 CallSlots[{Name, VC.VFunc.Offset}]
2091 .ConstCSInfo[VC.Args]
2092 .addSummaryTypeCheckedLoadUser(FS);
2093 }
2094 }
2095 }
2096 }
2097
2098 std::set<ValueInfo> DevirtTargets;
2099 // For each (type, offset) pair:
2100 for (auto &S : CallSlots) {
2101 // Search each of the members of the type identifier for the virtual
2102 // function implementation at offset S.first.ByteOffset, and add to
2103 // TargetsForSlot.
2104 std::vector<ValueInfo> TargetsForSlot;
2105 auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
2106 assert(TidSummary);
2107 if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
2108 S.first.ByteOffset)) {
2109 WholeProgramDevirtResolution *Res =
2110 &ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID)
2111 .WPDRes[S.first.ByteOffset];
2112
2113 if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
2114 DevirtTargets))
2115 continue;
2116 }
2117 }
2118
2119 // Optionally have the thin link print message for each devirtualized
2120 // function.
2121 if (PrintSummaryDevirt)
2122 for (const auto &DT : DevirtTargets)
2123 errs() << "Devirtualized call to " << DT << "\n";
2124
2125 return;
2126}