blob: 68d7bd5681372f7530bebf1181cd4b284f46c21d [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"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000049#include "llvm/ADT/iterator_range.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000050#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include "llvm/ADT/SmallVector.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
376 PassSummaryAction Action;
377 ModuleSummaryIndex *Summary;
378
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,
400 PassSummaryAction Action, ModuleSummaryIndex *Summary)
401 : M(M), AARGetter(AARGetter), Action(Action), Summary(Summary),
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000402 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000403 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000404 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000405 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000406 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000407 RemarksEnabled(areRemarksEnabled()) {}
408
409 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000410
Peter Collingbourne0312f612016-06-25 00:23:04 +0000411 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
412 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
413
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000414 void buildTypeIdentifierMap(
415 std::vector<VTableBits> &Bits,
416 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000417 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000418 bool
419 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
420 const std::set<TypeMemberInfo> &TypeMemberInfos,
421 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000422
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000423 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
424 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000425 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000426 VTableSlotInfo &SlotInfo,
427 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000428
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000429 bool tryEvaluateFunctionsWithArgs(
430 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000431 ArrayRef<uint64_t> Args);
432
433 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
434 uint64_t TheRetVal);
435 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000436 CallSiteInfo &CSInfo,
437 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000438
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000439 // Returns the global symbol name that is used to export information about the
440 // given vtable slot and list of arguments.
441 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
442 StringRef Name);
443
444 // This function is called during the export phase to create a symbol
445 // definition containing information about the given vtable slot and list of
446 // arguments.
447 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
448 Constant *C);
449
450 // This function is called during the import phase to create a reference to
451 // the symbol definition created during the export phase.
452 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000453 StringRef Name, unsigned AbsWidth = 0);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000454
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000455 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
456 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000457 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000458 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000459 CallSiteInfo &CSInfo,
460 WholeProgramDevirtResolution::ByArg *Res,
461 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000462
463 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
464 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000465 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000466 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000467 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000468
469 void rebuildGlobal(VTableBits &B);
470
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000471 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
472 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
473
474 // If we were able to eliminate all unsafe uses for a type checked load,
475 // eliminate the associated type tests by replacing them with true.
476 void removeRedundantTypeTests();
477
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000478 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000479
480 // Lower the module using the action and summary passed as command line
481 // arguments. For testing purposes only.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000482 static bool runForTesting(Module &M,
483 function_ref<AAResults &(Function &)> AARGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000484};
485
486struct WholeProgramDevirt : public ModulePass {
487 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000488
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000489 bool UseCommandLine = false;
490
491 PassSummaryAction Action;
492 ModuleSummaryIndex *Summary;
493
494 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
495 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
496 }
497
498 WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary)
499 : ModulePass(ID), Action(Action), Summary(Summary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000500 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
501 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000502
503 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000504 if (skipModule(M))
505 return false;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000506 if (UseCommandLine)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000507 return DevirtModule::runForTesting(M, LegacyAARGetter(*this));
508 return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run();
509 }
510
511 void getAnalysisUsage(AnalysisUsage &AU) const override {
512 AU.addRequired<AssumptionCacheTracker>();
513 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000514 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000515};
516
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000517} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000518
Peter Collingbourne37317f12017-02-17 18:17:04 +0000519INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
520 "Whole program devirtualization", false, false)
521INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
522INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
523INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
524 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000525char WholeProgramDevirt::ID = 0;
526
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000527ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action,
528 ModuleSummaryIndex *Summary) {
529 return new WholeProgramDevirt(Action, Summary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000530}
531
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000532PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000533 ModuleAnalysisManager &AM) {
534 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
535 auto AARGetter = [&](Function &F) -> AAResults & {
536 return FAM.getResult<AAManager>(F);
537 };
538 if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000539 return PreservedAnalyses::all();
540 return PreservedAnalyses::none();
541}
542
Peter Collingbourne37317f12017-02-17 18:17:04 +0000543bool DevirtModule::runForTesting(
544 Module &M, function_ref<AAResults &(Function &)> AARGetter) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000545 ModuleSummaryIndex Summary;
546
547 // Handle the command-line summary arguments. This code is for testing
548 // purposes only, so we handle errors directly.
549 if (!ClReadSummary.empty()) {
550 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
551 ": ");
552 auto ReadSummaryFile =
553 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
554
555 yaml::Input In(ReadSummaryFile->getBuffer());
556 In >> Summary;
557 ExitOnErr(errorCodeToError(In.error()));
558 }
559
Peter Collingbourne37317f12017-02-17 18:17:04 +0000560 bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000561
562 if (!ClWriteSummary.empty()) {
563 ExitOnError ExitOnErr(
564 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
565 std::error_code EC;
566 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
567 ExitOnErr(errorCodeToError(EC));
568
569 yaml::Output Out(OS);
570 Out << Summary;
571 }
572
573 return Changed;
574}
575
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000576void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000577 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000578 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000579 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000580 Bits.reserve(M.getGlobalList().size());
581 SmallVector<MDNode *, 2> Types;
582 for (GlobalVariable &GV : M.globals()) {
583 Types.clear();
584 GV.getMetadata(LLVMContext::MD_type, Types);
585 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000586 continue;
587
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000588 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000589 if (!BitsPtr) {
590 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000591 Bits.back().GV = &GV;
592 Bits.back().ObjectSize =
593 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000594 BitsPtr = &Bits.back();
595 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000596
597 for (MDNode *Type : Types) {
598 auto TypeID = Type->getOperand(1).get();
599
600 uint64_t Offset =
601 cast<ConstantInt>(
602 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
603 ->getZExtValue();
604
605 TypeIdMap[TypeID].insert({BitsPtr, Offset});
606 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000607 }
608}
609
Peter Collingbourne87867542016-12-09 01:10:11 +0000610Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
611 if (I->getType()->isPointerTy()) {
612 if (Offset == 0)
613 return I;
614 return nullptr;
615 }
616
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000617 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000618
619 if (auto *C = dyn_cast<ConstantStruct>(I)) {
620 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000621 if (Offset >= SL->getSizeInBytes())
622 return nullptr;
623
Peter Collingbourne87867542016-12-09 01:10:11 +0000624 unsigned Op = SL->getElementContainingOffset(Offset);
625 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
626 Offset - SL->getElementOffset(Op));
627 }
628 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000629 ArrayType *VTableTy = C->getType();
630 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
631
Peter Collingbourne87867542016-12-09 01:10:11 +0000632 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000633 if (Op >= C->getNumOperands())
634 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000635
Peter Collingbourne87867542016-12-09 01:10:11 +0000636 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
637 Offset % ElemSize);
638 }
639 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000640}
641
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000642bool DevirtModule::tryFindVirtualCallTargets(
643 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000644 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
645 for (const TypeMemberInfo &TM : TypeMemberInfos) {
646 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000647 return false;
648
Peter Collingbourne87867542016-12-09 01:10:11 +0000649 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
650 TM.Offset + ByteOffset);
651 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000652 return false;
653
Peter Collingbourne87867542016-12-09 01:10:11 +0000654 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000655 if (!Fn)
656 return false;
657
658 // We can disregard __cxa_pure_virtual as a possible call target, as
659 // calls to pure virtuals are UB.
660 if (Fn->getName() == "__cxa_pure_virtual")
661 continue;
662
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000663 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000664 }
665
666 // Give up if we couldn't find any targets.
667 return !TargetsForSlot.empty();
668}
669
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000670void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000671 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000672 auto Apply = [&](CallSiteInfo &CSInfo) {
673 for (auto &&VCallSite : CSInfo.CallSites) {
674 if (RemarksEnabled)
675 VCallSite.emitRemark("single-impl", TheFn->getName());
676 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
677 TheFn, VCallSite.CS.getCalledValue()->getType()));
678 // This use is no longer unsafe.
679 if (VCallSite.NumUnsafeUses)
680 --*VCallSite.NumUnsafeUses;
681 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000682 if (CSInfo.isExported()) {
683 IsExported = true;
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000684 CSInfo.markDevirt();
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000685 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000686 };
687 Apply(SlotInfo.CSInfo);
688 for (auto &P : SlotInfo.ConstCSInfo)
689 Apply(P.second);
690}
691
Peter Collingbournee2367412017-02-15 02:13:08 +0000692bool DevirtModule::trySingleImplDevirt(
693 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000694 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000695 // See if the program contains a single implementation of this virtual
696 // function.
697 Function *TheFn = TargetsForSlot[0].Fn;
698 for (auto &&Target : TargetsForSlot)
699 if (TheFn != Target.Fn)
700 return false;
701
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000702 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000703 if (RemarksEnabled)
704 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000705
706 bool IsExported = false;
707 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
708 if (!IsExported)
709 return false;
710
711 // If the only implementation has local linkage, we must promote to external
712 // to make it visible to thin LTO objects. We can only get here during the
713 // ThinLTO export phase.
714 if (TheFn->hasLocalLinkage()) {
715 TheFn->setLinkage(GlobalValue::ExternalLinkage);
716 TheFn->setVisibility(GlobalValue::HiddenVisibility);
717 TheFn->setName(TheFn->getName() + "$merged");
718 }
719
720 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
721 Res->SingleImplName = TheFn->getName();
722
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000723 return true;
724}
725
726bool DevirtModule::tryEvaluateFunctionsWithArgs(
727 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000728 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000729 // Evaluate each function and store the result in each target's RetVal
730 // field.
731 for (VirtualCallTarget &Target : TargetsForSlot) {
732 if (Target.Fn->arg_size() != Args.size() + 1)
733 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000734
735 Evaluator Eval(M.getDataLayout(), nullptr);
736 SmallVector<Constant *, 2> EvalArgs;
737 EvalArgs.push_back(
738 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000739 for (unsigned I = 0; I != Args.size(); ++I) {
740 auto *ArgTy = dyn_cast<IntegerType>(
741 Target.Fn->getFunctionType()->getParamType(I + 1));
742 if (!ArgTy)
743 return false;
744 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
745 }
746
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000747 Constant *RetVal;
748 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
749 !isa<ConstantInt>(RetVal))
750 return false;
751 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
752 }
753 return true;
754}
755
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000756void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
757 uint64_t TheRetVal) {
758 for (auto Call : CSInfo.CallSites)
759 Call.replaceAndErase(
760 "uniform-ret-val", FnName, RemarksEnabled,
761 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000762 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000763}
764
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000765bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000766 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
767 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000768 // Uniform return value optimization. If all functions return the same
769 // constant, replace all calls with that constant.
770 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
771 for (const VirtualCallTarget &Target : TargetsForSlot)
772 if (Target.RetVal != TheRetVal)
773 return false;
774
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000775 if (CSInfo.isExported()) {
776 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
777 Res->Info = TheRetVal;
778 }
779
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000780 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000781 if (RemarksEnabled)
782 for (auto &&Target : TargetsForSlot)
783 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000784 return true;
785}
786
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000787std::string DevirtModule::getGlobalName(VTableSlot Slot,
788 ArrayRef<uint64_t> Args,
789 StringRef Name) {
790 std::string FullName = "__typeid_";
791 raw_string_ostream OS(FullName);
792 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
793 for (uint64_t Arg : Args)
794 OS << '_' << Arg;
795 OS << '_' << Name;
796 return OS.str();
797}
798
799void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
800 StringRef Name, Constant *C) {
801 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
802 getGlobalName(Slot, Args, Name), C, &M);
803 GA->setVisibility(GlobalValue::HiddenVisibility);
804}
805
806Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000807 StringRef Name, unsigned AbsWidth) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000808 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
809 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000810 // We only need to set metadata if the global is newly created, in which
811 // case it would not have hidden visibility.
812 if (!GV || GV->getVisibility() == GlobalValue::HiddenVisibility)
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000813 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000814
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000815 GV->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000816 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
817 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
818 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
819 GV->setMetadata(LLVMContext::MD_absolute_symbol,
820 MDNode::get(M.getContext(), {MinC, MaxC}));
821 };
822 if (AbsWidth == IntPtrTy->getBitWidth())
823 SetAbsRange(~0ull, ~0ull); // Full set.
824 else if (AbsWidth)
825 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000826 return GV;
827}
828
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000829void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
830 bool IsOne,
831 Constant *UniqueMemberAddr) {
832 for (auto &&Call : CSInfo.CallSites) {
833 IRBuilder<> B(Call.CS.getInstruction());
834 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
835 Call.VTable, UniqueMemberAddr);
836 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
837 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp);
838 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000839 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000840}
841
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000842bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000843 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000844 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
845 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000846 // IsOne controls whether we look for a 0 or a 1.
847 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000848 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000849 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000850 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000851 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000852 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000853 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000854 }
855 }
856
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000857 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000858 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000859 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000860
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000861 Constant *UniqueMemberAddr =
862 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
863 UniqueMemberAddr = ConstantExpr::getGetElementPtr(
864 Int8Ty, UniqueMemberAddr,
865 ConstantInt::get(Int64Ty, UniqueMember->Offset));
866
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000867 if (CSInfo.isExported()) {
868 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
869 Res->Info = IsOne;
870
871 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
872 }
873
874 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000875 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
876 UniqueMemberAddr);
877
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000878 // Update devirtualization statistics for targets.
879 if (RemarksEnabled)
880 for (auto &&Target : TargetsForSlot)
881 Target.WasDevirt = true;
882
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000883 return true;
884 };
885
886 if (BitWidth == 1) {
887 if (tryUniqueRetValOptFor(true))
888 return true;
889 if (tryUniqueRetValOptFor(false))
890 return true;
891 }
892 return false;
893}
894
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000895void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
896 Constant *Byte, Constant *Bit) {
897 for (auto Call : CSInfo.CallSites) {
898 auto *RetType = cast<IntegerType>(Call.CS.getType());
899 IRBuilder<> B(Call.CS.getInstruction());
900 Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte);
901 if (RetType->getBitWidth() == 1) {
902 Value *Bits = B.CreateLoad(Addr);
903 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
904 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
905 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
906 IsBitSet);
907 } else {
908 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
909 Value *Val = B.CreateLoad(RetType, ValAddr);
910 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val);
911 }
912 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000913 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000914}
915
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000916bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000917 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
918 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000919 // This only works if the function returns an integer.
920 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
921 if (!RetType)
922 return false;
923 unsigned BitWidth = RetType->getBitWidth();
924 if (BitWidth > 64)
925 return false;
926
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000927 // Make sure that each function is defined, does not access memory, takes at
928 // least one argument, does not use its first argument (which we assume is
929 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000930 //
931 // Note that we test whether this copy of the function is readnone, rather
932 // than testing function attributes, which must hold for any copy of the
933 // function, even a less optimized version substituted at link time. This is
934 // sound because the virtual constant propagation optimizations effectively
935 // inline all implementations of the virtual function into each call site,
936 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000937 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +0000938 if (Target.Fn->isDeclaration() ||
939 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
940 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000941 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000942 Target.Fn->getReturnType() != RetType)
943 return false;
944 }
945
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000946 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000947 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
948 continue;
949
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000950 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
951 if (Res)
952 ResByArg = &Res->ResByArg[CSByConstantArg.first];
953
954 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000955 continue;
956
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000957 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
958 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000959 continue;
960
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000961 // Find an allocation offset in bits in all vtables associated with the
962 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000963 uint64_t AllocBefore =
964 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
965 uint64_t AllocAfter =
966 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
967
968 // Calculate the total amount of padding needed to store a value at both
969 // ends of the object.
970 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
971 for (auto &&Target : TargetsForSlot) {
972 TotalPaddingBefore += std::max<int64_t>(
973 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
974 TotalPaddingAfter += std::max<int64_t>(
975 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
976 }
977
978 // If the amount of padding is too large, give up.
979 // FIXME: do something smarter here.
980 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
981 continue;
982
983 // Calculate the offset to the value as a (possibly negative) byte offset
984 // and (if applicable) a bit offset, and store the values in the targets.
985 int64_t OffsetByte;
986 uint64_t OffsetBit;
987 if (TotalPaddingBefore <= TotalPaddingAfter)
988 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
989 OffsetBit);
990 else
991 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
992 OffsetBit);
993
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000994 if (RemarksEnabled)
995 for (auto &&Target : TargetsForSlot)
996 Target.WasDevirt = true;
997
Peter Collingbourne184773d2017-02-17 19:43:45 +0000998 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000999 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001000
1001 if (CSByConstantArg.second.isExported()) {
1002 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
1003 exportGlobal(Slot, CSByConstantArg.first, "byte",
1004 ConstantExpr::getIntToPtr(ByteConst, Int8PtrTy));
1005 exportGlobal(Slot, CSByConstantArg.first, "bit",
1006 ConstantExpr::getIntToPtr(BitConst, Int8PtrTy));
1007 }
1008
1009 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001010 applyVirtualConstProp(CSByConstantArg.second,
1011 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001012 }
1013 return true;
1014}
1015
1016void DevirtModule::rebuildGlobal(VTableBits &B) {
1017 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1018 return;
1019
1020 // Align each byte array to pointer width.
1021 unsigned PointerSize = M.getDataLayout().getPointerSize();
1022 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1023 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1024
1025 // Before was stored in reverse order; flip it now.
1026 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1027 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1028
1029 // Build an anonymous global containing the before bytes, followed by the
1030 // original initializer, followed by the after bytes.
1031 auto NewInit = ConstantStruct::getAnon(
1032 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1033 B.GV->getInitializer(),
1034 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1035 auto NewGV =
1036 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1037 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1038 NewGV->setSection(B.GV->getSection());
1039 NewGV->setComdat(B.GV->getComdat());
1040
Peter Collingbourne0312f612016-06-25 00:23:04 +00001041 // Copy the original vtable's metadata to the anonymous global, adjusting
1042 // offsets as required.
1043 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1044
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001045 // Build an alias named after the original global, pointing at the second
1046 // element (the original initializer).
1047 auto Alias = GlobalAlias::create(
1048 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1049 ConstantExpr::getGetElementPtr(
1050 NewInit->getType(), NewGV,
1051 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1052 ConstantInt::get(Int32Ty, 1)}),
1053 &M);
1054 Alias->setVisibility(B.GV->getVisibility());
1055 Alias->takeName(B.GV);
1056
1057 B.GV->replaceAllUsesWith(Alias);
1058 B.GV->eraseFromParent();
1059}
1060
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001061bool DevirtModule::areRemarksEnabled() {
1062 const auto &FL = M.getFunctionList();
1063 if (FL.empty())
1064 return false;
1065 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +00001066
1067 const auto &BBL = Fn.getBasicBlockList();
1068 if (BBL.empty())
1069 return false;
1070 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001071 return DI.isEnabled();
1072}
1073
Peter Collingbourne0312f612016-06-25 00:23:04 +00001074void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1075 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001076 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001077 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1078 // points to a member of the type identifier %md. Group calls by (type ID,
1079 // offset) pair (effectively the identity of the virtual function) and store
1080 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001081 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001082 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001083 I != E;) {
1084 auto CI = dyn_cast<CallInst>(I->getUser());
1085 ++I;
1086 if (!CI)
1087 continue;
1088
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001089 // Search for virtual calls based on %p and add them to DevirtCalls.
1090 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001091 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001092 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001093
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001094 // If we found any, add them to CallSlots. Only do this if we haven't seen
1095 // the vtable pointer before, as it may have been CSE'd with pointers from
1096 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001097 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001098 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001099 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1100 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001101 if (SeenPtrs.insert(Ptr).second) {
1102 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001103 CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0),
1104 Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001105 }
1106 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001107 }
1108
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001109 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001110 for (auto Assume : Assumes)
1111 Assume->eraseFromParent();
1112 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1113 // may use the vtable argument later.
1114 if (CI->use_empty())
1115 CI->eraseFromParent();
1116 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001117}
1118
1119void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1120 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1121
1122 for (auto I = TypeCheckedLoadFunc->use_begin(),
1123 E = TypeCheckedLoadFunc->use_end();
1124 I != E;) {
1125 auto CI = dyn_cast<CallInst>(I->getUser());
1126 ++I;
1127 if (!CI)
1128 continue;
1129
1130 Value *Ptr = CI->getArgOperand(0);
1131 Value *Offset = CI->getArgOperand(1);
1132 Value *TypeIdValue = CI->getArgOperand(2);
1133 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1134
1135 SmallVector<DevirtCallSite, 1> DevirtCalls;
1136 SmallVector<Instruction *, 1> LoadedPtrs;
1137 SmallVector<Instruction *, 1> Preds;
1138 bool HasNonCallUses = false;
1139 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1140 HasNonCallUses, CI);
1141
1142 // Start by generating "pessimistic" code that explicitly loads the function
1143 // pointer from the vtable and performs the type check. If possible, we will
1144 // eliminate the load and the type check later.
1145
1146 // If possible, only generate the load at the point where it is used.
1147 // This helps avoid unnecessary spills.
1148 IRBuilder<> LoadB(
1149 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1150 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1151 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1152 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1153
1154 for (Instruction *LoadedPtr : LoadedPtrs) {
1155 LoadedPtr->replaceAllUsesWith(LoadedValue);
1156 LoadedPtr->eraseFromParent();
1157 }
1158
1159 // Likewise for the type test.
1160 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1161 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1162
1163 for (Instruction *Pred : Preds) {
1164 Pred->replaceAllUsesWith(TypeTestCall);
1165 Pred->eraseFromParent();
1166 }
1167
1168 // We have already erased any extractvalue instructions that refer to the
1169 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1170 // (although this is unlikely). In that case, explicitly build a pair and
1171 // RAUW it.
1172 if (!CI->use_empty()) {
1173 Value *Pair = UndefValue::get(CI->getType());
1174 IRBuilder<> B(CI);
1175 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1176 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1177 CI->replaceAllUsesWith(Pair);
1178 }
1179
1180 // The number of unsafe uses is initially the number of uses.
1181 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1182 NumUnsafeUses = DevirtCalls.size();
1183
1184 // If the function pointer has a non-call user, we cannot eliminate the type
1185 // check, as one of those users may eventually call the pointer. Increment
1186 // the unsafe use count to make sure it cannot reach zero.
1187 if (HasNonCallUses)
1188 ++NumUnsafeUses;
1189 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001190 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1191 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001192 }
1193
1194 CI->eraseFromParent();
1195 }
1196}
1197
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001198void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001199 const TypeIdSummary *TidSummary =
1200 Summary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
1201 if (!TidSummary)
1202 return;
1203 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1204 if (ResI == TidSummary->WPDRes.end())
1205 return;
1206 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001207
1208 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1209 // The type of the function in the declaration is irrelevant because every
1210 // call site will cast it to the correct type.
1211 auto *SingleImpl = M.getOrInsertFunction(
1212 Res.SingleImplName, Type::getVoidTy(M.getContext()), nullptr);
1213
1214 // This is the import phase so we should not be exporting anything.
1215 bool IsExported = false;
1216 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1217 assert(!IsExported);
1218 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001219
1220 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1221 auto I = Res.ResByArg.find(CSByConstantArg.first);
1222 if (I == Res.ResByArg.end())
1223 continue;
1224 auto &ResByArg = I->second;
1225 // FIXME: We should figure out what to do about the "function name" argument
1226 // to the apply* functions, as the function names are unavailable during the
1227 // importing phase. For now we just pass the empty string. This does not
1228 // impact correctness because the function names are just used for remarks.
1229 switch (ResByArg.TheKind) {
1230 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1231 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1232 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001233 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1234 Constant *UniqueMemberAddr =
1235 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1236 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1237 UniqueMemberAddr);
1238 break;
1239 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001240 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
1241 Constant *Byte = importGlobal(Slot, CSByConstantArg.first, "byte", 32);
1242 Byte = ConstantExpr::getPtrToInt(Byte, Int32Ty);
1243 Constant *Bit = importGlobal(Slot, CSByConstantArg.first, "bit", 8);
1244 Bit = ConstantExpr::getPtrToInt(Bit, Int8Ty);
1245 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
1246 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001247 default:
1248 break;
1249 }
1250 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001251}
1252
1253void DevirtModule::removeRedundantTypeTests() {
1254 auto True = ConstantInt::getTrue(M.getContext());
1255 for (auto &&U : NumUnsafeUsesForTypeTest) {
1256 if (U.second == 0) {
1257 U.first->replaceAllUsesWith(True);
1258 U.first->eraseFromParent();
1259 }
1260 }
1261}
1262
Peter Collingbourne0312f612016-06-25 00:23:04 +00001263bool DevirtModule::run() {
1264 Function *TypeTestFunc =
1265 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1266 Function *TypeCheckedLoadFunc =
1267 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1268 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1269
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001270 // Normally if there are no users of the devirtualization intrinsics in the
1271 // module, this pass has nothing to do. But if we are exporting, we also need
1272 // to handle any users that appear only in the function summaries.
1273 if (Action != PassSummaryAction::Export &&
1274 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001275 AssumeFunc->use_empty()) &&
1276 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1277 return false;
1278
1279 if (TypeTestFunc && AssumeFunc)
1280 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1281
1282 if (TypeCheckedLoadFunc)
1283 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001284
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001285 if (Action == PassSummaryAction::Import) {
1286 for (auto &S : CallSlots)
1287 importResolution(S.first, S.second);
1288
1289 removeRedundantTypeTests();
1290
1291 // The rest of the code is only necessary when exporting or during regular
1292 // LTO, so we are done.
1293 return true;
1294 }
1295
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001296 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001297 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001298 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1299 buildTypeIdentifierMap(Bits, TypeIdMap);
1300 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001301 return true;
1302
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001303 // Collect information from summary about which calls to try to devirtualize.
1304 if (Action == PassSummaryAction::Export) {
1305 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1306 for (auto &P : TypeIdMap) {
1307 if (auto *TypeId = dyn_cast<MDString>(P.first))
1308 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1309 TypeId);
1310 }
1311
1312 for (auto &P : *Summary) {
1313 for (auto &S : P.second) {
1314 auto *FS = dyn_cast<FunctionSummary>(S.get());
1315 if (!FS)
1316 continue;
1317 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001318 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1319 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001320 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1321 true;
George Rimar5d8aea12017-03-10 10:31:56 +00001322 }
1323 }
1324 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1325 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001326 CallSlots[{MD, VF.Offset}]
1327 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001328 }
1329 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001330 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001331 FS->type_test_assume_const_vcalls()) {
1332 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001333 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001334 .ConstCSInfo[VC.Args]
1335 .SummaryHasTypeTestAssumeUsers = true;
1336 }
1337 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001338 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001339 FS->type_checked_load_const_vcalls()) {
1340 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001341 CallSlots[{MD, VC.VFunc.Offset}]
1342 .ConstCSInfo[VC.Args]
1343 .SummaryTypeCheckedLoadUsers.push_back(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001344 }
1345 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001346 }
1347 }
1348 }
1349
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001350 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001351 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001352 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001353 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001354 // Search each of the members of the type identifier for the virtual
1355 // function implementation at offset S.first.ByteOffset, and add to
1356 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001357 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001358 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1359 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001360 WholeProgramDevirtResolution *Res = nullptr;
1361 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID))
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001362 Res = &Summary
1363 ->getOrInsertTypeIdSummary(
1364 cast<MDString>(S.first.TypeID)->getString())
1365 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001366
1367 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001368 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first))
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001369 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001370
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001371 // Collect functions devirtualized at least for one call site for stats.
1372 if (RemarksEnabled)
1373 for (const auto &T : TargetsForSlot)
1374 if (T.WasDevirt)
1375 DevirtTargets[T.Fn->getName()] = T.Fn;
1376 }
1377
1378 // CFI-specific: if we are exporting and any llvm.type.checked.load
1379 // intrinsics were *not* devirtualized, we need to add the resulting
1380 // llvm.type.test intrinsics to the function summaries so that the
1381 // LowerTypeTests pass will export them.
1382 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) {
1383 auto GUID =
1384 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1385 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1386 FS->addTypeTest(GUID);
1387 for (auto &CCS : S.second.ConstCSInfo)
1388 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1389 FS->addTypeTest(GUID);
1390 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001391 }
1392
1393 if (RemarksEnabled) {
1394 // Generate remarks for each devirtualized function.
1395 for (const auto &DT : DevirtTargets) {
1396 Function *F = DT.second;
1397 DISubprogram *SP = F->getSubprogram();
Justin Bogner7bc978b2017-02-18 02:00:27 +00001398 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP,
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001399 Twine("devirtualized ") + F->getName());
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001400 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001401 }
1402
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001403 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001404
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001405 // Rebuild each global we touched as part of virtual constant propagation to
1406 // include the before and after bytes.
1407 if (DidVirtualConstProp)
1408 for (VTableBits &B : Bits)
1409 rebuildGlobal(B);
1410
1411 return true;
1412}