blob: 2c08cd82a5b5440c599309eaea535589942673b8 [file] [log] [blame]
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001//===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements whole program optimization of virtual calls in cases
Peter Collingbourne7efd7502016-06-24 21:21:32 +000011// where we know (via !type metadata) that the list of callees is fixed. This
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000012// includes the following:
13// - Single implementation devirtualization: if a virtual call has a single
14// possible callee, replace all calls with a direct call to that callee.
15// - Virtual constant propagation: if the virtual function's return type is an
16// integer <=64 bits and all possible callees are readnone, for each class and
17// each list of constant arguments: evaluate the function, store the return
18// value alongside the virtual table, and rewrite each virtual call as a load
19// from the virtual table.
20// - Uniform return value optimization: if the conditions for virtual constant
21// propagation hold and each function returns the same constant value, replace
22// each virtual call with that constant.
23// - Unique return value optimization for i1 return values: if the conditions
24// for virtual constant propagation hold and a single vtable's function
25// returns 0, or a single vtable's function returns 1, replace each virtual
26// call with a comparison of the vptr against that vtable's address.
27//
Peter Collingbourneb406baa2017-03-04 01:23:30 +000028// This pass is intended to be used during the regular and thin LTO pipelines.
29// During regular LTO, the pass determines the best optimization for each
30// virtual call and applies the resolutions directly to virtual calls that are
31// eligible for virtual call optimization (i.e. calls that use either of the
32// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). During
33// ThinLTO, the pass operates in two phases:
34// - Export phase: this is run during the thin link over a single merged module
35// that contains all vtables with !type metadata that participate in the link.
36// The pass computes a resolution for each virtual call and stores it in the
37// type identifier summary.
38// - Import phase: this is run during the thin backends over the individual
39// modules. The pass applies the resolutions previously computed during the
40// import phase to each eligible virtual call.
41//
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000042//===----------------------------------------------------------------------===//
43
44#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000045#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include "llvm/ADT/DenseMap.h"
47#include "llvm/ADT/DenseMapInfo.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000048#include "llvm/ADT/DenseSet.h"
49#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000051#include "llvm/ADT/iterator_range.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000052#include "llvm/Analysis/AliasAnalysis.h"
53#include "llvm/Analysis/BasicAliasAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000054#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000055#include "llvm/Analysis/TypeMetadataUtils.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000056#include "llvm/IR/CallSite.h"
57#include "llvm/IR/Constants.h"
58#include "llvm/IR/DataLayout.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/IR/DebugLoc.h"
60#include "llvm/IR/DerivedTypes.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 Buka66f53d72018-04-06 21:32:36 +0000114static cl::opt<int> ClThreshold("wholeprogramdevirt-branch-funnel-threshold",
115 cl::Hidden, cl::init(10), cl::ZeroOrMore,
116 cl::desc("Maximum number of call targets per "
117 "call site to enable branch funnels"));
118
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000119// Find the minimum offset that we may store a value of size Size bits at. If
120// IsAfter is set, look for an offset before the object, otherwise look for an
121// offset after the object.
122uint64_t
123wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
124 bool IsAfter, uint64_t Size) {
125 // Find a minimum offset taking into account only vtable sizes.
126 uint64_t MinByte = 0;
127 for (const VirtualCallTarget &Target : Targets) {
128 if (IsAfter)
129 MinByte = std::max(MinByte, Target.minAfterBytes());
130 else
131 MinByte = std::max(MinByte, Target.minBeforeBytes());
132 }
133
134 // Build a vector of arrays of bytes covering, for each target, a slice of the
135 // used region (see AccumBitVector::BytesUsed in
136 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
137 // this aligns the used regions to start at MinByte.
138 //
139 // In this example, A, B and C are vtables, # is a byte already allocated for
140 // a virtual function pointer, AAAA... (etc.) are the used regions for the
141 // vtables and Offset(X) is the value computed for the Offset variable below
142 // for X.
143 //
144 // Offset(A)
145 // | |
146 // |MinByte
147 // A: ################AAAAAAAA|AAAAAAAA
148 // B: ########BBBBBBBBBBBBBBBB|BBBB
149 // C: ########################|CCCCCCCCCCCCCCCC
150 // | Offset(B) |
151 //
152 // This code produces the slices of A, B and C that appear after the divider
153 // at MinByte.
154 std::vector<ArrayRef<uint8_t>> Used;
155 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000156 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
157 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000158 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
159 : MinByte - Target.minBeforeBytes();
160
161 // Disregard used regions that are smaller than Offset. These are
162 // effectively all-free regions that do not need to be checked.
163 if (VTUsed.size() > Offset)
164 Used.push_back(VTUsed.slice(Offset));
165 }
166
167 if (Size == 1) {
168 // Find a free bit in each member of Used.
169 for (unsigned I = 0;; ++I) {
170 uint8_t BitsUsed = 0;
171 for (auto &&B : Used)
172 if (I < B.size())
173 BitsUsed |= B[I];
174 if (BitsUsed != 0xff)
175 return (MinByte + I) * 8 +
176 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
177 }
178 } else {
179 // Find a free (Size/8) byte region in each member of Used.
180 // FIXME: see if alignment helps.
181 for (unsigned I = 0;; ++I) {
182 for (auto &&B : Used) {
183 unsigned Byte = 0;
184 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
185 if (B[I + Byte])
186 goto NextI;
187 ++Byte;
188 }
189 }
190 return (MinByte + I) * 8;
191 NextI:;
192 }
193 }
194}
195
196void wholeprogramdevirt::setBeforeReturnValues(
197 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
198 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
199 if (BitWidth == 1)
200 OffsetByte = -(AllocBefore / 8 + 1);
201 else
202 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
203 OffsetBit = AllocBefore % 8;
204
205 for (VirtualCallTarget &Target : Targets) {
206 if (BitWidth == 1)
207 Target.setBeforeBit(AllocBefore);
208 else
209 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
210 }
211}
212
213void wholeprogramdevirt::setAfterReturnValues(
214 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
215 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
216 if (BitWidth == 1)
217 OffsetByte = AllocAfter / 8;
218 else
219 OffsetByte = (AllocAfter + 7) / 8;
220 OffsetBit = AllocAfter % 8;
221
222 for (VirtualCallTarget &Target : Targets) {
223 if (BitWidth == 1)
224 Target.setAfterBit(AllocAfter);
225 else
226 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
227 }
228}
229
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000230VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
231 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000232 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000233
234namespace {
235
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000236// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000237// tables, and the ByteOffset is the offset in bytes from the address point to
238// the virtual function pointer.
239struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000240 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000241 uint64_t ByteOffset;
242};
243
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000244} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000245
Peter Collingbourne9b656522016-02-09 23:01:38 +0000246namespace llvm {
247
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000248template <> struct DenseMapInfo<VTableSlot> {
249 static VTableSlot getEmptyKey() {
250 return {DenseMapInfo<Metadata *>::getEmptyKey(),
251 DenseMapInfo<uint64_t>::getEmptyKey()};
252 }
253 static VTableSlot getTombstoneKey() {
254 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
255 DenseMapInfo<uint64_t>::getTombstoneKey()};
256 }
257 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000258 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000259 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
260 }
261 static bool isEqual(const VTableSlot &LHS,
262 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000263 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000264 }
265};
266
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000267} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000268
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000269namespace {
270
271// A virtual call site. VTable is the loaded virtual table pointer, and CS is
272// the indirect virtual call.
273struct VirtualCallSite {
274 Value *VTable;
275 CallSite CS;
276
Peter Collingbourne0312f612016-06-25 00:23:04 +0000277 // If non-null, this field points to the associated unsafe use count stored in
278 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
279 // of that field for details.
280 unsigned *NumUnsafeUses;
281
Sam Elliotte963c892017-08-21 16:57:21 +0000282 void
283 emitRemark(const StringRef OptName, const StringRef TargetName,
284 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Ivan Krasin54746452016-07-12 02:38:37 +0000285 Function *F = CS.getCaller();
Sam Elliotte963c892017-08-21 16:57:21 +0000286 DebugLoc DLoc = CS->getDebugLoc();
287 BasicBlock *Block = CS.getParent();
288
Sam Elliotte963c892017-08-21 16:57:21 +0000289 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000290 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
291 << NV("Optimization", OptName)
292 << ": devirtualized a call to "
293 << NV("FunctionName", TargetName));
Ivan Krasin54746452016-07-12 02:38:37 +0000294 }
295
Sam Elliotte963c892017-08-21 16:57:21 +0000296 void replaceAndErase(
297 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
298 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
299 Value *New) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000300 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000301 emitRemark(OptName, TargetName, OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000302 CS->replaceAllUsesWith(New);
303 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
304 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
305 II->getUnwindDest()->removePredecessor(II->getParent());
306 }
307 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000308 // This use is no longer unsafe.
309 if (NumUnsafeUses)
310 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000311 }
312};
313
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000314// Call site information collected for a specific VTableSlot and possibly a list
315// of constant integer arguments. The grouping by arguments is handled by the
316// VTableSlotInfo class.
317struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000318 /// The set of call sites for this slot. Used during regular LTO and the
319 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
320 /// call sites that appear in the merged module itself); in each of these
321 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000322 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000323
Peter Collingbourne29748562018-03-09 19:11:44 +0000324 /// Whether all call sites represented by this CallSiteInfo, including those
325 /// in summaries, have been devirtualized. This starts off as true because a
326 /// default constructed CallSiteInfo represents no call sites.
327 bool AllCallSitesDevirted = true;
328
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000329 // These fields are used during the export phase of ThinLTO and reflect
330 // information collected from function summaries.
331
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000332 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
333 /// this slot.
Peter Collingbourne29748562018-03-09 19:11:44 +0000334 bool SummaryHasTypeTestAssumeUsers = false;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000335
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000336 /// CFI-specific: a vector containing the list of function summaries that use
337 /// the llvm.type.checked.load intrinsic and therefore will require
338 /// resolutions for llvm.type.test in order to implement CFI checks if
339 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000340 /// pass will clear this vector by calling markDevirt(). If at the end of the
341 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
342 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000343 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000344
345 bool isExported() const {
346 return SummaryHasTypeTestAssumeUsers ||
347 !SummaryTypeCheckedLoadUsers.empty();
348 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000349
Peter Collingbourne29748562018-03-09 19:11:44 +0000350 void markSummaryHasTypeTestAssumeUsers() {
351 SummaryHasTypeTestAssumeUsers = true;
352 AllCallSitesDevirted = false;
353 }
354
355 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
356 SummaryTypeCheckedLoadUsers.push_back(FS);
357 AllCallSitesDevirted = false;
358 }
359
360 void markDevirt() {
361 AllCallSitesDevirted = true;
362
363 // As explained in the comment for SummaryTypeCheckedLoadUsers.
364 SummaryTypeCheckedLoadUsers.clear();
365 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000366};
367
368// Call site information collected for a specific VTableSlot.
369struct VTableSlotInfo {
370 // The set of call sites which do not have all constant integer arguments
371 // (excluding "this").
372 CallSiteInfo CSInfo;
373
374 // The set of call sites with all constant integer arguments (excluding
375 // "this"), grouped by argument list.
376 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
377
378 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
379
380private:
381 CallSiteInfo &findCallSiteInfo(CallSite CS);
382};
383
384CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
385 std::vector<uint64_t> Args;
386 auto *CI = dyn_cast<IntegerType>(CS.getType());
387 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
388 return CSInfo;
389 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
390 auto *CI = dyn_cast<ConstantInt>(Arg);
391 if (!CI || CI->getBitWidth() > 64)
392 return CSInfo;
393 Args.push_back(CI->getZExtValue());
394 }
395 return ConstCSInfo[Args];
396}
397
398void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
399 unsigned *NumUnsafeUses) {
Peter Collingbourne29748562018-03-09 19:11:44 +0000400 auto &CSI = findCallSiteInfo(CS);
401 CSI.AllCallSitesDevirted = false;
402 CSI.CallSites.push_back({VTable, CS, NumUnsafeUses});
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000403}
404
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000405struct DevirtModule {
406 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000407 function_ref<AAResults &(Function &)> AARGetter;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000408
Peter Collingbournef7691d82017-03-22 18:22:59 +0000409 ModuleSummaryIndex *ExportSummary;
410 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000411
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000412 IntegerType *Int8Ty;
413 PointerType *Int8PtrTy;
414 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000415 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000416 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000417
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000418 bool RemarksEnabled;
Sam Elliotte963c892017-08-21 16:57:21 +0000419 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000420
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000421 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000422
Peter Collingbourne0312f612016-06-25 00:23:04 +0000423 // This map keeps track of the number of "unsafe" uses of a loaded function
424 // pointer. The key is the associated llvm.type.test intrinsic call generated
425 // by this pass. An unsafe use is one that calls the loaded function pointer
426 // directly. Every time we eliminate an unsafe use (for example, by
427 // devirtualizing it or by applying virtual constant propagation), we
428 // decrement the value stored in this map. If a value reaches zero, we can
429 // eliminate the type check by RAUWing the associated llvm.type.test call with
430 // true.
431 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
432
Peter Collingbourne37317f12017-02-17 18:17:04 +0000433 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Sam Elliotte963c892017-08-21 16:57:21 +0000434 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000435 ModuleSummaryIndex *ExportSummary,
436 const ModuleSummaryIndex *ImportSummary)
437 : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
438 ImportSummary(ImportSummary), Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000439 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000440 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000441 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000442 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Sam Elliotte963c892017-08-21 16:57:21 +0000443 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000444 assert(!(ExportSummary && ImportSummary));
445 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000446
447 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000448
Peter Collingbourne0312f612016-06-25 00:23:04 +0000449 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
450 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
451
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000452 void buildTypeIdentifierMap(
453 std::vector<VTableBits> &Bits,
454 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000455 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000456 bool
457 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
458 const std::set<TypeMemberInfo> &TypeMemberInfos,
459 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000460
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000461 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
462 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000463 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000464 VTableSlotInfo &SlotInfo,
465 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000466
Peter Collingbourne29748562018-03-09 19:11:44 +0000467 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
468 bool &IsExported);
469 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
470 VTableSlotInfo &SlotInfo,
471 WholeProgramDevirtResolution *Res, VTableSlot Slot);
472
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000473 bool tryEvaluateFunctionsWithArgs(
474 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000475 ArrayRef<uint64_t> Args);
476
477 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
478 uint64_t TheRetVal);
479 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000480 CallSiteInfo &CSInfo,
481 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000482
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000483 // Returns the global symbol name that is used to export information about the
484 // given vtable slot and list of arguments.
485 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
486 StringRef Name);
487
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000488 bool shouldExportConstantsAsAbsoluteSymbols();
489
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000490 // This function is called during the export phase to create a symbol
491 // definition containing information about the given vtable slot and list of
492 // arguments.
493 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
494 Constant *C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000495 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
496 uint32_t Const, uint32_t &Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000497
498 // This function is called during the import phase to create a reference to
499 // the symbol definition created during the export phase.
500 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000501 StringRef Name);
502 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
503 StringRef Name, IntegerType *IntTy,
504 uint32_t Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000505
Peter Collingbourne29748562018-03-09 19:11:44 +0000506 Constant *getMemberAddr(const TypeMemberInfo *M);
507
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000508 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
509 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000510 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000511 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000512 CallSiteInfo &CSInfo,
513 WholeProgramDevirtResolution::ByArg *Res,
514 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000515
516 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
517 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000518 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000519 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000520 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000521
522 void rebuildGlobal(VTableBits &B);
523
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000524 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
525 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
526
527 // If we were able to eliminate all unsafe uses for a type checked load,
528 // eliminate the associated type tests by replacing them with true.
529 void removeRedundantTypeTests();
530
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000531 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000532
533 // Lower the module using the action and summary passed as command line
534 // arguments. For testing purposes only.
Sam Elliotte963c892017-08-21 16:57:21 +0000535 static bool runForTesting(
536 Module &M, function_ref<AAResults &(Function &)> AARGetter,
537 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000538};
539
540struct WholeProgramDevirt : public ModulePass {
541 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000542
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000543 bool UseCommandLine = false;
544
Peter Collingbournef7691d82017-03-22 18:22:59 +0000545 ModuleSummaryIndex *ExportSummary;
546 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000547
548 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
549 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
550 }
551
Peter Collingbournef7691d82017-03-22 18:22:59 +0000552 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
553 const ModuleSummaryIndex *ImportSummary)
554 : ModulePass(ID), ExportSummary(ExportSummary),
555 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000556 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
557 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000558
559 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000560 if (skipModule(M))
561 return false;
Sam Elliotte963c892017-08-21 16:57:21 +0000562
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000563 // In the new pass manager, we can request the optimization
564 // remark emitter pass on a per-function-basis, which the
565 // OREGetter will do for us.
566 // In the old pass manager, this is harder, so we just build
567 // an optimization remark emitter on the fly, when we need it.
568 std::unique_ptr<OptimizationRemarkEmitter> ORE;
569 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
570 ORE = make_unique<OptimizationRemarkEmitter>(F);
571 return *ORE;
572 };
Sam Elliotte963c892017-08-21 16:57:21 +0000573
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000574 if (UseCommandLine)
Sam Elliotte963c892017-08-21 16:57:21 +0000575 return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter);
576
577 return DevirtModule(M, LegacyAARGetter(*this), OREGetter, ExportSummary,
578 ImportSummary)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000579 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000580 }
581
582 void getAnalysisUsage(AnalysisUsage &AU) const override {
583 AU.addRequired<AssumptionCacheTracker>();
584 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000585 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000586};
587
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000588} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000589
Peter Collingbourne37317f12017-02-17 18:17:04 +0000590INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
591 "Whole program devirtualization", false, false)
592INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
593INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
594INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
595 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000596char WholeProgramDevirt::ID = 0;
597
Peter Collingbournef7691d82017-03-22 18:22:59 +0000598ModulePass *
599llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
600 const ModuleSummaryIndex *ImportSummary) {
601 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000602}
603
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000604PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000605 ModuleAnalysisManager &AM) {
606 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
607 auto AARGetter = [&](Function &F) -> AAResults & {
608 return FAM.getResult<AAManager>(F);
609 };
Sam Elliotte963c892017-08-21 16:57:21 +0000610 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
611 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
612 };
613 if (!DevirtModule(M, AARGetter, OREGetter, nullptr, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000614 return PreservedAnalyses::all();
615 return PreservedAnalyses::none();
616}
617
Peter Collingbourne37317f12017-02-17 18:17:04 +0000618bool DevirtModule::runForTesting(
Sam Elliotte963c892017-08-21 16:57:21 +0000619 Module &M, function_ref<AAResults &(Function &)> AARGetter,
620 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Eugene Leviant28d8a492018-01-22 13:35:40 +0000621 ModuleSummaryIndex Summary(/*IsPerformingAnalysis=*/false);
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000622
623 // Handle the command-line summary arguments. This code is for testing
624 // purposes only, so we handle errors directly.
625 if (!ClReadSummary.empty()) {
626 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
627 ": ");
628 auto ReadSummaryFile =
629 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
630
631 yaml::Input In(ReadSummaryFile->getBuffer());
632 In >> Summary;
633 ExitOnErr(errorCodeToError(In.error()));
634 }
635
Peter Collingbournef7691d82017-03-22 18:22:59 +0000636 bool Changed =
637 DevirtModule(
Sam Elliotte963c892017-08-21 16:57:21 +0000638 M, AARGetter, OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000639 ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
640 ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
641 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000642
643 if (!ClWriteSummary.empty()) {
644 ExitOnError ExitOnErr(
645 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
646 std::error_code EC;
647 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
648 ExitOnErr(errorCodeToError(EC));
649
650 yaml::Output Out(OS);
651 Out << Summary;
652 }
653
654 return Changed;
655}
656
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000657void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000658 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000659 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000660 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000661 Bits.reserve(M.getGlobalList().size());
662 SmallVector<MDNode *, 2> Types;
663 for (GlobalVariable &GV : M.globals()) {
664 Types.clear();
665 GV.getMetadata(LLVMContext::MD_type, Types);
666 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000667 continue;
668
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000669 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000670 if (!BitsPtr) {
671 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000672 Bits.back().GV = &GV;
673 Bits.back().ObjectSize =
674 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000675 BitsPtr = &Bits.back();
676 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000677
678 for (MDNode *Type : Types) {
679 auto TypeID = Type->getOperand(1).get();
680
681 uint64_t Offset =
682 cast<ConstantInt>(
683 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
684 ->getZExtValue();
685
686 TypeIdMap[TypeID].insert({BitsPtr, Offset});
687 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000688 }
689}
690
Peter Collingbourne87867542016-12-09 01:10:11 +0000691Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
692 if (I->getType()->isPointerTy()) {
693 if (Offset == 0)
694 return I;
695 return nullptr;
696 }
697
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000698 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000699
700 if (auto *C = dyn_cast<ConstantStruct>(I)) {
701 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000702 if (Offset >= SL->getSizeInBytes())
703 return nullptr;
704
Peter Collingbourne87867542016-12-09 01:10:11 +0000705 unsigned Op = SL->getElementContainingOffset(Offset);
706 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
707 Offset - SL->getElementOffset(Op));
708 }
709 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000710 ArrayType *VTableTy = C->getType();
711 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
712
Peter Collingbourne87867542016-12-09 01:10:11 +0000713 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000714 if (Op >= C->getNumOperands())
715 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000716
Peter Collingbourne87867542016-12-09 01:10:11 +0000717 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
718 Offset % ElemSize);
719 }
720 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000721}
722
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000723bool DevirtModule::tryFindVirtualCallTargets(
724 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000725 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
726 for (const TypeMemberInfo &TM : TypeMemberInfos) {
727 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000728 return false;
729
Peter Collingbourne87867542016-12-09 01:10:11 +0000730 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
731 TM.Offset + ByteOffset);
732 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000733 return false;
734
Peter Collingbourne87867542016-12-09 01:10:11 +0000735 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000736 if (!Fn)
737 return false;
738
739 // We can disregard __cxa_pure_virtual as a possible call target, as
740 // calls to pure virtuals are UB.
741 if (Fn->getName() == "__cxa_pure_virtual")
742 continue;
743
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000744 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000745 }
746
747 // Give up if we couldn't find any targets.
748 return !TargetsForSlot.empty();
749}
750
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000751void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000752 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000753 auto Apply = [&](CallSiteInfo &CSInfo) {
754 for (auto &&VCallSite : CSInfo.CallSites) {
755 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000756 VCallSite.emitRemark("single-impl", TheFn->getName(), OREGetter);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000757 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
758 TheFn, VCallSite.CS.getCalledValue()->getType()));
759 // This use is no longer unsafe.
760 if (VCallSite.NumUnsafeUses)
761 --*VCallSite.NumUnsafeUses;
762 }
Peter Collingbourne29748562018-03-09 19:11:44 +0000763 if (CSInfo.isExported())
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000764 IsExported = true;
Peter Collingbourne29748562018-03-09 19:11:44 +0000765 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000766 };
767 Apply(SlotInfo.CSInfo);
768 for (auto &P : SlotInfo.ConstCSInfo)
769 Apply(P.second);
770}
771
Peter Collingbournee2367412017-02-15 02:13:08 +0000772bool DevirtModule::trySingleImplDevirt(
773 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000774 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000775 // See if the program contains a single implementation of this virtual
776 // function.
777 Function *TheFn = TargetsForSlot[0].Fn;
778 for (auto &&Target : TargetsForSlot)
779 if (TheFn != Target.Fn)
780 return false;
781
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000782 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000783 if (RemarksEnabled)
784 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000785
786 bool IsExported = false;
787 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
788 if (!IsExported)
789 return false;
790
791 // If the only implementation has local linkage, we must promote to external
792 // to make it visible to thin LTO objects. We can only get here during the
793 // ThinLTO export phase.
794 if (TheFn->hasLocalLinkage()) {
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000795 std::string NewName = (TheFn->getName() + "$merged").str();
796
797 // Since we are renaming the function, any comdats with the same name must
798 // also be renamed. This is required when targeting COFF, as the comdat name
799 // must match one of the names of the symbols in the comdat.
800 if (Comdat *C = TheFn->getComdat()) {
801 if (C->getName() == TheFn->getName()) {
802 Comdat *NewC = M.getOrInsertComdat(NewName);
803 NewC->setSelectionKind(C->getSelectionKind());
804 for (GlobalObject &GO : M.global_objects())
805 if (GO.getComdat() == C)
806 GO.setComdat(NewC);
807 }
808 }
809
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000810 TheFn->setLinkage(GlobalValue::ExternalLinkage);
811 TheFn->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000812 TheFn->setName(NewName);
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000813 }
814
815 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
816 Res->SingleImplName = TheFn->getName();
817
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000818 return true;
819}
820
Peter Collingbourne29748562018-03-09 19:11:44 +0000821void DevirtModule::tryICallBranchFunnel(
822 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
823 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
824 Triple T(M.getTargetTriple());
825 if (T.getArch() != Triple::x86_64)
826 return;
827
Vitaly Buka66f53d72018-04-06 21:32:36 +0000828 if (TargetsForSlot.size() > ClThreshold)
Peter Collingbourne29748562018-03-09 19:11:44 +0000829 return;
830
831 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
832 if (!HasNonDevirt)
833 for (auto &P : SlotInfo.ConstCSInfo)
834 if (!P.second.AllCallSitesDevirted) {
835 HasNonDevirt = true;
836 break;
837 }
838
839 if (!HasNonDevirt)
840 return;
841
842 FunctionType *FT =
843 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
844 Function *JT;
845 if (isa<MDString>(Slot.TypeID)) {
846 JT = Function::Create(FT, Function::ExternalLinkage,
847 getGlobalName(Slot, {}, "branch_funnel"), &M);
848 JT->setVisibility(GlobalValue::HiddenVisibility);
849 } else {
850 JT = Function::Create(FT, Function::InternalLinkage, "branch_funnel", &M);
851 }
852 JT->addAttribute(1, Attribute::Nest);
853
854 std::vector<Value *> JTArgs;
855 JTArgs.push_back(JT->arg_begin());
856 for (auto &T : TargetsForSlot) {
857 JTArgs.push_back(getMemberAddr(T.TM));
858 JTArgs.push_back(T.Fn);
859 }
860
861 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
862 Constant *Intr =
863 Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
864
865 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
866 CI->setTailCallKind(CallInst::TCK_MustTail);
867 ReturnInst::Create(M.getContext(), nullptr, BB);
868
869 bool IsExported = false;
870 applyICallBranchFunnel(SlotInfo, JT, IsExported);
871 if (IsExported)
872 Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
873}
874
875void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
876 Constant *JT, bool &IsExported) {
877 auto Apply = [&](CallSiteInfo &CSInfo) {
878 if (CSInfo.isExported())
879 IsExported = true;
880 if (CSInfo.AllCallSitesDevirted)
881 return;
882 for (auto &&VCallSite : CSInfo.CallSites) {
883 CallSite CS = VCallSite.CS;
884
885 // Jump tables are only profitable if the retpoline mitigation is enabled.
886 Attribute FSAttr = CS.getCaller()->getFnAttribute("target-features");
887 if (FSAttr.hasAttribute(Attribute::None) ||
888 !FSAttr.getValueAsString().contains("+retpoline"))
889 continue;
890
891 if (RemarksEnabled)
892 VCallSite.emitRemark("branch-funnel", JT->getName(), OREGetter);
893
894 // Pass the address of the vtable in the nest register, which is r10 on
895 // x86_64.
896 std::vector<Type *> NewArgs;
897 NewArgs.push_back(Int8PtrTy);
898 for (Type *T : CS.getFunctionType()->params())
899 NewArgs.push_back(T);
900 PointerType *NewFT = PointerType::getUnqual(
901 FunctionType::get(CS.getFunctionType()->getReturnType(), NewArgs,
902 CS.getFunctionType()->isVarArg()));
903
904 IRBuilder<> IRB(CS.getInstruction());
905 std::vector<Value *> Args;
906 Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
907 for (unsigned I = 0; I != CS.getNumArgOperands(); ++I)
908 Args.push_back(CS.getArgOperand(I));
909
910 CallSite NewCS;
911 if (CS.isCall())
912 NewCS = IRB.CreateCall(IRB.CreateBitCast(JT, NewFT), Args);
913 else
914 NewCS = IRB.CreateInvoke(
915 IRB.CreateBitCast(JT, NewFT),
916 cast<InvokeInst>(CS.getInstruction())->getNormalDest(),
917 cast<InvokeInst>(CS.getInstruction())->getUnwindDest(), Args);
918 NewCS.setCallingConv(CS.getCallingConv());
919
920 AttributeList Attrs = CS.getAttributes();
921 std::vector<AttributeSet> NewArgAttrs;
922 NewArgAttrs.push_back(AttributeSet::get(
923 M.getContext(), ArrayRef<Attribute>{Attribute::get(
924 M.getContext(), Attribute::Nest)}));
925 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
926 NewArgAttrs.push_back(Attrs.getParamAttributes(I));
927 NewCS.setAttributes(
928 AttributeList::get(M.getContext(), Attrs.getFnAttributes(),
929 Attrs.getRetAttributes(), NewArgAttrs));
930
931 CS->replaceAllUsesWith(NewCS.getInstruction());
932 CS->eraseFromParent();
933
934 // This use is no longer unsafe.
935 if (VCallSite.NumUnsafeUses)
936 --*VCallSite.NumUnsafeUses;
937 }
938 // Don't mark as devirtualized because there may be callers compiled without
939 // retpoline mitigation, which would mean that they are lowered to
940 // llvm.type.test and therefore require an llvm.type.test resolution for the
941 // type identifier.
942 };
943 Apply(SlotInfo.CSInfo);
944 for (auto &P : SlotInfo.ConstCSInfo)
945 Apply(P.second);
946}
947
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000948bool DevirtModule::tryEvaluateFunctionsWithArgs(
949 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000950 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000951 // Evaluate each function and store the result in each target's RetVal
952 // field.
953 for (VirtualCallTarget &Target : TargetsForSlot) {
954 if (Target.Fn->arg_size() != Args.size() + 1)
955 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000956
957 Evaluator Eval(M.getDataLayout(), nullptr);
958 SmallVector<Constant *, 2> EvalArgs;
959 EvalArgs.push_back(
960 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000961 for (unsigned I = 0; I != Args.size(); ++I) {
962 auto *ArgTy = dyn_cast<IntegerType>(
963 Target.Fn->getFunctionType()->getParamType(I + 1));
964 if (!ArgTy)
965 return false;
966 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
967 }
968
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000969 Constant *RetVal;
970 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
971 !isa<ConstantInt>(RetVal))
972 return false;
973 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
974 }
975 return true;
976}
977
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000978void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
979 uint64_t TheRetVal) {
980 for (auto Call : CSInfo.CallSites)
981 Call.replaceAndErase(
Sam Elliotte963c892017-08-21 16:57:21 +0000982 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000983 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000984 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000985}
986
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000987bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000988 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
989 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000990 // Uniform return value optimization. If all functions return the same
991 // constant, replace all calls with that constant.
992 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
993 for (const VirtualCallTarget &Target : TargetsForSlot)
994 if (Target.RetVal != TheRetVal)
995 return false;
996
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000997 if (CSInfo.isExported()) {
998 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
999 Res->Info = TheRetVal;
1000 }
1001
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001002 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001003 if (RemarksEnabled)
1004 for (auto &&Target : TargetsForSlot)
1005 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001006 return true;
1007}
1008
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001009std::string DevirtModule::getGlobalName(VTableSlot Slot,
1010 ArrayRef<uint64_t> Args,
1011 StringRef Name) {
1012 std::string FullName = "__typeid_";
1013 raw_string_ostream OS(FullName);
1014 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1015 for (uint64_t Arg : Args)
1016 OS << '_' << Arg;
1017 OS << '_' << Name;
1018 return OS.str();
1019}
1020
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001021bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1022 Triple T(M.getTargetTriple());
1023 return (T.getArch() == Triple::x86 || T.getArch() == Triple::x86_64) &&
1024 T.getObjectFormat() == Triple::ELF;
1025}
1026
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001027void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1028 StringRef Name, Constant *C) {
1029 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1030 getGlobalName(Slot, Args, Name), C, &M);
1031 GA->setVisibility(GlobalValue::HiddenVisibility);
1032}
1033
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001034void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1035 StringRef Name, uint32_t Const,
1036 uint32_t &Storage) {
1037 if (shouldExportConstantsAsAbsoluteSymbols()) {
1038 exportGlobal(
1039 Slot, Args, Name,
1040 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1041 return;
1042 }
1043
1044 Storage = Const;
1045}
1046
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001047Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001048 StringRef Name) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001049 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
1050 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001051 if (GV)
1052 GV->setVisibility(GlobalValue::HiddenVisibility);
1053 return C;
1054}
1055
1056Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1057 StringRef Name, IntegerType *IntTy,
1058 uint32_t Storage) {
1059 if (!shouldExportConstantsAsAbsoluteSymbols())
1060 return ConstantInt::get(IntTy, Storage);
1061
1062 Constant *C = importGlobal(Slot, Args, Name);
1063 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1064 C = ConstantExpr::getPtrToInt(C, IntTy);
1065
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001066 // We only need to set metadata if the global is newly created, in which
1067 // case it would not have hidden visibility.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001068 if (GV->getMetadata(LLVMContext::MD_absolute_symbol))
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001069 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001070
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001071 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1072 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1073 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1074 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1075 MDNode::get(M.getContext(), {MinC, MaxC}));
1076 };
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001077 unsigned AbsWidth = IntTy->getBitWidth();
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001078 if (AbsWidth == IntPtrTy->getBitWidth())
1079 SetAbsRange(~0ull, ~0ull); // Full set.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001080 else
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001081 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001082 return C;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001083}
1084
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001085void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1086 bool IsOne,
1087 Constant *UniqueMemberAddr) {
1088 for (auto &&Call : CSInfo.CallSites) {
1089 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001090 Value *Cmp =
1091 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
1092 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001093 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
Sam Elliotte963c892017-08-21 16:57:21 +00001094 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1095 Cmp);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001096 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001097 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001098}
1099
Peter Collingbourne29748562018-03-09 19:11:44 +00001100Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1101 Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1102 return ConstantExpr::getGetElementPtr(Int8Ty, C,
1103 ConstantInt::get(Int64Ty, M->Offset));
1104}
1105
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001106bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001107 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001108 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1109 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001110 // IsOne controls whether we look for a 0 or a 1.
1111 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001112 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001113 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +00001114 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001115 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001116 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001117 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001118 }
1119 }
1120
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001121 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001122 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001123 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001124
Peter Collingbourne29748562018-03-09 19:11:44 +00001125 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001126 if (CSInfo.isExported()) {
1127 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1128 Res->Info = IsOne;
1129
1130 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1131 }
1132
1133 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001134 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1135 UniqueMemberAddr);
1136
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001137 // Update devirtualization statistics for targets.
1138 if (RemarksEnabled)
1139 for (auto &&Target : TargetsForSlot)
1140 Target.WasDevirt = true;
1141
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001142 return true;
1143 };
1144
1145 if (BitWidth == 1) {
1146 if (tryUniqueRetValOptFor(true))
1147 return true;
1148 if (tryUniqueRetValOptFor(false))
1149 return true;
1150 }
1151 return false;
1152}
1153
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001154void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1155 Constant *Byte, Constant *Bit) {
1156 for (auto Call : CSInfo.CallSites) {
1157 auto *RetType = cast<IntegerType>(Call.CS.getType());
1158 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001159 Value *Addr =
1160 B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001161 if (RetType->getBitWidth() == 1) {
1162 Value *Bits = B.CreateLoad(Addr);
1163 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1164 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1165 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
Sam Elliotte963c892017-08-21 16:57:21 +00001166 OREGetter, IsBitSet);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001167 } else {
1168 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1169 Value *Val = B.CreateLoad(RetType, ValAddr);
Sam Elliotte963c892017-08-21 16:57:21 +00001170 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1171 OREGetter, Val);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001172 }
1173 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001174 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001175}
1176
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001177bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001178 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1179 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001180 // This only works if the function returns an integer.
1181 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1182 if (!RetType)
1183 return false;
1184 unsigned BitWidth = RetType->getBitWidth();
1185 if (BitWidth > 64)
1186 return false;
1187
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001188 // Make sure that each function is defined, does not access memory, takes at
1189 // least one argument, does not use its first argument (which we assume is
1190 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +00001191 //
1192 // Note that we test whether this copy of the function is readnone, rather
1193 // than testing function attributes, which must hold for any copy of the
1194 // function, even a less optimized version substituted at link time. This is
1195 // sound because the virtual constant propagation optimizations effectively
1196 // inline all implementations of the virtual function into each call site,
1197 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001198 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +00001199 if (Target.Fn->isDeclaration() ||
1200 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1201 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001202 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001203 Target.Fn->getReturnType() != RetType)
1204 return false;
1205 }
1206
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001207 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001208 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1209 continue;
1210
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001211 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1212 if (Res)
1213 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1214
1215 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001216 continue;
1217
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001218 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1219 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001220 continue;
1221
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001222 // Find an allocation offset in bits in all vtables associated with the
1223 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001224 uint64_t AllocBefore =
1225 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1226 uint64_t AllocAfter =
1227 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1228
1229 // Calculate the total amount of padding needed to store a value at both
1230 // ends of the object.
1231 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1232 for (auto &&Target : TargetsForSlot) {
1233 TotalPaddingBefore += std::max<int64_t>(
1234 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1235 TotalPaddingAfter += std::max<int64_t>(
1236 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1237 }
1238
1239 // If the amount of padding is too large, give up.
1240 // FIXME: do something smarter here.
1241 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1242 continue;
1243
1244 // Calculate the offset to the value as a (possibly negative) byte offset
1245 // and (if applicable) a bit offset, and store the values in the targets.
1246 int64_t OffsetByte;
1247 uint64_t OffsetBit;
1248 if (TotalPaddingBefore <= TotalPaddingAfter)
1249 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1250 OffsetBit);
1251 else
1252 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1253 OffsetBit);
1254
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001255 if (RemarksEnabled)
1256 for (auto &&Target : TargetsForSlot)
1257 Target.WasDevirt = true;
1258
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001259
1260 if (CSByConstantArg.second.isExported()) {
1261 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001262 exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1263 ResByArg->Byte);
1264 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1265 ResByArg->Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001266 }
1267
1268 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001269 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1270 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001271 applyVirtualConstProp(CSByConstantArg.second,
1272 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001273 }
1274 return true;
1275}
1276
1277void DevirtModule::rebuildGlobal(VTableBits &B) {
1278 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1279 return;
1280
1281 // Align each byte array to pointer width.
1282 unsigned PointerSize = M.getDataLayout().getPointerSize();
1283 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1284 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1285
1286 // Before was stored in reverse order; flip it now.
1287 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1288 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1289
1290 // Build an anonymous global containing the before bytes, followed by the
1291 // original initializer, followed by the after bytes.
1292 auto NewInit = ConstantStruct::getAnon(
1293 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1294 B.GV->getInitializer(),
1295 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1296 auto NewGV =
1297 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1298 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1299 NewGV->setSection(B.GV->getSection());
1300 NewGV->setComdat(B.GV->getComdat());
1301
Peter Collingbourne0312f612016-06-25 00:23:04 +00001302 // Copy the original vtable's metadata to the anonymous global, adjusting
1303 // offsets as required.
1304 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1305
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001306 // Build an alias named after the original global, pointing at the second
1307 // element (the original initializer).
1308 auto Alias = GlobalAlias::create(
1309 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1310 ConstantExpr::getGetElementPtr(
1311 NewInit->getType(), NewGV,
1312 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1313 ConstantInt::get(Int32Ty, 1)}),
1314 &M);
1315 Alias->setVisibility(B.GV->getVisibility());
1316 Alias->takeName(B.GV);
1317
1318 B.GV->replaceAllUsesWith(Alias);
1319 B.GV->eraseFromParent();
1320}
1321
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001322bool DevirtModule::areRemarksEnabled() {
1323 const auto &FL = M.getFunctionList();
1324 if (FL.empty())
1325 return false;
1326 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +00001327
1328 const auto &BBL = Fn.getBasicBlockList();
1329 if (BBL.empty())
1330 return false;
1331 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001332 return DI.isEnabled();
1333}
1334
Peter Collingbourne0312f612016-06-25 00:23:04 +00001335void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1336 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001337 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001338 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1339 // points to a member of the type identifier %md. Group calls by (type ID,
1340 // offset) pair (effectively the identity of the virtual function) and store
1341 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001342 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001343 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001344 I != E;) {
1345 auto CI = dyn_cast<CallInst>(I->getUser());
1346 ++I;
1347 if (!CI)
1348 continue;
1349
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001350 // Search for virtual calls based on %p and add them to DevirtCalls.
1351 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001352 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001353 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001354
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001355 // If we found any, add them to CallSlots. Only do this if we haven't seen
1356 // the vtable pointer before, as it may have been CSE'd with pointers from
1357 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001358 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001359 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001360 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1361 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001362 if (SeenPtrs.insert(Ptr).second) {
1363 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne001052a2017-08-22 21:41:19 +00001364 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001365 }
1366 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001367 }
1368
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001369 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001370 for (auto Assume : Assumes)
1371 Assume->eraseFromParent();
1372 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1373 // may use the vtable argument later.
1374 if (CI->use_empty())
1375 CI->eraseFromParent();
1376 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001377}
1378
1379void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1380 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1381
1382 for (auto I = TypeCheckedLoadFunc->use_begin(),
1383 E = TypeCheckedLoadFunc->use_end();
1384 I != E;) {
1385 auto CI = dyn_cast<CallInst>(I->getUser());
1386 ++I;
1387 if (!CI)
1388 continue;
1389
1390 Value *Ptr = CI->getArgOperand(0);
1391 Value *Offset = CI->getArgOperand(1);
1392 Value *TypeIdValue = CI->getArgOperand(2);
1393 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1394
1395 SmallVector<DevirtCallSite, 1> DevirtCalls;
1396 SmallVector<Instruction *, 1> LoadedPtrs;
1397 SmallVector<Instruction *, 1> Preds;
1398 bool HasNonCallUses = false;
1399 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1400 HasNonCallUses, CI);
1401
1402 // Start by generating "pessimistic" code that explicitly loads the function
1403 // pointer from the vtable and performs the type check. If possible, we will
1404 // eliminate the load and the type check later.
1405
1406 // If possible, only generate the load at the point where it is used.
1407 // This helps avoid unnecessary spills.
1408 IRBuilder<> LoadB(
1409 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1410 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1411 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1412 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1413
1414 for (Instruction *LoadedPtr : LoadedPtrs) {
1415 LoadedPtr->replaceAllUsesWith(LoadedValue);
1416 LoadedPtr->eraseFromParent();
1417 }
1418
1419 // Likewise for the type test.
1420 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1421 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1422
1423 for (Instruction *Pred : Preds) {
1424 Pred->replaceAllUsesWith(TypeTestCall);
1425 Pred->eraseFromParent();
1426 }
1427
1428 // We have already erased any extractvalue instructions that refer to the
1429 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1430 // (although this is unlikely). In that case, explicitly build a pair and
1431 // RAUW it.
1432 if (!CI->use_empty()) {
1433 Value *Pair = UndefValue::get(CI->getType());
1434 IRBuilder<> B(CI);
1435 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1436 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1437 CI->replaceAllUsesWith(Pair);
1438 }
1439
1440 // The number of unsafe uses is initially the number of uses.
1441 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1442 NumUnsafeUses = DevirtCalls.size();
1443
1444 // If the function pointer has a non-call user, we cannot eliminate the type
1445 // check, as one of those users may eventually call the pointer. Increment
1446 // the unsafe use count to make sure it cannot reach zero.
1447 if (HasNonCallUses)
1448 ++NumUnsafeUses;
1449 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001450 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1451 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001452 }
1453
1454 CI->eraseFromParent();
1455 }
1456}
1457
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001458void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001459 const TypeIdSummary *TidSummary =
Peter Collingbournef7691d82017-03-22 18:22:59 +00001460 ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001461 if (!TidSummary)
1462 return;
1463 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1464 if (ResI == TidSummary->WPDRes.end())
1465 return;
1466 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001467
1468 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1469 // The type of the function in the declaration is irrelevant because every
1470 // call site will cast it to the correct type.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001471 auto *SingleImpl = M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001472 Res.SingleImplName, Type::getVoidTy(M.getContext()));
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001473
1474 // This is the import phase so we should not be exporting anything.
1475 bool IsExported = false;
1476 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1477 assert(!IsExported);
1478 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001479
1480 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1481 auto I = Res.ResByArg.find(CSByConstantArg.first);
1482 if (I == Res.ResByArg.end())
1483 continue;
1484 auto &ResByArg = I->second;
1485 // FIXME: We should figure out what to do about the "function name" argument
1486 // to the apply* functions, as the function names are unavailable during the
1487 // importing phase. For now we just pass the empty string. This does not
1488 // impact correctness because the function names are just used for remarks.
1489 switch (ResByArg.TheKind) {
1490 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1491 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1492 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001493 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1494 Constant *UniqueMemberAddr =
1495 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1496 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1497 UniqueMemberAddr);
1498 break;
1499 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001500 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001501 Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
1502 Int32Ty, ResByArg.Byte);
1503 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
1504 ResByArg.Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001505 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
Adrian Prantl0e6694d2017-12-19 22:05:25 +00001506 break;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001507 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001508 default:
1509 break;
1510 }
1511 }
Peter Collingbourne29748562018-03-09 19:11:44 +00001512
1513 if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
1514 auto *JT = M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
1515 Type::getVoidTy(M.getContext()));
1516 bool IsExported = false;
1517 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1518 assert(!IsExported);
1519 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001520}
1521
1522void DevirtModule::removeRedundantTypeTests() {
1523 auto True = ConstantInt::getTrue(M.getContext());
1524 for (auto &&U : NumUnsafeUsesForTypeTest) {
1525 if (U.second == 0) {
1526 U.first->replaceAllUsesWith(True);
1527 U.first->eraseFromParent();
1528 }
1529 }
1530}
1531
Peter Collingbourne0312f612016-06-25 00:23:04 +00001532bool DevirtModule::run() {
1533 Function *TypeTestFunc =
1534 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1535 Function *TypeCheckedLoadFunc =
1536 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1537 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1538
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001539 // Normally if there are no users of the devirtualization intrinsics in the
1540 // module, this pass has nothing to do. But if we are exporting, we also need
1541 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001542 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001543 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001544 AssumeFunc->use_empty()) &&
1545 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1546 return false;
1547
1548 if (TypeTestFunc && AssumeFunc)
1549 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1550
1551 if (TypeCheckedLoadFunc)
1552 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001553
Peter Collingbournef7691d82017-03-22 18:22:59 +00001554 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001555 for (auto &S : CallSlots)
1556 importResolution(S.first, S.second);
1557
1558 removeRedundantTypeTests();
1559
1560 // The rest of the code is only necessary when exporting or during regular
1561 // LTO, so we are done.
1562 return true;
1563 }
1564
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001565 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001566 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001567 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1568 buildTypeIdentifierMap(Bits, TypeIdMap);
1569 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001570 return true;
1571
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001572 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001573 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001574 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1575 for (auto &P : TypeIdMap) {
1576 if (auto *TypeId = dyn_cast<MDString>(P.first))
1577 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1578 TypeId);
1579 }
1580
Peter Collingbournef7691d82017-03-22 18:22:59 +00001581 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001582 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001583 auto *FS = dyn_cast<FunctionSummary>(S.get());
1584 if (!FS)
1585 continue;
1586 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001587 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1588 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001589 CallSlots[{MD, VF.Offset}]
1590 .CSInfo.markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001591 }
1592 }
1593 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1594 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001595 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001596 }
1597 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001598 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001599 FS->type_test_assume_const_vcalls()) {
1600 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001601 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001602 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001603 .markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001604 }
1605 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001606 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001607 FS->type_checked_load_const_vcalls()) {
1608 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001609 CallSlots[{MD, VC.VFunc.Offset}]
1610 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001611 .addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001612 }
1613 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001614 }
1615 }
1616 }
1617
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001618 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001619 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001620 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001621 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001622 // Search each of the members of the type identifier for the virtual
1623 // function implementation at offset S.first.ByteOffset, and add to
1624 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001625 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001626 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1627 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001628 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001629 if (ExportSummary && isa<MDString>(S.first.TypeID))
1630 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001631 ->getOrInsertTypeIdSummary(
1632 cast<MDString>(S.first.TypeID)->getString())
1633 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001634
Peter Collingbourne29748562018-03-09 19:11:44 +00001635 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res)) {
1636 DidVirtualConstProp |=
1637 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
1638
1639 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
1640 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001641
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001642 // Collect functions devirtualized at least for one call site for stats.
1643 if (RemarksEnabled)
1644 for (const auto &T : TargetsForSlot)
1645 if (T.WasDevirt)
1646 DevirtTargets[T.Fn->getName()] = T.Fn;
1647 }
1648
1649 // CFI-specific: if we are exporting and any llvm.type.checked.load
1650 // intrinsics were *not* devirtualized, we need to add the resulting
1651 // llvm.type.test intrinsics to the function summaries so that the
1652 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001653 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001654 auto GUID =
1655 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1656 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1657 FS->addTypeTest(GUID);
1658 for (auto &CCS : S.second.ConstCSInfo)
1659 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1660 FS->addTypeTest(GUID);
1661 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001662 }
1663
1664 if (RemarksEnabled) {
1665 // Generate remarks for each devirtualized function.
1666 for (const auto &DT : DevirtTargets) {
1667 Function *F = DT.second;
Sam Elliotte963c892017-08-21 16:57:21 +00001668
Sam Elliotte963c892017-08-21 16:57:21 +00001669 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +00001670 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
1671 << "devirtualized "
1672 << NV("FunctionName", F->getName()));
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001673 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001674 }
1675
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001676 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001677
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001678 // Rebuild each global we touched as part of virtual constant propagation to
1679 // include the before and after bytes.
1680 if (DidVirtualConstProp)
1681 for (VTableBits &B : Bits)
1682 rebuildGlobal(B);
1683
1684 return true;
1685}