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