File: GlobalDCE.cpp

package info (click to toggle)
swiftlang 6.1.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,604 kB
  • sloc: cpp: 9,901,740; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (649 lines) | stat: -rw-r--r-- 23,563 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate unreachable internal globals from the
// program.  It uses an aggressive algorithm, searching out globals that are
// known to be alive.  After it finds all of the globals which are needed, it
// deletes whatever is left over.  This allows it to delete recursive chunks of
// the program which are unreachable.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/IPO/GlobalDCE.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/TypeMetadataUtils.h"
#include "llvm/IR/GlobalPtrAuthInfo.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"

using namespace llvm;

#define DEBUG_TYPE "globaldce"

static cl::opt<bool>
    ClEnableVFE("enable-vfe", cl::Hidden, cl::init(true),
                cl::desc("Enable virtual function elimination"));

STATISTIC(NumAliases  , "Number of global aliases removed");
STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumIFuncs,    "Number of indirect functions removed");
STATISTIC(NumVariables, "Number of global variables removed");
STATISTIC(NumVFuncs,    "Number of virtual functions removed");

/// Returns true if F is effectively empty.
static bool isEmptyFunction(Function *F) {
  // Skip external functions.
  if (F->isDeclaration())
    return false;
  BasicBlock &Entry = F->getEntryBlock();
  for (auto &I : Entry) {
    if (I.isDebugOrPseudoInst())
      continue;
    if (auto *RI = dyn_cast<ReturnInst>(&I))
      return !RI->getReturnValue();
    break;
  }
  return false;
}

/// Compute the set of GlobalValue that depends from V.
/// The recursion stops as soon as a GlobalValue is met.
void GlobalDCEPass::ComputeDependencies(Value *V,
                                        SmallPtrSetImpl<GlobalValue *> &Deps) {
  if (auto *I = dyn_cast<Instruction>(V)) {
    Function *Parent = I->getParent()->getParent();
    Deps.insert(Parent);
  } else if (auto *GV = dyn_cast<GlobalValue>(V)) {
    Deps.insert(GV);
  } else if (auto *CE = dyn_cast<Constant>(V)) {
    // Avoid walking the whole tree of a big ConstantExprs multiple times.
    auto Where = ConstantDependenciesCache.find(CE);
    if (Where != ConstantDependenciesCache.end()) {
      auto const &K = Where->second;
      Deps.insert(K.begin(), K.end());
    } else {
      SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];
      for (User *CEUser : CE->users())
        ComputeDependencies(CEUser, LocalDeps);
      Deps.insert(LocalDeps.begin(), LocalDeps.end());
    }
  }
}

void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {
  SmallPtrSet<GlobalValue *, 8> Deps;
  for (User *User : GV.users())
    ComputeDependencies(User, Deps);
  Deps.erase(&GV); // Remove self-reference.
  for (GlobalValue *GVU : Deps) {
    // If this is a dep from a vtable to a virtual function, and it's within the
    // range specified in !vcall_visibility, and we have complete information
    // about all virtual call sites which could call though this vtable, then
    // skip it, because the call site information will be more precise.
    if (VFESafeVTablesAndFns.count(GVU) &&
        VFESafeVTablesAndFns[GVU].contains(&GV)) {
      LLVM_DEBUG(dbgs() << "Ignoring dep " << GVU->getName() << " -> "
                        << GV.getName() << "\n");
      continue;
    }
    GVDependencies[GVU].insert(&GV);
  }
}

/// Mark Global value as Live
void GlobalDCEPass::MarkLive(GlobalValue &GV,
                             SmallVectorImpl<GlobalValue *> *Updates) {
  auto const Ret = AliveGlobals.insert(&GV);
  if (!Ret.second)
    return;

  if (Updates)
    Updates->push_back(&GV);
  if (Comdat *C = GV.getComdat()) {
    for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
      MarkLive(*CM.second, Updates); // Recursion depth is only two because only
                                     // globals in the same comdat are visited.
    }
  }
}

