blob: 00769cd6322929f13ba0462f1c5aaaaaf28be2f6 [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"
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"
Ivan Krasinb05e06e2016-08-05 19:45:16 +000058#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/IR/DebugLoc.h"
60#include "llvm/IR/DerivedTypes.h"
Ivan Krasin54746452016-07-12 02:38:37 +000061#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000062#include "llvm/IR/Function.h"
63#include "llvm/IR/GlobalAlias.h"
64#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000065#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000066#include "llvm/IR/InstrTypes.h"
67#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000068#include "llvm/IR/Instructions.h"
69#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000070#include "llvm/IR/LLVMContext.h"
71#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000072#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000073#include "llvm/IR/ModuleSummaryIndexYAML.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000074#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000075#include "llvm/PassRegistry.h"
76#include "llvm/PassSupport.h"
77#include "llvm/Support/Casting.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000078#include "llvm/Support/Error.h"
79#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000080#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000081#include "llvm/Transforms/IPO.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000082#include "llvm/Transforms/IPO/FunctionAttrs.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000083#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000084#include <algorithm>
85#include <cstddef>
86#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000087#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000088#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000089
90using namespace llvm;
91using namespace wholeprogramdevirt;
92
93#define DEBUG_TYPE "wholeprogramdevirt"
94
Peter Collingbourne2b33f652017-02-13 19:26:18 +000095static cl::opt<PassSummaryAction> ClSummaryAction(
96 "wholeprogramdevirt-summary-action",
97 cl::desc("What to do with the summary when running this pass"),
98 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
99 clEnumValN(PassSummaryAction::Import, "import",
100 "Import typeid resolutions from summary and globals"),
101 clEnumValN(PassSummaryAction::Export, "export",
102 "Export typeid resolutions to summary and globals")),
103 cl::Hidden);
104
105static cl::opt<std::string> ClReadSummary(
106 "wholeprogramdevirt-read-summary",
107 cl::desc("Read summary from given YAML file before running pass"),
108 cl::Hidden);
109
110static cl::opt<std::string> ClWriteSummary(
111 "wholeprogramdevirt-write-summary",
112 cl::desc("Write summary to given YAML file after running pass"),
113 cl::Hidden);
114
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000115// Find the minimum offset that we may store a value of size Size bits at. If
116// IsAfter is set, look for an offset before the object, otherwise look for an
117// offset after the object.
118uint64_t
119wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
120 bool IsAfter, uint64_t Size) {
121 // Find a minimum offset taking into account only vtable sizes.
122 uint64_t MinByte = 0;
123 for (const VirtualCallTarget &Target : Targets) {
124 if (IsAfter)
125 MinByte = std::max(MinByte, Target.minAfterBytes());
126 else
127 MinByte = std::max(MinByte, Target.minBeforeBytes());
128 }
129
130 // Build a vector of arrays of bytes covering, for each target, a slice of the
131 // used region (see AccumBitVector::BytesUsed in
132 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
133 // this aligns the used regions to start at MinByte.
134 //
135 // In this example, A, B and C are vtables, # is a byte already allocated for
136 // a virtual function pointer, AAAA... (etc.) are the used regions for the
137 // vtables and Offset(X) is the value computed for the Offset variable below
138 // for X.
139 //
140 // Offset(A)
141 // | |
142 // |MinByte
143 // A: ################AAAAAAAA|AAAAAAAA
144 // B: ########BBBBBBBBBBBBBBBB|BBBB
145 // C: ########################|CCCCCCCCCCCCCCCC
146 // | Offset(B) |
147 //
148 // This code produces the slices of A, B and C that appear after the divider
149 // at MinByte.
150 std::vector<ArrayRef<uint8_t>> Used;
151 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000152 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
153 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000154 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
155 : MinByte - Target.minBeforeBytes();
156
157 // Disregard used regions that are smaller than Offset. These are
158 // effectively all-free regions that do not need to be checked.
159 if (VTUsed.size() > Offset)
160 Used.push_back(VTUsed.slice(Offset));
161 }
162
163 if (Size == 1) {
164 // Find a free bit in each member of Used.
165 for (unsigned I = 0;; ++I) {
166 uint8_t BitsUsed = 0;
167 for (auto &&B : Used)
168 if (I < B.size())
169 BitsUsed |= B[I];
170 if (BitsUsed != 0xff)
171 return (MinByte + I) * 8 +
172 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
173 }
174 } else {
175 // Find a free (Size/8) byte region in each member of Used.
176 // FIXME: see if alignment helps.
177 for (unsigned I = 0;; ++I) {
178 for (auto &&B : Used) {
179 unsigned Byte = 0;
180 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
181 if (B[I + Byte])
182 goto NextI;
183 ++Byte;
184 }
185 }
186 return (MinByte + I) * 8;
187 NextI:;
188 }
189 }
190}
191
192void wholeprogramdevirt::setBeforeReturnValues(
193 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
194 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
195 if (BitWidth == 1)
196 OffsetByte = -(AllocBefore / 8 + 1);
197 else
198 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
199 OffsetBit = AllocBefore % 8;
200
201 for (VirtualCallTarget &Target : Targets) {
202 if (BitWidth == 1)
203 Target.setBeforeBit(AllocBefore);
204 else
205 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
206 }
207}
208
209void wholeprogramdevirt::setAfterReturnValues(
210 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
211 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
212 if (BitWidth == 1)
213 OffsetByte = AllocAfter / 8;
214 else
215 OffsetByte = (AllocAfter + 7) / 8;
216 OffsetBit = AllocAfter % 8;
217
218 for (VirtualCallTarget &Target : Targets) {
219 if (BitWidth == 1)
220 Target.setAfterBit(AllocAfter);
221 else
222 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
223 }
224}
225
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000226VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
227 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000228 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000229
230namespace {
231
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000232// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000233// tables, and the ByteOffset is the offset in bytes from the address point to
234// the virtual function pointer.
235struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000236 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000237 uint64_t ByteOffset;
238};
239
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000240} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000241
Peter Collingbourne9b656522016-02-09 23:01:38 +0000242namespace llvm {
243
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000244template <> struct DenseMapInfo<VTableSlot> {
245 static VTableSlot getEmptyKey() {
246 return {DenseMapInfo<Metadata *>::getEmptyKey(),
247 DenseMapInfo<uint64_t>::getEmptyKey()};
248 }
249 static VTableSlot getTombstoneKey() {
250 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
251 DenseMapInfo<uint64_t>::getTombstoneKey()};
252 }
253 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000254 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000255 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
256 }
257 static bool isEqual(const VTableSlot &LHS,
258 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000259 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000260 }
261};
262
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000263} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000264
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000265namespace {
266
267// A virtual call site. VTable is the loaded virtual table pointer, and CS is
268// the indirect virtual call.
269struct VirtualCallSite {
270 Value *VTable;
271 CallSite CS;
272
Peter Collingbourne0312f612016-06-25 00:23:04 +0000273 // If non-null, this field points to the associated unsafe use count stored in
274 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
275 // of that field for details.
276 unsigned *NumUnsafeUses;
277
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000278 void emitRemark(const Twine &OptName, const Twine &TargetName) {
Ivan Krasin54746452016-07-12 02:38:37 +0000279 Function *F = CS.getCaller();
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000280 emitOptimizationRemark(
281 F->getContext(), DEBUG_TYPE, *F,
282 CS.getInstruction()->getDebugLoc(),
283 OptName + ": devirtualized a call to " + TargetName);
Ivan Krasin54746452016-07-12 02:38:37 +0000284 }
285
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000286 void replaceAndErase(const Twine &OptName, const Twine &TargetName,
287 bool RemarksEnabled, Value *New) {
288 if (RemarksEnabled)
289 emitRemark(OptName, TargetName);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000290 CS->replaceAllUsesWith(New);
291 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
292 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
293 II->getUnwindDest()->removePredecessor(II->getParent());
294 }
295 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000296 // This use is no longer unsafe.
297 if (NumUnsafeUses)
298 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000299 }
300};
301
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000302// Call site information collected for a specific VTableSlot and possibly a list
303// of constant integer arguments. The grouping by arguments is handled by the
304// VTableSlotInfo class.
305struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000306 /// The set of call sites for this slot. Used during regular LTO and the
307 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
308 /// call sites that appear in the merged module itself); in each of these
309 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000310 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000311
312 // These fields are used during the export phase of ThinLTO and reflect
313 // information collected from function summaries.
314
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000315 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
316 /// this slot.
317 bool SummaryHasTypeTestAssumeUsers;
318
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000319 /// CFI-specific: a vector containing the list of function summaries that use
320 /// the llvm.type.checked.load intrinsic and therefore will require
321 /// resolutions for llvm.type.test in order to implement CFI checks if
322 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000323 /// pass will clear this vector by calling markDevirt(). If at the end of the
324 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
325 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000326 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000327
328 bool isExported() const {
329 return SummaryHasTypeTestAssumeUsers ||
330 !SummaryTypeCheckedLoadUsers.empty();
331 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000332
333 /// As explained in the comment for SummaryTypeCheckedLoadUsers.
334 void markDevirt() { SummaryTypeCheckedLoadUsers.clear(); }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000335};
336
337// Call site information collected for a specific VTableSlot.
338struct VTableSlotInfo {
339 // The set of call sites which do not have all constant integer arguments
340 // (excluding "this").
341 CallSiteInfo CSInfo;
342
343 // The set of call sites with all constant integer arguments (excluding
344 // "this"), grouped by argument list.
345 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
346
347 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
348
349private:
350 CallSiteInfo &findCallSiteInfo(CallSite CS);
351};
352
353CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
354 std::vector<uint64_t> Args;
355 auto *CI = dyn_cast<IntegerType>(CS.getType());
356 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
357 return CSInfo;
358 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
359 auto *CI = dyn_cast<ConstantInt>(Arg);
360 if (!CI || CI->getBitWidth() > 64)
361 return CSInfo;
362 Args.push_back(CI->getZExtValue());
363 }
364 return ConstCSInfo[Args];
365}
366
367void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
368 unsigned *NumUnsafeUses) {
369 findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
370}
371
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000372struct DevirtModule {
373 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000374 function_ref<AAResults &(Function &)> AARGetter;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000375
Peter Collingbournef7691d82017-03-22 18:22:59 +0000376 ModuleSummaryIndex *ExportSummary;
377 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000378
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000379 IntegerType *Int8Ty;
380 PointerType *Int8PtrTy;
381 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000382 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000383 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000384
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000385 bool RemarksEnabled;
386
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000387 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000388
Peter Collingbourne0312f612016-06-25 00:23:04 +0000389 // This map keeps track of the number of "unsafe" uses of a loaded function
390 // pointer. The key is the associated llvm.type.test intrinsic call generated
391 // by this pass. An unsafe use is one that calls the loaded function pointer
392 // directly. Every time we eliminate an unsafe use (for example, by
393 // devirtualizing it or by applying virtual constant propagation), we
394 // decrement the value stored in this map. If a value reaches zero, we can
395 // eliminate the type check by RAUWing the associated llvm.type.test call with
396 // true.
397 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
398
Peter Collingbourne37317f12017-02-17 18:17:04 +0000399 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000400 ModuleSummaryIndex *ExportSummary,
401 const ModuleSummaryIndex *ImportSummary)
402 : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
403 ImportSummary(ImportSummary), Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000404 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000405 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000406 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000407 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Peter Collingbournef7691d82017-03-22 18:22:59 +0000408 RemarksEnabled(areRemarksEnabled()) {
409 assert(!(ExportSummary && ImportSummary));
410 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000411
412 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000413
Peter Collingbourne0312f612016-06-25 00:23:04 +0000414 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
415 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
416
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000417 void buildTypeIdentifierMap(
418 std::vector<VTableBits> &Bits,
419 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000420 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000421 bool
422 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
423 const std::set<TypeMemberInfo> &TypeMemberInfos,
424 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000425
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000426 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
427 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000428 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000429 VTableSlotInfo &SlotInfo,
430 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000431
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000432 bool tryEvaluateFunctionsWithArgs(
433 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000434 ArrayRef<uint64_t> Args);
435
436 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
437 uint64_t TheRetVal);
438 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000439 CallSiteInfo &CSInfo,
440 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000441
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000442 // Returns the global symbol name that is used to export information about the
443 // given vtable slot and list of arguments.
444 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
445 StringRef Name);
446
447 // This function is called during the export phase to create a symbol
448 // definition containing information about the given vtable slot and list of
449 // arguments.
450 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
451 Constant *C);
452
453 // This function is called during the import phase to create a reference to
454 // the symbol definition created during the export phase.
455 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000456 StringRef Name, unsigned AbsWidth = 0);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000457
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000458 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
459 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000460 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000461 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000462 CallSiteInfo &CSInfo,
463 WholeProgramDevirtResolution::ByArg *Res,
464 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000465
466 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
467 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000468 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000469 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000470 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000471
472 void rebuildGlobal(VTableBits &B);
473
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000474 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
475 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
476
477 // If we were able to eliminate all unsafe uses for a type checked load,
478 // eliminate the associated type tests by replacing them with true.
479 void removeRedundantTypeTests();
480
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000481 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000482
483 // Lower the module using the action and summary passed as command line
484 // arguments. For testing purposes only.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000485 static bool runForTesting(Module &M,
486 function_ref<AAResults &(Function &)> AARGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000487};
488
489struct WholeProgramDevirt : public ModulePass {
490 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000491
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000492 bool UseCommandLine = false;
493
Peter Collingbournef7691d82017-03-22 18:22:59 +0000494 ModuleSummaryIndex *ExportSummary;
495 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000496
497 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
498 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
499 }
500
Peter Collingbournef7691d82017-03-22 18:22:59 +0000501 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
502 const ModuleSummaryIndex *ImportSummary)
503 : ModulePass(ID), ExportSummary(ExportSummary),
504 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000505 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
506 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000507
508 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000509 if (skipModule(M))
510 return false;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000511 if (UseCommandLine)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000512 return DevirtModule::runForTesting(M, LegacyAARGetter(*this));
Peter Collingbournef7691d82017-03-22 18:22:59 +0000513 return DevirtModule(M, LegacyAARGetter(*this), ExportSummary, ImportSummary)
514 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000515 }
516
517 void getAnalysisUsage(AnalysisUsage &AU) const override {
518 AU.addRequired<AssumptionCacheTracker>();
519 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000520 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000521};
522
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000523} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000524
Peter Collingbourne37317f12017-02-17 18:17:04 +0000525INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
526 "Whole program devirtualization", false, false)
527INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
528INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
529INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
530 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000531char WholeProgramDevirt::ID = 0;
532
Peter Collingbournef7691d82017-03-22 18:22:59 +0000533ModulePass *
534llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
535 const ModuleSummaryIndex *ImportSummary) {
536 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000537}
538
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000539PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000540 ModuleAnalysisManager &AM) {
541 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
542 auto AARGetter = [&](Function &F) -> AAResults & {
543 return FAM.getResult<AAManager>(F);
544 };
Peter Collingbournef7691d82017-03-22 18:22:59 +0000545 if (!DevirtModule(M, AARGetter, nullptr, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000546 return PreservedAnalyses::all();
547 return PreservedAnalyses::none();
548}
549
Peter Collingbourne37317f12017-02-17 18:17:04 +0000550bool DevirtModule::runForTesting(
551 Module &M, function_ref<AAResults &(Function &)> AARGetter) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000552 ModuleSummaryIndex Summary;
553
554 // Handle the command-line summary arguments. This code is for testing
555 // purposes only, so we handle errors directly.
556 if (!ClReadSummary.empty()) {
557 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
558 ": ");
559 auto ReadSummaryFile =
560 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
561
562 yaml::Input In(ReadSummaryFile->getBuffer());
563 In >> Summary;
564 ExitOnErr(errorCodeToError(In.error()));
565 }
566
Peter Collingbournef7691d82017-03-22 18:22:59 +0000567 bool Changed =
568 DevirtModule(
569 M, AARGetter,
570 ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
571 ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
572 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000573
574 if (!ClWriteSummary.empty()) {
575 ExitOnError ExitOnErr(
576 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
577 std::error_code EC;
578 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
579 ExitOnErr(errorCodeToError(EC));
580
581 yaml::Output Out(OS);
582 Out << Summary;
583 }
584
585 return Changed;
586}
587
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000588void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000589 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000590 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000591 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000592 Bits.reserve(M.getGlobalList().size());
593 SmallVector<MDNode *, 2> Types;
594 for (GlobalVariable &GV : M.globals()) {
595 Types.clear();
596 GV.getMetadata(LLVMContext::MD_type, Types);
597 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000598 continue;
599
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000600 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000601 if (!BitsPtr) {
602 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000603 Bits.back().GV = &GV;
604 Bits.back().ObjectSize =
605 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000606 BitsPtr = &Bits.back();
607 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000608
609 for (MDNode *Type : Types) {
610 auto TypeID = Type->getOperand(1).get();
611
612 uint64_t Offset =
613 cast<ConstantInt>(
614 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
615 ->getZExtValue();
616
617 TypeIdMap[TypeID].insert({BitsPtr, Offset});
618 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000619 }
620}
621
Peter Collingbourne87867542016-12-09 01:10:11 +0000622Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
623 if (I->getType()->isPointerTy()) {
624 if (Offset == 0)
625 return I;
626 return nullptr;
627 }
628
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000629 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000630
631 if (auto *C = dyn_cast<ConstantStruct>(I)) {
632 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000633 if (Offset >= SL->getSizeInBytes())
634 return nullptr;
635
Peter Collingbourne87867542016-12-09 01:10:11 +0000636 unsigned Op = SL->getElementContainingOffset(Offset);
637 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
638 Offset - SL->getElementOffset(Op));
639 }
640 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000641 ArrayType *VTableTy = C->getType();
642 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
643
Peter Collingbourne87867542016-12-09 01:10:11 +0000644 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000645 if (Op >= C->getNumOperands())
646 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000647
Peter Collingbourne87867542016-12-09 01:10:11 +0000648 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
649 Offset % ElemSize);
650 }
651 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000652}
653
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000654bool DevirtModule::tryFindVirtualCallTargets(
655 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000656 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
657 for (const TypeMemberInfo &TM : TypeMemberInfos) {
658 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000659 return false;
660
Peter Collingbourne87867542016-12-09 01:10:11 +0000661 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
662 TM.Offset + ByteOffset);
663 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000664 return false;
665
Peter Collingbourne87867542016-12-09 01:10:11 +0000666 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000667 if (!Fn)
668 return false;
669
670 // We can disregard __cxa_pure_virtual as a possible call target, as
671 // calls to pure virtuals are UB.
672 if (Fn->getName() == "__cxa_pure_virtual")
673 continue;
674
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000675 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000676 }
677
678 // Give up if we couldn't find any targets.
679 return !TargetsForSlot.empty();
680}
681
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000682void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000683 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000684 auto Apply = [&](CallSiteInfo &CSInfo) {
685 for (auto &&VCallSite : CSInfo.CallSites) {
686 if (RemarksEnabled)
687 VCallSite.emitRemark("single-impl", TheFn->getName());
688 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
689 TheFn, VCallSite.CS.getCalledValue()->getType()));
690 // This use is no longer unsafe.
691 if (VCallSite.NumUnsafeUses)
692 --*VCallSite.NumUnsafeUses;
693 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000694 if (CSInfo.isExported()) {
695 IsExported = true;
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000696 CSInfo.markDevirt();
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000697 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000698 };
699 Apply(SlotInfo.CSInfo);
700 for (auto &P : SlotInfo.ConstCSInfo)
701 Apply(P.second);
702}
703
Peter Collingbournee2367412017-02-15 02:13:08 +0000704bool DevirtModule::trySingleImplDevirt(
705 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000706 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000707 // See if the program contains a single implementation of this virtual
708 // function.
709 Function *TheFn = TargetsForSlot[0].Fn;
710 for (auto &&Target : TargetsForSlot)
711 if (TheFn != Target.Fn)
712 return false;
713
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000714 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000715 if (RemarksEnabled)
716 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000717
718 bool IsExported = false;
719 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
720 if (!IsExported)
721 return false;
722
723 // If the only implementation has local linkage, we must promote to external
724 // to make it visible to thin LTO objects. We can only get here during the
725 // ThinLTO export phase.
726 if (TheFn->hasLocalLinkage()) {
727 TheFn->setLinkage(GlobalValue::ExternalLinkage);
728 TheFn->setVisibility(GlobalValue::HiddenVisibility);
729 TheFn->setName(TheFn->getName() + "$merged");
730 }
731
732 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
733 Res->SingleImplName = TheFn->getName();
734
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000735 return true;
736}
737
738bool DevirtModule::tryEvaluateFunctionsWithArgs(
739 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000740 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000741 // Evaluate each function and store the result in each target's RetVal
742 // field.
743 for (VirtualCallTarget &Target : TargetsForSlot) {
744 if (Target.Fn->arg_size() != Args.size() + 1)
745 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000746
747 Evaluator Eval(M.getDataLayout(), nullptr);
748 SmallVector<Constant *, 2> EvalArgs;
749 EvalArgs.push_back(
750 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000751 for (unsigned I = 0; I != Args.size(); ++I) {
752 auto *ArgTy = dyn_cast<IntegerType>(
753 Target.Fn->getFunctionType()->getParamType(I + 1));
754 if (!ArgTy)
755 return false;
756 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
757 }
758
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000759 Constant *RetVal;
760 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
761 !isa<ConstantInt>(RetVal))
762 return false;
763 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
764 }
765 return true;
766}
767
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000768void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
769 uint64_t TheRetVal) {
770 for (auto Call : CSInfo.CallSites)
771 Call.replaceAndErase(
772 "uniform-ret-val", FnName, RemarksEnabled,
773 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000774 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000775}
776
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000777bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000778 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
779 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000780 // Uniform return value optimization. If all functions return the same
781 // constant, replace all calls with that constant.
782 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
783 for (const VirtualCallTarget &Target : TargetsForSlot)
784 if (Target.RetVal != TheRetVal)
785 return false;
786
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000787 if (CSInfo.isExported()) {
788 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
789 Res->Info = TheRetVal;
790 }
791
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000792 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000793 if (RemarksEnabled)
794 for (auto &&Target : TargetsForSlot)
795 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000796 return true;
797}
798
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000799std::string DevirtModule::getGlobalName(VTableSlot Slot,
800 ArrayRef<uint64_t> Args,
801 StringRef Name) {
802 std::string FullName = "__typeid_";
803 raw_string_ostream OS(FullName);
804 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
805 for (uint64_t Arg : Args)
806 OS << '_' << Arg;
807 OS << '_' << Name;
808 return OS.str();
809}
810
811void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
812 StringRef Name, Constant *C) {
813 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
814 getGlobalName(Slot, Args, Name), C, &M);
815 GA->setVisibility(GlobalValue::HiddenVisibility);
816}
817
818Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000819 StringRef Name, unsigned AbsWidth) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000820 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
821 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000822 // We only need to set metadata if the global is newly created, in which
823 // case it would not have hidden visibility.
824 if (!GV || GV->getVisibility() == GlobalValue::HiddenVisibility)
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000825 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000826
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000827 GV->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000828 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
829 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
830 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
831 GV->setMetadata(LLVMContext::MD_absolute_symbol,
832 MDNode::get(M.getContext(), {MinC, MaxC}));
833 };
834 if (AbsWidth == IntPtrTy->getBitWidth())
835 SetAbsRange(~0ull, ~0ull); // Full set.
836 else if (AbsWidth)
837 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000838 return GV;
839}
840
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000841void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
842 bool IsOne,
843 Constant *UniqueMemberAddr) {
844 for (auto &&Call : CSInfo.CallSites) {
845 IRBuilder<> B(Call.CS.getInstruction());
846 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
847 Call.VTable, UniqueMemberAddr);
848 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
849 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp);
850 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000851 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000852}
853
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000854bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000855 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000856 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
857 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000858 // IsOne controls whether we look for a 0 or a 1.
859 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000860 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000861 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000862 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000863 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000864 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000865 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000866 }
867 }
868
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000869 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000870 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000871 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000872
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000873 Constant *UniqueMemberAddr =
874 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
875 UniqueMemberAddr = ConstantExpr::getGetElementPtr(
876 Int8Ty, UniqueMemberAddr,
877 ConstantInt::get(Int64Ty, UniqueMember->Offset));
878
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000879 if (CSInfo.isExported()) {
880 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
881 Res->Info = IsOne;
882
883 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
884 }
885
886 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000887 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
888 UniqueMemberAddr);
889
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000890 // Update devirtualization statistics for targets.
891 if (RemarksEnabled)
892 for (auto &&Target : TargetsForSlot)
893 Target.WasDevirt = true;
894
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000895 return true;
896 };
897
898 if (BitWidth == 1) {
899 if (tryUniqueRetValOptFor(true))
900 return true;
901 if (tryUniqueRetValOptFor(false))
902 return true;
903 }
904 return false;
905}
906
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000907void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
908 Constant *Byte, Constant *Bit) {
909 for (auto Call : CSInfo.CallSites) {
910 auto *RetType = cast<IntegerType>(Call.CS.getType());
911 IRBuilder<> B(Call.CS.getInstruction());
912 Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte);
913 if (RetType->getBitWidth() == 1) {
914 Value *Bits = B.CreateLoad(Addr);
915 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
916 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
917 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
918 IsBitSet);
919 } else {
920 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
921 Value *Val = B.CreateLoad(RetType, ValAddr);
922 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val);
923 }
924 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000925 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000926}
927
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000928bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000929 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
930 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000931 // This only works if the function returns an integer.
932 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
933 if (!RetType)
934 return false;
935 unsigned BitWidth = RetType->getBitWidth();
936 if (BitWidth > 64)
937 return false;
938
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000939 // Make sure that each function is defined, does not access memory, takes at
940 // least one argument, does not use its first argument (which we assume is
941 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000942 //
943 // Note that we test whether this copy of the function is readnone, rather
944 // than testing function attributes, which must hold for any copy of the
945 // function, even a less optimized version substituted at link time. This is
946 // sound because the virtual constant propagation optimizations effectively
947 // inline all implementations of the virtual function into each call site,
948 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000949 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +0000950 if (Target.Fn->isDeclaration() ||
951 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
952 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000953 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000954 Target.Fn->getReturnType() != RetType)
955 return false;
956 }
957
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000958 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000959 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
960 continue;
961
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000962 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
963 if (Res)
964 ResByArg = &Res->ResByArg[CSByConstantArg.first];
965
966 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000967 continue;
968
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000969 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
970 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000971 continue;
972
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000973 // Find an allocation offset in bits in all vtables associated with the
974 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000975 uint64_t AllocBefore =
976 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
977 uint64_t AllocAfter =
978 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
979
980 // Calculate the total amount of padding needed to store a value at both
981 // ends of the object.
982 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
983 for (auto &&Target : TargetsForSlot) {
984 TotalPaddingBefore += std::max<int64_t>(
985 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
986 TotalPaddingAfter += std::max<int64_t>(
987 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
988 }
989
990 // If the amount of padding is too large, give up.
991 // FIXME: do something smarter here.
992 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
993 continue;
994
995 // Calculate the offset to the value as a (possibly negative) byte offset
996 // and (if applicable) a bit offset, and store the values in the targets.
997 int64_t OffsetByte;
998 uint64_t OffsetBit;
999 if (TotalPaddingBefore <= TotalPaddingAfter)
1000 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1001 OffsetBit);
1002 else
1003 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1004 OffsetBit);
1005
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001006 if (RemarksEnabled)
1007 for (auto &&Target : TargetsForSlot)
1008 Target.WasDevirt = true;
1009
Peter Collingbourne184773d2017-02-17 19:43:45 +00001010 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001011 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001012
1013 if (CSByConstantArg.second.isExported()) {
1014 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
1015 exportGlobal(Slot, CSByConstantArg.first, "byte",
1016 ConstantExpr::getIntToPtr(ByteConst, Int8PtrTy));
1017 exportGlobal(Slot, CSByConstantArg.first, "bit",
1018 ConstantExpr::getIntToPtr(BitConst, Int8PtrTy));
1019 }
1020
1021 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001022 applyVirtualConstProp(CSByConstantArg.second,
1023 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001024 }
1025 return true;
1026}
1027
1028void DevirtModule::rebuildGlobal(VTableBits &B) {
1029 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1030 return;
1031
1032 // Align each byte array to pointer width.
1033 unsigned PointerSize = M.getDataLayout().getPointerSize();
1034 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1035 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1036
1037 // Before was stored in reverse order; flip it now.
1038 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1039 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1040
1041 // Build an anonymous global containing the before bytes, followed by the
1042 // original initializer, followed by the after bytes.
1043 auto NewInit = ConstantStruct::getAnon(
1044 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1045 B.GV->getInitializer(),
1046 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1047 auto NewGV =
1048 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1049 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1050 NewGV->setSection(B.GV->getSection());
1051 NewGV->setComdat(B.GV->getComdat());
1052
Peter Collingbourne0312f612016-06-25 00:23:04 +00001053 // Copy the original vtable's metadata to the anonymous global, adjusting
1054 // offsets as required.
1055 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1056
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001057 // Build an alias named after the original global, pointing at the second
1058 // element (the original initializer).
1059 auto Alias = GlobalAlias::create(
1060 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1061 ConstantExpr::getGetElementPtr(
1062 NewInit->getType(), NewGV,
1063 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1064 ConstantInt::get(Int32Ty, 1)}),
1065 &M);
1066 Alias->setVisibility(B.GV->getVisibility());
1067 Alias->takeName(B.GV);
1068
1069 B.GV->replaceAllUsesWith(Alias);
1070 B.GV->eraseFromParent();
1071}
1072
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001073bool DevirtModule::areRemarksEnabled() {
1074 const auto &FL = M.getFunctionList();
1075 if (FL.empty())
1076 return false;
1077 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +00001078
1079 const auto &BBL = Fn.getBasicBlockList();
1080 if (BBL.empty())
1081 return false;
1082 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001083 return DI.isEnabled();
1084}
1085
Peter Collingbourne0312f612016-06-25 00:23:04 +00001086void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1087 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001088 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001089 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1090 // points to a member of the type identifier %md. Group calls by (type ID,
1091 // offset) pair (effectively the identity of the virtual function) and store
1092 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001093 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001094 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001095 I != E;) {
1096 auto CI = dyn_cast<CallInst>(I->getUser());
1097 ++I;
1098 if (!CI)
1099 continue;
1100
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001101 // Search for virtual calls based on %p and add them to DevirtCalls.
1102 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001103 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001104 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001105
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001106 // If we found any, add them to CallSlots. Only do this if we haven't seen
1107 // the vtable pointer before, as it may have been CSE'd with pointers from
1108 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001109 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001110 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001111 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1112 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001113 if (SeenPtrs.insert(Ptr).second) {
1114 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001115 CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0),
1116 Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001117 }
1118 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001119 }
1120
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001121 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001122 for (auto Assume : Assumes)
1123 Assume->eraseFromParent();
1124 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1125 // may use the vtable argument later.
1126 if (CI->use_empty())
1127 CI->eraseFromParent();
1128 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001129}
1130
1131void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1132 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1133
1134 for (auto I = TypeCheckedLoadFunc->use_begin(),
1135 E = TypeCheckedLoadFunc->use_end();
1136 I != E;) {
1137 auto CI = dyn_cast<CallInst>(I->getUser());
1138 ++I;
1139 if (!CI)
1140 continue;
1141
1142 Value *Ptr = CI->getArgOperand(0);
1143 Value *Offset = CI->getArgOperand(1);
1144 Value *TypeIdValue = CI->getArgOperand(2);
1145 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1146
1147 SmallVector<DevirtCallSite, 1> DevirtCalls;
1148 SmallVector<Instruction *, 1> LoadedPtrs;
1149 SmallVector<Instruction *, 1> Preds;
1150 bool HasNonCallUses = false;
1151 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1152 HasNonCallUses, CI);
1153
1154 // Start by generating "pessimistic" code that explicitly loads the function
1155 // pointer from the vtable and performs the type check. If possible, we will
1156 // eliminate the load and the type check later.
1157
1158 // If possible, only generate the load at the point where it is used.
1159 // This helps avoid unnecessary spills.
1160 IRBuilder<> LoadB(
1161 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1162 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1163 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1164 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1165
1166 for (Instruction *LoadedPtr : LoadedPtrs) {
1167 LoadedPtr->replaceAllUsesWith(LoadedValue);
1168 LoadedPtr->eraseFromParent();
1169 }
1170
1171 // Likewise for the type test.
1172 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1173 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1174
1175 for (Instruction *Pred : Preds) {
1176 Pred->replaceAllUsesWith(TypeTestCall);
1177 Pred->eraseFromParent();
1178 }
1179
1180 // We have already erased any extractvalue instructions that refer to the
1181 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1182 // (although this is unlikely). In that case, explicitly build a pair and
1183 // RAUW it.
1184 if (!CI->use_empty()) {
1185 Value *Pair = UndefValue::get(CI->getType());
1186 IRBuilder<> B(CI);
1187 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1188 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1189 CI->replaceAllUsesWith(Pair);
1190 }
1191
1192 // The number of unsafe uses is initially the number of uses.
1193 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1194 NumUnsafeUses = DevirtCalls.size();
1195
1196 // If the function pointer has a non-call user, we cannot eliminate the type
1197 // check, as one of those users may eventually call the pointer. Increment
1198 // the unsafe use count to make sure it cannot reach zero.
1199 if (HasNonCallUses)
1200 ++NumUnsafeUses;
1201 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001202 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1203 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001204 }
1205
1206 CI->eraseFromParent();
1207 }
1208}
1209
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001210void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001211 const TypeIdSummary *TidSummary =
Peter Collingbournef7691d82017-03-22 18:22:59 +00001212 ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001213 if (!TidSummary)
1214 return;
1215 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1216 if (ResI == TidSummary->WPDRes.end())
1217 return;
1218 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001219
1220 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1221 // The type of the function in the declaration is irrelevant because every
1222 // call site will cast it to the correct type.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001223 auto *SingleImpl = M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001224 Res.SingleImplName, Type::getVoidTy(M.getContext()));
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001225
1226 // This is the import phase so we should not be exporting anything.
1227 bool IsExported = false;
1228 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1229 assert(!IsExported);
1230 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001231
1232 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1233 auto I = Res.ResByArg.find(CSByConstantArg.first);
1234 if (I == Res.ResByArg.end())
1235 continue;
1236 auto &ResByArg = I->second;
1237 // FIXME: We should figure out what to do about the "function name" argument
1238 // to the apply* functions, as the function names are unavailable during the
1239 // importing phase. For now we just pass the empty string. This does not
1240 // impact correctness because the function names are just used for remarks.
1241 switch (ResByArg.TheKind) {
1242 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1243 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1244 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001245 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1246 Constant *UniqueMemberAddr =
1247 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1248 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1249 UniqueMemberAddr);
1250 break;
1251 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001252 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
1253 Constant *Byte = importGlobal(Slot, CSByConstantArg.first, "byte", 32);
1254 Byte = ConstantExpr::getPtrToInt(Byte, Int32Ty);
1255 Constant *Bit = importGlobal(Slot, CSByConstantArg.first, "bit", 8);
1256 Bit = ConstantExpr::getPtrToInt(Bit, Int8Ty);
1257 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
1258 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001259 default:
1260 break;
1261 }
1262 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001263}
1264
1265void DevirtModule::removeRedundantTypeTests() {
1266 auto True = ConstantInt::getTrue(M.getContext());
1267 for (auto &&U : NumUnsafeUsesForTypeTest) {
1268 if (U.second == 0) {
1269 U.first->replaceAllUsesWith(True);
1270 U.first->eraseFromParent();
1271 }
1272 }
1273}
1274
Peter Collingbourne0312f612016-06-25 00:23:04 +00001275bool DevirtModule::run() {
1276 Function *TypeTestFunc =
1277 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1278 Function *TypeCheckedLoadFunc =
1279 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1280 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1281
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001282 // Normally if there are no users of the devirtualization intrinsics in the
1283 // module, this pass has nothing to do. But if we are exporting, we also need
1284 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001285 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001286 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001287 AssumeFunc->use_empty()) &&
1288 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1289 return false;
1290
1291 if (TypeTestFunc && AssumeFunc)
1292 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1293
1294 if (TypeCheckedLoadFunc)
1295 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001296
Peter Collingbournef7691d82017-03-22 18:22:59 +00001297 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001298 for (auto &S : CallSlots)
1299 importResolution(S.first, S.second);
1300
1301 removeRedundantTypeTests();
1302
1303 // The rest of the code is only necessary when exporting or during regular
1304 // LTO, so we are done.
1305 return true;
1306 }
1307
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001308 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001309 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001310 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1311 buildTypeIdentifierMap(Bits, TypeIdMap);
1312 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001313 return true;
1314
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001315 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001316 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001317 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1318 for (auto &P : TypeIdMap) {
1319 if (auto *TypeId = dyn_cast<MDString>(P.first))
1320 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1321 TypeId);
1322 }
1323
Peter Collingbournef7691d82017-03-22 18:22:59 +00001324 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001325 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001326 auto *FS = dyn_cast<FunctionSummary>(S.get());
1327 if (!FS)
1328 continue;
1329 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001330 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1331 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001332 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1333 true;
George Rimar5d8aea12017-03-10 10:31:56 +00001334 }
1335 }
1336 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1337 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001338 CallSlots[{MD, VF.Offset}]
1339 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001340 }
1341 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001342 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001343 FS->type_test_assume_const_vcalls()) {
1344 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001345 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001346 .ConstCSInfo[VC.Args]
1347 .SummaryHasTypeTestAssumeUsers = true;
1348 }
1349 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001350 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001351 FS->type_checked_load_const_vcalls()) {
1352 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001353 CallSlots[{MD, VC.VFunc.Offset}]
1354 .ConstCSInfo[VC.Args]
1355 .SummaryTypeCheckedLoadUsers.push_back(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001356 }
1357 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001358 }
1359 }
1360 }
1361
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001362 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001363 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001364 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001365 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001366 // Search each of the members of the type identifier for the virtual
1367 // function implementation at offset S.first.ByteOffset, and add to
1368 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001369 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001370 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1371 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001372 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001373 if (ExportSummary && isa<MDString>(S.first.TypeID))
1374 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001375 ->getOrInsertTypeIdSummary(
1376 cast<MDString>(S.first.TypeID)->getString())
1377 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001378
1379 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001380 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first))
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001381 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001382
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001383 // Collect functions devirtualized at least for one call site for stats.
1384 if (RemarksEnabled)
1385 for (const auto &T : TargetsForSlot)
1386 if (T.WasDevirt)
1387 DevirtTargets[T.Fn->getName()] = T.Fn;
1388 }
1389
1390 // CFI-specific: if we are exporting and any llvm.type.checked.load
1391 // intrinsics were *not* devirtualized, we need to add the resulting
1392 // llvm.type.test intrinsics to the function summaries so that the
1393 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001394 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001395 auto GUID =
1396 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1397 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1398 FS->addTypeTest(GUID);
1399 for (auto &CCS : S.second.ConstCSInfo)
1400 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1401 FS->addTypeTest(GUID);
1402 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001403 }
1404
1405 if (RemarksEnabled) {
1406 // Generate remarks for each devirtualized function.
1407 for (const auto &DT : DevirtTargets) {
1408 Function *F = DT.second;
1409 DISubprogram *SP = F->getSubprogram();
Justin Bogner7bc978b2017-02-18 02:00:27 +00001410 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP,
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001411 Twine("devirtualized ") + F->getName());
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001412 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001413 }
1414
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001415 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001416
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001417 // Rebuild each global we touched as part of virtual constant propagation to
1418 // include the before and after bytes.
1419 if (DidVirtualConstProp)
1420 for (VTableBits &B : Bits)
1421 rebuildGlobal(B);
1422
1423 return true;
1424}