blob: bbf0a925bfc8ded779eb20ca14994c27178685ee [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,
431 CallSiteInfo &CSInfo);
432
433 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
434 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000435 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000436 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000437 CallSiteInfo &CSInfo);
438
439 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
440 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000441 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000442 VTableSlotInfo &SlotInfo);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000443
444 void rebuildGlobal(VTableBits &B);
445
446 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000447
448 // Lower the module using the action and summary passed as command line
449 // arguments. For testing purposes only.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000450 static bool runForTesting(Module &M,
451 function_ref<AAResults &(Function &)> AARGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000452};
453
454struct WholeProgramDevirt : public ModulePass {
455 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000456
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000457 bool UseCommandLine = false;
458
459 PassSummaryAction Action;
460 ModuleSummaryIndex *Summary;
461
462 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
463 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
464 }
465
466 WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary)
467 : ModulePass(ID), Action(Action), Summary(Summary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000468 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
469 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000470
471 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000472 if (skipModule(M))
473 return false;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000474 if (UseCommandLine)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000475 return DevirtModule::runForTesting(M, LegacyAARGetter(*this));
476 return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run();
477 }
478
479 void getAnalysisUsage(AnalysisUsage &AU) const override {
480 AU.addRequired<AssumptionCacheTracker>();
481 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000482 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000483};
484
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000485} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000486
Peter Collingbourne37317f12017-02-17 18:17:04 +0000487INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
488 "Whole program devirtualization", false, false)
489INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
490INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
491INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
492 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000493char WholeProgramDevirt::ID = 0;
494
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000495ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action,
496 ModuleSummaryIndex *Summary) {
497 return new WholeProgramDevirt(Action, Summary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000498}
499
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000500PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000501 ModuleAnalysisManager &AM) {
502 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
503 auto AARGetter = [&](Function &F) -> AAResults & {
504 return FAM.getResult<AAManager>(F);
505 };
506 if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000507 return PreservedAnalyses::all();
508 return PreservedAnalyses::none();
509}
510
Peter Collingbourne37317f12017-02-17 18:17:04 +0000511bool DevirtModule::runForTesting(
512 Module &M, function_ref<AAResults &(Function &)> AARGetter) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000513 ModuleSummaryIndex Summary;
514
515 // Handle the command-line summary arguments. This code is for testing
516 // purposes only, so we handle errors directly.
517 if (!ClReadSummary.empty()) {
518 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
519 ": ");
520 auto ReadSummaryFile =
521 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
522
523 yaml::Input In(ReadSummaryFile->getBuffer());
524 In >> Summary;
525 ExitOnErr(errorCodeToError(In.error()));
526 }
527
Peter Collingbourne37317f12017-02-17 18:17:04 +0000528 bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000529
530 if (!ClWriteSummary.empty()) {
531 ExitOnError ExitOnErr(
532 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
533 std::error_code EC;
534 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
535 ExitOnErr(errorCodeToError(EC));
536
537 yaml::Output Out(OS);
538 Out << Summary;
539 }
540
541 return Changed;
542}
543
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000544void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000545 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000546 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000547 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000548 Bits.reserve(M.getGlobalList().size());
549 SmallVector<MDNode *, 2> Types;
550 for (GlobalVariable &GV : M.globals()) {
551 Types.clear();
552 GV.getMetadata(LLVMContext::MD_type, Types);
553 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000554 continue;
555
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000556 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000557 if (!BitsPtr) {
558 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000559 Bits.back().GV = &GV;
560 Bits.back().ObjectSize =
561 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000562 BitsPtr = &Bits.back();
563 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000564
565 for (MDNode *Type : Types) {
566 auto TypeID = Type->getOperand(1).get();
567
568 uint64_t Offset =
569 cast<ConstantInt>(
570 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
571 ->getZExtValue();
572
573 TypeIdMap[TypeID].insert({BitsPtr, Offset});
574 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000575 }
576}
577
Peter Collingbourne87867542016-12-09 01:10:11 +0000578Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
579 if (I->getType()->isPointerTy()) {
580 if (Offset == 0)
581 return I;
582 return nullptr;
583 }
584
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000585 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000586
587 if (auto *C = dyn_cast<ConstantStruct>(I)) {
588 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000589 if (Offset >= SL->getSizeInBytes())
590 return nullptr;
591
Peter Collingbourne87867542016-12-09 01:10:11 +0000592 unsigned Op = SL->getElementContainingOffset(Offset);
593 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
594 Offset - SL->getElementOffset(Op));
595 }
596 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000597 ArrayType *VTableTy = C->getType();
598 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
599
Peter Collingbourne87867542016-12-09 01:10:11 +0000600 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000601 if (Op >= C->getNumOperands())
602 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000603
Peter Collingbourne87867542016-12-09 01:10:11 +0000604 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
605 Offset % ElemSize);
606 }
607 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000608}
609
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000610bool DevirtModule::tryFindVirtualCallTargets(
611 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000612 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
613 for (const TypeMemberInfo &TM : TypeMemberInfos) {
614 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000615 return false;
616
Peter Collingbourne87867542016-12-09 01:10:11 +0000617 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
618 TM.Offset + ByteOffset);
619 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000620 return false;
621
Peter Collingbourne87867542016-12-09 01:10:11 +0000622 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000623 if (!Fn)
624 return false;
625
626 // We can disregard __cxa_pure_virtual as a possible call target, as
627 // calls to pure virtuals are UB.
628 if (Fn->getName() == "__cxa_pure_virtual")
629 continue;
630
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000631 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000632 }
633
634 // Give up if we couldn't find any targets.
635 return !TargetsForSlot.empty();
636}
637
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000638void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000639 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000640 auto Apply = [&](CallSiteInfo &CSInfo) {
641 for (auto &&VCallSite : CSInfo.CallSites) {
642 if (RemarksEnabled)
643 VCallSite.emitRemark("single-impl", TheFn->getName());
644 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
645 TheFn, VCallSite.CS.getCalledValue()->getType()));
646 // This use is no longer unsafe.
647 if (VCallSite.NumUnsafeUses)
648 --*VCallSite.NumUnsafeUses;
649 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000650 if (CSInfo.isExported()) {
651 IsExported = true;
652 CSInfo.SummaryTypeCheckedLoadUsers.clear();
653 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000654 };
655 Apply(SlotInfo.CSInfo);
656 for (auto &P : SlotInfo.ConstCSInfo)
657 Apply(P.second);
658}
659
Peter Collingbournee2367412017-02-15 02:13:08 +0000660bool DevirtModule::trySingleImplDevirt(
661 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000662 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000663 // See if the program contains a single implementation of this virtual
664 // function.
665 Function *TheFn = TargetsForSlot[0].Fn;
666 for (auto &&Target : TargetsForSlot)
667 if (TheFn != Target.Fn)
668 return false;
669
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000670 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000671 if (RemarksEnabled)
672 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000673
674 bool IsExported = false;
675 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
676 if (!IsExported)
677 return false;
678
679 // If the only implementation has local linkage, we must promote to external
680 // to make it visible to thin LTO objects. We can only get here during the
681 // ThinLTO export phase.
682 if (TheFn->hasLocalLinkage()) {
683 TheFn->setLinkage(GlobalValue::ExternalLinkage);
684 TheFn->setVisibility(GlobalValue::HiddenVisibility);
685 TheFn->setName(TheFn->getName() + "$merged");
686 }
687
688 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
689 Res->SingleImplName = TheFn->getName();
690
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000691 return true;
692}
693
694bool DevirtModule::tryEvaluateFunctionsWithArgs(
695 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000696 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000697 // Evaluate each function and store the result in each target's RetVal
698 // field.
699 for (VirtualCallTarget &Target : TargetsForSlot) {
700 if (Target.Fn->arg_size() != Args.size() + 1)
701 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000702
703 Evaluator Eval(M.getDataLayout(), nullptr);
704 SmallVector<Constant *, 2> EvalArgs;
705 EvalArgs.push_back(
706 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000707 for (unsigned I = 0; I != Args.size(); ++I) {
708 auto *ArgTy = dyn_cast<IntegerType>(
709 Target.Fn->getFunctionType()->getParamType(I + 1));
710 if (!ArgTy)
711 return false;
712 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
713 }
714
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000715 Constant *RetVal;
716 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
717 !isa<ConstantInt>(RetVal))
718 return false;
719 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
720 }
721 return true;
722}
723
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000724void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
725 uint64_t TheRetVal) {
726 for (auto Call : CSInfo.CallSites)
727 Call.replaceAndErase(
728 "uniform-ret-val", FnName, RemarksEnabled,
729 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
730}
731
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000732bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000733 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000734 // Uniform return value optimization. If all functions return the same
735 // constant, replace all calls with that constant.
736 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
737 for (const VirtualCallTarget &Target : TargetsForSlot)
738 if (Target.RetVal != TheRetVal)
739 return false;
740
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000741 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000742 if (RemarksEnabled)
743 for (auto &&Target : TargetsForSlot)
744 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000745 return true;
746}
747
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000748void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
749 bool IsOne,
750 Constant *UniqueMemberAddr) {
751 for (auto &&Call : CSInfo.CallSites) {
752 IRBuilder<> B(Call.CS.getInstruction());
753 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
754 Call.VTable, UniqueMemberAddr);
755 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
756 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp);
757 }
758}
759
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000760bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000761 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000762 CallSiteInfo &CSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000763 // IsOne controls whether we look for a 0 or a 1.
764 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000765 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000766 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000767 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000768 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000769 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000770 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000771 }
772 }
773
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000774 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000775 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000776 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000777
778 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000779 Constant *UniqueMemberAddr =
780 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
781 UniqueMemberAddr = ConstantExpr::getGetElementPtr(
782 Int8Ty, UniqueMemberAddr,
783 ConstantInt::get(Int64Ty, UniqueMember->Offset));
784
785 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
786 UniqueMemberAddr);
787
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000788 // Update devirtualization statistics for targets.
789 if (RemarksEnabled)
790 for (auto &&Target : TargetsForSlot)
791 Target.WasDevirt = true;
792
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000793 return true;
794 };
795
796 if (BitWidth == 1) {
797 if (tryUniqueRetValOptFor(true))
798 return true;
799 if (tryUniqueRetValOptFor(false))
800 return true;
801 }
802 return false;
803}
804
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000805void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
806 Constant *Byte, Constant *Bit) {
807 for (auto Call : CSInfo.CallSites) {
808 auto *RetType = cast<IntegerType>(Call.CS.getType());
809 IRBuilder<> B(Call.CS.getInstruction());
810 Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte);
811 if (RetType->getBitWidth() == 1) {
812 Value *Bits = B.CreateLoad(Addr);
813 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
814 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
815 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
816 IsBitSet);
817 } else {
818 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
819 Value *Val = B.CreateLoad(RetType, ValAddr);
820 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val);
821 }
822 }
823}
824
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000825bool DevirtModule::tryVirtualConstProp(
826 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000827 VTableSlotInfo &SlotInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000828 // This only works if the function returns an integer.
829 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
830 if (!RetType)
831 return false;
832 unsigned BitWidth = RetType->getBitWidth();
833 if (BitWidth > 64)
834 return false;
835
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000836 // Make sure that each function is defined, does not access memory, takes at
837 // least one argument, does not use its first argument (which we assume is
838 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000839 //
840 // Note that we test whether this copy of the function is readnone, rather
841 // than testing function attributes, which must hold for any copy of the
842 // function, even a less optimized version substituted at link time. This is
843 // sound because the virtual constant propagation optimizations effectively
844 // inline all implementations of the virtual function into each call site,
845 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000846 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +0000847 if (Target.Fn->isDeclaration() ||
848 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
849 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000850 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000851 Target.Fn->getReturnType() != RetType)
852 return false;
853 }
854
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000855 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000856 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
857 continue;
858
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000859 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000860 continue;
861
862 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
863 continue;
864
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000865 // Find an allocation offset in bits in all vtables associated with the
866 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000867 uint64_t AllocBefore =
868 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
869 uint64_t AllocAfter =
870 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
871
872 // Calculate the total amount of padding needed to store a value at both
873 // ends of the object.
874 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
875 for (auto &&Target : TargetsForSlot) {
876 TotalPaddingBefore += std::max<int64_t>(
877 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
878 TotalPaddingAfter += std::max<int64_t>(
879 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
880 }
881
882 // If the amount of padding is too large, give up.
883 // FIXME: do something smarter here.
884 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
885 continue;
886
887 // Calculate the offset to the value as a (possibly negative) byte offset
888 // and (if applicable) a bit offset, and store the values in the targets.
889 int64_t OffsetByte;
890 uint64_t OffsetBit;
891 if (TotalPaddingBefore <= TotalPaddingAfter)
892 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
893 OffsetBit);
894 else
895 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
896 OffsetBit);
897
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000898 if (RemarksEnabled)
899 for (auto &&Target : TargetsForSlot)
900 Target.WasDevirt = true;
901
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000902 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourne184773d2017-02-17 19:43:45 +0000903 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000904 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
905 applyVirtualConstProp(CSByConstantArg.second,
906 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000907 }
908 return true;
909}
910
911void DevirtModule::rebuildGlobal(VTableBits &B) {
912 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
913 return;
914
915 // Align each byte array to pointer width.
916 unsigned PointerSize = M.getDataLayout().getPointerSize();
917 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
918 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
919
920 // Before was stored in reverse order; flip it now.
921 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
922 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
923
924 // Build an anonymous global containing the before bytes, followed by the
925 // original initializer, followed by the after bytes.
926 auto NewInit = ConstantStruct::getAnon(
927 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
928 B.GV->getInitializer(),
929 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
930 auto NewGV =
931 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
932 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
933 NewGV->setSection(B.GV->getSection());
934 NewGV->setComdat(B.GV->getComdat());
935
Peter Collingbourne0312f612016-06-25 00:23:04 +0000936 // Copy the original vtable's metadata to the anonymous global, adjusting
937 // offsets as required.
938 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
939
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000940 // Build an alias named after the original global, pointing at the second
941 // element (the original initializer).
942 auto Alias = GlobalAlias::create(
943 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
944 ConstantExpr::getGetElementPtr(
945 NewInit->getType(), NewGV,
946 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
947 ConstantInt::get(Int32Ty, 1)}),
948 &M);
949 Alias->setVisibility(B.GV->getVisibility());
950 Alias->takeName(B.GV);
951
952 B.GV->replaceAllUsesWith(Alias);
953 B.GV->eraseFromParent();
954}
955
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000956bool DevirtModule::areRemarksEnabled() {
957 const auto &FL = M.getFunctionList();
958 if (FL.empty())
959 return false;
960 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +0000961
962 const auto &BBL = Fn.getBasicBlockList();
963 if (BBL.empty())
964 return false;
965 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000966 return DI.isEnabled();
967}
968
Peter Collingbourne0312f612016-06-25 00:23:04 +0000969void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
970 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000971 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000972 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
973 // points to a member of the type identifier %md. Group calls by (type ID,
974 // offset) pair (effectively the identity of the virtual function) and store
975 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000976 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000977 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000978 I != E;) {
979 auto CI = dyn_cast<CallInst>(I->getUser());
980 ++I;
981 if (!CI)
982 continue;
983
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000984 // Search for virtual calls based on %p and add them to DevirtCalls.
985 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000986 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +0000987 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000988
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000989 // If we found any, add them to CallSlots. Only do this if we haven't seen
990 // the vtable pointer before, as it may have been CSE'd with pointers from
991 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000992 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000993 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000994 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
995 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000996 if (SeenPtrs.insert(Ptr).second) {
997 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000998 CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0),
999 Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001000 }
1001 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001002 }
1003
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001004 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001005 for (auto Assume : Assumes)
1006 Assume->eraseFromParent();
1007 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1008 // may use the vtable argument later.
1009 if (CI->use_empty())
1010 CI->eraseFromParent();
1011 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001012}
1013
1014void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1015 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1016
1017 for (auto I = TypeCheckedLoadFunc->use_begin(),
1018 E = TypeCheckedLoadFunc->use_end();
1019 I != E;) {
1020 auto CI = dyn_cast<CallInst>(I->getUser());
1021 ++I;
1022 if (!CI)
1023 continue;
1024
1025 Value *Ptr = CI->getArgOperand(0);
1026 Value *Offset = CI->getArgOperand(1);
1027 Value *TypeIdValue = CI->getArgOperand(2);
1028 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1029
1030 SmallVector<DevirtCallSite, 1> DevirtCalls;
1031 SmallVector<Instruction *, 1> LoadedPtrs;
1032 SmallVector<Instruction *, 1> Preds;
1033 bool HasNonCallUses = false;
1034 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1035 HasNonCallUses, CI);
1036
1037 // Start by generating "pessimistic" code that explicitly loads the function
1038 // pointer from the vtable and performs the type check. If possible, we will
1039 // eliminate the load and the type check later.
1040
1041 // If possible, only generate the load at the point where it is used.
1042 // This helps avoid unnecessary spills.
1043 IRBuilder<> LoadB(
1044 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1045 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1046 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1047 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1048
1049 for (Instruction *LoadedPtr : LoadedPtrs) {
1050 LoadedPtr->replaceAllUsesWith(LoadedValue);
1051 LoadedPtr->eraseFromParent();
1052 }
1053
1054 // Likewise for the type test.
1055 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1056 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1057
1058 for (Instruction *Pred : Preds) {
1059 Pred->replaceAllUsesWith(TypeTestCall);
1060 Pred->eraseFromParent();
1061 }
1062
1063 // We have already erased any extractvalue instructions that refer to the
1064 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1065 // (although this is unlikely). In that case, explicitly build a pair and
1066 // RAUW it.
1067 if (!CI->use_empty()) {
1068 Value *Pair = UndefValue::get(CI->getType());
1069 IRBuilder<> B(CI);
1070 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1071 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1072 CI->replaceAllUsesWith(Pair);
1073 }
1074
1075 // The number of unsafe uses is initially the number of uses.
1076 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1077 NumUnsafeUses = DevirtCalls.size();
1078
1079 // If the function pointer has a non-call user, we cannot eliminate the type
1080 // check, as one of those users may eventually call the pointer. Increment
1081 // the unsafe use count to make sure it cannot reach zero.
1082 if (HasNonCallUses)
1083 ++NumUnsafeUses;
1084 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001085 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1086 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001087 }
1088
1089 CI->eraseFromParent();
1090 }
1091}
1092
1093bool DevirtModule::run() {
1094 Function *TypeTestFunc =
1095 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1096 Function *TypeCheckedLoadFunc =
1097 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1098 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1099
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001100 // Normally if there are no users of the devirtualization intrinsics in the
1101 // module, this pass has nothing to do. But if we are exporting, we also need
1102 // to handle any users that appear only in the function summaries.
1103 if (Action != PassSummaryAction::Export &&
1104 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001105 AssumeFunc->use_empty()) &&
1106 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1107 return false;
1108
1109 if (TypeTestFunc && AssumeFunc)
1110 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1111
1112 if (TypeCheckedLoadFunc)
1113 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001114
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001115 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001116 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001117 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1118 buildTypeIdentifierMap(Bits, TypeIdMap);
1119 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001120 return true;
1121
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001122 // Collect information from summary about which calls to try to devirtualize.
1123 if (Action == PassSummaryAction::Export) {
1124 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1125 for (auto &P : TypeIdMap) {
1126 if (auto *TypeId = dyn_cast<MDString>(P.first))
1127 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1128 TypeId);
1129 }
1130
1131 for (auto &P : *Summary) {
1132 for (auto &S : P.second) {
1133 auto *FS = dyn_cast<FunctionSummary>(S.get());
1134 if (!FS)
1135 continue;
1136 // FIXME: Only add live functions.
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001137 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls())
1138 for (Metadata *MD : MetadataByGUID[VF.GUID])
1139 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1140 true;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001141 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls())
1142 for (Metadata *MD : MetadataByGUID[VF.GUID])
1143 CallSlots[{MD, VF.Offset}]
1144 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
1145 for (const FunctionSummary::ConstVCall &VC :
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001146 FS->type_test_assume_const_vcalls())
1147 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1148 CallSlots[{MD, VC.VFunc.Offset}]
1149 .ConstCSInfo[VC.Args].SummaryHasTypeTestAssumeUsers = true;
1150 for (const FunctionSummary::ConstVCall &VC :
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001151 FS->type_checked_load_const_vcalls())
1152 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1153 CallSlots[{MD, VC.VFunc.Offset}]
1154 .ConstCSInfo[VC.Args]
1155 .SummaryTypeCheckedLoadUsers.push_back(FS);
1156 }
1157 }
1158 }
1159
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001160 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001161 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001162 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001163 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001164 // Search each of the members of the type identifier for the virtual
1165 // function implementation at offset S.first.ByteOffset, and add to
1166 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001167 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001168 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1169 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001170 WholeProgramDevirtResolution *Res = nullptr;
1171 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID))
1172 Res =
1173 &Summary
1174 ->getTypeIdSummary(cast<MDString>(S.first.TypeID)->getString())
1175 .WPDRes[S.first.ByteOffset];
1176
1177 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001178 tryVirtualConstProp(TargetsForSlot, S.second))
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001179 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001180
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001181 // Collect functions devirtualized at least for one call site for stats.
1182 if (RemarksEnabled)
1183 for (const auto &T : TargetsForSlot)
1184 if (T.WasDevirt)
1185 DevirtTargets[T.Fn->getName()] = T.Fn;
1186 }
1187
1188 // CFI-specific: if we are exporting and any llvm.type.checked.load
1189 // intrinsics were *not* devirtualized, we need to add the resulting
1190 // llvm.type.test intrinsics to the function summaries so that the
1191 // LowerTypeTests pass will export them.
1192 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) {
1193 auto GUID =
1194 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1195 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1196 FS->addTypeTest(GUID);
1197 for (auto &CCS : S.second.ConstCSInfo)
1198 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1199 FS->addTypeTest(GUID);
1200 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001201 }
1202
1203 if (RemarksEnabled) {
1204 // Generate remarks for each devirtualized function.
1205 for (const auto &DT : DevirtTargets) {
1206 Function *F = DT.second;
1207 DISubprogram *SP = F->getSubprogram();
Justin Bogner7bc978b2017-02-18 02:00:27 +00001208 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP,
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001209 Twine("devirtualized ") + F->getName());
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001210 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001211 }
1212
Peter Collingbourne0312f612016-06-25 00:23:04 +00001213 // If we were able to eliminate all unsafe uses for a type checked load,
1214 // eliminate the type test by replacing it with true.
1215 if (TypeCheckedLoadFunc) {
1216 auto True = ConstantInt::getTrue(M.getContext());
1217 for (auto &&U : NumUnsafeUsesForTypeTest) {
1218 if (U.second == 0) {
1219 U.first->replaceAllUsesWith(True);
1220 U.first->eraseFromParent();
1221 }
1222 }
1223 }
1224
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001225 // Rebuild each global we touched as part of virtual constant propagation to
1226 // include the before and after bytes.
1227 if (DidVirtualConstProp)
1228 for (VTableBits &B : Bits)
1229 rebuildGlobal(B);
1230
1231 return true;
1232}