void GlobalDCEPass::PropagateLivenessInGlobalValues() {
  // Propagate liveness from collected Global Values through the computed
  // dependencies.
  SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),
                                           AliveGlobals.end()};
  while (!NewLiveGVs.empty()) {
    GlobalValue *LGV = NewLiveGVs.pop_back_val();
    for (auto *GVD : GVDependencies[LGV])
      MarkLive(*GVD, &NewLiveGVs);
  }
}

/// Recursively iterate over the (sub-)constants in the vtable and look for
/// vptrs, if their offset is within [RangeStart..RangeEnd), add them to VFuncs.
static void FindVirtualFunctionsInVTable(Module &M, Constant *C,
                                         uint64_t RangeStart, uint64_t RangeEnd,
                                         SmallPtrSet<GlobalValue *, 8> *VFuncs,
                                         uint64_t BaseOffset = 0) {
  if (auto *GV = dyn_cast<GlobalValue>(C)) {
    if (RangeStart <= BaseOffset && BaseOffset < RangeEnd) {
      if (auto *F = dyn_cast<Function>(GV))
        VFuncs->insert(F);
      else if (auto PAI = GlobalPtrAuthInfo::analyze(GV))
        if (isa<Function>(PAI->getPointer()->stripPointerCasts()))
          VFuncs->insert(GV);
    }

    // Do not recurse outside of the current global.
    return;
  }

  if (auto *S = dyn_cast<ConstantStruct>(C)) {
    StructType *STy = dyn_cast<StructType>(S->getType());
    const StructLayout *SL = M.getDataLayout().getStructLayout(STy);
    for (auto EI : llvm::enumerate(STy->elements())) {
      auto Offset = SL->getElementOffset(EI.index());
      unsigned Op = SL->getElementContainingOffset(Offset);
      FindVirtualFunctionsInVTable(M, cast<Constant>(S->getOperand(Op)),
                                   RangeStart, RangeEnd, VFuncs,
                                   BaseOffset + Offset);
    }
  } else if (auto *A = dyn_cast<ConstantArray>(C)) {
    ArrayType *ATy = A->getType();
    auto EltSize = M.getDataLayout().getTypeAllocSize(ATy->getElementType());
    for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
      FindVirtualFunctionsInVTable(M, cast<Constant>(A->getOperand(i)),
                                   RangeStart, RangeEnd, VFuncs,
                                   BaseOffset + EltSize * i);
    }
  } else {
    for (auto &Op : C->operands()) {
      FindVirtualFunctionsInVTable(M, cast<Constant>(Op), RangeStart, RangeEnd,
                                   VFuncs, BaseOffset);
    }
  }
}

