blob: 09a982a2b37d8673f0b4d30d173bbc72f9bc293d [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
323 /// pass will clear this vector. If at the end of the pass the vector is
324 /// non-empty, we will need to add a use of llvm.type.test to each of the
325 /// function summaries in the vector.
326 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000327
328 bool isExported() const {
329 return SummaryHasTypeTestAssumeUsers ||
330 !SummaryTypeCheckedLoadUsers.empty();
331 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000332};
333
334// Call site information collected for a specific VTableSlot.
335struct VTableSlotInfo {
336 // The set of call sites which do not have all constant integer arguments
337 // (excluding "this").
338 CallSiteInfo CSInfo;
339
340 // The set of call sites with all constant integer arguments (excluding
341 // "this"), grouped by argument list.
342 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
343
344 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
345
346private:
347 CallSiteInfo &findCallSiteInfo(CallSite CS);
348};
349
350CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
351 std::vector<uint64_t> Args;
352 auto *CI = dyn_cast<IntegerType>(CS.getType());
353 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
354 return CSInfo;
355 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
356 auto *CI = dyn_cast<ConstantInt>(Arg);
357 if (!CI || CI->getBitWidth() > 64)
358 return CSInfo;
359 Args.push_back(CI->getZExtValue());
360 }
361 return ConstCSInfo[Args];
362}
363
364void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
365 unsigned *NumUnsafeUses) {
366 findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
367}
368
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000369struct DevirtModule {
370 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000371 function_ref<AAResults &(Function &)> AARGetter;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000372
373 PassSummaryAction Action;
374 ModuleSummaryIndex *Summary;
375
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000376 IntegerType *Int8Ty;
377 PointerType *Int8PtrTy;
378 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000379 IntegerType *Int64Ty;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000380
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000381 bool RemarksEnabled;
382
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000383 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000384
Peter Collingbourne0312f612016-06-25 00:23:04 +0000385 // This map keeps track of the number of "unsafe" uses of a loaded function
386 // pointer. The key is the associated llvm.type.test intrinsic call generated
387 // by this pass. An unsafe use is one that calls the loaded function pointer
388 // directly. Every time we eliminate an unsafe use (for example, by
389 // devirtualizing it or by applying virtual constant propagation), we
390 // decrement the value stored in this map. If a value reaches zero, we can
391 // eliminate the type check by RAUWing the associated llvm.type.test call with
392 // true.
393 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
394
Peter Collingbourne37317f12017-02-17 18:17:04 +0000395 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
396 PassSummaryAction Action, ModuleSummaryIndex *Summary)
397 : M(M), AARGetter(AARGetter), Action(Action), Summary(Summary),
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000398 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000399 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000400 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000401 Int64Ty(Type::getInt64Ty(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000402 RemarksEnabled(areRemarksEnabled()) {}
403
404 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000405
Peter Collingbourne0312f612016-06-25 00:23:04 +0000406 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
407 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
408
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000409 void buildTypeIdentifierMap(
410 std::vector<VTableBits> &Bits,
411 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000412 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000413 bool
414 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
415 const std::set<TypeMemberInfo> &TypeMemberInfos,
416 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000417
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000418 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
419 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000420 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000421 VTableSlotInfo &SlotInfo,
422 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000423
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000424 bool tryEvaluateFunctionsWithArgs(
425 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000426 ArrayRef<uint64_t> Args);
427
428 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
429 uint64_t TheRetVal);
430 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000431 CallSiteInfo &CSInfo,
432 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000433
434 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
435 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000436 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000437 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000438 CallSiteInfo &CSInfo);
439
440 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
441 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000442 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000443 VTableSlotInfo &SlotInfo,
444 WholeProgramDevirtResolution *Res);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000445
446 void rebuildGlobal(VTableBits &B);
447
448 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000449
450 // Lower the module using the action and summary passed as command line
451 // arguments. For testing purposes only.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000452 static bool runForTesting(Module &M,
453 function_ref<AAResults &(Function &)> AARGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000454};
455
456struct WholeProgramDevirt : public ModulePass {
457 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000458
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000459 bool UseCommandLine = false;
460
461 PassSummaryAction Action;
462 ModuleSummaryIndex *Summary;
463
464 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
465 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
466 }
467
468 WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary)
469 : ModulePass(ID), Action(Action), Summary(Summary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000470 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
471 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000472
473 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000474 if (skipModule(M))
475 return false;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000476 if (UseCommandLine)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000477 return DevirtModule::runForTesting(M, LegacyAARGetter(*this));
478 return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run();
479 }
480
481 void getAnalysisUsage(AnalysisUsage &AU) const override {
482 AU.addRequired<AssumptionCacheTracker>();
483 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000484 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000485};
486
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000487} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000488
Peter Collingbourne37317f12017-02-17 18:17:04 +0000489INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
490 "Whole program devirtualization", false, false)
491INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
492INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
493INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
494 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000495char WholeProgramDevirt::ID = 0;
496
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000497ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action,
498 ModuleSummaryIndex *Summary) {
499 return new WholeProgramDevirt(Action, Summary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000500}
501
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000502PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000503 ModuleAnalysisManager &AM) {
504 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
505 auto AARGetter = [&](Function &F) -> AAResults & {
506 return FAM.getResult<AAManager>(F);
507 };
508 if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000509 return PreservedAnalyses::all();
510 return PreservedAnalyses::none();
511}
512
Peter Collingbourne37317f12017-02-17 18:17:04 +0000513bool DevirtModule::runForTesting(
514 Module &M, function_ref<AAResults &(Function &)> AARGetter) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000515 ModuleSummaryIndex Summary;
516
517 // Handle the command-line summary arguments. This code is for testing
518 // purposes only, so we handle errors directly.
519 if (!ClReadSummary.empty()) {
520 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
521 ": ");
522 auto ReadSummaryFile =
523 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
524
525 yaml::Input In(ReadSummaryFile->getBuffer());
526 In >> Summary;
527 ExitOnErr(errorCodeToError(In.error()));
528 }
529
Peter Collingbourne37317f12017-02-17 18:17:04 +0000530 bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000531
532 if (!ClWriteSummary.empty()) {
533 ExitOnError ExitOnErr(
534 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
535 std::error_code EC;
536 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
537 ExitOnErr(errorCodeToError(EC));
538
539 yaml::Output Out(OS);
540 Out << Summary;
541 }
542
543 return Changed;
544}
545
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000546void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000547 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000548 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000549 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000550 Bits.reserve(M.getGlobalList().size());
551 SmallVector<MDNode *, 2> Types;
552 for (GlobalVariable &GV : M.globals()) {
553 Types.clear();
554 GV.getMetadata(LLVMContext::MD_type, Types);
555 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000556 continue;
557
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000558 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000559 if (!BitsPtr) {
560 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000561 Bits.back().GV = &GV;
562 Bits.back().ObjectSize =
563 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000564 BitsPtr = &Bits.back();
565 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000566
567 for (MDNode *Type : Types) {
568 auto TypeID = Type->getOperand(1).get();
569
570 uint64_t Offset =
571 cast<ConstantInt>(
572 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
573 ->getZExtValue();
574
575 TypeIdMap[TypeID].insert({BitsPtr, Offset});
576 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000577 }
578}
579
Peter Collingbourne87867542016-12-09 01:10:11 +0000580Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
581 if (I->getType()->isPointerTy()) {
582 if (Offset == 0)
583 return I;
584 return nullptr;
585 }
586
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000587 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000588
589 if (auto *C = dyn_cast<ConstantStruct>(I)) {
590 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000591 if (Offset >= SL->getSizeInBytes())
592 return nullptr;
593
Peter Collingbourne87867542016-12-09 01:10:11 +0000594 unsigned Op = SL->getElementContainingOffset(Offset);
595 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
596 Offset - SL->getElementOffset(Op));
597 }
598 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000599 ArrayType *VTableTy = C->getType();
600 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
601
Peter Collingbourne87867542016-12-09 01:10:11 +0000602 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000603 if (Op >= C->getNumOperands())
604 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000605
Peter Collingbourne87867542016-12-09 01:10:11 +0000606 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
607 Offset % ElemSize);
608 }
609 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000610}
611
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000612bool DevirtModule::tryFindVirtualCallTargets(
613 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000614 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
615 for (const TypeMemberInfo &TM : TypeMemberInfos) {
616 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000617 return false;
618
Peter Collingbourne87867542016-12-09 01:10:11 +0000619 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
620 TM.Offset + ByteOffset);
621 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000622 return false;
623
Peter Collingbourne87867542016-12-09 01:10:11 +0000624 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000625 if (!Fn)
626 return false;
627
628 // We can disregard __cxa_pure_virtual as a possible call target, as
629 // calls to pure virtuals are UB.
630 if (Fn->getName() == "__cxa_pure_virtual")
631 continue;
632
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000633 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000634 }
635
636 // Give up if we couldn't find any targets.
637 return !TargetsForSlot.empty();
638}
639
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000640void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000641 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000642 auto Apply = [&](CallSiteInfo &CSInfo) {
643 for (auto &&VCallSite : CSInfo.CallSites) {
644 if (RemarksEnabled)
645 VCallSite.emitRemark("single-impl", TheFn->getName());
646 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
647 TheFn, VCallSite.CS.getCalledValue()->getType()));
648 // This use is no longer unsafe.
649 if (VCallSite.NumUnsafeUses)
650 --*VCallSite.NumUnsafeUses;
651 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000652 if (CSInfo.isExported()) {
653 IsExported = true;
654 CSInfo.SummaryTypeCheckedLoadUsers.clear();
655 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000656 };
657 Apply(SlotInfo.CSInfo);
658 for (auto &P : SlotInfo.ConstCSInfo)
659 Apply(P.second);
660}
661
Peter Collingbournee2367412017-02-15 02:13:08 +0000662bool DevirtModule::trySingleImplDevirt(
663 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000664 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000665 // See if the program contains a single implementation of this virtual
666 // function.
667 Function *TheFn = TargetsForSlot[0].Fn;
668 for (auto &&Target : TargetsForSlot)
669 if (TheFn != Target.Fn)
670 return false;
671
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000672 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000673 if (RemarksEnabled)
674 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000675
676 bool IsExported = false;
677 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
678 if (!IsExported)
679 return false;
680
681 // If the only implementation has local linkage, we must promote to external
682 // to make it visible to thin LTO objects. We can only get here during the
683 // ThinLTO export phase.
684 if (TheFn->hasLocalLinkage()) {
685 TheFn->setLinkage(GlobalValue::ExternalLinkage);
686 TheFn->setVisibility(GlobalValue::HiddenVisibility);
687 TheFn->setName(TheFn->getName() + "$merged");
688 }
689
690 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
691 Res->SingleImplName = TheFn->getName();
692
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000693 return true;
694}
695
696bool DevirtModule::tryEvaluateFunctionsWithArgs(
697 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000698 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000699 // Evaluate each function and store the result in each target's RetVal
700 // field.
701 for (VirtualCallTarget &Target : TargetsForSlot) {
702 if (Target.Fn->arg_size() != Args.size() + 1)
703 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000704
705 Evaluator Eval(M.getDataLayout(), nullptr);
706 SmallVector<Constant *, 2> EvalArgs;
707 EvalArgs.push_back(
708 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000709 for (unsigned I = 0; I != Args.size(); ++I) {
710 auto *ArgTy = dyn_cast<IntegerType>(
711 Target.Fn->getFunctionType()->getParamType(I + 1));
712 if (!ArgTy)
713 return false;
714 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
715 }
716
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000717 Constant *RetVal;
718 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
719 !isa<ConstantInt>(RetVal))
720 return false;
721 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
722 }
723 return true;
724}
725
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000726void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
727 uint64_t TheRetVal) {
728 for (auto Call : CSInfo.CallSites)
729 Call.replaceAndErase(
730 "uniform-ret-val", FnName, RemarksEnabled,
731 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbournef0bb90b2017-03-04 01:38:05 +0000732 CSInfo.SummaryTypeCheckedLoadUsers.clear();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000733}
734
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000735bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000736 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
737 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000738 // Uniform return value optimization. If all functions return the same
739 // constant, replace all calls with that constant.
740 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
741 for (const VirtualCallTarget &Target : TargetsForSlot)
742 if (Target.RetVal != TheRetVal)
743 return false;
744
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000745 if (CSInfo.isExported()) {
746 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
747 Res->Info = TheRetVal;
748 }
749
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000750 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000751 if (RemarksEnabled)
752 for (auto &&Target : TargetsForSlot)
753 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000754 return true;
755}
756
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000757void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
758 bool IsOne,
759 Constant *UniqueMemberAddr) {
760 for (auto &&Call : CSInfo.CallSites) {
761 IRBuilder<> B(Call.CS.getInstruction());
762 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
763 Call.VTable, UniqueMemberAddr);
764 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
765 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp);
766 }
767}
768
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000769bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000770 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000771 CallSiteInfo &CSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000772 // IsOne controls whether we look for a 0 or a 1.
773 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000774 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000775 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000776 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000777 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000778 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000779 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000780 }
781 }
782
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000783 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000784 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000785 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000786
787 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000788 Constant *UniqueMemberAddr =
789 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
790 UniqueMemberAddr = ConstantExpr::getGetElementPtr(
791 Int8Ty, UniqueMemberAddr,
792 ConstantInt::get(Int64Ty, UniqueMember->Offset));
793
794 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
795 UniqueMemberAddr);
796
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000797 // Update devirtualization statistics for targets.
798 if (RemarksEnabled)
799 for (auto &&Target : TargetsForSlot)
800 Target.WasDevirt = true;
801
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000802 return true;
803 };
804
805 if (BitWidth == 1) {
806 if (tryUniqueRetValOptFor(true))
807 return true;
808 if (tryUniqueRetValOptFor(false))
809 return true;
810 }
811 return false;
812}
813
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000814void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
815 Constant *Byte, Constant *Bit) {
816 for (auto Call : CSInfo.CallSites) {
817 auto *RetType = cast<IntegerType>(Call.CS.getType());
818 IRBuilder<> B(Call.CS.getInstruction());
819 Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte);
820 if (RetType->getBitWidth() == 1) {
821 Value *Bits = B.CreateLoad(Addr);
822 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
823 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
824 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
825 IsBitSet);
826 } else {
827 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
828 Value *Val = B.CreateLoad(RetType, ValAddr);
829 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val);
830 }
831 }
832}
833
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000834bool DevirtModule::tryVirtualConstProp(
835 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000836 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000837 // This only works if the function returns an integer.
838 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
839 if (!RetType)
840 return false;
841 unsigned BitWidth = RetType->getBitWidth();
842 if (BitWidth > 64)
843 return false;
844
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000845 // Make sure that each function is defined, does not access memory, takes at
846 // least one argument, does not use its first argument (which we assume is
847 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000848 //
849 // Note that we test whether this copy of the function is readnone, rather
850 // than testing function attributes, which must hold for any copy of the
851 // function, even a less optimized version substituted at link time. This is
852 // sound because the virtual constant propagation optimizations effectively
853 // inline all implementations of the virtual function into each call site,
854 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000855 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +0000856 if (Target.Fn->isDeclaration() ||
857 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
858 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000859 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000860 Target.Fn->getReturnType() != RetType)
861 return false;
862 }
863
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000864 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000865 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
866 continue;
867
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000868 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
869 if (Res)
870 ResByArg = &Res->ResByArg[CSByConstantArg.first];
871
872 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000873 continue;
874
875 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
876 continue;
877
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000878 // Find an allocation offset in bits in all vtables associated with the
879 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000880 uint64_t AllocBefore =
881 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
882 uint64_t AllocAfter =
883 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
884
885 // Calculate the total amount of padding needed to store a value at both
886 // ends of the object.
887 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
888 for (auto &&Target : TargetsForSlot) {
889 TotalPaddingBefore += std::max<int64_t>(
890 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
891 TotalPaddingAfter += std::max<int64_t>(
892 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
893 }
894
895 // If the amount of padding is too large, give up.
896 // FIXME: do something smarter here.
897 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
898 continue;
899
900 // Calculate the offset to the value as a (possibly negative) byte offset
901 // and (if applicable) a bit offset, and store the values in the targets.
902 int64_t OffsetByte;
903 uint64_t OffsetBit;
904 if (TotalPaddingBefore <= TotalPaddingAfter)
905 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
906 OffsetBit);
907 else
908 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
909 OffsetBit);
910
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000911 if (RemarksEnabled)
912 for (auto &&Target : TargetsForSlot)
913 Target.WasDevirt = true;
914
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000915 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourne184773d2017-02-17 19:43:45 +0000916 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000917 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
918 applyVirtualConstProp(CSByConstantArg.second,
919 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000920 }
921 return true;
922}
923
924void DevirtModule::rebuildGlobal(VTableBits &B) {
925 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
926 return;
927
928 // Align each byte array to pointer width.
929 unsigned PointerSize = M.getDataLayout().getPointerSize();
930 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
931 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
932
933 // Before was stored in reverse order; flip it now.
934 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
935 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
936
937 // Build an anonymous global containing the before bytes, followed by the
938 // original initializer, followed by the after bytes.
939 auto NewInit = ConstantStruct::getAnon(
940 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
941 B.GV->getInitializer(),
942 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
943 auto NewGV =
944 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
945 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
946 NewGV->setSection(B.GV->getSection());
947 NewGV->setComdat(B.GV->getComdat());
948
Peter Collingbourne0312f612016-06-25 00:23:04 +0000949 // Copy the original vtable's metadata to the anonymous global, adjusting
950 // offsets as required.
951 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
952
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000953 // Build an alias named after the original global, pointing at the second
954 // element (the original initializer).
955 auto Alias = GlobalAlias::create(
956 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
957 ConstantExpr::getGetElementPtr(
958 NewInit->getType(), NewGV,
959 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
960 ConstantInt::get(Int32Ty, 1)}),
961 &M);
962 Alias->setVisibility(B.GV->getVisibility());
963 Alias->takeName(B.GV);
964
965 B.GV->replaceAllUsesWith(Alias);
966 B.GV->eraseFromParent();
967}
968
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000969bool DevirtModule::areRemarksEnabled() {
970 const auto &FL = M.getFunctionList();
971 if (FL.empty())
972 return false;
973 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +0000974
975 const auto &BBL = Fn.getBasicBlockList();
976 if (BBL.empty())
977 return false;
978 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000979 return DI.isEnabled();
980}
981
Peter Collingbourne0312f612016-06-25 00:23:04 +0000982void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
983 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000984 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000985 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
986 // points to a member of the type identifier %md. Group calls by (type ID,
987 // offset) pair (effectively the identity of the virtual function) and store
988 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000989 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000990 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000991 I != E;) {
992 auto CI = dyn_cast<CallInst>(I->getUser());
993 ++I;
994 if (!CI)
995 continue;
996
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000997 // Search for virtual calls based on %p and add them to DevirtCalls.
998 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000999 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001000 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001001
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001002 // If we found any, add them to CallSlots. Only do this if we haven't seen
1003 // the vtable pointer before, as it may have been CSE'd with pointers from
1004 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001005 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001006 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001007 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1008 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001009 if (SeenPtrs.insert(Ptr).second) {
1010 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001011 CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0),
1012 Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001013 }
1014 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001015 }
1016
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001017 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001018 for (auto Assume : Assumes)
1019 Assume->eraseFromParent();
1020 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1021 // may use the vtable argument later.
1022 if (CI->use_empty())
1023 CI->eraseFromParent();
1024 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001025}
1026
1027void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1028 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1029
1030 for (auto I = TypeCheckedLoadFunc->use_begin(),
1031 E = TypeCheckedLoadFunc->use_end();
1032 I != E;) {
1033 auto CI = dyn_cast<CallInst>(I->getUser());
1034 ++I;
1035 if (!CI)
1036 continue;
1037
1038 Value *Ptr = CI->getArgOperand(0);
1039 Value *Offset = CI->getArgOperand(1);
1040 Value *TypeIdValue = CI->getArgOperand(2);
1041 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1042
1043 SmallVector<DevirtCallSite, 1> DevirtCalls;
1044 SmallVector<Instruction *, 1> LoadedPtrs;
1045 SmallVector<Instruction *, 1> Preds;
1046 bool HasNonCallUses = false;
1047 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1048 HasNonCallUses, CI);
1049
1050 // Start by generating "pessimistic" code that explicitly loads the function
1051 // pointer from the vtable and performs the type check. If possible, we will
1052 // eliminate the load and the type check later.
1053
1054 // If possible, only generate the load at the point where it is used.
1055 // This helps avoid unnecessary spills.
1056 IRBuilder<> LoadB(
1057 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1058 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1059 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1060 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1061
1062 for (Instruction *LoadedPtr : LoadedPtrs) {
1063 LoadedPtr->replaceAllUsesWith(LoadedValue);
1064 LoadedPtr->eraseFromParent();
1065 }
1066
1067 // Likewise for the type test.
1068 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1069 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1070
1071 for (Instruction *Pred : Preds) {
1072 Pred->replaceAllUsesWith(TypeTestCall);
1073 Pred->eraseFromParent();
1074 }
1075
1076 // We have already erased any extractvalue instructions that refer to the
1077 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1078 // (although this is unlikely). In that case, explicitly build a pair and
1079 // RAUW it.
1080 if (!CI->use_empty()) {
1081 Value *Pair = UndefValue::get(CI->getType());
1082 IRBuilder<> B(CI);
1083 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1084 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1085 CI->replaceAllUsesWith(Pair);
1086 }
1087
1088 // The number of unsafe uses is initially the number of uses.
1089 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1090 NumUnsafeUses = DevirtCalls.size();
1091
1092 // If the function pointer has a non-call user, we cannot eliminate the type
1093 // check, as one of those users may eventually call the pointer. Increment
1094 // the unsafe use count to make sure it cannot reach zero.
1095 if (HasNonCallUses)
1096 ++NumUnsafeUses;
1097 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001098 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1099 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001100 }
1101
1102 CI->eraseFromParent();
1103 }
1104}
1105
1106bool DevirtModule::run() {
1107 Function *TypeTestFunc =
1108 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1109 Function *TypeCheckedLoadFunc =
1110 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1111 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1112
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001113 // Normally if there are no users of the devirtualization intrinsics in the
1114 // module, this pass has nothing to do. But if we are exporting, we also need
1115 // to handle any users that appear only in the function summaries.
1116 if (Action != PassSummaryAction::Export &&
1117 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001118 AssumeFunc->use_empty()) &&
1119 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1120 return false;
1121
1122 if (TypeTestFunc && AssumeFunc)
1123 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1124
1125 if (TypeCheckedLoadFunc)
1126 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001127
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001128 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001129 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001130 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1131 buildTypeIdentifierMap(Bits, TypeIdMap);
1132 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001133 return true;
1134
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001135 // Collect information from summary about which calls to try to devirtualize.
1136 if (Action == PassSummaryAction::Export) {
1137 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1138 for (auto &P : TypeIdMap) {
1139 if (auto *TypeId = dyn_cast<MDString>(P.first))
1140 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1141 TypeId);
1142 }
1143
1144 for (auto &P : *Summary) {
1145 for (auto &S : P.second) {
1146 auto *FS = dyn_cast<FunctionSummary>(S.get());
1147 if (!FS)
1148 continue;
1149 // FIXME: Only add live functions.
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001150 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls())
1151 for (Metadata *MD : MetadataByGUID[VF.GUID])
1152 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1153 true;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001154 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls())
1155 for (Metadata *MD : MetadataByGUID[VF.GUID])
1156 CallSlots[{MD, VF.Offset}]
1157 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
1158 for (const FunctionSummary::ConstVCall &VC :
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001159 FS->type_test_assume_const_vcalls())
1160 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1161 CallSlots[{MD, VC.VFunc.Offset}]
1162 .ConstCSInfo[VC.Args].SummaryHasTypeTestAssumeUsers = true;
1163 for (const FunctionSummary::ConstVCall &VC :
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001164 FS->type_checked_load_const_vcalls())
1165 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1166 CallSlots[{MD, VC.VFunc.Offset}]
1167 .ConstCSInfo[VC.Args]
1168 .SummaryTypeCheckedLoadUsers.push_back(FS);
1169 }
1170 }
1171 }
1172
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001173 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001174 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001175 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001176 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001177 // Search each of the members of the type identifier for the virtual
1178 // function implementation at offset S.first.ByteOffset, and add to
1179 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001180 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001181 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1182 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001183 WholeProgramDevirtResolution *Res = nullptr;
1184 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID))
1185 Res =
1186 &Summary
1187 ->getTypeIdSummary(cast<MDString>(S.first.TypeID)->getString())
1188 .WPDRes[S.first.ByteOffset];
1189
1190 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001191 tryVirtualConstProp(TargetsForSlot, S.second, Res))
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001192 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001193
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001194 // Collect functions devirtualized at least for one call site for stats.
1195 if (RemarksEnabled)
1196 for (const auto &T : TargetsForSlot)
1197 if (T.WasDevirt)
1198 DevirtTargets[T.Fn->getName()] = T.Fn;
1199 }
1200
1201 // CFI-specific: if we are exporting and any llvm.type.checked.load
1202 // intrinsics were *not* devirtualized, we need to add the resulting
1203 // llvm.type.test intrinsics to the function summaries so that the
1204 // LowerTypeTests pass will export them.
1205 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) {
1206 auto GUID =
1207 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1208 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1209 FS->addTypeTest(GUID);
1210 for (auto &CCS : S.second.ConstCSInfo)
1211 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1212 FS->addTypeTest(GUID);
1213 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001214 }
1215
1216 if (RemarksEnabled) {
1217 // Generate remarks for each devirtualized function.
1218 for (const auto &DT : DevirtTargets) {
1219 Function *F = DT.second;
1220 DISubprogram *SP = F->getSubprogram();
Justin Bogner7bc978b2017-02-18 02:00:27 +00001221 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP,
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001222 Twine("devirtualized ") + F->getName());
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001223 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001224 }
1225
Peter Collingbourne0312f612016-06-25 00:23:04 +00001226 // If we were able to eliminate all unsafe uses for a type checked load,
1227 // eliminate the type test by replacing it with true.
1228 if (TypeCheckedLoadFunc) {
1229 auto True = ConstantInt::getTrue(M.getContext());
1230 for (auto &&U : NumUnsafeUsesForTypeTest) {
1231 if (U.second == 0) {
1232 U.first->replaceAllUsesWith(True);
1233 U.first->eraseFromParent();
1234 }
1235 }
1236 }
1237
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001238 // Rebuild each global we touched as part of virtual constant propagation to
1239 // include the before and after bytes.
1240 if (DidVirtualConstProp)
1241 for (VTableBits &B : Bits)
1242 rebuildGlobal(B);
1243
1244 return true;
1245}