blob: c7d815232ef8cdb9a74974c83d5f709010d149dc [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//
Peter Collingbourneb406baa2017-03-04 01:23:30 +000027// This pass is intended to be used during the regular and thin LTO pipelines.
28// During regular LTO, the pass determines the best optimization for each
29// virtual call and applies the resolutions directly to virtual calls that are
30// eligible for virtual call optimization (i.e. calls that use either of the
31// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). During
32// ThinLTO, the pass operates in two phases:
33// - Export phase: this is run during the thin link over a single merged module
34// that contains all vtables with !type metadata that participate in the link.
35// The pass computes a resolution for each virtual call and stores it in the
36// type identifier summary.
37// - Import phase: this is run during the thin backends over the individual
38// modules. The pass applies the resolutions previously computed during the
39// import phase to each eligible virtual call.
40//
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000041//===----------------------------------------------------------------------===//
42
43#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000044#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000045#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/DenseMapInfo.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000047#include "llvm/ADT/DenseSet.h"
48#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000049#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000050#include "llvm/ADT/iterator_range.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000051#include "llvm/Analysis/AliasAnalysis.h"
52#include "llvm/Analysis/BasicAliasAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000053#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000054#include "llvm/Analysis/TypeMetadataUtils.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000055#include "llvm/IR/CallSite.h"
56#include "llvm/IR/Constants.h"
57#include "llvm/IR/DataLayout.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000058#include "llvm/IR/DebugLoc.h"
59#include "llvm/IR/DerivedTypes.h"
Teresa Johnsonf24136f2018-09-27 14:55:32 +000060#include "llvm/IR/Dominators.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000061#include "llvm/IR/Function.h"
62#include "llvm/IR/GlobalAlias.h"
63#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000064#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000065#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000067#include "llvm/IR/Instructions.h"
68#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000069#include "llvm/IR/LLVMContext.h"
70#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000071#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000072#include "llvm/IR/ModuleSummaryIndexYAML.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000073#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000074#include "llvm/PassRegistry.h"
75#include "llvm/PassSupport.h"
76#include "llvm/Support/Casting.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000077#include "llvm/Support/Error.h"
78#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000079#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000080#include "llvm/Transforms/IPO.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000081#include "llvm/Transforms/IPO/FunctionAttrs.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000082#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000083#include <algorithm>
84#include <cstddef>
85#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000086#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000087#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000088
89using namespace llvm;
90using namespace wholeprogramdevirt;
91
92#define DEBUG_TYPE "wholeprogramdevirt"
93
Peter Collingbourne2b33f652017-02-13 19:26:18 +000094static cl::opt<PassSummaryAction> ClSummaryAction(
95 "wholeprogramdevirt-summary-action",
96 cl::desc("What to do with the summary when running this pass"),
97 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
98 clEnumValN(PassSummaryAction::Import, "import",
99 "Import typeid resolutions from summary and globals"),
100 clEnumValN(PassSummaryAction::Export, "export",
101 "Export typeid resolutions to summary and globals")),
102 cl::Hidden);
103
104static cl::opt<std::string> ClReadSummary(
105 "wholeprogramdevirt-read-summary",
106 cl::desc("Read summary from given YAML file before running pass"),
107 cl::Hidden);
108
109static cl::opt<std::string> ClWriteSummary(
110 "wholeprogramdevirt-write-summary",
111 cl::desc("Write summary to given YAML file after running pass"),
112 cl::Hidden);
113
Vitaly Buka9cb59b92018-04-06 21:41:17 +0000114static cl::opt<unsigned>
115 ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
116 cl::init(10), cl::ZeroOrMore,
117 cl::desc("Maximum number of call targets per "
118 "call site to enable branch funnels"));
Vitaly Buka66f53d72018-04-06 21:32:36 +0000119
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000120// Find the minimum offset that we may store a value of size Size bits at. If
121// IsAfter is set, look for an offset before the object, otherwise look for an
122// offset after the object.
123uint64_t
124wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
125 bool IsAfter, uint64_t Size) {
126 // Find a minimum offset taking into account only vtable sizes.
127 uint64_t MinByte = 0;
128 for (const VirtualCallTarget &Target : Targets) {
129 if (IsAfter)
130 MinByte = std::max(MinByte, Target.minAfterBytes());
131 else
132 MinByte = std::max(MinByte, Target.minBeforeBytes());
133 }
134
135 // Build a vector of arrays of bytes covering, for each target, a slice of the
136 // used region (see AccumBitVector::BytesUsed in
137 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
138 // this aligns the used regions to start at MinByte.
139 //
140 // In this example, A, B and C are vtables, # is a byte already allocated for
141 // a virtual function pointer, AAAA... (etc.) are the used regions for the
142 // vtables and Offset(X) is the value computed for the Offset variable below
143 // for X.
144 //
145 // Offset(A)
146 // | |
147 // |MinByte
148 // A: ################AAAAAAAA|AAAAAAAA
149 // B: ########BBBBBBBBBBBBBBBB|BBBB
150 // C: ########################|CCCCCCCCCCCCCCCC
151 // | Offset(B) |
152 //
153 // This code produces the slices of A, B and C that appear after the divider
154 // at MinByte.
155 std::vector<ArrayRef<uint8_t>> Used;
156 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000157 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
158 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000159 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
160 : MinByte - Target.minBeforeBytes();
161
162 // Disregard used regions that are smaller than Offset. These are
163 // effectively all-free regions that do not need to be checked.
164 if (VTUsed.size() > Offset)
165 Used.push_back(VTUsed.slice(Offset));
166 }
167
168 if (Size == 1) {
169 // Find a free bit in each member of Used.
170 for (unsigned I = 0;; ++I) {
171 uint8_t BitsUsed = 0;
172 for (auto &&B : Used)
173 if (I < B.size())
174 BitsUsed |= B[I];
175 if (BitsUsed != 0xff)
176 return (MinByte + I) * 8 +
177 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
178 }
179 } else {
180 // Find a free (Size/8) byte region in each member of Used.
181 // FIXME: see if alignment helps.
182 for (unsigned I = 0;; ++I) {
183 for (auto &&B : Used) {
184 unsigned Byte = 0;
185 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
186 if (B[I + Byte])
187 goto NextI;
188 ++Byte;
189 }
190 }
191 return (MinByte + I) * 8;
192 NextI:;
193 }
194 }
195}
196
197void wholeprogramdevirt::setBeforeReturnValues(
198 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
199 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
200 if (BitWidth == 1)
201 OffsetByte = -(AllocBefore / 8 + 1);
202 else
203 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
204 OffsetBit = AllocBefore % 8;
205
206 for (VirtualCallTarget &Target : Targets) {
207 if (BitWidth == 1)
208 Target.setBeforeBit(AllocBefore);
209 else
210 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
211 }
212}
213
214void wholeprogramdevirt::setAfterReturnValues(
215 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
216 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
217 if (BitWidth == 1)
218 OffsetByte = AllocAfter / 8;
219 else
220 OffsetByte = (AllocAfter + 7) / 8;
221 OffsetBit = AllocAfter % 8;
222
223 for (VirtualCallTarget &Target : Targets) {
224 if (BitWidth == 1)
225 Target.setAfterBit(AllocAfter);
226 else
227 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
228 }
229}
230
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000231VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
232 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000233 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000234
235namespace {
236
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000237// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000238// tables, and the ByteOffset is the offset in bytes from the address point to
239// the virtual function pointer.
240struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000241 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000242 uint64_t ByteOffset;
243};
244
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000245} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000246
Peter Collingbourne9b656522016-02-09 23:01:38 +0000247namespace llvm {
248
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000249template <> struct DenseMapInfo<VTableSlot> {
250 static VTableSlot getEmptyKey() {
251 return {DenseMapInfo<Metadata *>::getEmptyKey(),
252 DenseMapInfo<uint64_t>::getEmptyKey()};
253 }
254 static VTableSlot getTombstoneKey() {
255 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
256 DenseMapInfo<uint64_t>::getTombstoneKey()};
257 }
258 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000259 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000260 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
261 }
262 static bool isEqual(const VTableSlot &LHS,
263 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000264 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000265 }
266};
267
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000268} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000269
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000270namespace {
271
272// A virtual call site. VTable is the loaded virtual table pointer, and CS is
273// the indirect virtual call.
274struct VirtualCallSite {
275 Value *VTable;
276 CallSite CS;
277
Peter Collingbourne0312f612016-06-25 00:23:04 +0000278 // If non-null, this field points to the associated unsafe use count stored in
279 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
280 // of that field for details.
281 unsigned *NumUnsafeUses;
282
Sam Elliotte963c892017-08-21 16:57:21 +0000283 void
284 emitRemark(const StringRef OptName, const StringRef TargetName,
285 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Ivan Krasin54746452016-07-12 02:38:37 +0000286 Function *F = CS.getCaller();
Sam Elliotte963c892017-08-21 16:57:21 +0000287 DebugLoc DLoc = CS->getDebugLoc();
288 BasicBlock *Block = CS.getParent();
289
Sam Elliotte963c892017-08-21 16:57:21 +0000290 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000291 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
292 << NV("Optimization", OptName)
293 << ": devirtualized a call to "
294 << NV("FunctionName", TargetName));
Ivan Krasin54746452016-07-12 02:38:37 +0000295 }
296
Sam Elliotte963c892017-08-21 16:57:21 +0000297 void replaceAndErase(
298 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
299 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
300 Value *New) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000301 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000302 emitRemark(OptName, TargetName, OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000303 CS->replaceAllUsesWith(New);
304 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
305 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
306 II->getUnwindDest()->removePredecessor(II->getParent());
307 }
308 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000309 // This use is no longer unsafe.
310 if (NumUnsafeUses)
311 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000312 }
313};
314
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000315// Call site information collected for a specific VTableSlot and possibly a list
316// of constant integer arguments. The grouping by arguments is handled by the
317// VTableSlotInfo class.
318struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000319 /// The set of call sites for this slot. Used during regular LTO and the
320 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
321 /// call sites that appear in the merged module itself); in each of these
322 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000323 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000324
Peter Collingbourne29748562018-03-09 19:11:44 +0000325 /// Whether all call sites represented by this CallSiteInfo, including those
326 /// in summaries, have been devirtualized. This starts off as true because a
327 /// default constructed CallSiteInfo represents no call sites.
328 bool AllCallSitesDevirted = true;
329
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000330 // These fields are used during the export phase of ThinLTO and reflect
331 // information collected from function summaries.
332
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000333 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
334 /// this slot.
Peter Collingbourne29748562018-03-09 19:11:44 +0000335 bool SummaryHasTypeTestAssumeUsers = false;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000336
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000337 /// CFI-specific: a vector containing the list of function summaries that use
338 /// the llvm.type.checked.load intrinsic and therefore will require
339 /// resolutions for llvm.type.test in order to implement CFI checks if
340 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000341 /// pass will clear this vector by calling markDevirt(). If at the end of the
342 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
343 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000344 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000345
346 bool isExported() const {
347 return SummaryHasTypeTestAssumeUsers ||
348 !SummaryTypeCheckedLoadUsers.empty();
349 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000350
Peter Collingbourne29748562018-03-09 19:11:44 +0000351 void markSummaryHasTypeTestAssumeUsers() {
352 SummaryHasTypeTestAssumeUsers = true;
353 AllCallSitesDevirted = false;
354 }
355
356 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
357 SummaryTypeCheckedLoadUsers.push_back(FS);
358 AllCallSitesDevirted = false;
359 }
360
361 void markDevirt() {
362 AllCallSitesDevirted = true;
363
364 // As explained in the comment for SummaryTypeCheckedLoadUsers.
365 SummaryTypeCheckedLoadUsers.clear();
366 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000367};
368
369// Call site information collected for a specific VTableSlot.
370struct VTableSlotInfo {
371 // The set of call sites which do not have all constant integer arguments
372 // (excluding "this").
373 CallSiteInfo CSInfo;
374
375 // The set of call sites with all constant integer arguments (excluding
376 // "this"), grouped by argument list.
377 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
378
379 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
380
381private:
382 CallSiteInfo &findCallSiteInfo(CallSite CS);
383};
384
385CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
386 std::vector<uint64_t> Args;
387 auto *CI = dyn_cast<IntegerType>(CS.getType());
388 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
389 return CSInfo;
390 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
391 auto *CI = dyn_cast<ConstantInt>(Arg);
392 if (!CI || CI->getBitWidth() > 64)
393 return CSInfo;
394 Args.push_back(CI->getZExtValue());
395 }
396 return ConstCSInfo[Args];
397}
398
399void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
400 unsigned *NumUnsafeUses) {
Peter Collingbourne29748562018-03-09 19:11:44 +0000401 auto &CSI = findCallSiteInfo(CS);
402 CSI.AllCallSitesDevirted = false;
403 CSI.CallSites.push_back({VTable, CS, NumUnsafeUses});
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000404}
405
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000406struct DevirtModule {
407 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000408 function_ref<AAResults &(Function &)> AARGetter;
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000409 function_ref<DominatorTree &(Function &)> LookupDomTree;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000410
Peter Collingbournef7691d82017-03-22 18:22:59 +0000411 ModuleSummaryIndex *ExportSummary;
412 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000413
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000414 IntegerType *Int8Ty;
415 PointerType *Int8PtrTy;
416 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000417 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000418 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000419
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000420 bool RemarksEnabled;
Sam Elliotte963c892017-08-21 16:57:21 +0000421 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000422
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000423 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000424
Peter Collingbourne0312f612016-06-25 00:23:04 +0000425 // This map keeps track of the number of "unsafe" uses of a loaded function
426 // pointer. The key is the associated llvm.type.test intrinsic call generated
427 // by this pass. An unsafe use is one that calls the loaded function pointer
428 // directly. Every time we eliminate an unsafe use (for example, by
429 // devirtualizing it or by applying virtual constant propagation), we
430 // decrement the value stored in this map. If a value reaches zero, we can
431 // eliminate the type check by RAUWing the associated llvm.type.test call with
432 // true.
433 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
434
Peter Collingbourne37317f12017-02-17 18:17:04 +0000435 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Sam Elliotte963c892017-08-21 16:57:21 +0000436 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000437 function_ref<DominatorTree &(Function &)> LookupDomTree,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000438 ModuleSummaryIndex *ExportSummary,
439 const ModuleSummaryIndex *ImportSummary)
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000440 : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree),
441 ExportSummary(ExportSummary), ImportSummary(ImportSummary),
442 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000443 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000444 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000445 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000446 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Sam Elliotte963c892017-08-21 16:57:21 +0000447 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000448 assert(!(ExportSummary && ImportSummary));
449 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000450
451 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000452
Peter Collingbourne0312f612016-06-25 00:23:04 +0000453 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
454 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
455
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000456 void buildTypeIdentifierMap(
457 std::vector<VTableBits> &Bits,
458 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000459 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000460 bool
461 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
462 const std::set<TypeMemberInfo> &TypeMemberInfos,
463 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000464
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000465 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
466 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000467 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000468 VTableSlotInfo &SlotInfo,
469 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000470
Peter Collingbourne29748562018-03-09 19:11:44 +0000471 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
472 bool &IsExported);
473 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
474 VTableSlotInfo &SlotInfo,
475 WholeProgramDevirtResolution *Res, VTableSlot Slot);
476
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000477 bool tryEvaluateFunctionsWithArgs(
478 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000479 ArrayRef<uint64_t> Args);
480
481 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
482 uint64_t TheRetVal);
483 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000484 CallSiteInfo &CSInfo,
485 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000486
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000487 // Returns the global symbol name that is used to export information about the
488 // given vtable slot and list of arguments.
489 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
490 StringRef Name);
491
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000492 bool shouldExportConstantsAsAbsoluteSymbols();
493
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000494 // This function is called during the export phase to create a symbol
495 // definition containing information about the given vtable slot and list of
496 // arguments.
497 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
498 Constant *C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000499 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
500 uint32_t Const, uint32_t &Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000501
502 // This function is called during the import phase to create a reference to
503 // the symbol definition created during the export phase.
504 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000505 StringRef Name);
506 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
507 StringRef Name, IntegerType *IntTy,
508 uint32_t Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000509
Peter Collingbourne29748562018-03-09 19:11:44 +0000510 Constant *getMemberAddr(const TypeMemberInfo *M);
511
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000512 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
513 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000514 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000515 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000516 CallSiteInfo &CSInfo,
517 WholeProgramDevirtResolution::ByArg *Res,
518 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000519
520 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
521 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000522 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000523 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000524 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000525
526 void rebuildGlobal(VTableBits &B);
527
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000528 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
529 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
530
531 // If we were able to eliminate all unsafe uses for a type checked load,
532 // eliminate the associated type tests by replacing them with true.
533 void removeRedundantTypeTests();
534
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000535 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000536
537 // Lower the module using the action and summary passed as command line
538 // arguments. For testing purposes only.
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000539 static bool
540 runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter,
541 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
542 function_ref<DominatorTree &(Function &)> LookupDomTree);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000543};
544
545struct WholeProgramDevirt : public ModulePass {
546 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000547
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000548 bool UseCommandLine = false;
549
Peter Collingbournef7691d82017-03-22 18:22:59 +0000550 ModuleSummaryIndex *ExportSummary;
551 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000552
553 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
554 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
555 }
556
Peter Collingbournef7691d82017-03-22 18:22:59 +0000557 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
558 const ModuleSummaryIndex *ImportSummary)
559 : ModulePass(ID), ExportSummary(ExportSummary),
560 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000561 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
562 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000563
564 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000565 if (skipModule(M))
566 return false;
Sam Elliotte963c892017-08-21 16:57:21 +0000567
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000568 // In the new pass manager, we can request the optimization
569 // remark emitter pass on a per-function-basis, which the
570 // OREGetter will do for us.
571 // In the old pass manager, this is harder, so we just build
572 // an optimization remark emitter on the fly, when we need it.
573 std::unique_ptr<OptimizationRemarkEmitter> ORE;
574 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
575 ORE = make_unique<OptimizationRemarkEmitter>(F);
576 return *ORE;
577 };
Sam Elliotte963c892017-08-21 16:57:21 +0000578
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000579 auto LookupDomTree = [this](Function &F) -> DominatorTree & {
580 return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
581 };
Sam Elliotte963c892017-08-21 16:57:21 +0000582
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000583 if (UseCommandLine)
584 return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter,
585 LookupDomTree);
586
587 return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree,
588 ExportSummary, ImportSummary)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000589 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000590 }
591
592 void getAnalysisUsage(AnalysisUsage &AU) const override {
593 AU.addRequired<AssumptionCacheTracker>();
594 AU.addRequired<TargetLibraryInfoWrapperPass>();
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000595 AU.addRequired<DominatorTreeWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000596 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000597};
598
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000599} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000600
Peter Collingbourne37317f12017-02-17 18:17:04 +0000601INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
602 "Whole program devirtualization", false, false)
603INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
604INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000605INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000606INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
607 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000608char WholeProgramDevirt::ID = 0;
609
Peter Collingbournef7691d82017-03-22 18:22:59 +0000610ModulePass *
611llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
612 const ModuleSummaryIndex *ImportSummary) {
613 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000614}
615
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000616PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000617 ModuleAnalysisManager &AM) {
618 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
619 auto AARGetter = [&](Function &F) -> AAResults & {
620 return FAM.getResult<AAManager>(F);
621 };
Sam Elliotte963c892017-08-21 16:57:21 +0000622 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
623 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
624 };
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000625 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {
626 return FAM.getResult<DominatorTreeAnalysis>(F);
627 };
628 if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary,
629 ImportSummary)
Teresa Johnson28023db2018-07-19 14:51:32 +0000630 .run())
Davide Italianod737dd22016-06-14 21:44:19 +0000631 return PreservedAnalyses::all();
632 return PreservedAnalyses::none();
633}
634
Peter Collingbourne37317f12017-02-17 18:17:04 +0000635bool DevirtModule::runForTesting(
Sam Elliotte963c892017-08-21 16:57:21 +0000636 Module &M, function_ref<AAResults &(Function &)> AARGetter,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000637 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
638 function_ref<DominatorTree &(Function &)> LookupDomTree) {
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000639 ModuleSummaryIndex Summary(/*HaveGVs=*/false);
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000640
641 // Handle the command-line summary arguments. This code is for testing
642 // purposes only, so we handle errors directly.
643 if (!ClReadSummary.empty()) {
644 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
645 ": ");
646 auto ReadSummaryFile =
647 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
648
649 yaml::Input In(ReadSummaryFile->getBuffer());
650 In >> Summary;
651 ExitOnErr(errorCodeToError(In.error()));
652 }
653
Peter Collingbournef7691d82017-03-22 18:22:59 +0000654 bool Changed =
655 DevirtModule(
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000656 M, AARGetter, OREGetter, LookupDomTree,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000657 ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
658 ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
659 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000660
661 if (!ClWriteSummary.empty()) {
662 ExitOnError ExitOnErr(
663 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
664 std::error_code EC;
665 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
666 ExitOnErr(errorCodeToError(EC));
667
668 yaml::Output Out(OS);
669 Out << Summary;
670 }
671
672 return Changed;
673}
674
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000675void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000676 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000677 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000678 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000679 Bits.reserve(M.getGlobalList().size());
680 SmallVector<MDNode *, 2> Types;
681 for (GlobalVariable &GV : M.globals()) {
682 Types.clear();
683 GV.getMetadata(LLVMContext::MD_type, Types);
Eugene Leviant2b70d612018-09-23 13:27:47 +0000684 if (GV.isDeclaration() || Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000685 continue;
686
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000687 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000688 if (!BitsPtr) {
689 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000690 Bits.back().GV = &GV;
691 Bits.back().ObjectSize =
692 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000693 BitsPtr = &Bits.back();
694 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000695
696 for (MDNode *Type : Types) {
697 auto TypeID = Type->getOperand(1).get();
698
699 uint64_t Offset =
700 cast<ConstantInt>(
701 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
702 ->getZExtValue();
703
704 TypeIdMap[TypeID].insert({BitsPtr, Offset});
705 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000706 }
707}
708
Peter Collingbourne87867542016-12-09 01:10:11 +0000709Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
710 if (I->getType()->isPointerTy()) {
711 if (Offset == 0)
712 return I;
713 return nullptr;
714 }
715
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000716 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000717
718 if (auto *C = dyn_cast<ConstantStruct>(I)) {
719 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000720 if (Offset >= SL->getSizeInBytes())
721 return nullptr;
722
Peter Collingbourne87867542016-12-09 01:10:11 +0000723 unsigned Op = SL->getElementContainingOffset(Offset);
724 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
725 Offset - SL->getElementOffset(Op));
726 }
727 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000728 ArrayType *VTableTy = C->getType();
729 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
730
Peter Collingbourne87867542016-12-09 01:10:11 +0000731 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000732 if (Op >= C->getNumOperands())
733 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000734
Peter Collingbourne87867542016-12-09 01:10:11 +0000735 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
736 Offset % ElemSize);
737 }
738 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000739}
740
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000741bool DevirtModule::tryFindVirtualCallTargets(
742 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000743 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
744 for (const TypeMemberInfo &TM : TypeMemberInfos) {
745 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000746 return false;
747
Peter Collingbourne87867542016-12-09 01:10:11 +0000748 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
749 TM.Offset + ByteOffset);
750 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000751 return false;
752
Peter Collingbourne87867542016-12-09 01:10:11 +0000753 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000754 if (!Fn)
755 return false;
756
757 // We can disregard __cxa_pure_virtual as a possible call target, as
758 // calls to pure virtuals are UB.
759 if (Fn->getName() == "__cxa_pure_virtual")
760 continue;
761
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000762 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000763 }
764
765 // Give up if we couldn't find any targets.
766 return !TargetsForSlot.empty();
767}
768
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000769void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000770 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000771 auto Apply = [&](CallSiteInfo &CSInfo) {
772 for (auto &&VCallSite : CSInfo.CallSites) {
773 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +0000774 VCallSite.emitRemark("single-impl",
775 TheFn->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000776 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
777 TheFn, VCallSite.CS.getCalledValue()->getType()));
778 // This use is no longer unsafe.
779 if (VCallSite.NumUnsafeUses)
780 --*VCallSite.NumUnsafeUses;
781 }
Peter Collingbourne29748562018-03-09 19:11:44 +0000782 if (CSInfo.isExported())
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000783 IsExported = true;
Peter Collingbourne29748562018-03-09 19:11:44 +0000784 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000785 };
786 Apply(SlotInfo.CSInfo);
787 for (auto &P : SlotInfo.ConstCSInfo)
788 Apply(P.second);
789}
790
Peter Collingbournee2367412017-02-15 02:13:08 +0000791bool DevirtModule::trySingleImplDevirt(
792 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000793 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000794 // See if the program contains a single implementation of this virtual
795 // function.
796 Function *TheFn = TargetsForSlot[0].Fn;
797 for (auto &&Target : TargetsForSlot)
798 if (TheFn != Target.Fn)
799 return false;
800
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000801 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000802 if (RemarksEnabled)
803 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000804
805 bool IsExported = false;
806 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
807 if (!IsExported)
808 return false;
809
810 // If the only implementation has local linkage, we must promote to external
811 // to make it visible to thin LTO objects. We can only get here during the
812 // ThinLTO export phase.
813 if (TheFn->hasLocalLinkage()) {
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000814 std::string NewName = (TheFn->getName() + "$merged").str();
815
816 // Since we are renaming the function, any comdats with the same name must
817 // also be renamed. This is required when targeting COFF, as the comdat name
818 // must match one of the names of the symbols in the comdat.
819 if (Comdat *C = TheFn->getComdat()) {
820 if (C->getName() == TheFn->getName()) {
821 Comdat *NewC = M.getOrInsertComdat(NewName);
822 NewC->setSelectionKind(C->getSelectionKind());
823 for (GlobalObject &GO : M.global_objects())
824 if (GO.getComdat() == C)
825 GO.setComdat(NewC);
826 }
827 }
828
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000829 TheFn->setLinkage(GlobalValue::ExternalLinkage);
830 TheFn->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000831 TheFn->setName(NewName);
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000832 }
833
834 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
835 Res->SingleImplName = TheFn->getName();
836
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000837 return true;
838}
839
Peter Collingbourne29748562018-03-09 19:11:44 +0000840void DevirtModule::tryICallBranchFunnel(
841 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
842 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
843 Triple T(M.getTargetTriple());
844 if (T.getArch() != Triple::x86_64)
845 return;
846
Vitaly Buka66f53d72018-04-06 21:32:36 +0000847 if (TargetsForSlot.size() > ClThreshold)
Peter Collingbourne29748562018-03-09 19:11:44 +0000848 return;
849
850 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
851 if (!HasNonDevirt)
852 for (auto &P : SlotInfo.ConstCSInfo)
853 if (!P.second.AllCallSitesDevirted) {
854 HasNonDevirt = true;
855 break;
856 }
857
858 if (!HasNonDevirt)
859 return;
860
861 FunctionType *FT =
862 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
863 Function *JT;
864 if (isa<MDString>(Slot.TypeID)) {
865 JT = Function::Create(FT, Function::ExternalLinkage,
Dylan McKayf920da02018-12-18 09:52:52 +0000866 M.getDataLayout().getProgramAddressSpace(),
Peter Collingbourne29748562018-03-09 19:11:44 +0000867 getGlobalName(Slot, {}, "branch_funnel"), &M);
868 JT->setVisibility(GlobalValue::HiddenVisibility);
869 } else {
Dylan McKayf920da02018-12-18 09:52:52 +0000870 JT = Function::Create(FT, Function::InternalLinkage,
871 M.getDataLayout().getProgramAddressSpace(),
872 "branch_funnel", &M);
Peter Collingbourne29748562018-03-09 19:11:44 +0000873 }
874 JT->addAttribute(1, Attribute::Nest);
875
876 std::vector<Value *> JTArgs;
877 JTArgs.push_back(JT->arg_begin());
878 for (auto &T : TargetsForSlot) {
879 JTArgs.push_back(getMemberAddr(T.TM));
880 JTArgs.push_back(T.Fn);
881 }
882
883 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
884 Constant *Intr =
885 Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
886
887 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
888 CI->setTailCallKind(CallInst::TCK_MustTail);
889 ReturnInst::Create(M.getContext(), nullptr, BB);
890
891 bool IsExported = false;
892 applyICallBranchFunnel(SlotInfo, JT, IsExported);
893 if (IsExported)
894 Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
895}
896
897void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
898 Constant *JT, bool &IsExported) {
899 auto Apply = [&](CallSiteInfo &CSInfo) {
900 if (CSInfo.isExported())
901 IsExported = true;
902 if (CSInfo.AllCallSitesDevirted)
903 return;
904 for (auto &&VCallSite : CSInfo.CallSites) {
905 CallSite CS = VCallSite.CS;
906
907 // Jump tables are only profitable if the retpoline mitigation is enabled.
908 Attribute FSAttr = CS.getCaller()->getFnAttribute("target-features");
909 if (FSAttr.hasAttribute(Attribute::None) ||
910 !FSAttr.getValueAsString().contains("+retpoline"))
911 continue;
912
913 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +0000914 VCallSite.emitRemark("branch-funnel",
915 JT->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne29748562018-03-09 19:11:44 +0000916
917 // Pass the address of the vtable in the nest register, which is r10 on
918 // x86_64.
919 std::vector<Type *> NewArgs;
920 NewArgs.push_back(Int8PtrTy);
921 for (Type *T : CS.getFunctionType()->params())
922 NewArgs.push_back(T);
923 PointerType *NewFT = PointerType::getUnqual(
924 FunctionType::get(CS.getFunctionType()->getReturnType(), NewArgs,
925 CS.getFunctionType()->isVarArg()));
926
927 IRBuilder<> IRB(CS.getInstruction());
928 std::vector<Value *> Args;
929 Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
930 for (unsigned I = 0; I != CS.getNumArgOperands(); ++I)
931 Args.push_back(CS.getArgOperand(I));
932
933 CallSite NewCS;
934 if (CS.isCall())
935 NewCS = IRB.CreateCall(IRB.CreateBitCast(JT, NewFT), Args);
936 else
937 NewCS = IRB.CreateInvoke(
938 IRB.CreateBitCast(JT, NewFT),
939 cast<InvokeInst>(CS.getInstruction())->getNormalDest(),
940 cast<InvokeInst>(CS.getInstruction())->getUnwindDest(), Args);
941 NewCS.setCallingConv(CS.getCallingConv());
942
943 AttributeList Attrs = CS.getAttributes();
944 std::vector<AttributeSet> NewArgAttrs;
945 NewArgAttrs.push_back(AttributeSet::get(
946 M.getContext(), ArrayRef<Attribute>{Attribute::get(
947 M.getContext(), Attribute::Nest)}));
948 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
949 NewArgAttrs.push_back(Attrs.getParamAttributes(I));
950 NewCS.setAttributes(
951 AttributeList::get(M.getContext(), Attrs.getFnAttributes(),
952 Attrs.getRetAttributes(), NewArgAttrs));
953
954 CS->replaceAllUsesWith(NewCS.getInstruction());
955 CS->eraseFromParent();
956
957 // This use is no longer unsafe.
958 if (VCallSite.NumUnsafeUses)
959 --*VCallSite.NumUnsafeUses;
960 }
961 // Don't mark as devirtualized because there may be callers compiled without
962 // retpoline mitigation, which would mean that they are lowered to
963 // llvm.type.test and therefore require an llvm.type.test resolution for the
964 // type identifier.
965 };
966 Apply(SlotInfo.CSInfo);
967 for (auto &P : SlotInfo.ConstCSInfo)
968 Apply(P.second);
969}
970
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000971bool DevirtModule::tryEvaluateFunctionsWithArgs(
972 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000973 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000974 // Evaluate each function and store the result in each target's RetVal
975 // field.
976 for (VirtualCallTarget &Target : TargetsForSlot) {
977 if (Target.Fn->arg_size() != Args.size() + 1)
978 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000979
980 Evaluator Eval(M.getDataLayout(), nullptr);
981 SmallVector<Constant *, 2> EvalArgs;
982 EvalArgs.push_back(
983 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000984 for (unsigned I = 0; I != Args.size(); ++I) {
985 auto *ArgTy = dyn_cast<IntegerType>(
986 Target.Fn->getFunctionType()->getParamType(I + 1));
987 if (!ArgTy)
988 return false;
989 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
990 }
991
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000992 Constant *RetVal;
993 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
994 !isa<ConstantInt>(RetVal))
995 return false;
996 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
997 }
998 return true;
999}
1000
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001001void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1002 uint64_t TheRetVal) {
1003 for (auto Call : CSInfo.CallSites)
1004 Call.replaceAndErase(
Sam Elliotte963c892017-08-21 16:57:21 +00001005 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001006 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001007 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001008}
1009
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001010bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001011 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
1012 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001013 // Uniform return value optimization. If all functions return the same
1014 // constant, replace all calls with that constant.
1015 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1016 for (const VirtualCallTarget &Target : TargetsForSlot)
1017 if (Target.RetVal != TheRetVal)
1018 return false;
1019
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001020 if (CSInfo.isExported()) {
1021 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
1022 Res->Info = TheRetVal;
1023 }
1024
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001025 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001026 if (RemarksEnabled)
1027 for (auto &&Target : TargetsForSlot)
1028 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001029 return true;
1030}
1031
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001032std::string DevirtModule::getGlobalName(VTableSlot Slot,
1033 ArrayRef<uint64_t> Args,
1034 StringRef Name) {
1035 std::string FullName = "__typeid_";
1036 raw_string_ostream OS(FullName);
1037 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1038 for (uint64_t Arg : Args)
1039 OS << '_' << Arg;
1040 OS << '_' << Name;
1041 return OS.str();
1042}
1043
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001044bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1045 Triple T(M.getTargetTriple());
1046 return (T.getArch() == Triple::x86 || T.getArch() == Triple::x86_64) &&
1047 T.getObjectFormat() == Triple::ELF;
1048}
1049
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001050void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1051 StringRef Name, Constant *C) {
1052 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1053 getGlobalName(Slot, Args, Name), C, &M);
1054 GA->setVisibility(GlobalValue::HiddenVisibility);
1055}
1056
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001057void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1058 StringRef Name, uint32_t Const,
1059 uint32_t &Storage) {
1060 if (shouldExportConstantsAsAbsoluteSymbols()) {
1061 exportGlobal(
1062 Slot, Args, Name,
1063 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1064 return;
1065 }
1066
1067 Storage = Const;
1068}
1069
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001070Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001071 StringRef Name) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001072 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
1073 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001074 if (GV)
1075 GV->setVisibility(GlobalValue::HiddenVisibility);
1076 return C;
1077}
1078
1079Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1080 StringRef Name, IntegerType *IntTy,
1081 uint32_t Storage) {
1082 if (!shouldExportConstantsAsAbsoluteSymbols())
1083 return ConstantInt::get(IntTy, Storage);
1084
1085 Constant *C = importGlobal(Slot, Args, Name);
1086 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1087 C = ConstantExpr::getPtrToInt(C, IntTy);
1088
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001089 // We only need to set metadata if the global is newly created, in which
1090 // case it would not have hidden visibility.
Benjamin Kramer0deb9a92018-05-31 13:29:58 +00001091 if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001092 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001093
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001094 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1095 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1096 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1097 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1098 MDNode::get(M.getContext(), {MinC, MaxC}));
1099 };
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001100 unsigned AbsWidth = IntTy->getBitWidth();
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001101 if (AbsWidth == IntPtrTy->getBitWidth())
1102 SetAbsRange(~0ull, ~0ull); // Full set.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001103 else
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001104 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001105 return C;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001106}
1107
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001108void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1109 bool IsOne,
1110 Constant *UniqueMemberAddr) {
1111 for (auto &&Call : CSInfo.CallSites) {
1112 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001113 Value *Cmp =
1114 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
1115 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001116 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
Sam Elliotte963c892017-08-21 16:57:21 +00001117 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1118 Cmp);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001119 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001120 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001121}
1122
Peter Collingbourne29748562018-03-09 19:11:44 +00001123Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1124 Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1125 return ConstantExpr::getGetElementPtr(Int8Ty, C,
1126 ConstantInt::get(Int64Ty, M->Offset));
1127}
1128
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001129bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001130 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001131 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1132 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001133 // IsOne controls whether we look for a 0 or a 1.
1134 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001135 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001136 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +00001137 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001138 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001139 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001140 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001141 }
1142 }
1143
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001144 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001145 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001146 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001147
Peter Collingbourne29748562018-03-09 19:11:44 +00001148 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001149 if (CSInfo.isExported()) {
1150 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1151 Res->Info = IsOne;
1152
1153 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1154 }
1155
1156 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001157 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1158 UniqueMemberAddr);
1159
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001160 // Update devirtualization statistics for targets.
1161 if (RemarksEnabled)
1162 for (auto &&Target : TargetsForSlot)
1163 Target.WasDevirt = true;
1164
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001165 return true;
1166 };
1167
1168 if (BitWidth == 1) {
1169 if (tryUniqueRetValOptFor(true))
1170 return true;
1171 if (tryUniqueRetValOptFor(false))
1172 return true;
1173 }
1174 return false;
1175}
1176
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001177void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1178 Constant *Byte, Constant *Bit) {
1179 for (auto Call : CSInfo.CallSites) {
1180 auto *RetType = cast<IntegerType>(Call.CS.getType());
1181 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001182 Value *Addr =
1183 B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001184 if (RetType->getBitWidth() == 1) {
1185 Value *Bits = B.CreateLoad(Addr);
1186 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1187 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1188 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
Sam Elliotte963c892017-08-21 16:57:21 +00001189 OREGetter, IsBitSet);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001190 } else {
1191 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1192 Value *Val = B.CreateLoad(RetType, ValAddr);
Sam Elliotte963c892017-08-21 16:57:21 +00001193 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1194 OREGetter, Val);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001195 }
1196 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001197 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001198}
1199
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001200bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001201 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1202 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001203 // This only works if the function returns an integer.
1204 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1205 if (!RetType)
1206 return false;
1207 unsigned BitWidth = RetType->getBitWidth();
1208 if (BitWidth > 64)
1209 return false;
1210
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001211 // Make sure that each function is defined, does not access memory, takes at
1212 // least one argument, does not use its first argument (which we assume is
1213 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +00001214 //
1215 // Note that we test whether this copy of the function is readnone, rather
1216 // than testing function attributes, which must hold for any copy of the
1217 // function, even a less optimized version substituted at link time. This is
1218 // sound because the virtual constant propagation optimizations effectively
1219 // inline all implementations of the virtual function into each call site,
1220 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001221 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +00001222 if (Target.Fn->isDeclaration() ||
1223 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1224 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001225 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001226 Target.Fn->getReturnType() != RetType)
1227 return false;
1228 }
1229
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001230 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001231 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1232 continue;
1233
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001234 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1235 if (Res)
1236 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1237
1238 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001239 continue;
1240
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001241 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1242 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001243 continue;
1244
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001245 // Find an allocation offset in bits in all vtables associated with the
1246 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001247 uint64_t AllocBefore =
1248 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1249 uint64_t AllocAfter =
1250 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1251
1252 // Calculate the total amount of padding needed to store a value at both
1253 // ends of the object.
1254 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1255 for (auto &&Target : TargetsForSlot) {
1256 TotalPaddingBefore += std::max<int64_t>(
1257 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1258 TotalPaddingAfter += std::max<int64_t>(
1259 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1260 }
1261
1262 // If the amount of padding is too large, give up.
1263 // FIXME: do something smarter here.
1264 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1265 continue;
1266
1267 // Calculate the offset to the value as a (possibly negative) byte offset
1268 // and (if applicable) a bit offset, and store the values in the targets.
1269 int64_t OffsetByte;
1270 uint64_t OffsetBit;
1271 if (TotalPaddingBefore <= TotalPaddingAfter)
1272 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1273 OffsetBit);
1274 else
1275 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1276 OffsetBit);
1277
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001278 if (RemarksEnabled)
1279 for (auto &&Target : TargetsForSlot)
1280 Target.WasDevirt = true;
1281
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001282
1283 if (CSByConstantArg.second.isExported()) {
1284 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001285 exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1286 ResByArg->Byte);
1287 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1288 ResByArg->Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001289 }
1290
1291 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001292 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1293 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001294 applyVirtualConstProp(CSByConstantArg.second,
1295 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001296 }
1297 return true;
1298}
1299
1300void DevirtModule::rebuildGlobal(VTableBits &B) {
1301 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1302 return;
1303
1304 // Align each byte array to pointer width.
1305 unsigned PointerSize = M.getDataLayout().getPointerSize();
1306 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1307 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1308
1309 // Before was stored in reverse order; flip it now.
1310 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1311 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1312
1313 // Build an anonymous global containing the before bytes, followed by the
1314 // original initializer, followed by the after bytes.
1315 auto NewInit = ConstantStruct::getAnon(
1316 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1317 B.GV->getInitializer(),
1318 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1319 auto NewGV =
1320 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1321 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1322 NewGV->setSection(B.GV->getSection());
1323 NewGV->setComdat(B.GV->getComdat());
1324
Peter Collingbourne0312f612016-06-25 00:23:04 +00001325 // Copy the original vtable's metadata to the anonymous global, adjusting
1326 // offsets as required.
1327 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1328
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001329 // Build an alias named after the original global, pointing at the second
1330 // element (the original initializer).
1331 auto Alias = GlobalAlias::create(
1332 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1333 ConstantExpr::getGetElementPtr(
1334 NewInit->getType(), NewGV,
1335 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1336 ConstantInt::get(Int32Ty, 1)}),
1337 &M);
1338 Alias->setVisibility(B.GV->getVisibility());
1339 Alias->takeName(B.GV);
1340
1341 B.GV->replaceAllUsesWith(Alias);
1342 B.GV->eraseFromParent();
1343}
1344
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001345bool DevirtModule::areRemarksEnabled() {
1346 const auto &FL = M.getFunctionList();
Teresa Johnson5e1c0e72018-09-18 13:42:24 +00001347 for (const Function &Fn : FL) {
1348 const auto &BBL = Fn.getBasicBlockList();
1349 if (BBL.empty())
1350 continue;
1351 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
1352 return DI.isEnabled();
1353 }
1354 return false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001355}
1356
Peter Collingbourne0312f612016-06-25 00:23:04 +00001357void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1358 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001359 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001360 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1361 // points to a member of the type identifier %md. Group calls by (type ID,
1362 // offset) pair (effectively the identity of the virtual function) and store
1363 // to CallSlots.
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001364 DenseSet<CallSite> SeenCallSites;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001365 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001366 I != E;) {
1367 auto CI = dyn_cast<CallInst>(I->getUser());
1368 ++I;
1369 if (!CI)
1370 continue;
1371
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001372 // Search for virtual calls based on %p and add them to DevirtCalls.
1373 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001374 SmallVector<CallInst *, 1> Assumes;
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001375 auto &DT = LookupDomTree(*CI->getFunction());
1376 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001377
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001378 // If we found any, add them to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001379 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001380 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001381 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1382 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001383 for (DevirtCallSite Call : DevirtCalls) {
1384 // Only add this CallSite if we haven't seen it before. The vtable
1385 // pointer may have been CSE'd with pointers from other call sites,
1386 // and we don't want to process call sites multiple times. We can't
1387 // just skip the vtable Ptr if it has been seen before, however, since
1388 // it may be shared by type tests that dominate different calls.
1389 if (SeenCallSites.insert(Call.CS).second)
Peter Collingbourne001052a2017-08-22 21:41:19 +00001390 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001391 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001392 }
1393
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001394 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001395 for (auto Assume : Assumes)
1396 Assume->eraseFromParent();
1397 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1398 // may use the vtable argument later.
1399 if (CI->use_empty())
1400 CI->eraseFromParent();
1401 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001402}
1403
1404void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1405 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1406
1407 for (auto I = TypeCheckedLoadFunc->use_begin(),
1408 E = TypeCheckedLoadFunc->use_end();
1409 I != E;) {
1410 auto CI = dyn_cast<CallInst>(I->getUser());
1411 ++I;
1412 if (!CI)
1413 continue;
1414
1415 Value *Ptr = CI->getArgOperand(0);
1416 Value *Offset = CI->getArgOperand(1);
1417 Value *TypeIdValue = CI->getArgOperand(2);
1418 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1419
1420 SmallVector<DevirtCallSite, 1> DevirtCalls;
1421 SmallVector<Instruction *, 1> LoadedPtrs;
1422 SmallVector<Instruction *, 1> Preds;
1423 bool HasNonCallUses = false;
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001424 auto &DT = LookupDomTree(*CI->getFunction());
Peter Collingbourne0312f612016-06-25 00:23:04 +00001425 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001426 HasNonCallUses, CI, DT);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001427
1428 // Start by generating "pessimistic" code that explicitly loads the function
1429 // pointer from the vtable and performs the type check. If possible, we will
1430 // eliminate the load and the type check later.
1431
1432 // If possible, only generate the load at the point where it is used.
1433 // This helps avoid unnecessary spills.
1434 IRBuilder<> LoadB(
1435 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1436 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1437 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1438 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1439
1440 for (Instruction *LoadedPtr : LoadedPtrs) {
1441 LoadedPtr->replaceAllUsesWith(LoadedValue);
1442 LoadedPtr->eraseFromParent();
1443 }
1444
1445 // Likewise for the type test.
1446 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1447 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1448
1449 for (Instruction *Pred : Preds) {
1450 Pred->replaceAllUsesWith(TypeTestCall);
1451 Pred->eraseFromParent();
1452 }
1453
1454 // We have already erased any extractvalue instructions that refer to the
1455 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1456 // (although this is unlikely). In that case, explicitly build a pair and
1457 // RAUW it.
1458 if (!CI->use_empty()) {
1459 Value *Pair = UndefValue::get(CI->getType());
1460 IRBuilder<> B(CI);
1461 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1462 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1463 CI->replaceAllUsesWith(Pair);
1464 }
1465
1466 // The number of unsafe uses is initially the number of uses.
1467 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1468 NumUnsafeUses = DevirtCalls.size();
1469
1470 // If the function pointer has a non-call user, we cannot eliminate the type
1471 // check, as one of those users may eventually call the pointer. Increment
1472 // the unsafe use count to make sure it cannot reach zero.
1473 if (HasNonCallUses)
1474 ++NumUnsafeUses;
1475 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001476 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1477 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001478 }
1479
1480 CI->eraseFromParent();
1481 }
1482}
1483
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001484void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001485 const TypeIdSummary *TidSummary =
Peter Collingbournef7691d82017-03-22 18:22:59 +00001486 ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001487 if (!TidSummary)
1488 return;
1489 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1490 if (ResI == TidSummary->WPDRes.end())
1491 return;
1492 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001493
1494 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1495 // The type of the function in the declaration is irrelevant because every
1496 // call site will cast it to the correct type.
James Y Knightfadf2502019-01-31 21:51:58 +00001497 auto *SingleImpl = M.getOrInsertFunction(
1498 Res.SingleImplName, Type::getVoidTy(M.getContext()));
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001499
1500 // This is the import phase so we should not be exporting anything.
1501 bool IsExported = false;
1502 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1503 assert(!IsExported);
1504 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001505
1506 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1507 auto I = Res.ResByArg.find(CSByConstantArg.first);
1508 if (I == Res.ResByArg.end())
1509 continue;
1510 auto &ResByArg = I->second;
1511 // FIXME: We should figure out what to do about the "function name" argument
1512 // to the apply* functions, as the function names are unavailable during the
1513 // importing phase. For now we just pass the empty string. This does not
1514 // impact correctness because the function names are just used for remarks.
1515 switch (ResByArg.TheKind) {
1516 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1517 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1518 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001519 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1520 Constant *UniqueMemberAddr =
1521 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1522 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1523 UniqueMemberAddr);
1524 break;
1525 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001526 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001527 Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
1528 Int32Ty, ResByArg.Byte);
1529 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
1530 ResByArg.Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001531 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
Adrian Prantl0e6694d2017-12-19 22:05:25 +00001532 break;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001533 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001534 default:
1535 break;
1536 }
1537 }
Peter Collingbourne29748562018-03-09 19:11:44 +00001538
1539 if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
James Y Knightfadf2502019-01-31 21:51:58 +00001540 auto *JT = M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
1541 Type::getVoidTy(M.getContext()));
Peter Collingbourne29748562018-03-09 19:11:44 +00001542 bool IsExported = false;
1543 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1544 assert(!IsExported);
1545 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001546}
1547
1548void DevirtModule::removeRedundantTypeTests() {
1549 auto True = ConstantInt::getTrue(M.getContext());
1550 for (auto &&U : NumUnsafeUsesForTypeTest) {
1551 if (U.second == 0) {
1552 U.first->replaceAllUsesWith(True);
1553 U.first->eraseFromParent();
1554 }
1555 }
1556}
1557
Peter Collingbourne0312f612016-06-25 00:23:04 +00001558bool DevirtModule::run() {
1559 Function *TypeTestFunc =
1560 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1561 Function *TypeCheckedLoadFunc =
1562 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1563 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1564
Teresa Johnson290a8392019-01-11 18:31:57 +00001565 // If only some of the modules were split, we cannot correctly handle
1566 // code that contains type tests or type checked loads.
1567 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
1568 (ImportSummary && ImportSummary->partiallySplitLTOUnits())) {
1569 if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1570 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
1571 report_fatal_error("inconsistent LTO Unit splitting with llvm.type.test "
1572 "or llvm.type.checked.load");
1573 return false;
1574 }
1575
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001576 // Normally if there are no users of the devirtualization intrinsics in the
1577 // module, this pass has nothing to do. But if we are exporting, we also need
1578 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001579 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001580 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001581 AssumeFunc->use_empty()) &&
1582 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1583 return false;
1584
1585 if (TypeTestFunc && AssumeFunc)
1586 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1587
1588 if (TypeCheckedLoadFunc)
1589 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001590
Peter Collingbournef7691d82017-03-22 18:22:59 +00001591 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001592 for (auto &S : CallSlots)
1593 importResolution(S.first, S.second);
1594
1595 removeRedundantTypeTests();
1596
1597 // The rest of the code is only necessary when exporting or during regular
1598 // LTO, so we are done.
1599 return true;
1600 }
1601
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001602 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001603 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001604 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1605 buildTypeIdentifierMap(Bits, TypeIdMap);
1606 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001607 return true;
1608
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001609 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001610 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001611 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1612 for (auto &P : TypeIdMap) {
1613 if (auto *TypeId = dyn_cast<MDString>(P.first))
1614 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1615 TypeId);
1616 }
1617
Peter Collingbournef7691d82017-03-22 18:22:59 +00001618 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001619 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001620 auto *FS = dyn_cast<FunctionSummary>(S.get());
1621 if (!FS)
1622 continue;
1623 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001624 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1625 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001626 CallSlots[{MD, VF.Offset}]
1627 .CSInfo.markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001628 }
1629 }
1630 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1631 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001632 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001633 }
1634 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001635 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001636 FS->type_test_assume_const_vcalls()) {
1637 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001638 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001639 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001640 .markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001641 }
1642 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001643 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001644 FS->type_checked_load_const_vcalls()) {
1645 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001646 CallSlots[{MD, VC.VFunc.Offset}]
1647 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001648 .addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001649 }
1650 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001651 }
1652 }
1653 }
1654
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001655 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001656 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001657 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001658 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001659 // Search each of the members of the type identifier for the virtual
1660 // function implementation at offset S.first.ByteOffset, and add to
1661 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001662 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001663 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1664 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001665 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001666 if (ExportSummary && isa<MDString>(S.first.TypeID))
1667 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001668 ->getOrInsertTypeIdSummary(
1669 cast<MDString>(S.first.TypeID)->getString())
1670 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001671
Peter Collingbourne29748562018-03-09 19:11:44 +00001672 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res)) {
1673 DidVirtualConstProp |=
1674 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
1675
1676 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
1677 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001678
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001679 // Collect functions devirtualized at least for one call site for stats.
1680 if (RemarksEnabled)
1681 for (const auto &T : TargetsForSlot)
1682 if (T.WasDevirt)
1683 DevirtTargets[T.Fn->getName()] = T.Fn;
1684 }
1685
1686 // CFI-specific: if we are exporting and any llvm.type.checked.load
1687 // intrinsics were *not* devirtualized, we need to add the resulting
1688 // llvm.type.test intrinsics to the function summaries so that the
1689 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001690 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001691 auto GUID =
1692 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1693 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1694 FS->addTypeTest(GUID);
1695 for (auto &CCS : S.second.ConstCSInfo)
1696 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1697 FS->addTypeTest(GUID);
1698 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001699 }
1700
1701 if (RemarksEnabled) {
1702 // Generate remarks for each devirtualized function.
1703 for (const auto &DT : DevirtTargets) {
1704 Function *F = DT.second;
Sam Elliotte963c892017-08-21 16:57:21 +00001705
Sam Elliotte963c892017-08-21 16:57:21 +00001706 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +00001707 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
1708 << "devirtualized "
1709 << NV("FunctionName", F->getName()));
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001710 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001711 }
1712
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001713 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001714
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001715 // Rebuild each global we touched as part of virtual constant propagation to
1716 // include the before and after bytes.
1717 if (DidVirtualConstProp)
1718 for (VTableBits &B : Bits)
1719 rebuildGlobal(B);
1720
1721 return true;
1722}