void GlobalDCEPass::ScanVTables(Module &M) {
  SmallVector<MDNode *, 2> Types;
  LLVM_DEBUG(dbgs() << "Building type info -> vtable map\n");

  for (GlobalVariable &GV : M.globals()) {
    Types.clear();
    GV.getMetadata(LLVMContext::MD_type, Types);
    if (GV.isDeclaration() || Types.empty())
      continue;

    // Use the typeid metadata on the vtable to build a mapping from typeids to
    // the list of (GV, offset) pairs which are the possible vtables for that
    // typeid.
    for (MDNode *Type : Types) {
      Metadata *TypeID = Type->getOperand(1).get();

      uint64_t Offset =
          cast<ConstantInt>(
              cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
              ->getZExtValue();

      TypeIdMap[TypeID].insert(std::make_pair(&GV, Offset));
    }

    // If the type corresponding to the vtable is private to this translation
    // unit, we know that we can see all virtual functions which might use it,
    // so VFE is safe.
    if (auto GO = dyn_cast<GlobalObject>(&GV)) {
      GlobalObject::VCallVisibility TypeVis = GO->getVCallVisibility();
      if (TypeVis == GlobalObject::VCallVisibilityTranslationUnit ||
          (InLTOPostLink &&
           TypeVis == GlobalObject::VCallVisibilityLinkageUnit)) {
        LLVM_DEBUG(dbgs() << GV.getName() << " is safe for VFE\n");

        // Find and record all the vfunctions that are within the offset range
        // specified in the !vcall_visibility attribute.
        auto Range = GO->getVTableOffsetRange();
        SmallPtrSet<GlobalValue *, 8> VFuncs;
        FindVirtualFunctionsInVTable(M, GV.getInitializer(), std::get<0>(Range),
                                     std::get<1>(Range), &VFuncs);
        VFESafeVTablesAndFns[&GV] = VFuncs;
      }
    }
  }
}

void GlobalDCEPass::ScanVTableLoad(Function *Caller, Metadata *TypeId,
                                   uint64_t CallOffset) {
  for (const auto &VTableInfo : TypeIdMap[TypeId]) {
    GlobalVariable *VTable = VTableInfo.first;
    uint64_t VTableOffset = VTableInfo.second;

    Constant *Ptr =
        getPointerAtOffset(VTable->getInitializer(), VTableOffset + CallOffset,
                           *Caller->getParent(), VTable);
    if (!Ptr) {
      LLVM_DEBUG(dbgs() << "can't find pointer in vtable!\n");
      VFESafeVTablesAndFns.erase(VTable);
      continue;
    }

    Ptr = Ptr->stripPointerCasts();

    GlobalValue *Callee = dyn_cast<Function>(Ptr);
    if (!Callee)
      if (GlobalPtrAuthInfo::analyze(Ptr))
        Callee = dyn_cast<GlobalValue>(Ptr);

    if (!Callee) {
      LLVM_DEBUG(dbgs() << "vtable entry is not function pointer or a .ptrauth "
                           "global variable!\n");
      VFESafeVTablesAndFns.erase(VTable);
      continue;
    }

    LLVM_DEBUG(dbgs() << "vfunc dep " << Caller->getName() << " -> "
                      << Callee->getName() << "\n");
    GVDependencies[Caller].insert(Callee);
  }
}

void GlobalDCEPass::ScanTypeCheckedLoadIntrinsics(Module &M) {
  LLVM_DEBUG(dbgs() << "Scanning type.checked.load intrinsics\n");
  Function *TypeCheckedLoadFunc =
      M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
  Function *TypeCheckedLoadRelativeFunc =
      M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load_relative));

  auto scan = [&](Function *CheckedLoadFunc) {
    if (!CheckedLoadFunc)
      return;

    for (auto *U : CheckedLoadFunc->users()) {
      auto CI = dyn_cast<CallInst>(U);
      if (!CI)
        continue;

      auto *Offset = dyn_cast<ConstantInt>(CI->getArgOperand(1));
      Value *TypeIdValue = CI->getArgOperand(2);
      auto *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();

      if (Offset) {
        ScanVTableLoad(CI->getFunction(), TypeId, Offset->getZExtValue());
      } else {
        // type.checked.load with a non-constant offset, so assume every entry
        // in every matching vtable is used.
        for (const auto &VTableInfo : TypeIdMap[TypeId]) {
          VFESafeVTablesAndFns.erase(VTableInfo.first);
        }
      }
    }
  };

  scan(TypeCheckedLoadFunc);
  scan(TypeCheckedLoadRelativeFunc);
}

void GlobalDCEPass::AddVirtualFunctionDependencies(Module &M) {
  if (!ClEnableVFE)
    return;

  // If the Virtual Function Elim module flag is present and set to zero, then
  // the vcall_visibility metadata was inserted for another optimization (WPD)
  // and we may not have type checked loads on all accesses to the vtable.
  // Don't attempt VFE in that case.
  auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
      M.getModuleFlag("Virtual Function Elim"));
  if (!Val || Val->isZero())
    return;

  ScanVTables(M);

  if (VFESafeVTablesAndFns.empty())
    return;

  ScanTypeCheckedLoadIntrinsics(M);

  LLVM_DEBUG(dbgs() << "VFE safe vtables:\n";
             for (auto &Entry
                  : VFESafeVTablesAndFns) dbgs()
             << "  " << Entry.first->getName() << "\n";);
}

