LLVM 23.0.0git
WholeProgramDevirt.cpp
Go to the documentation of this file.
1//===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements whole program optimization of virtual calls in cases
10// where we know (via !type metadata) that the list of callees is fixed. This
11// includes the following:
12// - Single implementation devirtualization: if a virtual call has a single
13// possible callee, replace all calls with a direct call to that callee.
14// - Virtual constant propagation: if the virtual function's return type is an
15// integer <=64 bits and all possible callees are readnone, for each class and
16// each list of constant arguments: evaluate the function, store the return
17// value alongside the virtual table, and rewrite each virtual call as a load
18// from the virtual table.
19// - Uniform return value optimization: if the conditions for virtual constant
20// propagation hold and each function returns the same constant value, replace
21// each virtual call with that constant.
22// - Unique return value optimization for i1 return values: if the conditions
23// for virtual constant propagation hold and a single vtable's function
24// returns 0, or a single vtable's function returns 1, replace each virtual
25// call with a comparison of the vptr against that vtable's address.
26//
27// This pass is intended to be used during the regular/thin and non-LTO
28// pipelines:
29//
30// During regular LTO, the pass determines the best optimization for each
31// virtual call and applies the resolutions directly to virtual calls that are
32// eligible for virtual call optimization (i.e. calls that use either of the
33// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics).
34//
35// During hybrid Regular/ThinLTO, the pass operates in two phases:
36// - Export phase: this is run during the thin link over a single merged module
37// that contains all vtables with !type metadata that participate in the link.
38// The pass computes a resolution for each virtual call and stores it in the
39// type identifier summary.
40// - Import phase: this is run during the thin backends over the individual
41// modules. The pass applies the resolutions previously computed during the
42// import phase to each eligible virtual call.
43//
44// During ThinLTO, the pass operates in two phases:
45// - Export phase: this is run during the thin link over the index which
46// contains a summary of all vtables with !type metadata that participate in
47// the link. It computes a resolution for each virtual call and stores it in
48// the type identifier summary. Only single implementation devirtualization
49// is supported.
50// - Import phase: (same as with hybrid case above).
51//
52// During Speculative devirtualization mode -not restricted to LTO-:
53// - The pass applies speculative devirtualization without requiring any type of
54// visibility.
55// - Skips other features like virtual constant propagation, uniform return
56// value optimization, unique return value optimization and branch funnels as
57// they need LTO.
58// - This mode is enabled via 'devirtualize-speculatively' flag.
59//
60//===----------------------------------------------------------------------===//
61
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/DenseSet.h"
67#include "llvm/ADT/MapVector.h"
69#include "llvm/ADT/Statistic.h"
79#include "llvm/IR/Constants.h"
80#include "llvm/IR/DataLayout.h"
81#include "llvm/IR/DebugLoc.h"
84#include "llvm/IR/Dominators.h"
85#include "llvm/IR/Function.h"
86#include "llvm/IR/GlobalAlias.h"
88#include "llvm/IR/IRBuilder.h"
89#include "llvm/IR/InstrTypes.h"
90#include "llvm/IR/Instruction.h"
92#include "llvm/IR/Intrinsics.h"
93#include "llvm/IR/LLVMContext.h"
94#include "llvm/IR/MDBuilder.h"
95#include "llvm/IR/Metadata.h"
96#include "llvm/IR/Module.h"
98#include "llvm/IR/PassManager.h"
100#include "llvm/Support/Casting.h"
103#include "llvm/Support/Errc.h"
104#include "llvm/Support/Error.h"
109#include "llvm/Transforms/IPO.h"
114#include <algorithm>
115#include <cmath>
116#include <cstddef>
117#include <map>
118#include <set>
119#include <string>
120
121using namespace llvm;
122using namespace wholeprogramdevirt;
123
124#define DEBUG_TYPE "wholeprogramdevirt"
125
126STATISTIC(NumDevirtTargets, "Number of whole program devirtualization targets");
127STATISTIC(NumSingleImpl, "Number of single implementation devirtualizations");
128STATISTIC(NumBranchFunnel, "Number of branch funnels");
129STATISTIC(NumUniformRetVal, "Number of uniform return value optimizations");
130STATISTIC(NumUniqueRetVal, "Number of unique return value optimizations");
131STATISTIC(NumVirtConstProp1Bit,
132 "Number of 1 bit virtual constant propagations");
133STATISTIC(NumVirtConstProp, "Number of virtual constant propagations");
134DEBUG_COUNTER(CallsToDevirt, "calls-to-devirt",
135 "Controls how many calls should be devirtualized.");
136
137namespace llvm {
138
140 "wholeprogramdevirt-summary-action",
141 cl::desc("What to do with the summary when running this pass"),
142 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
144 "Import typeid resolutions from summary and globals"),
146 "Export typeid resolutions to summary and globals")),
147 cl::Hidden);
148
150 "wholeprogramdevirt-read-summary",
151 cl::desc(
152 "Read summary from given bitcode or YAML file before running pass"),
153 cl::Hidden);
154
156 "wholeprogramdevirt-write-summary",
157 cl::desc("Write summary to given bitcode or YAML file after running pass. "
158 "Output file format is deduced from extension: *.bc means writing "
159 "bitcode, otherwise YAML"),
160 cl::Hidden);
161
162// TODO: This option eventually should support any public visibility vtables
163// with/out LTO.
165 "devirtualize-speculatively",
166 cl::desc("Enable speculative devirtualization optimization"),
167 cl::init(false));
168
170 ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
171 cl::init(10),
172 cl::desc("Maximum number of call targets per "
173 "call site to enable branch funnels"));
174
175static cl::opt<bool>
176 PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden,
177 cl::desc("Print index-based devirtualization messages"));
178
179/// Provide a way to force enable whole program visibility in tests.
180/// This is needed to support legacy tests that don't contain
181/// !vcall_visibility metadata (the mere presense of type tests
182/// previously implied hidden visibility).
183static cl::opt<bool>
184 WholeProgramVisibility("whole-program-visibility", cl::Hidden,
185 cl::desc("Enable whole program visibility"));
186
187/// Provide a way to force disable whole program for debugging or workarounds,
188/// when enabled via the linker.
190 "disable-whole-program-visibility", cl::Hidden,
191 cl::desc("Disable whole program visibility (overrides enabling options)"));
192
193/// Provide way to prevent certain function from being devirtualized
195 SkipFunctionNames("wholeprogramdevirt-skip",
196 cl::desc("Prevent function(s) from being devirtualized"),
198
200
201} // end namespace llvm
202
203/// With Clang, a pure virtual class's deleting destructor is emitted as a
204/// `llvm.trap` intrinsic followed by an unreachable IR instruction. In the
205/// context of whole program devirtualization, the deleting destructor of a pure
206/// virtual class won't be invoked by the source code so safe to skip as a
207/// devirtualize target.
208///
209/// However, not all unreachable functions are safe to skip. In some cases, the
210/// program intends to run such functions and terminate, for instance, a unit
211/// test may run a death test. A non-test program might (or allowed to) invoke
212/// such functions to report failures (whether/when it's a good practice or not
213/// is a different topic).
214///
215/// This option is enabled to keep an unreachable function as a possible
216/// devirtualize target to conservatively keep the program behavior.
217///
218/// TODO: Make a pure virtual class's deleting destructor precisely identifiable
219/// in Clang's codegen for more devirtualization in LLVM.
221 "wholeprogramdevirt-keep-unreachable-function",
222 cl::desc("Regard unreachable functions as possible devirtualize targets."),
223 cl::Hidden, cl::init(true));
224
225/// Mechanism to add runtime checking of devirtualization decisions, optionally
226/// trapping or falling back to indirect call on any that are not correct.
227/// Trapping mode is useful for debugging undefined behavior leading to failures
228/// with WPD. Fallback mode is useful for ensuring safety when whole program
229/// visibility may be compromised.
232 "wholeprogramdevirt-check", cl::Hidden,
233 cl::desc("Type of checking for incorrect devirtualizations"),
234 cl::values(clEnumValN(WPDCheckMode::None, "none", "No checking"),
235 clEnumValN(WPDCheckMode::Trap, "trap", "Trap when incorrect"),
237 "Fallback to indirect when incorrect")));
238
239namespace {
240struct PatternList {
241 std::vector<GlobPattern> Patterns;
242 template <class T> void init(const T &StringList) {
243 for (const auto &S : StringList)
245 Patterns.push_back(std::move(*Pat));
246 }
247 bool match(StringRef S) {
248 for (const GlobPattern &P : Patterns)
249 if (P.match(S))
250 return true;
251 return false;
252 }
253};
254} // namespace
255
256// Find the minimum offset that we may store a value of size Size bits at. If
257// IsAfter is set, look for an offset before the object, otherwise look for an
258// offset after the object.
261 bool IsAfter, uint64_t Size) {
262 // Find a minimum offset taking into account only vtable sizes.
263 uint64_t MinByte = 0;
264 for (const VirtualCallTarget &Target : Targets) {
265 if (IsAfter)
266 MinByte = std::max(MinByte, Target.minAfterBytes());
267 else
268 MinByte = std::max(MinByte, Target.minBeforeBytes());
269 }
270
271 // Build a vector of arrays of bytes covering, for each target, a slice of the
272 // used region (see AccumBitVector::BytesUsed in
273 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
274 // this aligns the used regions to start at MinByte.
275 //
276 // In this example, A, B and C are vtables, # is a byte already allocated for
277 // a virtual function pointer, AAAA... (etc.) are the used regions for the
278 // vtables and Offset(X) is the value computed for the Offset variable below
279 // for X.
280 //
281 // Offset(A)
282 // | |
283 // |MinByte
284 // A: ################AAAAAAAA|AAAAAAAA
285 // B: ########BBBBBBBBBBBBBBBB|BBBB
286 // C: ########################|CCCCCCCCCCCCCCCC
287 // | Offset(B) |
288 //
289 // This code produces the slices of A, B and C that appear after the divider
290 // at MinByte.
291 std::vector<ArrayRef<uint8_t>> Used;
292 for (const VirtualCallTarget &Target : Targets) {
293 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
294 : Target.TM->Bits->Before.BytesUsed;
295 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
296 : MinByte - Target.minBeforeBytes();
297
298 // Disregard used regions that are smaller than Offset. These are
299 // effectively all-free regions that do not need to be checked.
300 if (VTUsed.size() > Offset)
301 Used.push_back(VTUsed.slice(Offset));
302 }
303
304 if (Size == 1) {
305 // Find a free bit in each member of Used.
306 for (unsigned I = 0;; ++I) {
307 uint8_t BitsUsed = 0;
308 for (auto &&B : Used)
309 if (I < B.size())
310 BitsUsed |= B[I];
311 if (BitsUsed != 0xff)
312 return (MinByte + I) * 8 + llvm::countr_zero(uint8_t(~BitsUsed));
313 }
314 } else {
315 // Find a free (Size/8) byte region in each member of Used.
316 // FIXME: see if alignment helps.
317 for (unsigned I = 0;; ++I) {
318 for (auto &&B : Used) {
319 unsigned Byte = 0;
320 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
321 if (B[I + Byte])
322 goto NextI;
323 ++Byte;
324 }
325 }
326 // Rounding up ensures the constant is always stored at address we
327 // can directly load from without misalignment.
328 return alignTo((MinByte + I) * 8, Size);
329 NextI:;
330 }
331 }
332}
333
335 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
336 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
337 if (BitWidth == 1)
338 OffsetByte = -(AllocBefore / 8 + 1);
339 else
340 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
341 OffsetBit = AllocBefore % 8;
342
343 for (VirtualCallTarget &Target : Targets) {
344 if (BitWidth == 1)
345 Target.setBeforeBit(AllocBefore);
346 else
347 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
348 }
349}
350
353 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
354 if (BitWidth == 1)
355 OffsetByte = AllocAfter / 8;
356 else
357 OffsetByte = (AllocAfter + 7) / 8;
358 OffsetBit = AllocAfter % 8;
359
360 for (VirtualCallTarget &Target : Targets) {
361 if (BitWidth == 1)
362 Target.setAfterBit(AllocAfter);
363 else
364 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
365 }
366}
367
372
373namespace {
374
375// A slot in a set of virtual tables. The TypeID identifies the set of virtual
376// tables, and the ByteOffset is the offset in bytes from the address point to
377// the virtual function pointer.
378struct VTableSlot {
379 Metadata *TypeID;
380 uint64_t ByteOffset;
381};
382
383} // end anonymous namespace
384
385template <> struct llvm::DenseMapInfo<VTableSlot> {
386 static unsigned getHashValue(const VTableSlot &I) {
389 }
390 static bool isEqual(const VTableSlot &LHS,
391 const VTableSlot &RHS) {
392 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
393 }
394};
395
397 static unsigned getHashValue(const VTableSlotSummary &I) {
400 }
401 static bool isEqual(const VTableSlotSummary &LHS,
402 const VTableSlotSummary &RHS) {
403 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
404 }
405};
406
407// Returns true if the function must be unreachable based on ValueInfo.
408//
409// In particular, identifies a function as unreachable in the following
410// conditions
411// 1) All summaries are live.
412// 2) All function summaries indicate it's unreachable
413// 3) There is no non-function with the same GUID (which is rare)
416 return false;
417
418 if ((!TheFnVI) || TheFnVI.getSummaryList().empty()) {
419 // Returns false if ValueInfo is absent, or the summary list is empty
420 // (e.g., function declarations).
421 return false;
422 }
423
424 for (const auto &Summary : TheFnVI.getSummaryList()) {
425 // Conservatively returns false if any non-live functions are seen.
426 // In general either all summaries should be live or all should be dead.
427 if (!Summary->isLive())
428 return false;
429 if (auto *FS = dyn_cast<FunctionSummary>(Summary->getBaseObject())) {
430 if (!FS->fflags().MustBeUnreachable)
431 return false;
432 }
433 // Be conservative if a non-function has the same GUID (which is rare).
434 else
435 return false;
436 }
437 // All function summaries are live and all of them agree that the function is
438 // unreachble.
439 return true;
440}
441
442namespace {
443// A virtual call site. VTable is the loaded virtual table pointer, and CS is
444// the indirect virtual call.
445struct VirtualCallSite {
446 Value *VTable = nullptr;
447 CallBase &CB;
448
449 // If non-null, this field points to the associated unsafe use count stored in
450 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
451 // of that field for details.
452 unsigned *NumUnsafeUses = nullptr;
453
454 void
455 emitRemark(const StringRef OptName, const StringRef TargetName,
456 function_ref<OptimizationRemarkEmitter &(Function &)> OREGetter) {
457 Function *F = CB.getCaller();
458 DebugLoc DLoc = CB.getDebugLoc();
459 BasicBlock *Block = CB.getParent();
460
461 using namespace ore;
462 OREGetter(*F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
463 << NV("Optimization", OptName)
464 << ": devirtualized a call to "
465 << NV("FunctionName", TargetName));
466 }
467
468 void replaceAndErase(
469 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
470 function_ref<OptimizationRemarkEmitter &(Function &)> OREGetter,
471 Value *New) {
472 if (RemarksEnabled)
473 emitRemark(OptName, TargetName, OREGetter);
474 CB.replaceAllUsesWith(New);
475 if (auto *II = dyn_cast<InvokeInst>(&CB)) {
476 UncondBrInst::Create(II->getNormalDest(), CB.getIterator());
477 II->getUnwindDest()->removePredecessor(II->getParent());
478 }
479 CB.eraseFromParent();
480 // This use is no longer unsafe.
481 if (NumUnsafeUses)
482 --*NumUnsafeUses;
483 }
484};
485
486// Call site information collected for a specific VTableSlot and possibly a list
487// of constant integer arguments. The grouping by arguments is handled by the
488// VTableSlotInfo class.
489struct CallSiteInfo {
490 /// The set of call sites for this slot. Used during regular LTO and the
491 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
492 /// call sites that appear in the merged module itself); in each of these
493 /// cases we are directly operating on the call sites at the IR level.
494 std::vector<VirtualCallSite> CallSites;
495
496 /// Whether all call sites represented by this CallSiteInfo, including those
497 /// in summaries, have been devirtualized. This starts off as true because a
498 /// default constructed CallSiteInfo represents no call sites.
499 ///
500 /// If at the end of the pass there are still undevirtualized calls, we will
501 /// need to add a use of llvm.type.test to each of the function summaries in
502 /// the vector.
503 bool AllCallSitesDevirted = true;
504
505 // These fields are used during the export phase of ThinLTO and reflect
506 // information collected from function summaries.
507
508 /// CFI-specific: a vector containing the list of function summaries that use
509 /// the llvm.type.checked.load intrinsic and therefore will require
510 /// resolutions for llvm.type.test in order to implement CFI checks if
511 /// devirtualization was unsuccessful.
512 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
513
514 /// A vector containing the list of function summaries that use
515 /// assume(llvm.type.test).
516 std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
517
518 bool isExported() const {
519 return !SummaryTypeCheckedLoadUsers.empty() ||
520 !SummaryTypeTestAssumeUsers.empty();
521 }
522
523 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
524 SummaryTypeCheckedLoadUsers.push_back(FS);
525 AllCallSitesDevirted = false;
526 }
527
528 void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
529 SummaryTypeTestAssumeUsers.push_back(FS);
530 AllCallSitesDevirted = false;
531 }
532
533 void markDevirt() { AllCallSitesDevirted = true; }
534};
535
536// Call site information collected for a specific VTableSlot.
537struct VTableSlotInfo {
538 // The set of call sites which do not have all constant integer arguments
539 // (excluding "this").
540 CallSiteInfo CSInfo;
541
542 // The set of call sites with all constant integer arguments (excluding
543 // "this"), grouped by argument list.
544 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
545
546 void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses);
547
548private:
549 CallSiteInfo &findCallSiteInfo(CallBase &CB);
550};
551
552CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) {
553 std::vector<uint64_t> Args;
554 auto *CBType = dyn_cast<IntegerType>(CB.getType());
555 if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty())
556 return CSInfo;
557 for (auto &&Arg : drop_begin(CB.args())) {
558 auto *CI = dyn_cast<ConstantInt>(Arg);
559 if (!CI || CI->getBitWidth() > 64)
560 return CSInfo;
561 Args.push_back(CI->getZExtValue());
562 }
563 return ConstCSInfo[Args];
564}
565
566void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB,
567 unsigned *NumUnsafeUses) {
568 auto &CSI = findCallSiteInfo(CB);
569 CSI.AllCallSitesDevirted = false;
570 CSI.CallSites.push_back({VTable, CB, NumUnsafeUses});
571}
572
573struct DevirtModule {
574 Module &M;
577
578 ModuleSummaryIndex *const ExportSummary;
579 const ModuleSummaryIndex *const ImportSummary;
580
581 IntegerType *const Int8Ty;
582 PointerType *const Int8PtrTy;
583 IntegerType *const Int32Ty;
584 IntegerType *const Int64Ty;
585 IntegerType *const IntPtrTy;
586 /// Sizeless array type, used for imported vtables. This provides a signal
587 /// to analyzers that these imports may alias, as they do for example
588 /// when multiple unique return values occur in the same vtable.
589 ArrayType *const Int8Arr0Ty;
590
591 const bool RemarksEnabled;
592 std::function<OptimizationRemarkEmitter &(Function &)> OREGetter;
593 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
594
595 // Calls that have already been optimized. We may add a call to multiple
596 // VTableSlotInfos if vtable loads are coalesced and need to make sure not to
597 // optimize a call more than once.
598 SmallPtrSet<CallBase *, 8> OptimizedCalls;
599
600 // Store calls that had their ptrauth bundle removed. They are to be deleted
601 // at the end of the optimization.
602 SmallVector<CallBase *, 8> CallsWithPtrAuthBundleRemoved;
603
604 // This map keeps track of the number of "unsafe" uses of a loaded function
605 // pointer. The key is the associated llvm.type.test intrinsic call generated
606 // by this pass. An unsafe use is one that calls the loaded function pointer
607 // directly. Every time we eliminate an unsafe use (for example, by
608 // devirtualizing it or by applying virtual constant propagation), we
609 // decrement the value stored in this map. If a value reaches zero, we can
610 // eliminate the type check by RAUWing the associated llvm.type.test call with
611 // true.
612 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
613 PatternList FunctionsToSkip;
614
615 const bool DevirtSpeculatively;
616 DevirtModule(Module &M, ModuleAnalysisManager &MAM,
617 ModuleSummaryIndex *ExportSummary,
618 const ModuleSummaryIndex *ImportSummary,
619 bool DevirtSpeculatively)
620 : M(M), MAM(MAM),
621 FAM(MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager()),
622 ExportSummary(ExportSummary), ImportSummary(ImportSummary),
623 Int8Ty(Type::getInt8Ty(M.getContext())),
624 Int8PtrTy(PointerType::getUnqual(M.getContext())),
625 Int32Ty(Type::getInt32Ty(M.getContext())),
626 Int64Ty(Type::getInt64Ty(M.getContext())),
627 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
628 Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)),
629 RemarksEnabled(areRemarksEnabled()),
630 OREGetter([&](Function &F) -> OptimizationRemarkEmitter & {
631 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
632 }),
633 DevirtSpeculatively(DevirtSpeculatively) {
634 assert(!(ExportSummary && ImportSummary));
635 FunctionsToSkip.init(SkipFunctionNames);
636 }
637
638 bool areRemarksEnabled();
639
640 void
641 scanTypeTestUsers(Function *TypeTestFunc,
642 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
643 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
644
645 void buildTypeIdentifierMap(
646 std::vector<VTableBits> &Bits,
647 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
648
649 bool
650 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
651 const std::set<TypeMemberInfo> &TypeMemberInfos,
652 uint64_t ByteOffset,
653 ModuleSummaryIndex *ExportSummary);
654
655 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
656 bool &IsExported);
657 bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
659 VTableSlotInfo &SlotInfo,
660 WholeProgramDevirtResolution *Res);
661
662 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Function &JT,
663 bool &IsExported);
664 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
665 VTableSlotInfo &SlotInfo,
666 WholeProgramDevirtResolution *Res, VTableSlot Slot);
667
668 bool tryEvaluateFunctionsWithArgs(
670 ArrayRef<uint64_t> Args);
671
672 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
673 uint64_t TheRetVal);
674 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
675 CallSiteInfo &CSInfo,
676 WholeProgramDevirtResolution::ByArg *Res);
677
678 // Returns the global symbol name that is used to export information about the
679 // given vtable slot and list of arguments.
680 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
681 StringRef Name);
682
683 bool shouldExportConstantsAsAbsoluteSymbols();
684
685 // This function is called during the export phase to create a symbol
686 // definition containing information about the given vtable slot and list of
687 // arguments.
688 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
689 Constant *C);
690 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
691 uint32_t Const, uint32_t &Storage);
692
693 // This function is called during the import phase to create a reference to
694 // the symbol definition created during the export phase.
695 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
696 StringRef Name);
697 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
698 StringRef Name, IntegerType *IntTy,
699 uint32_t Storage);
700
701 Constant *getMemberAddr(const TypeMemberInfo *M);
702
703 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
704 Constant *UniqueMemberAddr);
705 bool tryUniqueRetValOpt(unsigned BitWidth,
707 CallSiteInfo &CSInfo,
708 WholeProgramDevirtResolution::ByArg *Res,
709 VTableSlot Slot, ArrayRef<uint64_t> Args);
710
711 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
712 Constant *Byte, Constant *Bit);
713 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
714 VTableSlotInfo &SlotInfo,
715 WholeProgramDevirtResolution *Res, VTableSlot Slot);
716
717 void rebuildGlobal(VTableBits &B);
718
719 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
720 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
721
722 // If we were able to eliminate all unsafe uses for a type checked load,
723 // eliminate the associated type tests by replacing them with true.
724 void removeRedundantTypeTests();
725
726 bool run();
727
728 // Look up the corresponding ValueInfo entry of `TheFn` in `ExportSummary`.
729 //
730 // Caller guarantees that `ExportSummary` is not nullptr.
731 static ValueInfo lookUpFunctionValueInfo(Function *TheFn,
732 ModuleSummaryIndex *ExportSummary);
733
734 // Returns true if the function definition must be unreachable.
735 //
736 // Note if this helper function returns true, `F` is guaranteed
737 // to be unreachable; if it returns false, `F` might still
738 // be unreachable but not covered by this helper function.
739 //
740 // Implementation-wise, if function definition is present, IR is analyzed; if
741 // not, look up function flags from ExportSummary as a fallback.
742 static bool mustBeUnreachableFunction(Function *const F,
743 ModuleSummaryIndex *ExportSummary);
744
745 // Lower the module using the action and summary passed as command line
746 // arguments. For testing purposes only.
747 static bool runForTesting(Module &M, ModuleAnalysisManager &MAM,
748 bool DevirtSpeculatively);
749};
750
751struct DevirtIndex {
752 ModuleSummaryIndex &ExportSummary;
753 // The set in which to record GUIDs exported from their module by
754 // devirtualization, used by client to ensure they are not internalized.
755 std::set<GlobalValue::GUID> &ExportedGUIDs;
756 // A map in which to record the information necessary to locate the WPD
757 // resolution for local targets in case they are exported by cross module
758 // importing.
759 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
760 // We have hardcoded the promoted and renamed function name in the WPD
761 // summary, so we need to ensure that they will be renamed. Note this and
762 // that adding the current names to this set ensures we continue to rename
763 // them.
764 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr;
765
766 MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
767
768 PatternList FunctionsToSkip;
769
770 DevirtIndex(
771 ModuleSummaryIndex &ExportSummary,
772 std::set<GlobalValue::GUID> &ExportedGUIDs,
773 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
774 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr)
775 : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
776 LocalWPDTargetsMap(LocalWPDTargetsMap),
777 ExternallyVisibleSymbolNamesPtr(ExternallyVisibleSymbolNamesPtr) {
778 FunctionsToSkip.init(SkipFunctionNames);
779 }
780
781 bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
782 const TypeIdCompatibleVtableInfo TIdInfo,
783 uint64_t ByteOffset);
784
785 bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
786 VTableSlotSummary &SlotSummary,
787 VTableSlotInfo &SlotInfo,
788 WholeProgramDevirtResolution *Res,
789 std::set<ValueInfo> &DevirtTargets);
790
791 void run();
792};
793} // end anonymous namespace
794
797 if (UseCommandLine) {
798 if (!DevirtModule::runForTesting(M, MAM, ClDevirtualizeSpeculatively))
799 return PreservedAnalyses::all();
801 }
802
803 std::optional<ModuleSummaryIndex> Index;
805 // Build the ExportSummary from the module.
807 "ExportSummary is expected to be empty in non-LTO mode");
808 ProfileSummaryInfo PSI(M);
809 Index.emplace(buildModuleSummaryIndex(M, nullptr, &PSI));
810 ExportSummary = Index.has_value() ? &Index.value() : nullptr;
811 }
812 if (!DevirtModule(M, MAM, ExportSummary, ImportSummary, DevirtSpeculatively)
813 .run())
814 return PreservedAnalyses::all();
816}
817
818// Enable whole program visibility if enabled by client (e.g. linker) or
819// internal option, and not force disabled.
820bool llvm::hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) {
821 return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) &&
823}
824
825static bool
827 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
828 // TypeID for member function pointer type is an internal construct
829 // and won't exist in IsVisibleToRegularObj. The full TypeID
830 // will be present and participate in invalidation.
831 if (TypeID.ends_with(".virtual"))
832 return false;
833
834 // TypeID that doesn't start with Itanium mangling (_ZTS) will be
835 // non-externally visible types which cannot interact with
836 // external native files. See CodeGenModule::CreateMetadataIdentifierImpl.
837 if (!TypeID.consume_front("_ZTS"))
838 return false;
839
840 // TypeID is keyed off the type name symbol (_ZTS). However, the native
841 // object may not contain this symbol if it does not contain a key
842 // function for the base type and thus only contains a reference to the
843 // type info (_ZTI). To catch this case we query using the type info
844 // symbol corresponding to the TypeID.
845 std::string TypeInfo = ("_ZTI" + TypeID).str();
846 return IsVisibleToRegularObj(TypeInfo);
847}
848
849static bool
851 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
853 GV.getMetadata(LLVMContext::MD_type, Types);
854
855 for (auto *Type : Types)
856 if (auto *TypeID = dyn_cast<MDString>(Type->getOperand(1).get()))
857 return typeIDVisibleToRegularObj(TypeID->getString(),
858 IsVisibleToRegularObj);
859
860 return false;
861}
862
863/// If whole program visibility asserted, then upgrade all public vcall
864/// visibility metadata on vtable definitions to linkage unit visibility in
865/// Module IR (for regular or hybrid LTO).
867 Module &M, bool WholeProgramVisibilityEnabledInLTO,
868 const DenseSet<GlobalValue::GUID> &DynamicExportSymbols,
869 bool ValidateAllVtablesHaveTypeInfos,
870 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
871 if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
872 return;
873
874 for (GlobalVariable &GV : M.globals()) {
875 // Add linkage unit visibility to any variable with type metadata, which are
876 // the vtable definitions. We won't have an existing vcall_visibility
877 // metadata on vtable definitions with public visibility.
878 if (GV.hasMetadata(LLVMContext::MD_type) &&
880 // Don't upgrade the visibility for symbols exported to the dynamic
881 // linker, as we have no information on their eventual use.
882 !DynamicExportSymbols.count(GV.getGUID()) &&
883 // With validation enabled, we want to exclude symbols visible to
884 // regular objects. Local symbols will be in this group due to the
885 // current implementation but those with VCallVisibilityTranslationUnit
886 // will have already been marked in clang so are unaffected.
887 !(ValidateAllVtablesHaveTypeInfos &&
888 skipUpdateDueToValidation(GV, IsVisibleToRegularObj)))
890 }
891}
892
894 bool WholeProgramVisibilityEnabledInLTO) {
895 llvm::TimeTraceScope timeScope("Update public type test calls");
896 Function *PublicTypeTestFunc =
897 Intrinsic::getDeclarationIfExists(&M, Intrinsic::public_type_test);
898 if (!PublicTypeTestFunc)
899 return;
900 if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) {
901 Function *TypeTestFunc =
902 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::type_test);
903 for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
904 auto *CI = cast<CallInst>(U.getUser());
905 auto *NewCI = CallInst::Create(
906 TypeTestFunc, {CI->getArgOperand(0), CI->getArgOperand(1)}, {}, "",
907 CI->getIterator());
908 CI->replaceAllUsesWith(NewCI);
909 CI->eraseFromParent();
910 }
911 } else {
912 // TODO: Don't replace public type tests when speculative devirtualization
913 // gets enabled in LTO mode.
914 auto *True = ConstantInt::getTrue(M.getContext());
915 for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
916 auto *CI = cast<CallInst>(U.getUser());
917 CI->replaceAllUsesWith(True);
918 CI->eraseFromParent();
919 }
920 }
921}
922
923/// Based on typeID string, get all associated vtable GUIDS that are
924/// visible to regular objects.
926 ModuleSummaryIndex &Index,
927 DenseSet<GlobalValue::GUID> &VisibleToRegularObjSymbols,
928 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
929 for (const auto &TypeID : Index.typeIdCompatibleVtableMap()) {
930 if (typeIDVisibleToRegularObj(TypeID.first, IsVisibleToRegularObj))
931 for (const TypeIdOffsetVtableInfo &P : TypeID.second)
932 VisibleToRegularObjSymbols.insert(P.VTableVI.getGUID());
933 }
934}
935
936/// If whole program visibility asserted, then upgrade all public vcall
937/// visibility metadata on vtable definition summaries to linkage unit
938/// visibility in Module summary index (for ThinLTO).
940 ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO,
941 const DenseSet<GlobalValue::GUID> &DynamicExportSymbols,
942 const DenseSet<GlobalValue::GUID> &VisibleToRegularObjSymbols) {
943 if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
944 return;
945 for (auto &P : Index) {
946 // Don't upgrade the visibility for symbols exported to the dynamic
947 // linker, as we have no information on their eventual use.
948 if (DynamicExportSymbols.count(P.first))
949 continue;
950 // With validation enabled, we want to exclude symbols visible to regular
951 // objects. Local symbols will be in this group due to the current
952 // implementation but those with VCallVisibilityTranslationUnit will have
953 // already been marked in clang so are unaffected.
954 if (VisibleToRegularObjSymbols.count(P.first))
955 continue;
956 for (auto &S : P.second.getSummaryList()) {
957 auto *GVar = dyn_cast<GlobalVarSummary>(S.get());
958 if (!GVar ||
959 GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic)
960 continue;
961 GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit);
962 }
963 }
964}
965
967 ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
968 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
969 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
970 DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap,
971 ExternallyVisibleSymbolNamesPtr)
972 .run();
973}
974
976 ModuleSummaryIndex &Summary,
977 function_ref<bool(StringRef, ValueInfo)> IsExported,
978 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
979 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
980 for (auto &T : LocalWPDTargetsMap) {
981 auto &VI = T.first;
982 // This was enforced earlier during trySingleImplDevirt.
983 assert(VI.getSummaryList().size() == 1 &&
984 "Devirt of local target has more than one copy");
985 auto &S = VI.getSummaryList()[0];
986 if (!IsExported(S->modulePath(), VI))
987 continue;
988
989 // It's been exported by a cross module import.
990 for (auto &SlotSummary : T.second) {
991 auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
992 assert(TIdSum);
993 auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
994 assert(WPDRes != TIdSum->WPDRes.end());
995 if (ExternallyVisibleSymbolNamesPtr)
996 ExternallyVisibleSymbolNamesPtr->insert(WPDRes->second.SingleImplName);
997 WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
998 WPDRes->second.SingleImplName,
999 Summary.getModuleHash(S->modulePath()));
1000 }
1001 }
1002}
1003
1005 // Check that summary index contains regular LTO module when performing
1006 // export to prevent occasional use of index from pure ThinLTO compilation
1007 // (-fno-split-lto-module). This kind of summary index is passed to
1008 // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting.
1009 const auto &ModPaths = Summary->modulePaths();
1011 !ModPaths.contains(ModuleSummaryIndex::getRegularLTOModuleName()))
1012 return createStringError(
1014 "combined summary should contain Regular LTO module");
1015 return ErrorSuccess();
1016}
1017
1018bool DevirtModule::runForTesting(Module &M, ModuleAnalysisManager &MAM,
1019 bool DevirtSpeculatively) {
1020 std::unique_ptr<ModuleSummaryIndex> Summary =
1021 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
1022
1023 // Handle the command-line summary arguments. This code is for testing
1024 // purposes only, so we handle errors directly.
1025 if (!ClReadSummary.empty()) {
1026 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
1027 ": ");
1028 auto ReadSummaryFile =
1030 if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
1031 getModuleSummaryIndex(*ReadSummaryFile)) {
1032 Summary = std::move(*SummaryOrErr);
1033 ExitOnErr(checkCombinedSummaryForTesting(Summary.get()));
1034 } else {
1035 // Try YAML if we've failed with bitcode.
1036 consumeError(SummaryOrErr.takeError());
1037 yaml::Input In(ReadSummaryFile->getBuffer());
1038 In >> *Summary;
1039 ExitOnErr(errorCodeToError(In.error()));
1040 }
1041 }
1042
1043 bool Changed =
1044 DevirtModule(M, MAM,
1046 : nullptr,
1048 : nullptr,
1049 DevirtSpeculatively)
1050 .run();
1051
1052 if (!ClWriteSummary.empty()) {
1053 ExitOnError ExitOnErr(
1054 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
1055 std::error_code EC;
1056 if (StringRef(ClWriteSummary).ends_with(".bc")) {
1057 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None);
1058 ExitOnErr(errorCodeToError(EC));
1059 writeIndexToFile(*Summary, OS);
1060 } else {
1061 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_TextWithCRLF);
1062 ExitOnErr(errorCodeToError(EC));
1063 yaml::Output Out(OS);
1064 Out << *Summary;
1065 }
1066 }
1067
1068 return Changed;
1069}
1070
1071void DevirtModule::buildTypeIdentifierMap(
1072 std::vector<VTableBits> &Bits,
1073 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
1074 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
1075 Bits.reserve(M.global_size());
1077 for (GlobalVariable &GV : M.globals()) {
1078 Types.clear();
1079 GV.getMetadata(LLVMContext::MD_type, Types);
1080 if (GV.isDeclaration() || Types.empty())
1081 continue;
1082
1083 VTableBits *&BitsPtr = GVToBits[&GV];
1084 if (!BitsPtr) {
1085 Bits.emplace_back();
1086 Bits.back().GV = &GV;
1087 Bits.back().ObjectSize =
1088 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
1089 BitsPtr = &Bits.back();
1090 }
1091
1092 for (MDNode *Type : Types) {
1093 auto *TypeID = Type->getOperand(1).get();
1094
1095 uint64_t Offset =
1097 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
1098 ->getZExtValue();
1099
1100 TypeIdMap[TypeID].insert({BitsPtr, Offset});
1101 }
1102 }
1103}
1104
1105bool DevirtModule::tryFindVirtualCallTargets(
1106 std::vector<VirtualCallTarget> &TargetsForSlot,
1107 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset,
1108 ModuleSummaryIndex *ExportSummary) {
1109 for (const TypeMemberInfo &TM : TypeMemberInfos) {
1110 if (!TM.Bits->GV->isConstant())
1111 return false;
1112
1113 // Without DevirtSpeculatively, we cannot perform whole program
1114 // devirtualization analysis on a vtable with public LTO visibility.
1115 if (!DevirtSpeculatively && TM.Bits->GV->getVCallVisibility() ==
1117 return false;
1118
1119 Function *Fn = nullptr;
1120 Constant *C = nullptr;
1121 std::tie(Fn, C) =
1122 getFunctionAtVTableOffset(TM.Bits->GV, TM.Offset + ByteOffset, M);
1123
1124 if (!Fn)
1125 return false;
1126
1127 if (FunctionsToSkip.match(Fn->getName()))
1128 return false;
1129
1130 // We can disregard __cxa_pure_virtual as a possible call target, as
1131 // calls to pure virtuals are UB.
1132 if (Fn->getName() == "__cxa_pure_virtual")
1133 continue;
1134
1135 // In most cases empty functions will be overridden by the
1136 // implementation of the derived class, so we can skip them.
1137 if (DevirtSpeculatively && Fn->getReturnType()->isVoidTy() &&
1138 Fn->getInstructionCount() <= 1)
1139 continue;
1140
1141 // We can disregard unreachable functions as possible call targets, as
1142 // unreachable functions shouldn't be called.
1143 if (mustBeUnreachableFunction(Fn, ExportSummary))
1144 continue;
1145
1146 // Save the symbol used in the vtable to use as the devirtualization
1147 // target.
1148 auto *GV = dyn_cast<GlobalValue>(C);
1149 assert(GV);
1150 TargetsForSlot.push_back({GV, &TM});
1151 }
1152
1153 // Give up if we couldn't find any targets.
1154 return !TargetsForSlot.empty();
1155}
1156
1157bool DevirtIndex::tryFindVirtualCallTargets(
1158 std::vector<ValueInfo> &TargetsForSlot,
1159 const TypeIdCompatibleVtableInfo TIdInfo, uint64_t ByteOffset) {
1160 for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
1161 // Find a representative copy of the vtable initializer.
1162 // We can have multiple available_externally, linkonce_odr and weak_odr
1163 // vtable initializers. We can also have multiple external vtable
1164 // initializers in the case of comdats, which we cannot check here.
1165 // The linker should give an error in this case.
1166 //
1167 // Also, handle the case of same-named local Vtables with the same path
1168 // and therefore the same GUID. This can happen if there isn't enough
1169 // distinguishing path when compiling the source file. In that case we
1170 // conservatively return false early.
1171 if (P.VTableVI.hasLocal() && P.VTableVI.getSummaryList().size() > 1)
1172 return false;
1173 const GlobalVarSummary *VS = nullptr;
1174 for (const auto &S : P.VTableVI.getSummaryList()) {
1175 auto *CurVS = cast<GlobalVarSummary>(S->getBaseObject());
1176 if (!CurVS->vTableFuncs().empty() ||
1177 // Previously clang did not attach the necessary type metadata to
1178 // available_externally vtables, in which case there would not
1179 // be any vtable functions listed in the summary and we need
1180 // to treat this case conservatively (in case the bitcode is old).
1181 // However, we will also not have any vtable functions in the
1182 // case of a pure virtual base class. In that case we do want
1183 // to set VS to avoid treating it conservatively.
1185 VS = CurVS;
1186 // We cannot perform whole program devirtualization analysis on a vtable
1187 // with public LTO visibility.
1188 if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
1189 return false;
1190 break;
1191 }
1192 }
1193 // There will be no VS if all copies are available_externally having no
1194 // type metadata. In that case we can't safely perform WPD.
1195 if (!VS)
1196 return false;
1197 if (!VS->isLive())
1198 continue;
1199 for (auto VTP : VS->vTableFuncs()) {
1200 if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
1201 continue;
1202
1203 if (mustBeUnreachableFunction(VTP.FuncVI))
1204 continue;
1205
1206 TargetsForSlot.push_back(VTP.FuncVI);
1207 }
1208 }
1209
1210 // Give up if we couldn't find any targets.
1211 return !TargetsForSlot.empty();
1212}
1213
1214void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
1215 Constant *TheFn, bool &IsExported) {
1216 // Don't devirtualize function if we're told to skip it
1217 // in -wholeprogramdevirt-skip.
1218 if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName()))
1219 return;
1220 auto Apply = [&](CallSiteInfo &CSInfo) {
1221 for (auto &&VCallSite : CSInfo.CallSites) {
1222 if (!OptimizedCalls.insert(&VCallSite.CB).second)
1223 continue;
1224
1225 // Stop when the number of devirted calls reaches the cutoff.
1226 if (!DebugCounter::shouldExecute(CallsToDevirt))
1227 continue;
1228
1229 if (RemarksEnabled)
1230 VCallSite.emitRemark("single-impl",
1231 TheFn->stripPointerCasts()->getName(), OREGetter);
1232 NumSingleImpl++;
1233 auto &CB = VCallSite.CB;
1234 assert(!CB.getCalledFunction() && "devirtualizing direct call?");
1235 IRBuilder<> Builder(&CB);
1236 Value *Callee =
1237 Builder.CreateBitCast(TheFn, CB.getCalledOperand()->getType());
1238
1239 // If trap checking is enabled, add support to compare the virtual
1240 // function pointer to the devirtualized target. In case of a mismatch,
1241 // perform a debug trap.
1243 auto *Cond = Builder.CreateICmpNE(CB.getCalledOperand(), Callee);
1245 Cond, &CB, /*Unreachable=*/false,
1246 MDBuilder(M.getContext()).createUnlikelyBranchWeights());
1247 Builder.SetInsertPoint(ThenTerm);
1248 Function *TrapFn =
1249 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::debugtrap);
1250 auto *CallTrap = Builder.CreateCall(TrapFn);
1251 CallTrap->setDebugLoc(CB.getDebugLoc());
1252 }
1253
1254 // If fallback checking or speculative devirtualization are enabled,
1255 // add support to compare the virtual function pointer to the
1256 // devirtualized target. In case of a mismatch, fall back to indirect
1257 // call.
1258 if (DevirtCheckMode == WPDCheckMode::Fallback || DevirtSpeculatively) {
1259 MDNode *Weights = MDBuilder(M.getContext()).createLikelyBranchWeights();
1260 // Version the indirect call site. If the called value is equal to the
1261 // given callee, 'NewInst' will be executed, otherwise the original call
1262 // site will be executed.
1263 CallBase &NewInst = versionCallSite(CB, Callee, Weights);
1264 NewInst.setCalledOperand(Callee);
1265 // Since the new call site is direct, we must clear metadata that
1266 // is only appropriate for indirect calls. This includes !prof and
1267 // !callees metadata.
1268 NewInst.setMetadata(LLVMContext::MD_prof, nullptr);
1269 NewInst.setMetadata(LLVMContext::MD_callees, nullptr);
1270 // Additionally, we should remove them from the fallback indirect call,
1271 // so that we don't attempt to perform indirect call promotion later.
1272 CB.setMetadata(LLVMContext::MD_prof, nullptr);
1273 CB.setMetadata(LLVMContext::MD_callees, nullptr);
1274 }
1275
1276 // In either trapping or non-checking mode, devirtualize original call.
1277 else {
1278 // Devirtualize unconditionally.
1279 CB.setCalledOperand(Callee);
1280 // Since the call site is now direct, we must clear metadata that
1281 // is only appropriate for indirect calls. This includes !prof and
1282 // !callees metadata.
1283 CB.setMetadata(LLVMContext::MD_prof, nullptr);
1284 CB.setMetadata(LLVMContext::MD_callees, nullptr);
1285 if (CB.getCalledOperand() &&
1287 auto *NewCS = CallBase::removeOperandBundle(
1289 CB.replaceAllUsesWith(NewCS);
1290 // Schedule for deletion at the end of pass run.
1291 CallsWithPtrAuthBundleRemoved.push_back(&CB);
1292 }
1293 }
1294
1295 // This use is no longer unsafe.
1296 if (VCallSite.NumUnsafeUses)
1297 --*VCallSite.NumUnsafeUses;
1298 }
1299 if (CSInfo.isExported())
1300 IsExported = true;
1301 CSInfo.markDevirt();
1302 };
1303 Apply(SlotInfo.CSInfo);
1304 for (auto &P : SlotInfo.ConstCSInfo)
1305 Apply(P.second);
1306}
1307
1308static bool addCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
1309 // We can't add calls if we haven't seen a definition
1310 if (Callee.getSummaryList().empty())
1311 return false;
1312
1313 // Insert calls into the summary index so that the devirtualized targets
1314 // are eligible for import.
1315 // FIXME: Annotate type tests with hotness. For now, mark these as hot
1316 // to better ensure we have the opportunity to inline them.
1317 bool IsExported = false;
1318 auto &S = Callee.getSummaryList()[0];
1319 CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* HasTailCall = */ false);
1320 auto AddCalls = [&](CallSiteInfo &CSInfo) {
1321 for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
1322 FS->addCall({Callee, CI});
1323 IsExported |= S->modulePath() != FS->modulePath();
1324 }
1325 for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
1326 FS->addCall({Callee, CI});
1327 IsExported |= S->modulePath() != FS->modulePath();
1328 }
1329 };
1330 AddCalls(SlotInfo.CSInfo);
1331 for (auto &P : SlotInfo.ConstCSInfo)
1332 AddCalls(P.second);
1333 return IsExported;
1334}
1335
1336bool DevirtModule::trySingleImplDevirt(
1337 ModuleSummaryIndex *ExportSummary,
1338 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1339 WholeProgramDevirtResolution *Res) {
1340 // See if the program contains a single implementation of this virtual
1341 // function.
1342 auto *TheFn = TargetsForSlot[0].Fn;
1343 for (auto &&Target : TargetsForSlot)
1344 if (TheFn != Target.Fn)
1345 return false;
1346
1347 // If so, update each call site to call that implementation directly.
1348 if (RemarksEnabled || AreStatisticsEnabled())
1349 TargetsForSlot[0].WasDevirt = true;
1350
1351 bool IsExported = false;
1352 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
1353 if (!IsExported)
1354 return false;
1355
1356 // If the only implementation has local linkage, we must promote to external
1357 // to make it visible to thin LTO objects. We can only get here during the
1358 // ThinLTO export phase.
1359 if (TheFn->hasLocalLinkage()) {
1360 std::string NewName = (TheFn->getName() + ".llvm.merged").str();
1361
1362 // Since we are renaming the function, any comdats with the same name must
1363 // also be renamed. This is required when targeting COFF, as the comdat name
1364 // must match one of the names of the symbols in the comdat.
1365 if (Comdat *C = TheFn->getComdat()) {
1366 if (C->getName() == TheFn->getName()) {
1367 Comdat *NewC = M.getOrInsertComdat(NewName);
1368 NewC->setSelectionKind(C->getSelectionKind());
1369 for (GlobalObject &GO : M.global_objects())
1370 if (GO.getComdat() == C)
1371 GO.setComdat(NewC);
1372 }
1373 }
1374
1375 TheFn->setLinkage(GlobalValue::ExternalLinkage);
1376 TheFn->setVisibility(GlobalValue::HiddenVisibility);
1377 TheFn->setName(NewName);
1378 }
1379 if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
1380 // Any needed promotion of 'TheFn' has already been done during
1381 // LTO unit split, so we can ignore return value of AddCalls.
1382 addCalls(SlotInfo, TheFnVI);
1383
1385 Res->SingleImplName = std::string(TheFn->getName());
1386
1387 return true;
1388}
1389
1390bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
1391 VTableSlotSummary &SlotSummary,
1392 VTableSlotInfo &SlotInfo,
1393 WholeProgramDevirtResolution *Res,
1394 std::set<ValueInfo> &DevirtTargets) {
1395 // See if the program contains a single implementation of this virtual
1396 // function.
1397 auto TheFn = TargetsForSlot[0];
1398 for (auto &&Target : TargetsForSlot)
1399 if (TheFn != Target)
1400 return false;
1401
1402 // Don't devirtualize if we don't have target definition.
1403 auto Size = TheFn.getSummaryList().size();
1404 if (!Size)
1405 return false;
1406
1407 // Don't devirtualize function if we're told to skip it
1408 // in -wholeprogramdevirt-skip.
1409 if (FunctionsToSkip.match(TheFn.name()))
1410 return false;
1411
1412 // If the summary list contains multiple summaries where at least one is
1413 // a local, give up, as we won't know which (possibly promoted) name to use.
1414 if (TheFn.hasLocal() && Size > 1)
1415 return false;
1416
1417 // Collect functions devirtualized at least for one call site for stats.
1419 DevirtTargets.insert(TheFn);
1420
1421 auto &S = TheFn.getSummaryList()[0];
1422 bool IsExported = addCalls(SlotInfo, TheFn);
1423 if (IsExported)
1424 ExportedGUIDs.insert(TheFn.getGUID());
1425
1426 // Record in summary for use in devirtualization during the ThinLTO import
1427 // step.
1429 if (GlobalValue::isLocalLinkage(S->linkage())) {
1430 if (IsExported) {
1431 // If target is a local function and we are exporting it by
1432 // devirtualizing a call in another module, we need to record the
1433 // promoted name.
1434 if (ExternallyVisibleSymbolNamesPtr)
1435 ExternallyVisibleSymbolNamesPtr->insert(TheFn.name());
1437 TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
1438 } else {
1439 LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
1440 Res->SingleImplName = std::string(TheFn.name());
1441 }
1442 } else
1443 Res->SingleImplName = std::string(TheFn.name());
1444
1445 // Name will be empty if this thin link driven off of serialized combined
1446 // index (e.g. llvm-lto). However, WPD is not supported/invoked for the
1447 // legacy LTO API anyway.
1448 assert(!Res->SingleImplName.empty());
1449
1450 return true;
1451}
1452
1453void DevirtModule::tryICallBranchFunnel(
1454 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1455 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1456 Triple T(M.getTargetTriple());
1457 if (T.getArch() != Triple::x86_64)
1458 return;
1459
1460 if (TargetsForSlot.size() > ClThreshold)
1461 return;
1462
1463 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
1464 if (!HasNonDevirt)
1465 for (auto &P : SlotInfo.ConstCSInfo)
1466 if (!P.second.AllCallSitesDevirted) {
1467 HasNonDevirt = true;
1468 break;
1469 }
1470
1471 if (!HasNonDevirt)
1472 return;
1473
1474 // If any GV is AvailableExternally, not to generate branch.funnel.
1475 // NOTE: It is to avoid crash in LowerTypeTest.
1476 // If the branch.funnel is generated, because GV.isDeclarationForLinker(),
1477 // in LowerTypeTestsModule::lower(), its GlobalTypeMember would NOT
1478 // be saved in GlobalTypeMembers[&GV]. Then crash happens in
1479 // buildBitSetsFromDisjointSet due to GlobalTypeMembers[&GV] is NULL.
1480 // Even doing experiment to save it in GlobalTypeMembers[&GV] and
1481 // making GlobalTypeMembers[&GV] be not NULL, crash could avoid from
1482 // buildBitSetsFromDisjointSet. But still report_fatal_error in Verifier
1483 // or SelectionDAGBuilder later, because operands linkage type consistency
1484 // check of icall.branch.funnel can not pass.
1485 for (auto &T : TargetsForSlot) {
1486 if (T.TM->Bits->GV->hasAvailableExternallyLinkage())
1487 return;
1488 }
1489
1490 FunctionType *FT =
1491 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
1492 Function *JT;
1493 if (isa<MDString>(Slot.TypeID)) {
1495 M.getDataLayout().getProgramAddressSpace(),
1496 getGlobalName(Slot, {}, "branch_funnel"), &M);
1498 } else {
1500 M.getDataLayout().getProgramAddressSpace(),
1501 "branch_funnel", &M);
1502 }
1503 JT->addParamAttr(0, Attribute::Nest);
1504
1505 std::vector<Value *> JTArgs;
1506 JTArgs.push_back(JT->arg_begin());
1507 for (auto &T : TargetsForSlot) {
1508 JTArgs.push_back(getMemberAddr(T.TM));
1509 JTArgs.push_back(T.Fn);
1510 }
1511
1512 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
1514 &M, llvm::Intrinsic::icall_branch_funnel, {});
1515
1516 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
1517 CI->setTailCallKind(CallInst::TCK_MustTail);
1518 ReturnInst::Create(M.getContext(), nullptr, BB);
1519
1520 bool IsExported = false;
1521 applyICallBranchFunnel(SlotInfo, *JT, IsExported);
1522 if (IsExported)
1524
1525 if (!JT->getEntryCount().has_value()) {
1526 // FIXME: we could pass through thinlto the necessary information.
1528 }
1529}
1530
1531void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
1532 Function &JT, bool &IsExported) {
1533 DenseMap<Function *, double> FunctionEntryCounts;
1534 auto Apply = [&](CallSiteInfo &CSInfo) {
1535 if (CSInfo.isExported())
1536 IsExported = true;
1537 if (CSInfo.AllCallSitesDevirted)
1538 return;
1539
1540 std::map<CallBase *, CallBase *> CallBases;
1541 for (auto &&VCallSite : CSInfo.CallSites) {
1542 CallBase &CB = VCallSite.CB;
1543
1544 if (CallBases.find(&CB) != CallBases.end()) {
1545 // When finding devirtualizable calls, it's possible to find the same
1546 // vtable passed to multiple llvm.type.test or llvm.type.checked.load
1547 // calls, which can cause duplicate call sites to be recorded in
1548 // [Const]CallSites. If we've already found one of these
1549 // call instances, just ignore it. It will be replaced later.
1550 continue;
1551 }
1552
1553 // Jump tables are only profitable if the retpoline mitigation is enabled.
1554 Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features");
1555 if (!FSAttr.isValid() ||
1556 !FSAttr.getValueAsString().contains("+retpoline"))
1557 continue;
1558
1559 NumBranchFunnel++;
1560 if (RemarksEnabled)
1561 VCallSite.emitRemark("branch-funnel", JT.getName(), OREGetter);
1562
1563 // Pass the address of the vtable in the nest register, which is r10 on
1564 // x86_64.
1565 std::vector<Type *> NewArgs;
1566 NewArgs.push_back(Int8PtrTy);
1567 append_range(NewArgs, CB.getFunctionType()->params());
1568 FunctionType *NewFT =
1570 CB.getFunctionType()->isVarArg());
1571 IRBuilder<> IRB(&CB);
1572 std::vector<Value *> Args;
1573 Args.push_back(VCallSite.VTable);
1574 llvm::append_range(Args, CB.args());
1575
1576 CallBase *NewCS = nullptr;
1578 // Accumulate the call frequencies of the original call site, and use
1579 // that as total entry count for the funnel function.
1580 auto &F = *CB.getCaller();
1581 auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
1582 auto EC = BFI.getBlockFreq(&F.getEntryBlock());
1583 auto CC = F.getEntryCount();
1584 double CallCount = 0.0;
1585 if (EC.getFrequency() != 0 && CC && *CC != 0) {
1586 double CallFreq =
1587 static_cast<double>(
1588 BFI.getBlockFreq(CB.getParent()).getFrequency()) /
1589 EC.getFrequency();
1590 CallCount = CallFreq * *CC;
1591 }
1592 FunctionEntryCounts[&JT] += CallCount;
1593 }
1594 if (isa<CallInst>(CB))
1595 NewCS = IRB.CreateCall(NewFT, &JT, Args);
1596 else
1597 NewCS =
1598 IRB.CreateInvoke(NewFT, &JT, cast<InvokeInst>(CB).getNormalDest(),
1599 cast<InvokeInst>(CB).getUnwindDest(), Args);
1600 NewCS->setCallingConv(CB.getCallingConv());
1601
1602 AttributeList Attrs = CB.getAttributes();
1603 std::vector<AttributeSet> NewArgAttrs;
1604 NewArgAttrs.push_back(AttributeSet::get(
1605 M.getContext(), ArrayRef<Attribute>{Attribute::get(
1606 M.getContext(), Attribute::Nest)}));
1607 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
1608 NewArgAttrs.push_back(Attrs.getParamAttrs(I));
1609 NewCS->setAttributes(
1610 AttributeList::get(M.getContext(), Attrs.getFnAttrs(),
1611 Attrs.getRetAttrs(), NewArgAttrs));
1612
1613 CallBases[&CB] = NewCS;
1614
1615 // This use is no longer unsafe.
1616 if (VCallSite.NumUnsafeUses)
1617 --*VCallSite.NumUnsafeUses;
1618 }
1619 // Don't mark as devirtualized because there may be callers compiled without
1620 // retpoline mitigation, which would mean that they are lowered to
1621 // llvm.type.test and therefore require an llvm.type.test resolution for the
1622 // type identifier.
1623
1624 for (auto &[Old, New] : CallBases) {
1625 Old->replaceAllUsesWith(New);
1626 Old->eraseFromParent();
1627 }
1628 };
1629 Apply(SlotInfo.CSInfo);
1630 for (auto &P : SlotInfo.ConstCSInfo)
1631 Apply(P.second);
1632 for (auto &[F, C] : FunctionEntryCounts) {
1633 assert(!F->getEntryCount() &&
1634 "Unexpected entry count for funnel that was freshly synthesized");
1635 F->setEntryCount(static_cast<uint64_t>(std::round(C)));
1636 }
1637}
1638
1639bool DevirtModule::tryEvaluateFunctionsWithArgs(
1641 ArrayRef<uint64_t> Args) {
1642 // Evaluate each function and store the result in each target's RetVal
1643 // field.
1644 for (VirtualCallTarget &Target : TargetsForSlot) {
1645 // TODO: Skip for now if the vtable symbol was an alias to a function,
1646 // need to evaluate whether it would be correct to analyze the aliasee
1647 // function for this optimization.
1648 auto *Fn = dyn_cast<Function>(Target.Fn);
1649 if (!Fn)
1650 return false;
1651
1652 if (Fn->arg_size() != Args.size() + 1)
1653 return false;
1654
1655 Evaluator Eval(M.getDataLayout(), nullptr);
1657 EvalArgs.push_back(
1659 for (unsigned I = 0; I != Args.size(); ++I) {
1660 auto *ArgTy =
1662 if (!ArgTy)
1663 return false;
1664 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
1665 }
1666
1667 Constant *RetVal;
1668 if (!Eval.EvaluateFunction(Fn, RetVal, EvalArgs) ||
1669 !isa<ConstantInt>(RetVal))
1670 return false;
1671 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
1672 }
1673 return true;
1674}
1675
1676void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1677 uint64_t TheRetVal) {
1678 for (auto Call : CSInfo.CallSites) {
1679 if (!OptimizedCalls.insert(&Call.CB).second)
1680 continue;
1681 NumUniformRetVal++;
1682 Call.replaceAndErase(
1683 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
1684 ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal));
1685 }
1686 CSInfo.markDevirt();
1687}
1688
1689bool DevirtModule::tryUniformRetValOpt(
1690 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
1691 WholeProgramDevirtResolution::ByArg *Res) {
1692 // Uniform return value optimization. If all functions return the same
1693 // constant, replace all calls with that constant.
1694 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1695 for (const VirtualCallTarget &Target : TargetsForSlot)
1696 if (Target.RetVal != TheRetVal)
1697 return false;
1698
1699 if (CSInfo.isExported()) {
1701 Res->Info = TheRetVal;
1702 }
1703
1704 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
1705 if (RemarksEnabled || AreStatisticsEnabled())
1706 for (auto &&Target : TargetsForSlot)
1707 Target.WasDevirt = true;
1708 return true;
1709}
1710
1711std::string DevirtModule::getGlobalName(VTableSlot Slot,
1712 ArrayRef<uint64_t> Args,
1713 StringRef Name) {
1714 std::string FullName = "__typeid_";
1715 raw_string_ostream OS(FullName);
1716 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1717 for (uint64_t Arg : Args)
1718 OS << '_' << Arg;
1719 OS << '_' << Name;
1720 return FullName;
1721}
1722
1723bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1724 Triple T(M.getTargetTriple());
1725 return T.isX86() && T.getObjectFormat() == Triple::ELF;
1726}
1727
1728void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1729 StringRef Name, Constant *C) {
1730 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1731 getGlobalName(Slot, Args, Name), C, &M);
1733}
1734
1735void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1736 StringRef Name, uint32_t Const,
1737 uint32_t &Storage) {
1738 if (shouldExportConstantsAsAbsoluteSymbols()) {
1739 exportGlobal(
1740 Slot, Args, Name,
1741 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1742 return;
1743 }
1744
1745 Storage = Const;
1746}
1747
1748Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1749 StringRef Name) {
1750 GlobalVariable *GV =
1751 M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty);
1753 return GV;
1754}
1755
1756Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1757 StringRef Name, IntegerType *IntTy,
1758 uint32_t Storage) {
1759 if (!shouldExportConstantsAsAbsoluteSymbols())
1760 return ConstantInt::get(IntTy, Storage);
1761
1762 Constant *C = importGlobal(Slot, Args, Name);
1763 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1764 C = ConstantExpr::getPtrToInt(C, IntTy);
1765
1766 // We only need to set metadata if the global is newly created, in which
1767 // case it would not have hidden visibility.
1768 if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
1769 return C;
1770
1771 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1772 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1773 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1774 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1775 MDNode::get(M.getContext(), {MinC, MaxC}));
1776 };
1777 unsigned AbsWidth = IntTy->getBitWidth();
1778 if (AbsWidth == IntPtrTy->getBitWidth()) {
1779 uint64_t AllOnes = IntTy->getBitMask();
1780 SetAbsRange(AllOnes, AllOnes); // Full set.
1781 } else {
1782 SetAbsRange(0, 1ull << AbsWidth);
1783 }
1784 return C;
1785}
1786
1787void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1788 bool IsOne,
1789 Constant *UniqueMemberAddr) {
1790 for (auto &&Call : CSInfo.CallSites) {
1791 if (!OptimizedCalls.insert(&Call.CB).second)
1792 continue;
1793 IRBuilder<> B(&Call.CB);
1794 Value *Cmp =
1795 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable,
1796 B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType()));
1797 Cmp = B.CreateZExt(Cmp, Call.CB.getType());
1798 NumUniqueRetVal++;
1799 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1800 Cmp);
1801 }
1802 CSInfo.markDevirt();
1803}
1804
1805Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1806 return ConstantExpr::getPtrAdd(M->Bits->GV,
1807 ConstantInt::get(Int64Ty, M->Offset));
1808}
1809
1810bool DevirtModule::tryUniqueRetValOpt(
1811 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
1812 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1813 VTableSlot Slot, ArrayRef<uint64_t> Args) {
1814 // IsOne controls whether we look for a 0 or a 1.
1815 auto tryUniqueRetValOptFor = [&](bool IsOne) {
1816 const TypeMemberInfo *UniqueMember = nullptr;
1817 for (const VirtualCallTarget &Target : TargetsForSlot) {
1818 if (Target.RetVal == (IsOne ? 1 : 0)) {
1819 if (UniqueMember)
1820 return false;
1821 UniqueMember = Target.TM;
1822 }
1823 }
1824
1825 // We should have found a unique member or bailed out by now. We already
1826 // checked for a uniform return value in tryUniformRetValOpt.
1827 assert(UniqueMember);
1828
1829 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
1830 if (CSInfo.isExported()) {
1832 Res->Info = IsOne;
1833
1834 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1835 }
1836
1837 // Replace each call with the comparison.
1838 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1839 UniqueMemberAddr);
1840
1841 // Update devirtualization statistics for targets.
1842 if (RemarksEnabled || AreStatisticsEnabled())
1843 for (auto &&Target : TargetsForSlot)
1844 Target.WasDevirt = true;
1845
1846 return true;
1847 };
1848
1849 if (BitWidth == 1) {
1850 if (tryUniqueRetValOptFor(true))
1851 return true;
1852 if (tryUniqueRetValOptFor(false))
1853 return true;
1854 }
1855 return false;
1856}
1857
1858void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1859 Constant *Byte, Constant *Bit) {
1860 for (auto Call : CSInfo.CallSites) {
1861 if (!OptimizedCalls.insert(&Call.CB).second)
1862 continue;
1863 auto *RetType = cast<IntegerType>(Call.CB.getType());
1864 IRBuilder<> B(&Call.CB);
1865 Value *Addr = B.CreatePtrAdd(Call.VTable, Byte);
1866 if (RetType->getBitWidth() == 1) {
1867 Value *Bits = B.CreateLoad(Int8Ty, Addr);
1868 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1869 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1870 NumVirtConstProp1Bit++;
1871 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
1872 OREGetter, IsBitSet);
1873 } else {
1874 Value *Val = B.CreateLoad(RetType, Addr);
1875 NumVirtConstProp++;
1876 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1877 OREGetter, Val);
1878 }
1879 }
1880 CSInfo.markDevirt();
1881}
1882
1883bool DevirtModule::tryVirtualConstProp(
1884 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1885 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1886 // TODO: Skip for now if the vtable symbol was an alias to a function,
1887 // need to evaluate whether it would be correct to analyze the aliasee
1888 // function for this optimization.
1889 auto *Fn = dyn_cast<Function>(TargetsForSlot[0].Fn);
1890 if (!Fn)
1891 return false;
1892 // This only works if the function returns an integer.
1893 auto *RetType = dyn_cast<IntegerType>(Fn->getReturnType());
1894 if (!RetType)
1895 return false;
1896 unsigned BitWidth = RetType->getBitWidth();
1897
1898 // TODO: Since we can evaluated these constants at compile-time, we can save
1899 // some space by calculating the smallest range of values that all these
1900 // constants can fit in, then only allocate enough space to fit those values.
1901 // At each callsite, we can get the original type by doing a sign/zero
1902 // extension. For example, if we would store an i64, but we can see that all
1903 // the values fit into an i16, then we can store an i16 before/after the
1904 // vtable and at each callsite do a s/zext.
1905 if (BitWidth > 64)
1906 return false;
1907
1908 Align TypeAlignment = M.getDataLayout().getABIIntegerTypeAlignment(BitWidth);
1909
1910 // Make sure that each function is defined, does not access memory, takes at
1911 // least one argument, does not use its first argument (which we assume is
1912 // 'this'), and has the same return type.
1913 //
1914 // Note that we test whether this copy of the function is readnone, rather
1915 // than testing function attributes, which must hold for any copy of the
1916 // function, even a less optimized version substituted at link time. This is
1917 // sound because the virtual constant propagation optimizations effectively
1918 // inline all implementations of the virtual function into each call site,
1919 // rather than using function attributes to perform local optimization.
1920 for (VirtualCallTarget &Target : TargetsForSlot) {
1921 // TODO: Skip for now if the vtable symbol was an alias to a function,
1922 // need to evaluate whether it would be correct to analyze the aliasee
1923 // function for this optimization.
1924 auto *Fn = dyn_cast<Function>(Target.Fn);
1925 if (!Fn)
1926 return false;
1927
1928 if (Fn->isDeclaration() || Fn->isInterposable() ||
1929 !computeFunctionBodyMemoryAccess(*Fn, FAM.getResult<AAManager>(*Fn))
1931 Fn->arg_empty() || !Fn->arg_begin()->use_empty() ||
1932 Fn->getReturnType() != RetType)
1933 return false;
1934
1935 // This only works if the integer size is at most the alignment of the
1936 // vtable. If the table is underaligned, then we can't guarantee that the
1937 // constant will always be aligned to the integer type alignment. For
1938 // example, if the table is `align 1`, we can never guarantee that an i32
1939 // stored before/after the vtable is 32-bit aligned without changing the
1940 // alignment of the new global.
1941 GlobalVariable *GV = Target.TM->Bits->GV;
1942 Align TableAlignment = M.getDataLayout().getValueOrABITypeAlignment(
1943 GV->getAlign(), GV->getValueType());
1944 if (TypeAlignment > TableAlignment)
1945 return false;
1946 }
1947
1948 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
1949 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1950 continue;
1951
1952 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1953 if (Res)
1954 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1955
1956 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
1957 continue;
1958
1959 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1960 ResByArg, Slot, CSByConstantArg.first))
1961 continue;
1962
1963 // Find an allocation offset in bits in all vtables associated with the
1964 // type.
1965 // TODO: If there would be "holes" in the vtable that were added by
1966 // padding, we could place i1s there to reduce any extra padding that
1967 // would be introduced by the i1s.
1968 uint64_t AllocBefore =
1969 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1970 uint64_t AllocAfter =
1971 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1972
1973 // Calculate the total amount of padding needed to store a value at both
1974 // ends of the object.
1975 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1976 for (auto &&Target : TargetsForSlot) {
1977 TotalPaddingBefore += std::max<int64_t>(
1978 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1979 TotalPaddingAfter += std::max<int64_t>(
1980 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1981 }
1982
1983 // If the amount of padding is too large, give up.
1984 // FIXME: do something smarter here.
1985 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1986 continue;
1987
1988 // Calculate the offset to the value as a (possibly negative) byte offset
1989 // and (if applicable) a bit offset, and store the values in the targets.
1990 int64_t OffsetByte;
1991 uint64_t OffsetBit;
1992 if (TotalPaddingBefore <= TotalPaddingAfter)
1993 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1994 OffsetBit);
1995 else
1996 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1997 OffsetBit);
1998
1999 // In an earlier check we forbade constant propagation from operating on
2000 // tables whose alignment is less than the alignment needed for loading
2001 // the constant. Thus, the address we take the offset from will always be
2002 // aligned to at least this integer alignment. Now, we need to ensure that
2003 // the offset is also aligned to this integer alignment to ensure we always
2004 // have an aligned load.
2005 assert(OffsetByte % TypeAlignment.value() == 0);
2006
2007 if (RemarksEnabled || AreStatisticsEnabled())
2008 for (auto &&Target : TargetsForSlot)
2009 Target.WasDevirt = true;
2010
2011
2012 if (CSByConstantArg.second.isExported()) {
2014 ResByArg->Byte = OffsetByte;
2015 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
2016 ResByArg->Bit);
2017 }
2018
2019 // Rewrite each call to a load from OffsetByte/OffsetBit.
2020 Constant *ByteConst = ConstantInt::getSigned(Int32Ty, OffsetByte);
2021 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
2022 applyVirtualConstProp(CSByConstantArg.second,
2023 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
2024 }
2025 return true;
2026}
2027
2028void DevirtModule::rebuildGlobal(VTableBits &B) {
2029 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
2030 return;
2031
2032 // Align the before byte array to the global's minimum alignment so that we
2033 // don't break any alignment requirements on the global.
2034 Align Alignment = M.getDataLayout().getValueOrABITypeAlignment(
2035 B.GV->getAlign(), B.GV->getValueType());
2036 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
2037
2038 // Before was stored in reverse order; flip it now.
2039 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
2040 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
2041
2042 // Build an anonymous global containing the before bytes, followed by the
2043 // original initializer, followed by the after bytes.
2044 auto *NewInit = ConstantStruct::getAnon(
2045 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
2046 B.GV->getInitializer(),
2047 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
2048 auto *NewGV =
2049 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
2050 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
2051 NewGV->setSection(B.GV->getSection());
2052 NewGV->setComdat(B.GV->getComdat());
2053 NewGV->setAlignment(B.GV->getAlign());
2054
2055 // Copy the original vtable's metadata to the anonymous global, adjusting
2056 // offsets as required.
2057 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
2058
2059 // Build an alias named after the original global, pointing at the second
2060 // element (the original initializer).
2061 auto *Alias = GlobalAlias::create(
2062 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
2064 NewInit->getType(), NewGV,
2065 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
2066 ConstantInt::get(Int32Ty, 1)}),
2067 &M);
2068 Alias->setVisibility(B.GV->getVisibility());
2069 Alias->takeName(B.GV);
2070
2071 B.GV->replaceAllUsesWith(Alias);
2072 B.GV->eraseFromParent();
2073}
2074
2075bool DevirtModule::areRemarksEnabled() {
2076 const auto &FL = M.getFunctionList();
2077 for (const Function &Fn : FL) {
2078 if (Fn.empty())
2079 continue;
2080 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &Fn.front());
2081 return DI.isEnabled();
2082 }
2083 return false;
2084}
2085
2086void DevirtModule::scanTypeTestUsers(
2087 Function *TypeTestFunc,
2088 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
2089 // Find all virtual calls via a virtual table pointer %p under an assumption
2090 // of the form llvm.assume(llvm.type.test(%p, %md)) or
2091 // llvm.assume(llvm.public.type.test(%p, %md)).
2092 // This indicates that %p points to a member of the type identifier %md.
2093 // Group calls by (type ID, offset) pair (effectively the identity of the
2094 // virtual function) and store to CallSlots.
2095 for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) {
2096 auto *CI = dyn_cast<CallInst>(U.getUser());
2097 if (!CI)
2098 continue;
2099 // Search for virtual calls based on %p and add them to DevirtCalls.
2102 auto &DT = FAM.getResult<DominatorTreeAnalysis>(*CI->getFunction());
2103 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
2104
2105 Metadata *TypeId =
2106 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
2107 // If we found any, add them to CallSlots.
2108 if (!Assumes.empty()) {
2109 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
2110 for (DevirtCallSite Call : DevirtCalls)
2111 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr);
2112 }
2113
2114 auto RemoveTypeTestAssumes = [&]() {
2115 // We no longer need the assumes or the type test.
2116 for (auto *Assume : Assumes)
2117 Assume->eraseFromParent();
2118 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
2119 // may use the vtable argument later.
2120 if (CI->use_empty())
2121 CI->eraseFromParent();
2122 };
2123
2124 // At this point we could remove all type test assume sequences, as they
2125 // were originally inserted for WPD. However, we can keep these in the
2126 // code stream for later analysis (e.g. to help drive more efficient ICP
2127 // sequences). They will eventually be removed by a second LowerTypeTests
2128 // invocation that cleans them up. In order to do this correctly, the first
2129 // LowerTypeTests invocation needs to know that they have "Unknown" type
2130 // test resolution, so that they aren't treated as Unsat and lowered to
2131 // False, which will break any uses on assumes. Below we remove any type
2132 // test assumes that will not be treated as Unknown by LTT.
2133
2134 // The type test assumes will be treated by LTT as Unsat if the type id is
2135 // not used on a global (in which case it has no entry in the TypeIdMap).
2136 if (!TypeIdMap.count(TypeId))
2137 RemoveTypeTestAssumes();
2138
2139 // For ThinLTO importing, we need to remove the type test assumes if this is
2140 // an MDString type id without a corresponding TypeIdSummary. Any
2141 // non-MDString type ids are ignored and treated as Unknown by LTT, so their
2142 // type test assumes can be kept. If the MDString type id is missing a
2143 // TypeIdSummary (e.g. because there was no use on a vcall, preventing the
2144 // exporting phase of WPD from analyzing it), then it would be treated as
2145 // Unsat by LTT and we need to remove its type test assumes here. If not
2146 // used on a vcall we don't need them for later optimization use in any
2147 // case.
2148 else if (ImportSummary && isa<MDString>(TypeId)) {
2149 const TypeIdSummary *TidSummary =
2150 ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString());
2151 if (!TidSummary)
2152 RemoveTypeTestAssumes();
2153 else
2154 // If one was created it should not be Unsat, because if we reached here
2155 // the type id was used on a global.
2157 }
2158 }
2159}
2160
2161void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
2162 Function *TypeTestFunc =
2163 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::type_test);
2164
2165 for (Use &U : llvm::make_early_inc_range(TypeCheckedLoadFunc->uses())) {
2166 auto *CI = dyn_cast<CallInst>(U.getUser());
2167 if (!CI)
2168 continue;
2169
2170 Value *Ptr = CI->getArgOperand(0);
2171 Value *Offset = CI->getArgOperand(1);
2172 Value *TypeIdValue = CI->getArgOperand(2);
2173 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
2174
2178 bool HasNonCallUses = false;
2179 auto &DT = FAM.getResult<DominatorTreeAnalysis>(*CI->getFunction());
2180 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
2181 HasNonCallUses, CI, DT);
2182
2183 // Start by generating "pessimistic" code that explicitly loads the function
2184 // pointer from the vtable and performs the type check. If possible, we will
2185 // eliminate the load and the type check later.
2186
2187 // If possible, only generate the load at the point where it is used.
2188 // This helps avoid unnecessary spills.
2189 IRBuilder<> LoadB(
2190 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
2191
2192 Value *LoadedValue = nullptr;
2193 if (TypeCheckedLoadFunc->getIntrinsicID() ==
2194 Intrinsic::type_checked_load_relative) {
2196 &M, Intrinsic::load_relative, {Int32Ty});
2197 LoadedValue = LoadB.CreateCall(LoadRelFunc, {Ptr, Offset});
2198 } else {
2199 Value *GEP = LoadB.CreatePtrAdd(Ptr, Offset);
2200 LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEP);
2201 }
2202
2203 for (Instruction *LoadedPtr : LoadedPtrs) {
2204 LoadedPtr->replaceAllUsesWith(LoadedValue);
2205 LoadedPtr->eraseFromParent();
2206 }
2207
2208 // Likewise for the type test.
2209 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
2210 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
2211
2212 for (Instruction *Pred : Preds) {
2213 Pred->replaceAllUsesWith(TypeTestCall);
2214 Pred->eraseFromParent();
2215 }
2216
2217 // We have already erased any extractvalue instructions that refer to the
2218 // intrinsic call, but the intrinsic may have other non-extractvalue uses
2219 // (although this is unlikely). In that case, explicitly build a pair and
2220 // RAUW it.
2221 if (!CI->use_empty()) {
2222 Value *Pair = PoisonValue::get(CI->getType());
2223 IRBuilder<> B(CI);
2224 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
2225 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
2226 CI->replaceAllUsesWith(Pair);
2227 }
2228
2229 // The number of unsafe uses is initially the number of uses.
2230 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
2231 NumUnsafeUses = DevirtCalls.size();
2232
2233 // If the function pointer has a non-call user, we cannot eliminate the type
2234 // check, as one of those users may eventually call the pointer. Increment
2235 // the unsafe use count to make sure it cannot reach zero.
2236 if (HasNonCallUses)
2237 ++NumUnsafeUses;
2238 for (DevirtCallSite Call : DevirtCalls) {
2239 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB,
2240 &NumUnsafeUses);
2241 }
2242
2243 CI->eraseFromParent();
2244 }
2245}
2246
2247void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
2248 auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
2249 if (!TypeId)
2250 return;
2251 const TypeIdSummary *TidSummary =
2252 ImportSummary->getTypeIdSummary(TypeId->getString());
2253 if (!TidSummary)
2254 return;
2255 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
2256 if (ResI == TidSummary->WPDRes.end())
2257 return;
2258 const WholeProgramDevirtResolution &Res = ResI->second;
2259
2261 assert(!Res.SingleImplName.empty());
2262 // The type of the function in the declaration is irrelevant because every
2263 // call site will cast it to the correct type.
2264 Constant *SingleImpl =
2265 cast<Constant>(M.getOrInsertFunction(Res.SingleImplName,
2266 Type::getVoidTy(M.getContext()))
2267 .getCallee());
2268
2269 // This is the import phase so we should not be exporting anything.
2270 bool IsExported = false;
2271 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
2272 assert(!IsExported);
2273 }
2274
2275 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
2276 auto I = Res.ResByArg.find(CSByConstantArg.first);
2277 if (I == Res.ResByArg.end())
2278 continue;
2279 auto &ResByArg = I->second;
2280 // FIXME: We should figure out what to do about the "function name" argument
2281 // to the apply* functions, as the function names are unavailable during the
2282 // importing phase. For now we just pass the empty string. This does not
2283 // impact correctness because the function names are just used for remarks.
2284 switch (ResByArg.TheKind) {
2286 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
2287 break;
2289 Constant *UniqueMemberAddr =
2290 importGlobal(Slot, CSByConstantArg.first, "unique_member");
2291 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
2292 UniqueMemberAddr);
2293 break;
2294 }
2296 Constant *Byte = ConstantInt::get(Int32Ty, ResByArg.Byte);
2297 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
2298 ResByArg.Bit);
2299 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
2300 break;
2301 }
2302 default:
2303 break;
2304 }
2305 }
2306
2308 // The type of the function is irrelevant, because it's bitcast at calls
2309 // anyhow.
2310 auto *JT = cast<Function>(
2311 M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
2312 Type::getVoidTy(M.getContext()))
2313 .getCallee());
2314 bool IsExported = false;
2315 applyICallBranchFunnel(SlotInfo, *JT, IsExported);
2316 assert(!IsExported);
2317 }
2318}
2319
2320void DevirtModule::removeRedundantTypeTests() {
2321 auto *True = ConstantInt::getTrue(M.getContext());
2322 for (auto &&U : NumUnsafeUsesForTypeTest) {
2323 if (U.second == 0) {
2324 U.first->replaceAllUsesWith(True);
2325 U.first->eraseFromParent();
2326 }
2327 }
2328}
2329
2330ValueInfo
2331DevirtModule::lookUpFunctionValueInfo(Function *TheFn,
2332 ModuleSummaryIndex *ExportSummary) {
2333 assert((ExportSummary != nullptr) &&
2334 "Caller guarantees ExportSummary is not nullptr");
2335
2336 const auto TheFnGUID = TheFn->getGUID();
2337 const auto TheFnGUIDWithExportedName =
2339 // Look up ValueInfo with the GUID in the current linkage.
2340 ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFnGUID);
2341 // If no entry is found and GUID is different from GUID computed using
2342 // exported name, look up ValueInfo with the exported name unconditionally.
2343 // This is a fallback.
2344 //
2345 // The reason to have a fallback:
2346 // 1. LTO could enable global value internalization via
2347 // `enable-lto-internalization`.
2348 // 2. The GUID in ExportedSummary is computed using exported name.
2349 if ((!TheFnVI) && (TheFnGUID != TheFnGUIDWithExportedName)) {
2350 TheFnVI = ExportSummary->getValueInfo(TheFnGUIDWithExportedName);
2351 }
2352 return TheFnVI;
2353}
2354
2355bool DevirtModule::mustBeUnreachableFunction(
2356 Function *const F, ModuleSummaryIndex *ExportSummary) {
2358 return false;
2359 // First, learn unreachability by analyzing function IR.
2360 if (!F->isDeclaration()) {
2361 // A function must be unreachable if its entry block ends with an
2362 // 'unreachable'.
2363 return isa<UnreachableInst>(F->getEntryBlock().getTerminator());
2364 }
2365 // Learn unreachability from ExportSummary if ExportSummary is present.
2366 return ExportSummary &&
2368 DevirtModule::lookUpFunctionValueInfo(F, ExportSummary));
2369}
2370
2371bool DevirtModule::run() {
2372 // If only some of the modules were split, we cannot correctly perform
2373 // this transformation. We already checked for the presense of type tests
2374 // with partially split modules during the thin link, and would have emitted
2375 // an error if any were found, so here we can simply return.
2376 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
2377 (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
2378 return false;
2379
2380 Function *PublicTypeTestFunc = nullptr;
2381 // If we are in speculative devirtualization mode, we can work on the public
2382 // type test intrinsics.
2383 if (DevirtSpeculatively)
2384 PublicTypeTestFunc =
2385 Intrinsic::getDeclarationIfExists(&M, Intrinsic::public_type_test);
2386 Function *TypeTestFunc =
2387 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_test);
2388 Function *TypeCheckedLoadFunc =
2389 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_checked_load);
2390 Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
2391 &M, Intrinsic::type_checked_load_relative);
2392 Function *AssumeFunc =
2393 Intrinsic::getDeclarationIfExists(&M, Intrinsic::assume);
2394
2395 // Normally if there are no users of the devirtualization intrinsics in the
2396 // module, this pass has nothing to do. But if we are exporting, we also need
2397 // to handle any users that appear only in the function summaries.
2398 if (!ExportSummary &&
2399 (((!PublicTypeTestFunc || PublicTypeTestFunc->use_empty()) &&
2400 (!TypeTestFunc || TypeTestFunc->use_empty())) ||
2401 !AssumeFunc || AssumeFunc->use_empty()) &&
2402 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()) &&
2403 (!TypeCheckedLoadRelativeFunc ||
2404 TypeCheckedLoadRelativeFunc->use_empty()))
2405 return false;
2406
2407 // Rebuild type metadata into a map for easy lookup.
2408 std::vector<VTableBits> Bits;
2409 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
2410 buildTypeIdentifierMap(Bits, TypeIdMap);
2411
2412 if (PublicTypeTestFunc && AssumeFunc)
2413 scanTypeTestUsers(PublicTypeTestFunc, TypeIdMap);
2414
2415 if (TypeTestFunc && AssumeFunc)
2416 scanTypeTestUsers(TypeTestFunc, TypeIdMap);
2417
2418 if (TypeCheckedLoadFunc)
2419 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
2420
2421 if (TypeCheckedLoadRelativeFunc)
2422 scanTypeCheckedLoadUsers(TypeCheckedLoadRelativeFunc);
2423
2424 if (ImportSummary) {
2425 for (auto &S : CallSlots)
2426 importResolution(S.first, S.second);
2427
2428 removeRedundantTypeTests();
2429
2430 // We have lowered or deleted the type intrinsics, so we will no longer have
2431 // enough information to reason about the liveness of virtual function
2432 // pointers in GlobalDCE.
2433 for (GlobalVariable &GV : M.globals())
2434 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2435
2436 // The rest of the code is only necessary when exporting or during regular
2437 // LTO, so we are done.
2438 return true;
2439 }
2440
2441 if (TypeIdMap.empty())
2442 return true;
2443
2444 // Collect information from summary about which calls to try to devirtualize.
2445 if (ExportSummary) {
2446 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
2447 for (auto &P : TypeIdMap) {
2448 if (auto *TypeId = dyn_cast<MDString>(P.first))
2450 TypeId->getString())]
2451 .push_back(TypeId);
2452 }
2453
2454 for (auto &P : *ExportSummary) {
2455 for (auto &S : P.second.getSummaryList()) {
2456 auto *FS = dyn_cast<FunctionSummary>(S.get());
2457 if (!FS)
2458 continue;
2459 // FIXME: Only add live functions.
2460 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2461 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
2462 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2463 }
2464 }
2465 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2466 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
2467 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2468 }
2469 }
2470 for (const FunctionSummary::ConstVCall &VC :
2471 FS->type_test_assume_const_vcalls()) {
2472 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2473 CallSlots[{MD, VC.VFunc.Offset}]
2474 .ConstCSInfo[VC.Args]
2475 .addSummaryTypeTestAssumeUser(FS);
2476 }
2477 }
2478 for (const FunctionSummary::ConstVCall &VC :
2479 FS->type_checked_load_const_vcalls()) {
2480 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2481 CallSlots[{MD, VC.VFunc.Offset}]
2482 .ConstCSInfo[VC.Args]
2483 .addSummaryTypeCheckedLoadUser(FS);
2484 }
2485 }
2486 }
2487 }
2488 }
2489
2490 // For each (type, offset) pair:
2491 bool DidVirtualConstProp = false;
2492 std::map<std::string, GlobalValue *> DevirtTargets;
2493 for (auto &S : CallSlots) {
2494 // Search each of the members of the type identifier for the virtual
2495 // function implementation at offset S.first.ByteOffset, and add to
2496 // TargetsForSlot.
2497 std::vector<VirtualCallTarget> TargetsForSlot;
2498 WholeProgramDevirtResolution *Res = nullptr;
2499 const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID];
2500 if (ExportSummary && isa<MDString>(S.first.TypeID) &&
2501 TypeMemberInfos.size())
2502 // For any type id used on a global's type metadata, create the type id
2503 // summary resolution regardless of whether we can devirtualize, so that
2504 // lower type tests knows the type id is not Unsat. If it was not used on
2505 // a global's type metadata, the TypeIdMap entry set will be empty, and
2506 // we don't want to create an entry (with the default Unknown type
2507 // resolution), which can prevent detection of the Unsat.
2508 Res = &ExportSummary
2509 ->getOrInsertTypeIdSummary(
2510 cast<MDString>(S.first.TypeID)->getString())
2511 .WPDRes[S.first.ByteOffset];
2512 if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos,
2513 S.first.ByteOffset, ExportSummary)) {
2514 bool SingleImplDevirt =
2515 trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res);
2516 // Out of speculative devirtualization mode, Try to apply virtual constant
2517 // propagation or branch funneling.
2518 // TODO: This should eventually be enabled for non-public type tests.
2519 if (!SingleImplDevirt && !DevirtSpeculatively) {
2520 DidVirtualConstProp |=
2521 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
2522
2523 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
2524 }
2525
2526 // Collect functions devirtualized at least for one call site for stats.
2527 if (RemarksEnabled || AreStatisticsEnabled())
2528 for (const auto &T : TargetsForSlot)
2529 if (T.WasDevirt)
2530 DevirtTargets[std::string(T.Fn->getName())] = T.Fn;
2531 }
2532
2533 // CFI-specific: if we are exporting and any llvm.type.checked.load
2534 // intrinsics were *not* devirtualized, we need to add the resulting
2535 // llvm.type.test intrinsics to the function summaries so that the
2536 // LowerTypeTests pass will export them.
2537 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
2539 cast<MDString>(S.first.TypeID)->getString());
2540 auto AddTypeTestsForTypeCheckedLoads = [&](CallSiteInfo &CSI) {
2541 if (!CSI.AllCallSitesDevirted)
2542 for (auto *FS : CSI.SummaryTypeCheckedLoadUsers)
2543 FS->addTypeTest(GUID);
2544 };
2545 AddTypeTestsForTypeCheckedLoads(S.second.CSInfo);
2546 for (auto &CCS : S.second.ConstCSInfo)
2547 AddTypeTestsForTypeCheckedLoads(CCS.second);
2548 }
2549 }
2550
2551 if (RemarksEnabled) {
2552 // Generate remarks for each devirtualized function.
2553 for (const auto &DT : DevirtTargets) {
2554 GlobalValue *GV = DT.second;
2555 auto *F = dyn_cast<Function>(GV);
2556 if (!F) {
2557 auto *A = dyn_cast<GlobalAlias>(GV);
2558 assert(A && isa<Function>(A->getAliasee()));
2559 F = dyn_cast<Function>(A->getAliasee());
2560 assert(F);
2561 }
2562
2563 using namespace ore;
2564 OREGetter(*F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
2565 << "devirtualized " << NV("FunctionName", DT.first));
2566 }
2567 }
2568
2569 NumDevirtTargets += DevirtTargets.size();
2570
2571 removeRedundantTypeTests();
2572
2573 // Rebuild each global we touched as part of virtual constant propagation to
2574 // include the before and after bytes.
2575 if (DidVirtualConstProp)
2576 for (VTableBits &B : Bits)
2577 rebuildGlobal(B);
2578
2579 // We have lowered or deleted the type intrinsics, so we will no longer have
2580 // enough information to reason about the liveness of virtual function
2581 // pointers in GlobalDCE.
2582 for (GlobalVariable &GV : M.globals())
2583 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2584
2585 for (auto *CI : CallsWithPtrAuthBundleRemoved)
2586 CI->eraseFromParent();
2587
2588 return true;
2589}
2590
2591void DevirtIndex::run() {
2592 if (ExportSummary.typeIdCompatibleVtableMap().empty())
2593 return;
2594
2595 // Assert that we haven't made any changes that would affect the hasLocal()
2596 // flag on the GUID summary info.
2597 assert(!ExportSummary.withInternalizeAndPromote() &&
2598 "Expect index-based WPD to run before internalization and promotion");
2599
2600 DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
2601 for (const auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
2602 NameByGUID[GlobalValue::getGUIDAssumingExternalLinkage(P.first)].push_back(
2603 P.first);
2604 // Create the type id summary resolution regardlness of whether we can
2605 // devirtualize, so that lower type tests knows the type id is used on
2606 // a global and not Unsat. We do this here rather than in the loop over the
2607 // CallSlots, since that handling will only see type tests that directly
2608 // feed assumes, and we would miss any that aren't currently handled by WPD
2609 // (such as type tests that feed assumes via phis).
2610 ExportSummary.getOrInsertTypeIdSummary(P.first);
2611 }
2612
2613 // Collect information from summary about which calls to try to devirtualize.
2614 for (auto &P : ExportSummary) {
2615 for (auto &S : P.second.getSummaryList()) {
2616 auto *FS = dyn_cast<FunctionSummary>(S.get());
2617 if (!FS)
2618 continue;
2619 // FIXME: Only add live functions.
2620 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2621 for (StringRef Name : NameByGUID[VF.GUID]) {
2622 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2623 }
2624 }
2625 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2626 for (StringRef Name : NameByGUID[VF.GUID]) {
2627 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2628 }
2629 }
2630 for (const FunctionSummary::ConstVCall &VC :
2631 FS->type_test_assume_const_vcalls()) {
2632 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2633 CallSlots[{Name, VC.VFunc.Offset}]
2634 .ConstCSInfo[VC.Args]
2635 .addSummaryTypeTestAssumeUser(FS);
2636 }
2637 }
2638 for (const FunctionSummary::ConstVCall &VC :
2639 FS->type_checked_load_const_vcalls()) {
2640 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2641 CallSlots[{Name, VC.VFunc.Offset}]
2642 .ConstCSInfo[VC.Args]
2643 .addSummaryTypeCheckedLoadUser(FS);
2644 }
2645 }
2646 }
2647 }
2648
2649 std::set<ValueInfo> DevirtTargets;
2650 // For each (type, offset) pair:
2651 for (auto &S : CallSlots) {
2652 // Search each of the members of the type identifier for the virtual
2653 // function implementation at offset S.first.ByteOffset, and add to
2654 // TargetsForSlot.
2655 std::vector<ValueInfo> TargetsForSlot;
2656 auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
2657 assert(TidSummary);
2658 // The type id summary would have been created while building the NameByGUID
2659 // map earlier.
2660 WholeProgramDevirtResolution *Res =
2661 &ExportSummary.getTypeIdSummary(S.first.TypeID)
2662 ->WPDRes[S.first.ByteOffset];
2663 if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
2664 S.first.ByteOffset)) {
2665
2666 if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
2667 DevirtTargets))
2668 continue;
2669 }
2670 }
2671
2672 // Optionally have the thin link print message for each devirtualized
2673 // function.
2675 for (const auto &DT : DevirtTargets)
2676 errs() << "Devirtualized call to " << DT << "\n";
2677
2678 NumDevirtTargets += DevirtTargets.size();
2679}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
@ CallSiteInfo
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Provides passes for computing function attributes based on interprocedural analyses.
#define DEBUG_TYPE
static void emitRemark(const Function &F, OptimizationRemarkEmitter &ORE, bool Skip)
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static cl::opt< PassSummaryAction > ClSummaryAction("lowertypetests-summary-action", cl::desc("What to do with the summary when running this pass"), cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), clEnumValN(PassSummaryAction::Import, "import", "Import typeid resolutions from summary and globals"), clEnumValN(PassSummaryAction::Export, "export", "Export typeid resolutions to summary and globals")), cl::Hidden)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
#define T
static bool mustBeUnreachableFunction(const Function &F)
This is the interface to build a ModuleSummaryIndex for a module.
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
WPDCheckMode
Mechanism to add runtime checking of devirtualization decisions, optionally trapping or falling back ...
static bool typeIDVisibleToRegularObj(StringRef TypeID, function_ref< bool(StringRef)> IsVisibleToRegularObj)
static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary)
static bool addCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee)
static cl::opt< WPDCheckMode > DevirtCheckMode("wholeprogramdevirt-check", cl::Hidden, cl::desc("Type of checking for incorrect devirtualizations"), cl::values(clEnumValN(WPDCheckMode::None, "none", "No checking"), clEnumValN(WPDCheckMode::Trap, "trap", "Trap when incorrect"), clEnumValN(WPDCheckMode::Fallback, "fallback", "Fallback to indirect when incorrect")))
static cl::opt< bool > WholeProgramDevirtKeepUnreachableFunction("wholeprogramdevirt-keep-unreachable-function", cl::desc("Regard unreachable functions as possible devirtualize targets."), cl::Hidden, cl::init(true))
With Clang, a pure virtual class's deleting destructor is emitted as a llvm.trap intrinsic followed b...
static bool skipUpdateDueToValidation(GlobalVariable &GV, function_ref< bool(StringRef)> IsVisibleToRegularObj)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
void setCallingConv(CallingConv::ID CC)
bool arg_empty() const
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
void setCalledOperand(Value *V)
static LLVM_ABI CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ ICMP_NE
not equal
Definition InstrTypes.h:762
void setSelectionKind(SelectionKind Val)
Definition Comdat.h:48
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList)
Create an "inbounds" getelementptr.
Definition Constants.h:1507
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1497
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:643
const Constant * stripPointerCasts() const
Definition Constant.h:233
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static bool shouldExecute(CounterInfo &Counter)
bool empty() const
Definition DenseMap.h:171
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Subclass of Error for the sole purpose of identifying the success path in the type system.
Definition Error.h:334
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
Type * getParamType(unsigned i) const
Parameter type accessors.
ArrayRef< Type * > params() const
bool isVarArg() const
Type * getReturnType() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
bool empty() const
Definition Function.h:833
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
bool arg_empty() const
Definition Function.h:876
const BasicBlock & front() const
Definition Function.h:834
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:758
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
arg_iterator arg_begin()
Definition Function.h:842
std::optional< uint64_t > getEntryCount() const
Get the entry count for this function.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:661
size_t arg_size() const
Definition Function.h:875
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in this function.
Definition Function.cpp:361
static LLVM_ABI Expected< GlobPattern > create(StringRef Pat, std::optional< size_t > MaxSubPatterns={}, bool SlashAgnostic=false)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI VCallVisibility getVCallVisibility() const
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
LLVM_ABI void setVCallVisibilityMetadata(VCallVisibility Visibility)
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
LLVM_ABI GUID getGUID() const
Return a 64-bit global unique ID for this value.
Definition Globals.cpp:103
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
void setVisibility(VisibilityTypes V)
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
uint64_t getBitMask() const
Return a bitmask with ones set for all of the bits that can be set by an unsigned version of this typ...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
Root of the metadata hierarchy.
Definition Metadata.h:64
Class to hold module path string table and global value map, and encapsulate methods for operating on...
const TypeIdSummary * getTypeIdSummary(StringRef TypeId) const
This returns either a pointer to the type id summary (if present in the summary map) or null (if not ...
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
static constexpr const char * getRegularLTOModuleName()
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Analysis providing profile information.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
Target - Wrapper for Target specific information.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
bool use_empty() const
Definition Value.h:346
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Changed
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:804
LLVM_ABI uint64_t findLowestOffset(ArrayRef< VirtualCallTarget > Targets, bool IsAfter, uint64_t Size)
LLVM_ABI void setAfterReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocAfter, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
LLVM_ABI void setBeforeReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocBefore, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:573
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
LLVM_ABI void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Perform index-based whole program devirtualization on the Summary index.
LLVM_ABI MemoryEffects computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
static cl::opt< bool > DisableWholeProgramVisibility("disable-whole-program-visibility", cl::Hidden, cl::desc("Disable whole program visibility (overrides enabling options)"))
Provide a way to force disable whole program for debugging or workarounds, when enabled via the linke...
static cl::opt< bool > WholeProgramVisibility("whole-program-visibility", cl::Hidden, cl::desc("Enable whole program visibility"))
Provide a way to force enable whole program visibility in tests.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static cl::opt< unsigned > ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden, cl::init(10), cl::desc("Maximum number of call targets per " "call site to enable branch funnels"))
@ Export
Export information to summary.
Definition IPO.h:57
@ None
Do nothing.
Definition IPO.h:55
@ Import
Import information from summary.
Definition IPO.h:56
static cl::opt< std::string > ClReadSummary("wholeprogramdevirt-read-summary", cl::desc("Read summary from given bitcode or YAML file before running pass"), cl::Hidden)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI, std::function< const StackSafetyInfo *(const Function &F)> GetSSICallback=[](const Function &F) -> const StackSafetyInfo *{ return nullptr;})
Direct function to compute a ModuleSummaryIndex from a given module.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO)
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
@ invalid_argument
Definition Errc.h:56
LLVM_ABI void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
static cl::opt< std::string > ClWriteSummary("wholeprogramdevirt-write-summary", cl::desc("Write summary to given bitcode or YAML file after running pass. " "Output file format is deduced from extension: *.bc means writing " "bitcode, otherwise YAML"), cl::Hidden)
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
LLVM_ABI void getVisibleToRegularObjVtableGUIDs(ModuleSummaryIndex &Index, DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols, function_ref< bool(StringRef)> IsVisibleToRegularObj)
Based on typeID string, get all associated vtable GUIDS that are visible to regular objects.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
LLVM_ABI void findDevirtualizableCallsForTypeCheckedLoad(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< Instruction * > &LoadedPtrs, SmallVectorImpl< Instruction * > &Preds, bool &HasNonCallUses, const CallInst *CI, DominatorTree &DT)
Given a call to the intrinsic @llvm.type.checked.load, find all devirtualizable call sites based on t...
LLVM_ABI CallBase & versionCallSite(CallBase &CB, Value *Callee, MDNode *BranchWeights)
Predicate and clone the given call site.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void setExplicitlyUnknownFunctionEntryCount(Function &F, StringRef PassName)
Analogous to setExplicitlyUnknownBranchWeights, but for functions and their entry counts.
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
static cl::list< std::string > SkipFunctionNames("wholeprogramdevirt-skip", cl::desc("Prevent function(s) from being devirtualized"), cl::Hidden, cl::CommaSeparated)
Provide way to prevent certain function from being devirtualized.
static cl::opt< PassSummaryAction > ClSummaryAction("wholeprogramdevirt-summary-action", cl::desc("What to do with the summary when running this pass"), cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), clEnumValN(PassSummaryAction::Import, "import", "Import typeid resolutions from summary and globals"), clEnumValN(PassSummaryAction::Export, "export", "Export typeid resolutions to summary and globals")), cl::Hidden)
IntPtrTy
Definition InstrProf.h:82
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition Error.h:1261
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static cl::opt< bool > ClDevirtualizeSpeculatively("devirtualize-speculatively", cl::desc("Enable speculative devirtualization optimization"), cl::init(false))
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
static cl::opt< bool > PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden, cl::desc("Print index-based devirtualization messages"))
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI void findDevirtualizableCallsForTypeTest(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< CallInst * > &Assumes, const CallInst *CI, DominatorTree &DT)
Given a call to the intrinsic @llvm.type.test, find all devirtualizable call sites based on the call ...
LLVM_ABI void updateVCallVisibilityInModule(Module &M, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, bool ValidateAllVtablesHaveTypeInfos, function_ref< bool(StringRef)> IsVisibleToRegularObj)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI std::pair< Function *, Constant * > getFunctionAtVTableOffset(GlobalVariable *GV, uint64_t Offset, Module &M)
Given a vtable and a specified offset, returns the function and the trivial pointer at the specified ...
LLVM_ABI void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Class to accumulate and hold information about a callee.
static unsigned getHashValue(const VTableSlotSummary &I)
static bool isEqual(const VTableSlotSummary &LHS, const VTableSlotSummary &RHS)
static bool isEqual(const VTableSlot &LHS, const VTableSlot &RHS)
static unsigned getHashValue(const VTableSlot &I)
An information struct used to provide DenseMap with the various necessary components for a given valu...
The following data structures summarize type metadata information.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
enum llvm::TypeTestResolution::Kind TheKind
Struct that holds a reference to a particular GUID in a global value summary.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
const ModuleSummaryIndex * ImportSummary
ModuleSummaryIndex * ExportSummary
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
LLVM_ABI VirtualCallTarget(GlobalValue *Fn, const TypeMemberInfo *TM)