static bool RemoveConditionalTargetsFromUsedList(Module &M) {
  auto *Used = M.getGlobalVariable("llvm.used");
  if (!Used)
    return false;

  auto *UsedConditional = M.getNamedMetadata("llvm.used.conditional");
  if (!UsedConditional)
    return false;
  if (UsedConditional->getNumOperands() == 0)
    return false;

  // Construct a set of conditionally used targets.
  SmallPtrSet<GlobalValue *, 8> Targets;
  for (auto *M : UsedConditional->operands()) {
    assert(M->getNumOperands() == 3);
    auto *V = mdconst::extract_or_null<GlobalValue>(M->getOperand(0));
    if (!V)
      continue;
    Targets.insert(V);
  }

  if (Targets.empty())
    return false;

  // Now remove all targets from @llvm.used.
  SmallPtrSet<GlobalValue *, 8> NewUsedArray;
  const ConstantArray *UsedList = cast<ConstantArray>(Used->getInitializer());
  for (Value *Op : UsedList->operands()) {
    GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
    if (Targets.contains(G))
      continue;
    NewUsedArray.insert(G);
  }
  Used = setUsedInitializer(*Used, NewUsedArray);
  return true;
}

// Parse one entry from !llvm.used.conditional list as a triplet of
// { target, type, dependencies } and evaluate the conditional dependency, i.e.
// check liveness of all dependencies and based on type conclude whether the
// target is supposed to be declared alive. If yes, return the target, otherwise
// return nullptr.
GlobalValue *GlobalDCEPass::TargetFromConditionalUsedIfLive(MDNode *M) {
  assert(M->getNumOperands() == 3);
  auto *Target = mdconst::extract_or_null<GlobalValue>(M->getOperand(0));
  if (!Target)
    return nullptr;

  auto *DependenciesMD = dyn_cast_or_null<MDNode>(M->getOperand(2).get());
  SmallPtrSet<GlobalValue *, 8> Dependencies;
  if (DependenciesMD == nullptr) {
    Dependencies.insert(nullptr);
  } else {
    for (auto &DependencyMD : DependenciesMD->operands()) {
      auto *Dependency = DependencyMD.get();
      if (!Dependency)
        continue; // Allow null, skip.
      auto *C =
          mdconst::extract_or_null<Constant>(Dependency)->stripPointerCasts();
      if (dyn_cast<UndefValue>(C))
        continue; // Allow undef, skip.
      Dependencies.insert(cast<GlobalValue>(C));
    }
  }

  bool AllDependenciesAlive = Dependencies.empty() ? false : true;
  bool AnyDependencyAlive = false;
  for (auto *Dep : Dependencies) {
    GlobalObject *GlobalObjectDep = dyn_cast<GlobalObject>(Dep);
    bool Live;
    // For the purposes of llvm.used.conditional based stripping,
    // consider all dependencies that are declarations to be live.
    if (GlobalObjectDep && GlobalObjectDep->isDeclaration())
      Live = true;
    else
      Live = AliveGlobals.count(Dep) != 0;
    if (Live)
      AnyDependencyAlive = true;
    else
      AllDependenciesAlive = false;
  }

  auto *Type = mdconst::extract_or_null<ConstantInt>(M->getOperand(1));
  switch (Type->getValue().getSExtValue()) {
  case 0:
    return AnyDependencyAlive ? Target : nullptr;
  case 1:
    return AllDependenciesAlive ? Target : nullptr;
  default:
    llvm_unreachable("bad !llvm.used.conditional type");
  }
}

void GlobalDCEPass::PropagateLivenessToConditionallyUsed(Module &M) {
  auto *Used = M.getGlobalVariable("llvm.used");
  if (!Used)
    return;
  auto *UsedConditional = M.getNamedMetadata("llvm.used.conditional");
  if (!UsedConditional)
    return;

  SmallPtrSet<GlobalValue *, 8> NewUsedArray;
  const ConstantArray *UsedList = cast<ConstantArray>(Used->getInitializer());
  for (Value *Op : UsedList->operands()) {
    NewUsedArray.insert(cast<GlobalValue>(Op->stripPointerCasts()));
  }

  // Repeat the liveness propagation iteraticely, one iteration might force
  // other conditionally used globals to become alive.
  while (true) {
    PropagateLivenessInGlobalValues();

    unsigned OldSize = NewUsedArray.size();
    for (auto *M : UsedConditional->operands()) {
      auto *Target = TargetFromConditionalUsedIfLive(M);
      if (!Target) continue;

      NewUsedArray.insert(Target);
      MarkLive(*Target);
      LLVM_DEBUG(dbgs() << "Conditionally used target alive: "
                        << Target->getName() << "\n");
    }

    unsigned NewSize = NewUsedArray.size();
    LLVM_DEBUG(dbgs() << "Conditionally used iteration end, old size: "
                      << OldSize << " new size: " << NewSize << "\n");

    // Stop the iteration once we reach a steady state (no new additions to
    // @llvm.used).
    if (NewSize == OldSize) break;
  }

  Used = setUsedInitializer(*Used, NewUsedArray);
  MarkLive(*Used);
}

PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) {
  bool Changed = false;

  // The algorithm first computes the set L of global variables that are
  // trivially live.  Then it walks the initialization of these variables to
  // compute the globals used to initialize them, which effectively builds a
  // directed graph where nodes are global variables, and an edge from A to B
  // means B is used to initialize A.  Finally, it propagates the liveness
  // information through the graph starting from the nodes in L. Nodes note
  // marked as alive are discarded.

  // Remove empty functions from the global ctors list.
  Changed |= optimizeGlobalCtorsList(
      M, [](uint32_t, Function *F) { return isEmptyFunction(F); });

  // Collect the set of members for each comdat.
  for (Function &F : M)
    if (Comdat *C = F.getComdat())
      ComdatMembers.insert(std::make_pair(C, &F));
  for (GlobalVariable &GV : M.globals())
    if (Comdat *C = GV.getComdat())
      ComdatMembers.insert(std::make_pair(C, &GV));
  for (GlobalAlias &GA : M.aliases())
    if (Comdat *C = GA.getComdat())
      ComdatMembers.insert(std::make_pair(C, &GA));

  // Add dependencies between virtual call sites and the virtual functions they
  // might call, if we have that information.
  AddVirtualFunctionDependencies(M);

  // Process the !llvm.used.conditional list and (temporarily, see below)
  // remove all "targets" from @llvm.used. No effect if `!llvm.used.conditional`
  // is not present in the module.
  bool UsedConditionalPresent = RemoveConditionalTargetsFromUsedList(M);

  // Loop over the module, adding globals which are obviously necessary.
  for (GlobalObject &GO : M.global_objects()) {
    GO.removeDeadConstantUsers();
    // Functions with external linkage are needed if they have a body.
    // Externally visible & appending globals are needed, if they have an
    // initializer.
    if (!GO.isDeclaration())
      if (!GO.isDiscardableIfUnused())
        MarkLive(GO);

    UpdateGVDependencies(GO);
  }

  // Compute direct dependencies of aliases.
  for (GlobalAlias &GA : M.aliases()) {
    GA.removeDeadConstantUsers();
    // Externally visible aliases are needed.
    if (!GA.isDiscardableIfUnused())
      MarkLive(GA);

    UpdateGVDependencies(GA);
  }

  // Compute direct dependencies of ifuncs.
  for (GlobalIFunc &GIF : M.ifuncs()) {
    GIF.removeDeadConstantUsers();
    // Externally visible ifuncs are needed.
    if (!GIF.isDiscardableIfUnused())
      MarkLive(GIF);

    UpdateGVDependencies(GIF);
  }

  // Step 2 of !llvm.used.conditional processing: If any conditionally used
  // "targets" are alive, put them back into @llvm.used.
  if (UsedConditionalPresent) {
    PropagateLivenessToConditionallyUsed(M);
  }

  PropagateLivenessInGlobalValues();

  // Now that all globals which are needed are in the AliveGlobals set, we loop
  // through the program, deleting those which are not alive.
  //

  // The first pass is to drop initializers of global variables which are dead.
  std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
  for (GlobalVariable &GV : M.globals())
    if (!AliveGlobals.count(&GV)) {
      DeadGlobalVars.push_back(&GV);         // Keep track of dead globals
      if (GV.hasInitializer()) {
        Constant *Init = GV.getInitializer();
        GV.setInitializer(nullptr);
        if (isSafeToDestroyConstant(Init))
          Init->destroyConstant();
      }
    }

  // The second pass drops the bodies of functions which are dead...
  std::vector<Function *> DeadFunctions;
  for (Function &F : M)
    if (!AliveGlobals.count(&F)) {
      DeadFunctions.push_back(&F);         // Keep track of dead globals
      if (!F.isDeclaration())
        F.deleteBody();
    }

  // The third pass drops targets of aliases which are dead...
  std::vector<GlobalAlias*> DeadAliases;
  for (GlobalAlias &GA : M.aliases())
    if (!AliveGlobals.count(&GA)) {
      DeadAliases.push_back(&GA);
      GA.setAliasee(nullptr);
    }

  // The fourth pass drops targets of ifuncs which are dead...
  std::vector<GlobalIFunc*> DeadIFuncs;
  for (GlobalIFunc &GIF : M.ifuncs())
    if (!AliveGlobals.count(&GIF)) {
      DeadIFuncs.push_back(&GIF);
      GIF.setResolver(nullptr);
    }

  // Now that all interferences have been dropped, delete the actual objects
  // themselves.
  auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
    GV->removeDeadConstantUsers();
    GV->eraseFromParent();
    Changed = true;
  };

  NumFunctions += DeadFunctions.size();
  for (Function *F : DeadFunctions) {
    if (!F->use_empty()) {
      // Virtual functions might still be referenced by one or more vtables,
      // but if we've proven them to be unused then it's safe to replace the
      // virtual function pointers with null, allowing us to remove the
      // function itself.
      ++NumVFuncs;

      // Detect vfuncs that are referenced as "relative pointers" which are used
      // in Swift vtables, i.e. entries in the form of:
      //
      //   i32 trunc (i64 sub (i64 ptrtoint @f, i64 ptrtoint ...)) to i32)
      //
      // In this case, replace the whole "sub" expression with constant 0 to
      // avoid leaving a weird sub(0, symbol) expression behind.
      replaceRelativePointerUsersWithZero(F);

      F->replaceNonMetadataUsesWith(ConstantPointerNull::get(F->getType()));
    }
    EraseUnusedGlobalValue(F);
  }

  NumVariables += DeadGlobalVars.size();
  for (GlobalVariable *GV : DeadGlobalVars) {
    if (!GV->use_empty()) {
      // Normally, a vtable only contain Function references that are eliminated
      // by VFE, and their "leftover uses" are handled by the for loop above.
      // But with ptrauth on, we can also get "leftover uses" of GlobalVariables
      // because the vtable references the .ptrauth wrappers instead. So we need
      // to apply the same use-erasing logic as above. The same reasoning as
      // above applies: These are proven to be unused, so they're safe to
      // replace with null.
      GV->replaceNonMetadataUsesWith(ConstantPointerNull::get(GV->getType()));
    }
    EraseUnusedGlobalValue(GV);
  }

  NumAliases += DeadAliases.size();
  for (GlobalAlias *GA : DeadAliases)
    EraseUnusedGlobalValue(GA);

  NumIFuncs += DeadIFuncs.size();
  for (GlobalIFunc *GIF : DeadIFuncs)
    EraseUnusedGlobalValue(GIF);

  // Make sure that all memory is released
  AliveGlobals.clear();
  ConstantDependenciesCache.clear();
  GVDependencies.clear();
  ComdatMembers.clear();
  TypeIdMap.clear();
  VFESafeVTablesAndFns.clear();

  if (Changed)
    return PreservedAnalyses::none();
  return PreservedAnalyses::all();
}

void GlobalDCEPass::printPipeline(
    raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
  static_cast<PassInfoMixin<GlobalDCEPass> *>(this)->printPipeline(
      OS, MapClassName2PassName);
  if (InLTOPostLink)
    OS << "<vfe-linkage-unit-visibility>";
}