Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
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
// Rewrite call/invoke instructions so as to make potential relocations
10
// performed by the garbage collector explicit in the IR.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
15
16
#include "llvm/ADT/ArrayRef.h"
17
#include "llvm/ADT/DenseMap.h"
18
#include "llvm/ADT/DenseSet.h"
19
#include "llvm/ADT/MapVector.h"
20
#include "llvm/ADT/None.h"
21
#include "llvm/ADT/Optional.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/SetVector.h"
24
#include "llvm/ADT/SmallSet.h"
25
#include "llvm/ADT/SmallVector.h"
26
#include "llvm/ADT/StringRef.h"
27
#include "llvm/ADT/iterator_range.h"
28
#include "llvm/Analysis/DomTreeUpdater.h"
29
#include "llvm/Analysis/TargetLibraryInfo.h"
30
#include "llvm/Analysis/TargetTransformInfo.h"
31
#include "llvm/IR/Argument.h"
32
#include "llvm/IR/Attributes.h"
33
#include "llvm/IR/BasicBlock.h"
34
#include "llvm/IR/CallingConv.h"
35
#include "llvm/IR/Constant.h"
36
#include "llvm/IR/Constants.h"
37
#include "llvm/IR/DataLayout.h"
38
#include "llvm/IR/DerivedTypes.h"
39
#include "llvm/IR/Dominators.h"
40
#include "llvm/IR/Function.h"
41
#include "llvm/IR/IRBuilder.h"
42
#include "llvm/IR/InstIterator.h"
43
#include "llvm/IR/InstrTypes.h"
44
#include "llvm/IR/Instruction.h"
45
#include "llvm/IR/Instructions.h"
46
#include "llvm/IR/IntrinsicInst.h"
47
#include "llvm/IR/Intrinsics.h"
48
#include "llvm/IR/LLVMContext.h"
49
#include "llvm/IR/MDBuilder.h"
50
#include "llvm/IR/Metadata.h"
51
#include "llvm/IR/Module.h"
52
#include "llvm/IR/Statepoint.h"
53
#include "llvm/IR/Type.h"
54
#include "llvm/IR/User.h"
55
#include "llvm/IR/Value.h"
56
#include "llvm/IR/ValueHandle.h"
57
#include "llvm/Pass.h"
58
#include "llvm/Support/Casting.h"
59
#include "llvm/Support/CommandLine.h"
60
#include "llvm/Support/Compiler.h"
61
#include "llvm/Support/Debug.h"
62
#include "llvm/Support/ErrorHandling.h"
63
#include "llvm/Support/raw_ostream.h"
64
#include "llvm/Transforms/Scalar.h"
65
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66
#include "llvm/Transforms/Utils/Local.h"
67
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
68
#include <algorithm>
69
#include <cassert>
70
#include <cstddef>
71
#include <cstdint>
72
#include <iterator>
73
#include <set>
74
#include <string>
75
#include <utility>
76
#include <vector>
77
78
#define DEBUG_TYPE "rewrite-statepoints-for-gc"
79
80
using namespace llvm;
81
82
// Print the liveset found at the insert location
83
static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
84
                                  cl::init(false));
85
static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
86
                                      cl::init(false));
87
88
// Print out the base pointers for debugging
89
static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
90
                                       cl::init(false));
91
92
// Cost threshold measuring when it is profitable to rematerialize value instead
93
// of relocating it
94
static cl::opt<unsigned>
95
RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
96
                           cl::init(6));
97
98
#ifdef EXPENSIVE_CHECKS
99
static bool ClobberNonLive = true;
100
#else
101
static bool ClobberNonLive = false;
102
#endif
103
104
static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
105
                                                  cl::location(ClobberNonLive),
106
                                                  cl::Hidden);
107
108
static cl::opt<bool>
109
    AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
110
                                   cl::Hidden, cl::init(true));
111
112
/// The IR fed into RewriteStatepointsForGC may have had attributes and
113
/// metadata implying dereferenceability that are no longer valid/correct after
114
/// RewriteStatepointsForGC has run. This is because semantically, after
115
/// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
116
/// heap. stripNonValidData (conservatively) restores
117
/// correctness by erasing all attributes in the module that externally imply
118
/// dereferenceability. Similar reasoning also applies to the noalias
119
/// attributes and metadata. gc.statepoint can touch the entire heap including
120
/// noalias objects.
121
/// Apart from attributes and metadata, we also remove instructions that imply
122
/// constant physical memory: llvm.invariant.start.
123
static void stripNonValidData(Module &M);
124
125
static bool shouldRewriteStatepointsIn(Function &F);
126
127
PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
128
45
                                               ModuleAnalysisManager &AM) {
129
45
  bool Changed = false;
130
45
  auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
131
402
  for (Function &F : M) {
132
402
    // Nothing to do for declarations.
133
402
    if (F.isDeclaration() || 
F.empty()152
)
134
250
      continue;
135
152
136
152
    // Policy choice says not to rewrite - the most common reason is that we're
137
152
    // compiling code without a GCStrategy.
138
152
    if (!shouldRewriteStatepointsIn(F))
139
8
      continue;
140
144
141
144
    auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
142
144
    auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
143
144
    auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
144
144
    Changed |= runOnFunction(F, DT, TTI, TLI);
145
144
  }
146
45
  if (!Changed)
147
2
    return PreservedAnalyses::all();
148
43
149
43
  // stripNonValidData asserts that shouldRewriteStatepointsIn
150
43
  // returns true for at least one function in the module.  Since at least
151
43
  // one function changed, we know that the precondition is satisfied.
152
43
  stripNonValidData(M);
153
43
154
43
  PreservedAnalyses PA;
155
43
  PA.preserve<TargetIRAnalysis>();
156
43
  PA.preserve<TargetLibraryAnalysis>();
157
43
  return PA;
158
43
}
159
160
namespace {
161
162
class RewriteStatepointsForGCLegacyPass : public ModulePass {
163
  RewriteStatepointsForGC Impl;
164
165
public:
166
  static char ID; // Pass identification, replacement for typeid
167
168
46
  RewriteStatepointsForGCLegacyPass() : ModulePass(ID), Impl() {
169
46
    initializeRewriteStatepointsForGCLegacyPassPass(
170
46
        *PassRegistry::getPassRegistry());
171
46
  }
172
173
46
  bool runOnModule(Module &M) override {
174
46
    bool Changed = false;
175
46
    const TargetLibraryInfo &TLI =
176
46
        getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
177
411
    for (Function &F : M) {
178
411
      // Nothing to do for declarations.
179
411
      if (F.isDeclaration() || 
F.empty()153
)
180
258
        continue;
181
153
182
153
      // Policy choice says not to rewrite - the most common reason is that
183
153
      // we're compiling code without a GCStrategy.
184
153
      if (!shouldRewriteStatepointsIn(F))
185
8
        continue;
186
145
187
145
      TargetTransformInfo &TTI =
188
145
          getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
189
145
      auto &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
190
145
191
145
      Changed |= Impl.runOnFunction(F, DT, TTI, TLI);
192
145
    }
193
46
194
46
    if (!Changed)
195
2
      return false;
196
44
197
44
    // stripNonValidData asserts that shouldRewriteStatepointsIn
198
44
    // returns true for at least one function in the module.  Since at least
199
44
    // one function changed, we know that the precondition is satisfied.
200
44
    stripNonValidData(M);
201
44
    return true;
202
44
  }
203
204
46
  void getAnalysisUsage(AnalysisUsage &AU) const override {
205
46
    // We add and rewrite a bunch of instructions, but don't really do much
206
46
    // else.  We could in theory preserve a lot more analyses here.
207
46
    AU.addRequired<DominatorTreeWrapperPass>();
208
46
    AU.addRequired<TargetTransformInfoWrapperPass>();
209
46
    AU.addRequired<TargetLibraryInfoWrapperPass>();
210
46
  }
211
};
212
213
} // end anonymous namespace
214
215
char RewriteStatepointsForGCLegacyPass::ID = 0;
216
217
0
ModulePass *llvm::createRewriteStatepointsForGCLegacyPass() {
218
0
  return new RewriteStatepointsForGCLegacyPass();
219
0
}
220
221
36.0k
INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass,
222
36.0k
                      "rewrite-statepoints-for-gc",
223
36.0k
                      "Make relocations explicit at statepoints", false, false)
224
36.0k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
225
36.0k
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
226
36.0k
INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass,
227
                    "rewrite-statepoints-for-gc",
228
                    "Make relocations explicit at statepoints", false, false)
229
230
namespace {
231
232
struct GCPtrLivenessData {
233
  /// Values defined in this block.
234
  MapVector<BasicBlock *, SetVector<Value *>> KillSet;
235
236
  /// Values used in this block (and thus live); does not included values
237
  /// killed within this block.
238
  MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
239
240
  /// Values live into this basic block (i.e. used by any
241
  /// instruction in this basic block or ones reachable from here)
242
  MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
243
244
  /// Values live out of this basic block (i.e. live into
245
  /// any successor block)
246
  MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
247
};
248
249
// The type of the internal cache used inside the findBasePointers family
250
// of functions.  From the callers perspective, this is an opaque type and
251
// should not be inspected.
252
//
253
// In the actual implementation this caches two relations:
254
// - The base relation itself (i.e. this pointer is based on that one)
255
// - The base defining value relation (i.e. before base_phi insertion)
256
// Generally, after the execution of a full findBasePointer call, only the
257
// base relation will remain.  Internally, we add a mixture of the two
258
// types, then update all the second type to the first type
259
using DefiningValueMapTy = MapVector<Value *, Value *>;
260
using StatepointLiveSetTy = SetVector<Value *>;
261
using RematerializedValueMapTy =
262
    MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
263
264
struct PartiallyConstructedSafepointRecord {
265
  /// The set of values known to be live across this safepoint
266
  StatepointLiveSetTy LiveSet;
267
268
  /// Mapping from live pointers to a base-defining-value
269
  MapVector<Value *, Value *> PointerToBase;
270
271
  /// The *new* gc.statepoint instruction itself.  This produces the token
272
  /// that normal path gc.relocates and the gc.result are tied to.
273
  Instruction *StatepointToken;
274
275
  /// Instruction to which exceptional gc relocates are attached
276
  /// Makes it easier to iterate through them during relocationViaAlloca.
277
  Instruction *UnwindToken;
278
279
  /// Record live values we are rematerialized instead of relocating.
280
  /// They are not included into 'LiveSet' field.
281
  /// Maps rematerialized copy to it's original value.
282
  RematerializedValueMapTy RematerializedValues;
283
};
284
285
} // end anonymous namespace
286
287
648
static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
288
648
  Optional<OperandBundleUse> DeoptBundle =
289
648
      Call->getOperandBundle(LLVMContext::OB_deopt);
290
648
291
648
  if (!DeoptBundle.hasValue()) {
292
140
    assert(AllowStatepointWithNoDeoptInfo &&
293
140
           "Found non-leaf call without deopt info!");
294
140
    return None;
295
140
  }
296
508
297
508
  return DeoptBundle.getValue().Inputs;
298
508
}
299
300
/// Compute the live-in set for every basic block in the function
301
static void computeLiveInValues(DominatorTree &DT, Function &F,
302
                                GCPtrLivenessData &Data);
303
304
/// Given results from the dataflow liveness computation, find the set of live
305
/// Values at a particular instruction.
306
static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
307
                              StatepointLiveSetTy &out);
308
309
// TODO: Once we can get to the GCStrategy, this becomes
310
// Optional<bool> isGCManagedPointer(const Type *Ty) const override {
311
312
15.9k
static bool isGCPointerType(Type *T) {
313
15.9k
  if (auto *PT = dyn_cast<PointerType>(T))
314
6.99k
    // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
315
6.99k
    // GC managed heap.  We know that a pointer into this heap needs to be
316
6.99k
    // updated and that no other pointer does.
317
6.99k
    return PT->getAddressSpace() == 1;
318
8.97k
  return false;
319
8.97k
}
320
321
// Return true if this type is one which a) is a gc pointer or contains a GC
322
// pointer and b) is of a type this code expects to encounter as a live value.
323
// (The insertion code will assert that a type which matches (a) and not (b)
324
// is not encountered.)
325
15.1k
static bool isHandledGCPointerType(Type *T) {
326
15.1k
  // We fully support gc pointers
327
15.1k
  if (isGCPointerType(T))
328
3.83k
    return true;
329
11.3k
  // We partially support vectors of gc pointers. The code will assert if it
330
11.3k
  // can't handle something.
331
11.3k
  if (auto VT = dyn_cast<VectorType>(T))
332
822
    if (isGCPointerType(VT->getElementType()))
333
768
      return true;
334
10.5k
  return false;
335
10.5k
}
336
337
#ifndef NDEBUG
338
/// Returns true if this type contains a gc pointer whether we know how to
339
/// handle that type or not.
340
static bool containsGCPtrType(Type *Ty) {
341
  if (isGCPointerType(Ty))
342
    return true;
343
  if (VectorType *VT = dyn_cast<VectorType>(Ty))
344
    return isGCPointerType(VT->getScalarType());
345
  if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
346
    return containsGCPtrType(AT->getElementType());
347
  if (StructType *ST = dyn_cast<StructType>(Ty))
348
    return llvm::any_of(ST->elements(), containsGCPtrType);
349
  return false;
350
}
351
352
// Returns true if this is a type which a) is a gc pointer or contains a GC
353
// pointer and b) is of a type which the code doesn't expect (i.e. first class
354
// aggregates).  Used to trip assertions.
355
static bool isUnhandledGCPointerType(Type *Ty) {
356
  return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
357
}
358
#endif
359
360
// Return the name of the value suffixed with the provided value, or if the
361
// value didn't have a name, the default value specified.
362
static std::string suffixed_name_or(Value *V, StringRef Suffix,
363
1.02k
                                    StringRef DefaultName) {
364
1.02k
  return V->hasName() ? 
(V->getName() + Suffix).str()1.01k
:
DefaultName.str()4
;
365
1.02k
}
366
367
// Conservatively identifies any definitions which might be live at the
368
// given instruction. The  analysis is performed immediately before the
369
// given instruction. Values defined by that instruction are not considered
370
// live.  Values used by that instruction are considered live.
371
static void analyzeParsePointLiveness(
372
    DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
373
324
    PartiallyConstructedSafepointRecord &Result) {
374
324
  StatepointLiveSetTy LiveSet;
375
324
  findLiveSetAtInst(Call, OriginalLivenessData, LiveSet);
376
324
377
324
  if (PrintLiveSet) {
378
0
    dbgs() << "Live Variables:\n";
379
0
    for (Value *V : LiveSet)
380
0
      dbgs() << " " << V->getName() << " " << *V << "\n";
381
0
  }
382
324
  if (PrintLiveSetSize) {
383
0
    dbgs() << "Safepoint For: " << Call->getCalledValue()->getName() << "\n";
384
0
    dbgs() << "Number live values: " << LiveSet.size() << "\n";
385
0
  }
386
324
  Result.LiveSet = LiveSet;
387
324
}
388
389
static bool isKnownBaseResult(Value *V);
390
391
namespace {
392
393
/// A single base defining value - An immediate base defining value for an
394
/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
395
/// For instructions which have multiple pointer [vector] inputs or that
396
/// transition between vector and scalar types, there is no immediate base
397
/// defining value.  The 'base defining value' for 'Def' is the transitive
398
/// closure of this relation stopping at the first instruction which has no
399
/// immediate base defining value.  The b.d.v. might itself be a base pointer,
400
/// but it can also be an arbitrary derived pointer.
401
struct BaseDefiningValueResult {
402
  /// Contains the value which is the base defining value.
403
  Value * const BDV;
404
405
  /// True if the base defining value is also known to be an actual base
406
  /// pointer.
407
  const bool IsKnownBase;
408
409
  BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
410
561
    : BDV(BDV), IsKnownBase(IsKnownBase) {
411
#ifndef NDEBUG
412
    // Check consistency between new and old means of checking whether a BDV is
413
    // a base.
414
    bool MustBeBase = isKnownBaseResult(BDV);
415
    assert(!MustBeBase || MustBeBase == IsKnownBase);
416
#endif
417
  }
418
};
419
420
} // end anonymous namespace
421
422
static BaseDefiningValueResult findBaseDefiningValue(Value *I);
423
424
/// Return a base defining value for the 'Index' element of the given vector
425
/// instruction 'I'.  If Index is null, returns a BDV for the entire vector
426
/// 'I'.  As an optimization, this method will try to determine when the
427
/// element is known to already be a base pointer.  If this can be established,
428
/// the second value in the returned pair will be true.  Note that either a
429
/// vector or a pointer typed value can be returned.  For the former, the
430
/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
431
/// If the later, the return pointer is a BDV (or possibly a base) for the
432
/// particular element in 'I'.
433
static BaseDefiningValueResult
434
137
findBaseDefiningValueOfVector(Value *I) {
435
137
  // Each case parallels findBaseDefiningValue below, see that code for
436
137
  // detailed motivation.
437
137
438
137
  if (isa<Argument>(I))
439
18
    // An incoming argument to the function is a base pointer
440
18
    return BaseDefiningValueResult(I, true);
441
119
442
119
  if (isa<Constant>(I))
443
31
    // Base of constant vector consists only of constant null pointers.
444
31
    // For reasoning see similar case inside 'findBaseDefiningValue' function.
445
31
    return BaseDefiningValueResult(ConstantAggregateZero::get(I->getType()),
446
31
                                   true);
447
88
448
88
  if (isa<LoadInst>(I))
449
12
    return BaseDefiningValueResult(I, true);
450
76
451
76
  if (isa<InsertElementInst>(I))
452
32
    // We don't know whether this vector contains entirely base pointers or
453
32
    // not.  To be conservatively correct, we treat it as a BDV and will
454
32
    // duplicate code as needed to construct a parallel vector of bases.
455
32
    return BaseDefiningValueResult(I, false);
456
44
457
44
  if (isa<ShuffleVectorInst>(I))
458
12
    // We don't know whether this vector contains entirely base pointers or
459
12
    // not.  To be conservatively correct, we treat it as a BDV and will
460
12
    // duplicate code as needed to construct a parallel vector of bases.
461
12
    // TODO: There a number of local optimizations which could be applied here
462
12
    // for particular sufflevector patterns.
463
12
    return BaseDefiningValueResult(I, false);
464
32
465
32
  // The behavior of getelementptr instructions is the same for vector and
466
32
  // non-vector data types.
467
32
  if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
468
12
    return findBaseDefiningValue(GEP->getPointerOperand());
469
20
470
20
  // If the pointer comes through a bitcast of a vector of pointers to
471
20
  // a vector of another type of pointer, then look through the bitcast
472
20
  if (auto *BC = dyn_cast<BitCastInst>(I))
473
6
    return findBaseDefiningValue(BC->getOperand(0));
474
14
475
14
  // We assume that functions in the source language only return base
476
14
  // pointers.  This should probably be generalized via attributes to support
477
14
  // both source language and internal functions.
478
14
  if (isa<CallInst>(I) || 
isa<InvokeInst>(I)12
)
479
2
    return BaseDefiningValueResult(I, true);
480
12
481
12
  // A PHI or Select is a base defining value.  The outer findBasePointer
482
12
  // algorithm is responsible for constructing a base value for this BDV.
483
12
  assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
484
12
         "unknown vector instruction - no base found for vector element");
485
12
  return BaseDefiningValueResult(I, false);
486
12
}
487
488
/// Helper function for findBasePointer - Will return a value which either a)
489
/// defines the base pointer for the input, b) blocks the simple search
490
/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
491
/// from pointer to vector type or back.
492
761
static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
493
761
  assert(I->getType()->isPtrOrPtrVectorTy() &&
494
761
         "Illegal to ask for the base pointer of a non-pointer type");
495
761
496
761
  if (I->getType()->isVectorTy())
497
137
    return findBaseDefiningValueOfVector(I);
498
624
499
624
  if (isa<Argument>(I))
500
265
    // An incoming argument to the function is a base pointer
501
265
    // We should have never reached here if this argument isn't an gc value
502
265
    return BaseDefiningValueResult(I, true);
503
359
504
359
  if (isa<Constant>(I)) {
505
26
    // We assume that objects with a constant base (e.g. a global) can't move
506
26
    // and don't need to be reported to the collector because they are always
507
26
    // live. Besides global references, all kinds of constants (e.g. undef,
508
26
    // constant expressions, null pointers) can be introduced by the inliner or
509
26
    // the optimizer, especially on dynamically dead paths.
510
26
    // Here we treat all of them as having single null base. By doing this we
511
26
    // trying to avoid problems reporting various conflicts in a form of
512
26
    // "phi (const1, const2)" or "phi (const, regular gc ptr)".
513
26
    // See constant.ll file for relevant test cases.
514
26
515
26
    return BaseDefiningValueResult(
516
26
        ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
517
26
  }
518
333
519
333
  if (CastInst *CI = dyn_cast<CastInst>(I)) {
520
40
    Value *Def = CI->stripPointerCasts();
521
40
    // If stripping pointer casts changes the address space there is an
522
40
    // addrspacecast in between.
523
40
    assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
524
40
               cast<PointerType>(CI->getType())->getAddressSpace() &&
525
40
           "unsupported addrspacecast");
526
40
    // If we find a cast instruction here, it means we've found a cast which is
527
40
    // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
528
40
    // handle int->ptr conversion.
529
40
    assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
530
40
    return findBaseDefiningValue(Def);
531
40
  }
532
293
533
293
  if (isa<LoadInst>(I))
534
8
    // The value loaded is an gc base itself
535
8
    return BaseDefiningValueResult(I, true);
536
285
537
285
  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
538
142
    // The base of this GEP is the base
539
142
    return findBaseDefiningValue(GEP->getPointerOperand());
540
143
541
143
  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
542
0
    switch (II->getIntrinsicID()) {
543
0
    default:
544
0
      // fall through to general call handling
545
0
      break;
546
0
    case Intrinsic::experimental_gc_statepoint:
547
0
      llvm_unreachable("statepoints don't produce pointers");
548
0
    case Intrinsic::experimental_gc_relocate:
549
0
      // Rerunning safepoint insertion after safepoints are already
550
0
      // inserted is not supported.  It could probably be made to work,
551
0
      // but why are you doing this?  There's no good reason.
552
0
      llvm_unreachable("repeat safepoint insertion is not supported");
553
0
    case Intrinsic::gcroot:
554
0
      // Currently, this mechanism hasn't been extended to work with gcroot.
555
0
      // There's no reason it couldn't be, but I haven't thought about the
556
0
      // implications much.
557
0
      llvm_unreachable(
558
143
          "interaction with the gcroot mechanism is not supported");
559
143
    }
560
143
  }
561
143
  // We assume that functions in the source language only return base
562
143
  // pointers.  This should probably be generalized via attributes to support
563
143
  // both source language and internal functions.
564
143
  if (isa<CallInst>(I) || 
isa<InvokeInst>(I)115
)
565
32
    return BaseDefiningValueResult(I, true);
566
111
567
111
  // TODO: I have absolutely no idea how to implement this part yet.  It's not
568
111
  // necessarily hard, I just haven't really looked at it yet.
569
111
  assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
570
111
571
111
  if (isa<AtomicCmpXchgInst>(I))
572
0
    // A CAS is effectively a atomic store and load combined under a
573
0
    // predicate.  From the perspective of base pointers, we just treat it
574
0
    // like a load.
575
0
    return BaseDefiningValueResult(I, true);
576
111
577
111
  assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
578
111
                                   "binary ops which don't apply to pointers");
579
111
580
111
  // The aggregate ops.  Aggregates can either be in the heap or on the
581
111
  // stack, but in either case, this is simply a field load.  As a result,
582
111
  // this is a defining definition of the base just like a load is.
583
111
  if (isa<ExtractValueInst>(I))
584
0
    return BaseDefiningValueResult(I, true);
585
111
586
111
  // We should never see an insert vector since that would require we be
587
111
  // tracing back a struct value not a pointer value.
588
111
  assert(!isa<InsertValueInst>(I) &&
589
111
         "Base pointer for a struct is meaningless");
590
111
591
111
  // An extractelement produces a base result exactly when it's input does.
592
111
  // We may need to insert a parallel instruction to extract the appropriate
593
111
  // element out of the base vector corresponding to the input. Given this,
594
111
  // it's analogous to the phi and select case even though it's not a merge.
595
111
  if (isa<ExtractElementInst>(I))
596
32
    // Note: There a lot of obvious peephole cases here.  This are deliberately
597
32
    // handled after the main base pointer inference algorithm to make writing
598
32
    // test cases to exercise that code easier.
599
32
    return BaseDefiningValueResult(I, false);
600
79
601
79
  // The last two cases here don't return a base pointer.  Instead, they
602
79
  // return a value which dynamically selects from among several base
603
79
  // derived pointers (each with it's own base potentially).  It's the job of
604
79
  // the caller to resolve these.
605
79
  assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
606
79
         "missing instruction case in findBaseDefiningValing");
607
79
  return BaseDefiningValueResult(I, false);
608
79
}
609
610
/// Returns the base defining value for this value.
611
1.78k
static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
612
1.78k
  Value *&Cached = Cache[I];
613
1.78k
  if (!Cached) {
614
561
    Cached = findBaseDefiningValue(I).BDV;
615
561
    LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
616
561
                      << Cached->getName() << "\n");
617
561
  }
618
1.78k
  assert(Cache[I] != nullptr);
619
1.78k
  return Cached;
620
1.78k
}
621
622
/// Return a base pointer for this value if known.  Otherwise, return it's
623
/// base defining value.
624
1.78k
static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
625
1.78k
  Value *Def = findBaseDefiningValueCached(I, Cache);
626
1.78k
  auto Found = Cache.find(Def);
627
1.78k
  if (Found != Cache.end()) {
628
1.10k
    // Either a base-of relation, or a self reference.  Caller must check.
629
1.10k
    return Found->second;
630
1.10k
  }
631
684
  // Only a BDV available
632
684
  return Def;
633
684
}
634
635
/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
636
/// is it known to be a base pointer?  Or do we need to continue searching.
637
1.78k
static bool isKnownBaseResult(Value *V) {
638
1.78k
  if (!isa<PHINode>(V) && 
!isa<SelectInst>(V)1.54k
&&
639
1.78k
      
!isa<ExtractElementInst>(V)1.51k
&&
!isa<InsertElementInst>(V)1.44k
&&
640
1.78k
      
!isa<ShuffleVectorInst>(V)1.25k
) {
641
1.17k
    // no recursion possible
642
1.17k
    return true;
643
1.17k
  }
644
612
  if (isa<Instruction>(V) &&
645
612
      cast<Instruction>(V)->getMetadata("is_base_value")) {
646
16
    // This is a previously inserted base phi or select.  We know
647
16
    // that this is a base value.
648
16
    return true;
649
16
  }
650
596
651
596
  // We need to keep searching
652
596
  return false;
653
596
}
654
655
namespace {
656
657
/// Models the state of a single base defining value in the findBasePointer
658
/// algorithm for determining where a new instruction is needed to propagate
659
/// the base of this BDV.
660
class BDVState {
661
public:
662
  enum Status { Unknown, Base, Conflict };
663
664
698
  BDVState() : BaseValue(nullptr) {}
665
666
  explicit BDVState(Status Status, Value *BaseValue = nullptr)
667
342
      : Status(Status), BaseValue(BaseValue) {
668
342
    assert(Status != Base || BaseValue);
669
342
  }
670
671
587
  explicit BDVState(Value *BaseValue) : Status(Base), BaseValue(BaseValue) {}
672
673
2.00k
  Status getStatus() const { return Status; }
674
1.08k
  Value *getBaseValue() const { return BaseValue; }
675
676
443
  bool isBase() const { return getStatus() == Base; }
677
306
  bool isUnknown() const { return getStatus() == Unknown; }
678
322
  bool isConflict() const { return getStatus() == Conflict; }
679
680
510
  bool operator==(const BDVState &Other) const {
681
510
    return BaseValue == Other.BaseValue && 
Status == Other.Status416
;
682
510
  }
683
684
510
  bool operator!=(const BDVState &other) const { return !(*this == other); }
685
686
  LLVM_DUMP_METHOD
687
0
  void dump() const {
688
0
    print(dbgs());
689
0
    dbgs() << '\n';
690
0
  }
691
692
0
  void print(raw_ostream &OS) const {
693
0
    switch (getStatus()) {
694
0
    case Unknown:
695
0
      OS << "U";
696
0
      break;
697
0
    case Base:
698
0
      OS << "B";
699
0
      break;
700
0
    case Conflict:
701
0
      OS << "C";
702
0
      break;
703
0
    }
704
0
    OS << " (" << getBaseValue() << " - "
705
0
       << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << "): ";
706
0
  }
707
708
private:
709
  Status Status = Unknown;
710
  AssertingVH<Value> BaseValue; // Non-null only if Status == Base.
711
};
712
713
} // end anonymous namespace
714
715
#ifndef NDEBUG
716
static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
717
  State.print(OS);
718
  return OS;
719
}
720
#endif
721
722
929
static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS) {
723
929
  switch (LHS.getStatus()) {
724
929
  case BDVState::Unknown:
725
546
    return RHS;
726
929
727
929
  case BDVState::Base:
728
306
    assert(LHS.getBaseValue() && "can't be null");
729
306
    if (RHS.isUnknown())
730
24
      return LHS;
731
282
732
282
    if (RHS.isBase()) {
733
266
      if (LHS.getBaseValue() == RHS.getBaseValue()) {
734
68
        assert(LHS == RHS && "equality broken!");
735
68
        return LHS;
736
68
      }
737
198
      return BDVState(BDVState::Conflict);
738
198
    }
739
16
    assert(RHS.isConflict() && "only three states!");
740
16
    return BDVState(BDVState::Conflict);
741
16
742
77
  case BDVState::Conflict:
743
77
    return LHS;
744
0
  }
745
0
  llvm_unreachable("only three states!");
746
0
}
747
748
// Values of type BDVState form a lattice, and this function implements the meet
749
// operation.
750
929
static BDVState meetBDVState(const BDVState &LHS, const BDVState &RHS) {
751
929
  BDVState Result = meetBDVStateImpl(LHS, RHS);
752
929
  assert(Result == meetBDVStateImpl(RHS, LHS) &&
753
929
         "Math is wrong: meet does not commute!");
754
929
  return Result;
755
929
}
756
757
/// For a given value or instruction, figure out what base ptr its derived from.
758
/// For gc objects, this is simply itself.  On success, returns a value which is
759
/// the base pointer.  (This is reliable and can be used for relocation.)  On
760
/// failure, returns nullptr.
761
342
static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
762
342
  Value *Def = findBaseOrBDV(I, Cache);
763
342
764
342
  if (isKnownBaseResult(Def))
765
246
    return Def;
766
96
767
96
  // Here's the rough algorithm:
768
96
  // - For every SSA value, construct a mapping to either an actual base
769
96
  //   pointer or a PHI which obscures the base pointer.
770
96
  // - Construct a mapping from PHI to unknown TOP state.  Use an
771
96
  //   optimistic algorithm to propagate base pointer information.  Lattice
772
96
  //   looks like:
773
96
  //   UNKNOWN
774
96
  //   b1 b2 b3 b4
775
96
  //   CONFLICT
776
96
  //   When algorithm terminates, all PHIs will either have a single concrete
777
96
  //   base or be in a conflict state.
778
96
  // - For every conflict, insert a dummy PHI node without arguments.  Add
779
96
  //   these to the base[Instruction] = BasePtr mapping.  For every
780
96
  //   non-conflict, add the actual base.
781
96
  //  - For every conflict, add arguments for the base[a] of each input
782
96
  //   arguments.
783
96
  //
784
96
  // Note: A simpler form of this would be to add the conflict form of all
785
96
  // PHIs without running the optimistic algorithm.  This would be
786
96
  // analogous to pessimistic data flow and would likely lead to an
787
96
  // overall worse solution.
788
96
789
#ifndef NDEBUG
790
  auto isExpectedBDVType = [](Value *BDV) {
791
    return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
792
           isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
793
           isa<ShuffleVectorInst>(BDV);
794
  };
795
#endif
796
797
96
  // Once populated, will contain a mapping from each potentially non-base BDV
798
96
  // to a lattice value (described above) which corresponds to that BDV.
799
96
  // We use the order of insertion (DFS over the def/use graph) to provide a
800
96
  // stable deterministic ordering for visiting DenseMaps (which are unordered)
801
96
  // below.  This is important for deterministic compilation.
802
96
  MapVector<Value *, BDVState> States;
803
96
804
96
  // Recursively fill in all base defining values reachable from the initial
805
96
  // one for which we don't already know a definite base value for
806
96
  /* scope */ {
807
96
    SmallVector<Value*, 16> Worklist;
808
96
    Worklist.push_back(Def);
809
96
    States.insert({Def, BDVState()});
810
257
    while (!Worklist.empty()) {
811
161
      Value *Current = Worklist.pop_back_val();
812
161
      assert(!isKnownBaseResult(Current) && "why did it get added?");
813
161
814
298
      auto visitIncomingValue = [&](Value *InVal) {
815
298
        Value *Base = findBaseOrBDV(InVal, Cache);
816
298
        if (isKnownBaseResult(Base))
817
206
          // Known bases won't need new instructions introduced and can be
818
206
          // ignored safely
819
206
          return;
820
92
        assert(isExpectedBDVType(Base) && "the only non-base values "
821
92
               "we see should be base defining values");
822
92
        if (States.insert(std::make_pair(Base, BDVState())).second)
823
65
          Worklist.push_back(Base);
824
92
      };
825
161
      if (PHINode *PN = dyn_cast<PHINode>(Current)) {
826
71
        for (Value *InVal : PN->incoming_values())
827
150
          visitIncomingValue(InVal);
828
90
      } else if (SelectInst *SI = dyn_cast<SelectInst>(Current)) {
829
14
        visitIncomingValue(SI->getTrueValue());
830
14
        visitIncomingValue(SI->getFalseValue());
831
76
      } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
832
32
        visitIncomingValue(EE->getVectorOperand());
833
44
      } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
834
32
        visitIncomingValue(IE->getOperand(0)); // vector operand
835
32
        visitIncomingValue(IE->getOperand(1)); // scalar operand
836
32
      } else 
if (auto *12
SV12
= dyn_cast<ShuffleVectorInst>(Current)) {
837
12
        visitIncomingValue(SV->getOperand(0));
838
12
        visitIncomingValue(SV->getOperand(1));
839
12
      }
840
0
      else {
841
0
        llvm_unreachable("Unimplemented instruction case");
842
0
      }
843
161
    }
844
96
  }
845
96
846
#ifndef NDEBUG
847
  LLVM_DEBUG(dbgs() << "States after initialization:\n");
848
  for (auto Pair : States) {
849
    LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
850
  }
851
#endif
852
853
96
  // Return a phi state for a base defining value.  We'll generate a new
854
96
  // base state for known bases and expect to find a cached state otherwise.
855
929
  
auto getStateForBDV = [&](Value *baseValue) 96
{
856
929
    if (isKnownBaseResult(baseValue))
857
587
      return BDVState(baseValue);
858
342
    auto I = States.find(baseValue);
859
342
    assert(I != States.end() && "lookup failed!");
860
342
    return I->second;
861
342
  };
862
96
863
96
  bool Progress = true;
864
345
  while (Progress) {
865
#ifndef NDEBUG
866
    const size_t OldSize = States.size();
867
#endif
868
    Progress = false;
869
249
    // We're only changing values in this loop, thus safe to keep iterators.
870
249
    // Since this is computing a fixed point, the order of visit does not
871
249
    // effect the result.  TODO: We could use a worklist here and make this run
872
249
    // much faster.
873
510
    for (auto Pair : States) {
874
510
      Value *BDV = Pair.first;
875
510
      assert(!isKnownBaseResult(BDV) && "why did it get added?");
876
510
877
510
      // Given an input value for the current instruction, return a BDVState
878
510
      // instance which represents the BDV of that value.
879
929
      auto getStateForInput = [&](Value *V) mutable {
880
929
        Value *BDV = findBaseOrBDV(V, Cache);
881
929
        return getStateForBDV(BDV);
882
929
      };
883
510
884
510
      BDVState NewState;
885
510
      if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
886
32
        NewState = meetBDVState(NewState, getStateForInput(SI->getTrueValue()));
887
32
        NewState =
888
32
            meetBDVState(NewState, getStateForInput(SI->getFalseValue()));
889
478
      } else if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
890
191
        for (Value *Val : PN->incoming_values())
891
404
          NewState = meetBDVState(NewState, getStateForInput(Val));
892
287
      } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
893
113
        // The 'meet' for an extractelement is slightly trivial, but it's still
894
113
        // useful in that it drives us to conflict if our input is.
895
113
        NewState =
896
113
            meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
897
174
      } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)){
898
126
        // Given there's a inherent type mismatch between the operands, will
899
126
        // *always* produce Conflict.
900
126
        NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(0)));
901
126
        NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(1)));
902
126
      } else {
903
48
        // The only instance this does not return a Conflict is when both the
904
48
        // vector operands are the same vector.
905
48
        auto *SV = cast<ShuffleVectorInst>(BDV);
906
48
        NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
907
48
        NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
908
48
      }
909
510
910
510
      BDVState OldState = States[BDV];
911
510
      if (OldState != NewState) {
912
187
        Progress = true;
913
187
        States[BDV] = NewState;
914
187
      }
915
510
    }
916
249
917
249
    assert(OldSize == States.size() &&
918
249
           "fixed point shouldn't be adding any new nodes to state");
919
249
  }
920
96
921
#ifndef NDEBUG
922
  LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
923
  for (auto Pair : States) {
924
    LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
925
  }
926
#endif
927
928
96
  // Insert Phis for all conflicts
929
96
  // TODO: adjust naming patterns to avoid this order of iteration dependency
930
161
  for (auto Pair : States) {
931
161
    Instruction *I = cast<Instruction>(Pair.first);
932
161
    BDVState State = Pair.second;
933
161
    assert(!isKnownBaseResult(I) && "why did it get added?");
934
161
    assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
935
161
936
161
    // extractelement instructions are a bit special in that we may need to
937
161
    // insert an extract even when we know an exact base for the instruction.
938
161
    // The problem is that we need to convert from a vector base to a scalar
939
161
    // base for the particular indice we're interested in.
940
161
    if (State.isBase() && 
isa<ExtractElementInst>(I)42
&&
941
161
        
isa<VectorType>(State.getBaseValue()->getType())9
) {
942
9
      auto *EE = cast<ExtractElementInst>(I);
943
9
      // TODO: In many cases, the new instruction is just EE itself.  We should
944
9
      // exploit this, but can't do it here since it would break the invariant
945
9
      // about the BDV not being known to be a base.
946
9
      auto *BaseInst = ExtractElementInst::Create(
947
9
          State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
948
9
      BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
949
9
      States[I] = BDVState(BDVState::Base, BaseInst);
950
9
    }
951
161
952
161
    // Since we're joining a vector and scalar base, they can never be the
953
161
    // same.  As a result, we should always see insert element having reached
954
161
    // the conflict state.
955
161
    assert(!isa<InsertElementInst>(I) || State.isConflict());
956
161
957
161
    if (!State.isConflict())
958
42
      continue;
959
119
960
119
    /// Create and insert a new instruction which will represent the base of
961
119
    /// the given instruction 'I'.
962
119
    auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
963
119
      if (isa<PHINode>(I)) {
964
48
        BasicBlock *BB = I->getParent();
965
48
        int NumPreds = pred_size(BB);
966
48
        assert(NumPreds > 0 && "how did we reach here");
967
48
        std::string Name = suffixed_name_or(I, ".base", "base_phi");
968
48
        return PHINode::Create(I->getType(), NumPreds, Name, I);
969
71
      } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
970
6
        // The undef will be replaced later
971
6
        UndefValue *Undef = UndefValue::get(SI->getType());
972
6
        std::string Name = suffixed_name_or(I, ".base", "base_select");
973
6
        return SelectInst::Create(SI->getCondition(), Undef, Undef, Name, SI);
974
65
      } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
975
23
        UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
976
23
        std::string Name = suffixed_name_or(I, ".base", "base_ee");
977
23
        return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
978
23
                                          EE);
979
42
      } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
980
32
        UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
981
32
        UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
982
32
        std::string Name = suffixed_name_or(I, ".base", "base_ie");
983
32
        return InsertElementInst::Create(VecUndef, ScalarUndef,
984
32
                                         IE->getOperand(2), Name, IE);
985
32
      } else {
986
10
        auto *SV = cast<ShuffleVectorInst>(I);
987
10
        UndefValue *VecUndef = UndefValue::get(SV->getOperand(0)->getType());
988
10
        std::string Name = suffixed_name_or(I, ".base", "base_sv");
989
10
        return new ShuffleVectorInst(VecUndef, VecUndef, SV->getOperand(2),
990
10
                                     Name, SV);
991
10
      }
992
119
    };
993
119
    Instruction *BaseInst = MakeBaseInstPlaceholder(I);
994
119
    // Add metadata marking this as a base value
995
119
    BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
996
119
    States[I] = BDVState(BDVState::Conflict, BaseInst);
997
119
  }
998
96
999
96
  // Returns a instruction which produces the base pointer for a given
1000
96
  // instruction.  The instruction is assumed to be an input to one of the BDVs
1001
96
  // seen in the inference algorithm above.  As such, we must either already
1002
96
  // know it's base defining value is a base, or have inserted a new
1003
96
  // instruction to propagate the base of it's BDV and have entered that newly
1004
96
  // introduced instruction into the state table.  In either case, we are
1005
96
  // assured to be able to determine an instruction which produces it's base
1006
96
  // pointer.
1007
219
  auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
1008
219
    Value *BDV = findBaseOrBDV(Input, Cache);
1009
219
    Value *Base = nullptr;
1010
219
    if (isKnownBaseResult(BDV)) {
1011
153
      Base = BDV;
1012
153
    } else {
1013
66
      // Either conflict or base.
1014
66
      assert(States.count(BDV));
1015
66
      Base = States[BDV].getBaseValue();
1016
66
    }
1017
219
    assert(Base && "Can't be null");
1018
219
    // The cast is needed since base traversal may strip away bitcasts
1019
219
    if (Base->getType() != Input->getType() && 
InsertPt12
)
1020
12
      Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
1021
219
    return Base;
1022
219
  };
1023
96
1024
96
  // Fixup all the inputs of the new PHIs.  Visit order needs to be
1025
96
  // deterministic and predictable because we're naming newly created
1026
96
  // instructions.
1027
161
  for (auto Pair : States) {
1028
161
    Instruction *BDV = cast<Instruction>(Pair.first);
1029
161
    BDVState State = Pair.second;
1030
161
1031
161
    assert(!isKnownBaseResult(BDV) && "why did it get added?");
1032
161
    assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1033
161
    if (!State.isConflict())
1034
42
      continue;
1035
119
1036
119
    if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
1037
48
      PHINode *PN = cast<PHINode>(BDV);
1038
48
      unsigned NumPHIValues = PN->getNumIncomingValues();
1039
152
      for (unsigned i = 0; i < NumPHIValues; 
i++104
) {
1040
104
        Value *InVal = PN->getIncomingValue(i);
1041
104
        BasicBlock *InBB = PN->getIncomingBlock(i);
1042
104
1043
104
        // If we've already seen InBB, add the same incoming value
1044
104
        // we added for it earlier.  The IR verifier requires phi
1045
104
        // nodes with multiple entries from the same basic block
1046
104
        // to have the same incoming value for each of those
1047
104
        // entries.  If we don't do this check here and basephi
1048
104
        // has a different type than base, we'll end up adding two
1049
104
        // bitcasts (and hence two distinct values) as incoming
1050
104
        // values for the same basic block.
1051
104
1052
104
        int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
1053
104
        if (BlockIndex != -1) {
1054
4
          Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
1055
4
          BasePHI->addIncoming(OldBase, InBB);
1056
4
1057
#ifndef NDEBUG
1058
          Value *Base = getBaseForInput(InVal, nullptr);
1059
          // In essence this assert states: the only way two values
1060
          // incoming from the same basic block may be different is by
1061
          // being different bitcasts of the same value.  A cleanup
1062
          // that remains TODO is changing findBaseOrBDV to return an
1063
          // llvm::Value of the correct type (and still remain pure).
1064
          // This will remove the need to add bitcasts.
1065
          assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
1066
                 "Sanity -- findBaseOrBDV should be pure!");
1067
#endif
1068
          continue;
1069
4
        }
1070
100
1071
100
        // Find the instruction which produces the base for each input.  We may
1072
100
        // need to insert a bitcast in the incoming block.
1073
100
        // TODO: Need to split critical edges if insertion is needed
1074
100
        Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1075
100
        BasePHI->addIncoming(Base, InBB);
1076
100
      }
1077
48
      assert(BasePHI->getNumIncomingValues() == NumPHIValues);
1078
71
    } else if (SelectInst *BaseSI =
1079
6
                   dyn_cast<SelectInst>(State.getBaseValue())) {
1080
6
      SelectInst *SI = cast<SelectInst>(BDV);
1081
6
1082
6
      // Find the instruction which produces the base for each input.
1083
6
      // We may need to insert a bitcast.
1084
6
      BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1085
6
      BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
1086
65
    } else if (auto *BaseEE =
1087
23
                   dyn_cast<ExtractElementInst>(State.getBaseValue())) {
1088
23
      Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
1089
23
      // Find the instruction which produces the base for each input.  We may
1090
23
      // need to insert a bitcast.
1091
23
      BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1092
42
    } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
1093
32
      auto *BdvIE = cast<InsertElementInst>(BDV);
1094
64
      auto UpdateOperand = [&](int OperandIdx) {
1095
64
        Value *InVal = BdvIE->getOperand(OperandIdx);
1096
64
        Value *Base = getBaseForInput(InVal, BaseIE);
1097
64
        BaseIE->setOperand(OperandIdx, Base);
1098
64
      };
1099
32
      UpdateOperand(0); // vector operand
1100
32
      UpdateOperand(1); // scalar operand
1101
32
    } else {
1102
10
      auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1103
10
      auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1104
20
      auto UpdateOperand = [&](int OperandIdx) {
1105
20
        Value *InVal = BdvSV->getOperand(OperandIdx);
1106
20
        Value *Base = getBaseForInput(InVal, BaseSV);
1107
20
        BaseSV->setOperand(OperandIdx, Base);
1108
20
      };
1109
10
      UpdateOperand(0); // vector operand
1110
10
      UpdateOperand(1); // vector operand
1111
10
    }
1112
119
  }
1113
96
1114
96
  // Cache all of our results so we can cheaply reuse them
1115
96
  // NOTE: This is actually two caches: one of the base defining value
1116
96
  // relation and one of the base pointer relation!  FIXME
1117
161
  for (auto Pair : States) {
1118
161
    auto *BDV = Pair.first;
1119
161
    Value *Base = Pair.second.getBaseValue();
1120
161
    assert(BDV && Base);
1121
161
    assert(!isKnownBaseResult(BDV) && "why did it get added?");
1122
161
1123
161
    LLVM_DEBUG(
1124
161
        dbgs() << "Updating base value cache"
1125
161
               << " for: " << BDV->getName() << " from: "
1126
161
               << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1127
161
               << " to: " << Base->getName() << "\n");
1128
161
1129
161
    if (Cache.count(BDV)) {
1130
137
      assert(isKnownBaseResult(Base) &&
1131
137
             "must be something we 'know' is a base pointer");
1132
137
      // Once we transition from the BDV relation being store in the Cache to
1133
137
      // the base relation being stored, it must be stable
1134
137
      assert((!isKnownBaseResult(Cache[BDV]) || Cache[BDV] == Base) &&
1135
137
             "base relation should be stable");
1136
137
    }
1137
161
    Cache[BDV] = Base;
1138
161
  }
1139
96
  assert(Cache.count(Def));
1140
96
  return Cache[Def];
1141
96
}
1142
1143
// For a set of live pointers (base and/or derived), identify the base
1144
// pointer of the object which they are derived from.  This routine will
1145
// mutate the IR graph as needed to make the 'base' pointer live at the
1146
// definition site of 'derived'.  This ensures that any use of 'derived' can
1147
// also use 'base'.  This may involve the insertion of a number of
1148
// additional PHI nodes.
1149
//
1150
// preconditions: live is a set of pointer type Values
1151
//
1152
// side effects: may insert PHI nodes into the existing CFG, will preserve
1153
// CFG, will not remove or mutate any existing nodes
1154
//
1155
// post condition: PointerToBase contains one (derived, base) pair for every
1156
// pointer in live.  Note that derived can be equal to base if the original
1157
// pointer was a base pointer.
1158
static void
1159
findBasePointers(const StatepointLiveSetTy &live,
1160
                 MapVector<Value *, Value *> &PointerToBase,
1161
324
                 DominatorTree *DT, DefiningValueMapTy &DVCache) {
1162
342
  for (Value *ptr : live) {
1163
342
    Value *base = findBasePointer(ptr, DVCache);
1164
342
    assert(base && "failed to find base pointer");
1165
342
    PointerToBase[ptr] = base;
1166
342
    assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1167
342
            DT->dominates(cast<Instruction>(base)->getParent(),
1168
342
                          cast<Instruction>(ptr)->getParent())) &&
1169
342
           "The base we found better dominate the derived pointer");
1170
342
  }
1171
324
}
1172
1173
/// Find the required based pointers (and adjust the live set) for the given
1174
/// parse point.
1175
static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1176
                             CallBase *Call,
1177
324
                             PartiallyConstructedSafepointRecord &result) {
1178
324
  MapVector<Value *, Value *> PointerToBase;
1179
324
  findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
1180
324
1181
324
  if (PrintBasePointers) {
1182
30
    errs() << "Base Pairs (w/o Relocation):\n";
1183
30
    for (auto &Pair : PointerToBase) {
1184
30
      errs() << " derived ";
1185
30
      Pair.first->printAsOperand(errs(), false);
1186
30
      errs() << " base ";
1187
30
      Pair.second->printAsOperand(errs(), false);
1188
30
      errs() << "\n";;
1189
30
    }
1190
30
  }
1191
324
1192
324
  result.PointerToBase = PointerToBase;
1193
324
}
1194
1195
/// Given an updated version of the dataflow liveness results, update the
1196
/// liveset and base pointer maps for the call site CS.
1197
static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1198
                                  CallBase *Call,
1199
                                  PartiallyConstructedSafepointRecord &result);
1200
1201
static void recomputeLiveInValues(
1202
    Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
1203
279
    MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1204
279
  // TODO-PERF: reuse the original liveness, then simply run the dataflow
1205
279
  // again.  The old values are still live and will help it stabilize quickly.
1206
279
  GCPtrLivenessData RevisedLivenessData;
1207
279
  computeLiveInValues(DT, F, RevisedLivenessData);
1208
603
  for (size_t i = 0; i < records.size(); 
i++324
) {
1209
324
    struct PartiallyConstructedSafepointRecord &info = records[i];
1210
324
    recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info);
1211
324
  }
1212
279
}
1213
1214
// When inserting gc.relocate and gc.result calls, we need to ensure there are
1215
// no uses of the original value / return value between the gc.statepoint and
1216
// the gc.relocate / gc.result call.  One case which can arise is a phi node
1217
// starting one of the successor blocks.  We also need to be able to insert the
1218
// gc.relocates only on the path which goes through the statepoint.  We might
1219
// need to split an edge to make this possible.
1220
static BasicBlock *
1221
normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1222
68
                            DominatorTree &DT) {
1223
68
  BasicBlock *Ret = BB;
1224
68
  if (!BB->getUniquePredecessor())
1225
12
    Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1226
68
1227
68
  // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1228
68
  // from it
1229
68
  FoldSingleEntryPHINodes(Ret);
1230
68
  assert(!isa<PHINode>(Ret->begin()) &&
1231
68
         "All PHI nodes should have been removed!");
1232
68
1233
68
  // At this point, we can safely insert a gc.relocate or gc.result as the first
1234
68
  // instruction in Ret if needed.
1235
68
  return Ret;
1236
68
}
1237
1238
// Create new attribute set containing only attributes which can be transferred
1239
// from original call to the safepoint.
1240
324
static AttributeList legalizeCallAttributes(AttributeList AL) {
1241
324
  if (AL.isEmpty())
1242
314
    return AL;
1243
10
1244
10
  // Remove the readonly, readnone, and statepoint function attributes.
1245
10
  AttrBuilder FnAttrs = AL.getFnAttributes();
1246
10
  FnAttrs.removeAttribute(Attribute::ReadNone);
1247
10
  FnAttrs.removeAttribute(Attribute::ReadOnly);
1248
14
  for (Attribute A : AL.getFnAttributes()) {
1249
14
    if (isStatepointDirectiveAttr(A))
1250
4
      FnAttrs.remove(A);
1251
14
  }
1252
10
1253
10
  // Just skip parameter and return attributes for now
1254
10
  LLVMContext &Ctx = AL.getContext();
1255
10
  return AttributeList::get(Ctx, AttributeList::FunctionIndex,
1256
10
                            AttributeSet::get(Ctx, FnAttrs));
1257
10
}
1258
1259
/// Helper function to place all gc relocates necessary for the given
1260
/// statepoint.
1261
/// Inputs:
1262
///   liveVariables - list of variables to be relocated.
1263
///   liveStart - index of the first live variable.
1264
///   basePtrs - base pointers.
1265
///   statepointToken - statepoint instruction to which relocates should be
1266
///   bound.
1267
///   Builder - Llvm IR builder to be used to construct new calls.
1268
static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1269
                              const int LiveStart,
1270
                              ArrayRef<Value *> BasePtrs,
1271
                              Instruction *StatepointToken,
1272
358
                              IRBuilder<> Builder) {
1273
358
  if (LiveVariables.empty())
1274
70
    return;
1275
288
1276
451
  
auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) 288
{
1277
451
    auto ValIt = llvm::find(LiveVec, Val);
1278
451
    assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1279
451
    size_t Index = std::distance(LiveVec.begin(), ValIt);
1280
451
    assert(Index < LiveVec.size() && "Bug in std::find?");
1281
451
    return Index;
1282
451
  };
1283
288
  Module *M = StatepointToken->getModule();
1284
288
1285
288
  // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1286
288
  // element type is i8 addrspace(1)*). We originally generated unique
1287
288
  // declarations for each pointer type, but this proved problematic because
1288
288
  // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1289
288
  // towards a single unified pointer type anyways, we can just cast everything
1290
288
  // to an i8* of the right address space.  A bitcast is added later to convert
1291
288
  // gc_relocate to the actual value's type.
1292
298
  auto getGCRelocateDecl = [&] (Type *Ty) {
1293
298
    assert(isHandledGCPointerType(Ty));
1294
298
    auto AS = Ty->getScalarType()->getPointerAddressSpace();
1295
298
    Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1296
298
    if (auto *VT = dyn_cast<VectorType>(Ty))
1297
28
      NewTy = VectorType::get(NewTy, VT->getNumElements());
1298
298
    return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1299
298
                                     {NewTy});
1300
298
  };
1301
288
1302
288
  // Lazily populated map from input types to the canonicalized form mentioned
1303
288
  // in the comment above.  This should probably be cached somewhere more
1304
288
  // broadly.
1305
288
  DenseMap<Type *, Function *> TypeToDeclMap;
1306
288
1307
739
  for (unsigned i = 0; i < LiveVariables.size(); 
i++451
) {
1308
451
    // Generate the gc.relocate call and save the result
1309
451
    Value *BaseIdx =
1310
451
      Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
1311
451
    Value *LiveIdx = Builder.getInt32(LiveStart + i);
1312
451
1313
451
    Type *Ty = LiveVariables[i]->getType();
1314
451
    if (!TypeToDeclMap.count(Ty))
1315
298
      TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1316
451
    Function *GCRelocateDecl = TypeToDeclMap[Ty];
1317
451
1318
451
    // only specify a debug name if we can give a useful one
1319
451
    CallInst *Reloc = Builder.CreateCall(
1320
451
        GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1321
451
        suffixed_name_or(LiveVariables[i], ".relocated", ""));
1322
451
    // Trick CodeGen into thinking there are lots of free registers at this
1323
451
    // fake call.
1324
451
    Reloc->setCallingConv(CallingConv::Cold);
1325
451
  }
1326
288
}
1327
1328
namespace {
1329
1330
/// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
1331
/// avoids having to worry about keeping around dangling pointers to Values.
1332
class DeferredReplacement {
1333
  AssertingVH<Instruction> Old;
1334
  AssertingVH<Instruction> New;
1335
  bool IsDeoptimize = false;
1336
1337
324
  DeferredReplacement() = default;
1338
1339
public:
1340
36
  static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1341
36
    assert(Old != New && Old && New &&
1342
36
           "Cannot RAUW equal values or to / from null!");
1343
36
1344
36
    DeferredReplacement D;
1345
36
    D.Old = Old;
1346
36
    D.New = New;
1347
36
    return D;
1348
36
  }
1349
1350
280
  static DeferredReplacement createDelete(Instruction *ToErase) {
1351
280
    DeferredReplacement D;
1352
280
    D.Old = ToErase;
1353
280
    return D;
1354
280
  }
1355
1356
8
  static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1357
#ifndef NDEBUG
1358
    auto *F = cast<CallInst>(Old)->getCalledFunction();
1359
    assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1360
           "Only way to construct a deoptimize deferred replacement");
1361
#endif
1362
    DeferredReplacement D;
1363
8
    D.Old = Old;
1364
8
    D.IsDeoptimize = true;
1365
8
    return D;
1366
8
  }
1367
1368
  /// Does the task represented by this instance.
1369
324
  void doReplacement() {
1370
324
    Instruction *OldI = Old;
1371
324
    Instruction *NewI = New;
1372
324
1373
324
    assert(OldI != NewI && "Disallowed at construction?!");
1374
324
    assert((!IsDeoptimize || !New) &&
1375
324
           "Deoptimize intrinsics are not replaced!");
1376
324
1377
324
    Old = nullptr;
1378
324
    New = nullptr;
1379
324
1380
324
    if (NewI)
1381
36
      OldI->replaceAllUsesWith(NewI);
1382
324
1383
324
    if (IsDeoptimize) {
1384
8
      // Note: we've inserted instructions, so the call to llvm.deoptimize may
1385
8
      // not necessarily be followed by the matching return.
1386
8
      auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1387
8
      new UnreachableInst(RI->getContext(), RI);
1388
8
      RI->eraseFromParent();
1389
8
    }
1390
324
1391
324
    OldI->eraseFromParent();
1392
324
  }
1393
};
1394
1395
} // end anonymous namespace
1396
1397
324
static StringRef getDeoptLowering(CallBase *Call) {
1398
324
  const char *DeoptLowering = "deopt-lowering";
1399
324
  if (Call->hasFnAttr(DeoptLowering)) {
1400
6
    // FIXME: Calls have a *really* confusing interface around attributes
1401
6
    // with values.
1402
6
    const AttributeList &CSAS = Call->getAttributes();
1403
6
    if (CSAS.hasAttribute(AttributeList::FunctionIndex, DeoptLowering))
1404
2
      return CSAS.getAttribute(AttributeList::FunctionIndex, DeoptLowering)
1405
2
          .getValueAsString();
1406
4
    Function *F = Call->getCalledFunction();
1407
4
    assert(F && F->hasFnAttribute(DeoptLowering));
1408
4
    return F->getFnAttribute(DeoptLowering).getValueAsString();
1409
4
  }
1410
318
  return "live-through";
1411
318
}
1412
1413
static void
1414
makeStatepointExplicitImpl(CallBase *Call, /* to replace */
1415
                           const SmallVectorImpl<Value *> &BasePtrs,
1416
                           const SmallVectorImpl<Value *> &LiveVariables,
1417
                           PartiallyConstructedSafepointRecord &Result,
1418
324
                           std::vector<DeferredReplacement> &Replacements) {
1419
324
  assert(BasePtrs.size() == LiveVariables.size());
1420
324
1421
324
  // Then go ahead and use the builder do actually do the inserts.  We insert
1422
324
  // immediately before the previous instruction under the assumption that all
1423
324
  // arguments will be available here.  We can't insert afterwards since we may
1424
324
  // be replacing a terminator.
1425
324
  IRBuilder<> Builder(Call);
1426
324
1427
324
  ArrayRef<Value *> GCArgs(LiveVariables);
1428
324
  uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
1429
324
  uint32_t NumPatchBytes = 0;
1430
324
  uint32_t Flags = uint32_t(StatepointFlags::None);
1431
324
1432
324
  ArrayRef<Use> CallArgs(Call->arg_begin(), Call->arg_end());
1433
324
  ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(Call);
1434
324
  ArrayRef<Use> TransitionArgs;
1435
324
  if (auto TransitionBundle =
1436
2
          Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
1437
2
    Flags |= uint32_t(StatepointFlags::GCTransition);
1438
2
    TransitionArgs = TransitionBundle->Inputs;
1439
2
  }
1440
324
1441
324
  // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1442
324
  // with a return value, we lower then as never returning calls to
1443
324
  // __llvm_deoptimize that are followed by unreachable to get better codegen.
1444
324
  bool IsDeoptimize = false;
1445
324
1446
324
  StatepointDirectives SD =
1447
324
      parseStatepointDirectivesFromAttrs(Call->getAttributes());
1448
324
  if (SD.NumPatchBytes)
1449
2
    NumPatchBytes = *SD.NumPatchBytes;
1450
324
  if (SD.StatepointID)
1451
2
    StatepointID = *SD.StatepointID;
1452
324
1453
324
  // Pass through the requested lowering if any.  The default is live-through.
1454
324
  StringRef DeoptLowering = getDeoptLowering(Call);
1455
324
  if (DeoptLowering.equals("live-in"))
1456
4
    Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1457
320
  else {
1458
320
    assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1459
320
  }
1460
324
1461
324
  Value *CallTarget = Call->getCalledValue();
1462
324
  if (Function *F = dyn_cast<Function>(CallTarget)) {
1463
324
    if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
1464
8
      // Calls to llvm.experimental.deoptimize are lowered to calls to the
1465
8
      // __llvm_deoptimize symbol.  We want to resolve this now, since the
1466
8
      // verifier does not allow taking the address of an intrinsic function.
1467
8
1468
8
      SmallVector<Type *, 8> DomainTy;
1469
8
      for (Value *Arg : CallArgs)
1470
4
        DomainTy.push_back(Arg->getType());
1471
8
      auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1472
8
                                    /* isVarArg = */ false);
1473
8
1474
8
      // Note: CallTarget can be a bitcast instruction of a symbol if there are
1475
8
      // calls to @llvm.experimental.deoptimize with different argument types in
1476
8
      // the same module.  This is fine -- we assume the frontend knew what it
1477
8
      // was doing when generating this kind of IR.
1478
8
      CallTarget = F->getParent()
1479
8
                       ->getOrInsertFunction("__llvm_deoptimize", FTy)
1480
8
                       .getCallee();
1481
8
1482
8
      IsDeoptimize = true;
1483
8
    }
1484
324
  }
1485
324
1486
324
  // Create the statepoint given all the arguments
1487
324
  Instruction *Token = nullptr;
1488
324
  if (auto *CI = dyn_cast<CallInst>(Call)) {
1489
290
    CallInst *SPCall = Builder.CreateGCStatepointCall(
1490
290
        StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1491
290
        TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1492
290
1493
290
    SPCall->setTailCallKind(CI->getTailCallKind());
1494
290
    SPCall->setCallingConv(CI->getCallingConv());
1495
290
1496
290
    // Currently we will fail on parameter attributes and on certain
1497
290
    // function attributes.  In case if we can handle this set of attributes -
1498
290
    // set up function attrs directly on statepoint and return attrs later for
1499
290
    // gc_result intrinsic.
1500
290
    SPCall->setAttributes(legalizeCallAttributes(CI->getAttributes()));
1501
290
1502
290
    Token = SPCall;
1503
290
1504
290
    // Put the following gc_result and gc_relocate calls immediately after the
1505
290
    // the old call (which we're about to delete)
1506
290
    assert(CI->getNextNode() && "Not a terminator, must have next!");
1507
290
    Builder.SetInsertPoint(CI->getNextNode());
1508
290
    Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
1509
290
  } else {
1510
34
    auto *II = cast<InvokeInst>(Call);
1511
34
1512
34
    // Insert the new invoke into the old block.  We'll remove the old one in a
1513
34
    // moment at which point this will become the new terminator for the
1514
34
    // original block.
1515
34
    InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
1516
34
        StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
1517
34
        II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
1518
34
        "statepoint_token");
1519
34
1520
34
    SPInvoke->setCallingConv(II->getCallingConv());
1521
34
1522
34
    // Currently we will fail on parameter attributes and on certain
1523
34
    // function attributes.  In case if we can handle this set of attributes -
1524
34
    // set up function attrs directly on statepoint and return attrs later for
1525
34
    // gc_result intrinsic.
1526
34
    SPInvoke->setAttributes(legalizeCallAttributes(II->getAttributes()));
1527
34
1528
34
    Token = SPInvoke;
1529
34
1530
34
    // Generate gc relocates in exceptional path
1531
34
    BasicBlock *UnwindBlock = II->getUnwindDest();
1532
34
    assert(!isa<PHINode>(UnwindBlock->begin()) &&
1533
34
           UnwindBlock->getUniquePredecessor() &&
1534
34
           "can't safely insert in this block!");
1535
34
1536
34
    Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
1537
34
    Builder.SetCurrentDebugLocation(II->getDebugLoc());
1538
34
1539
34
    // Attach exceptional gc relocates to the landingpad.
1540
34
    Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1541
34
    Result.UnwindToken = ExceptionalToken;
1542
34
1543
34
    const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
1544
34
    CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1545
34
                      Builder);
1546
34
1547
34
    // Generate gc relocates and returns for normal block
1548
34
    BasicBlock *NormalDest = II->getNormalDest();
1549
34
    assert(!isa<PHINode>(NormalDest->begin()) &&
1550
34
           NormalDest->getUniquePredecessor() &&
1551
34
           "can't safely insert in this block!");
1552
34
1553
34
    Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1554
34
1555
34
    // gc relocates will be generated later as if it were regular call
1556
34
    // statepoint
1557
34
  }
1558
324
  assert(Token && "Should be set in one of the above branches!");
1559
324
1560
324
  if (IsDeoptimize) {
1561
8
    // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1562
8
    // transform the tail-call like structure to a call to a void function
1563
8
    // followed by unreachable to get better codegen.
1564
8
    Replacements.push_back(
1565
8
        DeferredReplacement::createDeoptimizeReplacement(Call));
1566
316
  } else {
1567
316
    Token->setName("statepoint_token");
1568
316
    if (!Call->getType()->isVoidTy() && 
!Call->use_empty()44
) {
1569
36
      StringRef Name = Call->hasName() ? 
Call->getName()32
:
""4
;
1570
36
      CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
1571
36
      GCResult->setAttributes(
1572
36
          AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1573
36
                             Call->getAttributes().getRetAttributes()));
1574
36
1575
36
      // We cannot RAUW or delete CS.getInstruction() because it could be in the
1576
36
      // live set of some other safepoint, in which case that safepoint's
1577
36
      // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1578
36
      // llvm::Instruction.  Instead, we defer the replacement and deletion to
1579
36
      // after the live sets have been made explicit in the IR, and we no longer
1580
36
      // have raw pointers to worry about.
1581
36
      Replacements.emplace_back(
1582
36
          DeferredReplacement::createRAUW(Call, GCResult));
1583
280
    } else {
1584
280
      Replacements.emplace_back(DeferredReplacement::createDelete(Call));
1585
280
    }
1586
316
  }
1587
324
1588
324
  Result.StatepointToken = Token;
1589
324
1590
324
  // Second, create a gc.relocate for every live variable
1591
324
  const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
1592
324
  CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1593
324
}
1594
1595
// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1596
// which make the relocations happening at this safepoint explicit.
1597
//
1598
// WARNING: Does not do any fixup to adjust users of the original live
1599
// values.  That's the callers responsibility.
1600
static void
1601
makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
1602
                       PartiallyConstructedSafepointRecord &Result,
1603
324
                       std::vector<DeferredReplacement> &Replacements) {
1604
324
  const auto &LiveSet = Result.LiveSet;
1605
324
  const auto &PointerToBase = Result.PointerToBase;
1606
324
1607
324
  // Convert to vector for efficient cross referencing.
1608
324
  SmallVector<Value *, 64> BaseVec, LiveVec;
1609
324
  LiveVec.reserve(LiveSet.size());
1610
324
  BaseVec.reserve(LiveSet.size());
1611
407
  for (Value *L : LiveSet) {
1612
407
    LiveVec.push_back(L);
1613
407
    assert(PointerToBase.count(L));
1614
407
    Value *Base = PointerToBase.find(L)->second;
1615
407
    BaseVec.push_back(Base);
1616
407
  }
1617
324
  assert(LiveVec.size() == BaseVec.size());
1618
324
1619
324
  // Do the actual rewriting and delete the old statepoint
1620
324
  makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements);
1621
324
}
1622
1623
// Helper function for the relocationViaAlloca.
1624
//
1625
// It receives iterator to the statepoint gc relocates and emits a store to the
1626
// assigned location (via allocaMap) for the each one of them.  It adds the
1627
// visited values into the visitedLiveValues set, which we will later use them
1628
// for sanity checking.
1629
static void
1630
insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1631
                       DenseMap<Value *, AllocaInst *> &AllocaMap,
1632
358
                       DenseSet<Value *> &VisitedLiveValues) {
1633
487
  for (User *U : GCRelocs) {
1634
487
    GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1635
487
    if (!Relocate)
1636
36
      continue;
1637
451
1638
451
    Value *OriginalValue = Relocate->getDerivedPtr();
1639
451
    assert(AllocaMap.count(OriginalValue));
1640
451
    Value *Alloca = AllocaMap[OriginalValue];
1641
451
1642
451
    // Emit store into the related alloca
1643
451
    // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1644
451
    // the correct type according to alloca.
1645
451
    assert(Relocate->getNextNode() &&
1646
451
           "Should always have one since it's not a terminator");
1647
451
    IRBuilder<> Builder(Relocate->getNextNode());
1648
451
    Value *CastedRelocatedValue =
1649
451
      Builder.CreateBitCast(Relocate,
1650
451
                            cast<AllocaInst>(Alloca)->getAllocatedType(),
1651
451
                            suffixed_name_or(Relocate, ".casted", ""));
1652
451
1653
451
    StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1654
451
    Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1655
451
1656
#ifndef NDEBUG
1657
    VisitedLiveValues.insert(OriginalValue);
1658
#endif
1659
  }
1660
358
}
1661
1662
// Helper function for the "relocationViaAlloca". Similar to the
1663
// "insertRelocationStores" but works for rematerialized values.
1664
static void insertRematerializationStores(
1665
    const RematerializedValueMapTy &RematerializedValues,
1666
    DenseMap<Value *, AllocaInst *> &AllocaMap,
1667
324
    DenseSet<Value *> &VisitedLiveValues) {
1668
324
  for (auto RematerializedValuePair: RematerializedValues) {
1669
40
    Instruction *RematerializedValue = RematerializedValuePair.first;
1670
40
    Value *OriginalValue = RematerializedValuePair.second;
1671
40
1672
40
    assert(AllocaMap.count(OriginalValue) &&
1673
40
           "Can not find alloca for rematerialized value");
1674
40
    Value *Alloca = AllocaMap[OriginalValue];
1675
40
1676
40
    StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1677
40
    Store->insertAfter(RematerializedValue);
1678
40
1679
#ifndef NDEBUG
1680
    VisitedLiveValues.insert(OriginalValue);
1681
#endif
1682
  }
1683
324
}
1684
1685
/// Do all the relocation update via allocas and mem2reg
1686
static void relocationViaAlloca(
1687
    Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1688
279
    ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1689
#ifndef NDEBUG
1690
  // record initial number of (static) allocas; we'll check we have the same
1691
  // number when we get done.
1692
  int InitialAllocaNum = 0;
1693
  for (Instruction &I : F.getEntryBlock())
1694
    if (isa<AllocaInst>(I))
1695
      InitialAllocaNum++;
1696
#endif
1697
1698
279
  // TODO-PERF: change data structures, reserve
1699
279
  DenseMap<Value *, AllocaInst *> AllocaMap;
1700
279
  SmallVector<AllocaInst *, 200> PromotableAllocas;
1701
279
  // Used later to chack that we have enough allocas to store all values
1702
279
  std::size_t NumRematerializedValues = 0;
1703
279
  PromotableAllocas.reserve(Live.size());
1704
279
1705
279
  // Emit alloca for "LiveValue" and record it in "allocaMap" and
1706
279
  // "PromotableAllocas"
1707
279
  const DataLayout &DL = F.getParent()->getDataLayout();
1708
418
  auto emitAllocaFor = [&](Value *LiveValue) {
1709
418
    AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
1710
418
                                        DL.getAllocaAddrSpace(), "",
1711
418
                                        F.getEntryBlock().getFirstNonPHI());
1712
418
    AllocaMap[LiveValue] = Alloca;
1713
418
    PromotableAllocas.push_back(Alloca);
1714
418
  };
1715
279
1716
279
  // Emit alloca for each live gc pointer
1717
279
  for (Value *V : Live)
1718
382
    emitAllocaFor(V);
1719
279
1720
279
  // Emit allocas for rematerialized values
1721
279
  for (const auto &Info : Records)
1722
324
    for (auto RematerializedValuePair : Info.RematerializedValues) {
1723
40
      Value *OriginalValue = RematerializedValuePair.second;
1724
40
      if (AllocaMap.count(OriginalValue) != 0)
1725
4
        continue;
1726
36
1727
36
      emitAllocaFor(OriginalValue);
1728
36
      ++NumRematerializedValues;
1729
36
    }
1730
279
1731
279
  // The next two loops are part of the same conceptual operation.  We need to
1732
279
  // insert a store to the alloca after the original def and at each
1733
279
  // redefinition.  We need to insert a load before each use.  These are split
1734
279
  // into distinct loops for performance reasons.
1735
279
1736
279
  // Update gc pointer after each statepoint: either store a relocated value or
1737
279
  // null (if no relocated value was found for this gc pointer and it is not a
1738
279
  // gc_result).  This must happen before we update the statepoint with load of
1739
279
  // alloca otherwise we lose the link between statepoint and old def.
1740
324
  for (const auto &Info : Records) {
1741
324
    Value *Statepoint = Info.StatepointToken;
1742
324
1743
324
    // This will be used for consistency check
1744
324
    DenseSet<Value *> VisitedLiveValues;
1745
324
1746
324
    // Insert stores for normal statepoint gc relocates
1747
324
    insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1748
324
1749
324
    // In case if it was invoke statepoint
1750
324
    // we will insert stores for exceptional path gc relocates.
1751
324
    if (isa<InvokeInst>(Statepoint)) {
1752
34
      insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1753
34
                             VisitedLiveValues);
1754
34
    }
1755
324
1756
324
    // Do similar thing with rematerialized values
1757
324
    insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1758
324
                                  VisitedLiveValues);
1759
324
1760
324
    if (ClobberNonLive) {
1761
0
      // As a debugging aid, pretend that an unrelocated pointer becomes null at
1762
0
      // the gc.statepoint.  This will turn some subtle GC problems into
1763
0
      // slightly easier to debug SEGVs.  Note that on large IR files with
1764
0
      // lots of gc.statepoints this is extremely costly both memory and time
1765
0
      // wise.
1766
0
      SmallVector<AllocaInst *, 64> ToClobber;
1767
0
      for (auto Pair : AllocaMap) {
1768
0
        Value *Def = Pair.first;
1769
0
        AllocaInst *Alloca = Pair.second;
1770
0
1771
0
        // This value was relocated
1772
0
        if (VisitedLiveValues.count(Def)) {
1773
0
          continue;
1774
0
        }
1775
0
        ToClobber.push_back(Alloca);
1776
0
      }
1777
0
1778
0
      auto InsertClobbersAt = [&](Instruction *IP) {
1779
0
        for (auto *AI : ToClobber) {
1780
0
          auto PT = cast<PointerType>(AI->getAllocatedType());
1781
0
          Constant *CPN = ConstantPointerNull::get(PT);
1782
0
          StoreInst *Store = new StoreInst(CPN, AI);
1783
0
          Store->insertBefore(IP);
1784
0
        }
1785
0
      };
1786
0
1787
0
      // Insert the clobbering stores.  These may get intermixed with the
1788
0
      // gc.results and gc.relocates, but that's fine.
1789
0
      if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1790
0
        InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1791
0
        InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1792
0
      } else {
1793
0
        InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1794
0
      }
1795
0
    }
1796
324
  }
1797
279
1798
279
  // Update use with load allocas and add store for gc_relocated.
1799
418
  for (auto Pair : AllocaMap) {
1800
418
    Value *Def = Pair.first;
1801
418
    AllocaInst *Alloca = Pair.second;
1802
418
1803
418
    // We pre-record the uses of allocas so that we dont have to worry about
1804
418
    // later update that changes the user information..
1805
418
1806
418
    SmallVector<Instruction *, 20> Uses;
1807
418
    // PERF: trade a linear scan for repeated reallocation
1808
418
    Uses.reserve(Def->getNumUses());
1809
889
    for (User *U : Def->users()) {
1810
889
      if (!isa<ConstantExpr>(U)) {
1811
889
        // If the def has a ConstantExpr use, then the def is either a
1812
889
        // ConstantExpr use itself or null.  In either case
1813
889
        // (recursively in the first, directly in the second), the oop
1814
889
        // it is ultimately dependent on is null and this particular
1815
889
        // use does not need to be fixed up.
1816
889
        Uses.push_back(cast<Instruction>(U));
1817
889
      }
1818
889
    }
1819
418
1820
418
    llvm::sort(Uses);
1821
418
    auto Last = std::unique(Uses.begin(), Uses.end());
1822
418
    Uses.erase(Last, Uses.end());
1823
418
1824
828
    for (Instruction *Use : Uses) {
1825
828
      if (isa<PHINode>(Use)) {
1826
59
        PHINode *Phi = cast<PHINode>(Use);
1827
179
        for (unsigned i = 0; i < Phi->getNumIncomingValues(); 
i++120
) {
1828
120
          if (Def == Phi->getIncomingValue(i)) {
1829
64
            LoadInst *Load =
1830
64
                new LoadInst(Alloca->getAllocatedType(), Alloca, "",
1831
64
                             Phi->getIncomingBlock(i)->getTerminator());
1832
64
            Phi->setIncomingValue(i, Load);
1833
64
          }
1834
120
        }
1835
769
      } else {
1836
769
        LoadInst *Load =
1837
769
            new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
1838
769
        Use->replaceUsesOfWith(Def, Load);
1839
769
      }
1840
828
    }
1841
418
1842
418
    // Emit store for the initial gc value.  Store must be inserted after load,
1843
418
    // otherwise store will be in alloca's use list and an extra load will be
1844
418
    // inserted before it.
1845
418
    StoreInst *Store = new StoreInst(Def, Alloca);
1846
418
    if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1847
240
      if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1848
2
        // InvokeInst is a terminator so the store need to be inserted into its
1849
2
        // normal destination block.
1850
2
        BasicBlock *NormalDest = Invoke->getNormalDest();
1851
2
        Store->insertBefore(NormalDest->getFirstNonPHI());
1852
238
      } else {
1853
238
        assert(!Inst->isTerminator() &&
1854
238
               "The only terminator that can produce a value is "
1855
238
               "InvokeInst which is handled above.");
1856
238
        Store->insertAfter(Inst);
1857
238
      }
1858
240
    } else {
1859
178
      assert(isa<Argument>(Def));
1860
178
      Store->insertAfter(cast<Instruction>(Alloca));
1861
178
    }
1862
418
  }
1863
279
1864
279
  assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1865
279
         "we must have the same allocas with lives");
1866
279
  if (!PromotableAllocas.empty()) {
1867
239
    // Apply mem2reg to promote alloca to SSA
1868
239
    PromoteMemToReg(PromotableAllocas, DT);
1869
239
  }
1870
279
1871
#ifndef NDEBUG
1872
  for (auto &I : F.getEntryBlock())
1873
    if (isa<AllocaInst>(I))
1874
      InitialAllocaNum--;
1875
  assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1876
#endif
1877
}
1878
1879
/// Implement a unique function which doesn't require we sort the input
1880
/// vector.  Doing so has the effect of changing the output of a couple of
1881
/// tests in ways which make them less useful in testing fused safepoints.
1882
279
template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1883
279
  SmallSet<T, 8> Seen;
1884
407
  Vec.erase(remove_if(Vec, [&](const T &V) { return !Seen.insert(V).second; }),
1885
279
            Vec.end());
1886
279
}
1887
1888
/// Insert holders so that each Value is obviously live through the entire
1889
/// lifetime of the call.
1890
static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
1891
648
                                 SmallVectorImpl<CallInst *> &Holders) {
1892
648
  if (Values.empty())
1893
364
    // No values to hold live, might as well not insert the empty holder
1894
364
    return;
1895
284
1896
284
  Module *M = Call->getModule();
1897
284
  // Use a dummy vararg function to actually hold the values live
1898
284
  FunctionCallee Func = M->getOrInsertFunction(
1899
284
      "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
1900
284
  if (isa<CallInst>(Call)) {
1901
256
    // For call safepoints insert dummy calls right after safepoint
1902
256
    Holders.push_back(
1903
256
        CallInst::Create(Func, Values, "", &*++Call->getIterator()));
1904
256
    return;
1905
256
  }
1906
28
  // For invoke safepooints insert dummy calls both in normal and
1907
28
  // exceptional destination blocks
1908
28
  auto *II = cast<InvokeInst>(Call);
1909
28
  Holders.push_back(CallInst::Create(
1910
28
      Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1911
28
  Holders.push_back(CallInst::Create(
1912
28
      Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1913
28
}
1914
1915
static void findLiveReferences(
1916
    Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
1917
279
    MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1918
279
  GCPtrLivenessData OriginalLivenessData;
1919
279
  computeLiveInValues(DT, F, OriginalLivenessData);
1920
603
  for (size_t i = 0; i < records.size(); 
i++324
) {
1921
324
    struct PartiallyConstructedSafepointRecord &info = records[i];
1922
324
    analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
1923
324
  }
1924
279
}
1925
1926
// Helper function for the "rematerializeLiveValues". It walks use chain
1927
// starting from the "CurrentValue" until it reaches the root of the chain, i.e.
1928
// the base or a value it cannot process. Only "simple" values are processed
1929
// (currently it is GEP's and casts). The returned root is  examined by the
1930
// callers of findRematerializableChainToBasePointer.  Fills "ChainToBase" array
1931
// with all visited values.
1932
static Value* findRematerializableChainToBasePointer(
1933
  SmallVectorImpl<Instruction*> &ChainToBase,
1934
555
  Value *CurrentValue) {
1935
555
  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1936
84
    ChainToBase.push_back(GEP);
1937
84
    return findRematerializableChainToBasePointer(ChainToBase,
1938
84
                                                  GEP->getPointerOperand());
1939
84
  }
1940
471
1941
471
  if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1942
30
    if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1943
2
      return CI;
1944
28
1945
28
    ChainToBase.push_back(CI);
1946
28
    return findRematerializableChainToBasePointer(ChainToBase,
1947
28
                                                  CI->getOperand(0));
1948
28
  }
1949
441
1950
441
  // We have reached the root of the chain, which is either equal to the base or
1951
441
  // is the first unsupported value along the use chain.
1952
441
  return CurrentValue;
1953
441
}
1954
1955
// Helper function for the "rematerializeLiveValues". Compute cost of the use
1956
// chain we are going to rematerialize.
1957
static unsigned
1958
chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1959
46
                       TargetTransformInfo &TTI) {
1960
46
  unsigned Cost = 0;
1961
46
1962
72
  for (Instruction *Instr : Chain) {
1963
72
    if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1964
24
      assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1965
24
             "non noop cast is found during rematerialization");
1966
24
1967
24
      Type *SrcTy = CI->getOperand(0)->getType();
1968
24
      Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy, CI);
1969
24
1970
48
    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1971
48
      // Cost of the address calculation
1972
48
      Type *ValTy = GEP->getSourceElementType();
1973
48
      Cost += TTI.getAddressComputationCost(ValTy);
1974
48
1975
48
      // And cost of the GEP itself
1976
48
      // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1977
48
      //       allowed for the external usage)
1978
48
      if (!GEP->hasAllConstantIndices())
1979
10
        Cost += 2;
1980
48
1981
48
    } else {
1982
0
      llvm_unreachable("unsupported instruction type during rematerialization");
1983
0
    }
1984
72
  }
1985
46
1986
46
  return Cost;
1987
46
}
1988
1989
6
static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
1990
6
  unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
1991
6
  if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
1992
6
      OrigRootPhi.getParent() != AlternateRootPhi.getParent())
1993
0
    return false;
1994
6
  // Map of incoming values and their corresponding basic blocks of
1995
6
  // OrigRootPhi.
1996
6
  SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
1997
18
  for (unsigned i = 0; i < PhiNum; 
i++12
)
1998
12
    CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
1999
12
        OrigRootPhi.getIncomingBlock(i);
2000
6
2001
6
  // Both current and base PHIs should have same incoming values and
2002
6
  // the same basic blocks corresponding to the incoming values.
2003
18
  for (unsigned i = 0; i < PhiNum; 
i++12
) {
2004
12
    auto CIVI =
2005
12
        CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
2006
12
    if (CIVI == CurrentIncomingValues.end())
2007
0
      return false;
2008
12
    BasicBlock *CurrentIncomingBB = CIVI->second;
2009
12
    if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
2010
0
      return false;
2011
12
  }
2012
6
  return true;
2013
6
}
2014
2015
// From the statepoint live set pick values that are cheaper to recompute then
2016
// to relocate. Remove this values from the live set, rematerialize them after
2017
// statepoint and record them in "Info" structure. Note that similar to
2018
// relocated values we don't do any user adjustments here.
2019
static void rematerializeLiveValues(CallBase *Call,
2020
                                    PartiallyConstructedSafepointRecord &Info,
2021
324
                                    TargetTransformInfo &TTI) {
2022
324
  const unsigned int ChainLengthThreshold = 10;
2023
324
2024
324
  // Record values we are going to delete from this statepoint live set.
2025
324
  // We can not di this in following loop due to iterator invalidation.
2026
324
  SmallVector<Value *, 32> LiveValuesToBeDeleted;
2027
324
2028
443
  for (Value *LiveValue: Info.LiveSet) {
2029
443
    // For each live pointer find its defining chain
2030
443
    SmallVector<Instruction *, 3> ChainToBase;
2031
443
    assert(Info.PointerToBase.count(LiveValue));
2032
443
    Value *RootOfChain =
2033
443
      findRematerializableChainToBasePointer(ChainToBase,
2034
443
                                             LiveValue);
2035
443
2036
443
    // Nothing to do, or chain is too long
2037
443
    if ( ChainToBase.size() == 0 ||
2038
443
        
ChainToBase.size() > ChainLengthThreshold60
)
2039
385
      continue;
2040
58
2041
58
    // Handle the scenario where the RootOfChain is not equal to the
2042
58
    // Base Value, but they are essentially the same phi values.
2043
58
    if (RootOfChain != Info.PointerToBase[LiveValue]) {
2044
18
      PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
2045
18
      PHINode *AlternateRootPhi = dyn_cast<PHINode>(Info.PointerToBase[LiveValue]);
2046
18
      if (!OrigRootPhi || 
!AlternateRootPhi16
)
2047
12
        continue;
2048
6
      // PHI nodes that have the same incoming values, and belonging to the same
2049
6
      // basic blocks are essentially the same SSA value.  When the original phi
2050
6
      // has incoming values with different base pointers, the original phi is
2051
6
      // marked as conflict, and an additional `AlternateRootPhi` with the same
2052
6
      // incoming values get generated by the findBasePointer function. We need
2053
6
      // to identify the newly generated AlternateRootPhi (.base version of phi)
2054
6
      // and RootOfChain (the original phi node itself) are the same, so that we
2055
6
      // can rematerialize the gep and casts. This is a workaround for the
2056
6
      // deficiency in the findBasePointer algorithm.
2057
6
      if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2058
0
        continue;
2059
6
      // Now that the phi nodes are proved to be the same, assert that
2060
6
      // findBasePointer's newly generated AlternateRootPhi is present in the
2061
6
      // liveset of the call.
2062
6
      assert(Info.LiveSet.count(AlternateRootPhi));
2063
6
    }
2064
58
    // Compute cost of this chain
2065
58
    unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2066
46
    // TODO: We can also account for cases when we will be able to remove some
2067
46
    //       of the rematerialized values by later optimization passes. I.e if
2068
46
    //       we rematerialized several intersecting chains. Or if original values
2069
46
    //       don't have any uses besides this statepoint.
2070
46
2071
46
    // For invokes we need to rematerialize each chain twice - for normal and
2072
46
    // for unwind basic blocks. Model this by multiplying cost by two.
2073
46
    if (isa<InvokeInst>(Call)) {
2074
4
      Cost *= 2;
2075
4
    }
2076
46
    // If it's too expensive - skip it
2077
46
    if (Cost >= RematerializationThreshold)
2078
10
      continue;
2079
36
2080
36
    // Remove value from the live set
2081
36
    LiveValuesToBeDeleted.push_back(LiveValue);
2082
36
2083
36
    // Clone instructions and record them inside "Info" structure
2084
36
2085
36
    // Walk backwards to visit top-most instructions first
2086
36
    std::reverse(ChainToBase.begin(), ChainToBase.end());
2087
36
2088
36
    // Utility function which clones all instructions from "ChainToBase"
2089
36
    // and inserts them before "InsertBefore". Returns rematerialized value
2090
36
    // which should be used after statepoint.
2091
36
    auto rematerializeChain = [&ChainToBase](
2092
40
        Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
2093
40
      Instruction *LastClonedValue = nullptr;
2094
40
      Instruction *LastValue = nullptr;
2095
62
      for (Instruction *Instr: ChainToBase) {
2096
62
        // Only GEP's and casts are supported as we need to be careful to not
2097
62
        // introduce any new uses of pointers not in the liveset.
2098
62
        // Note that it's fine to introduce new uses of pointers which were
2099
62
        // otherwise not used after this statepoint.
2100
62
        assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2101
62
2102
62
        Instruction *ClonedValue = Instr->clone();
2103
62
        ClonedValue->insertBefore(InsertBefore);
2104
62
        ClonedValue->setName(Instr->getName() + ".remat");
2105
62
2106
62
        // If it is not first instruction in the chain then it uses previously
2107
62
        // cloned value. We should update it to use cloned value.
2108
62
        if (LastClonedValue) {
2109
22
          assert(LastValue);
2110
22
          ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2111
#ifndef NDEBUG
2112
          for (auto OpValue : ClonedValue->operand_values()) {
2113
            // Assert that cloned instruction does not use any instructions from
2114
            // this chain other than LastClonedValue
2115
            assert(!is_contained(ChainToBase, OpValue) &&
2116
                   "incorrect use in rematerialization chain");
2117
            // Assert that the cloned instruction does not use the RootOfChain
2118
            // or the AlternateLiveBase.
2119
            assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
2120
          }
2121
#endif
2122
40
        } else {
2123
40
          // For the first instruction, replace the use of unrelocated base i.e.
2124
40
          // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
2125
40
          // live set. They have been proved to be the same PHI nodes.  Note
2126
40
          // that the *only* use of the RootOfChain in the ChainToBase list is
2127
40
          // the first Value in the list.
2128
40
          if (RootOfChain != AlternateLiveBase)
2129
6
            ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
2130
40
        }
2131
62
2132
62
        LastClonedValue = ClonedValue;
2133
62
        LastValue = Instr;
2134
62
      }
2135
40
      assert(LastClonedValue);
2136
40
      return LastClonedValue;
2137
40
    };
2138
36
2139
36
    // Different cases for calls and invokes. For invokes we need to clone
2140
36
    // instructions both on normal and unwind path.
2141
36
    if (isa<CallInst>(Call)) {
2142
32
      Instruction *InsertBefore = Call->getNextNode();
2143
32
      assert(InsertBefore);
2144
32
      Instruction *RematerializedValue = rematerializeChain(
2145
32
          InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2146
32
      Info.RematerializedValues[RematerializedValue] = LiveValue;
2147
32
    } else {
2148
4
      auto *Invoke = cast<InvokeInst>(Call);
2149
4
2150
4
      Instruction *NormalInsertBefore =
2151
4
          &*Invoke->getNormalDest()->getFirstInsertionPt();
2152
4
      Instruction *UnwindInsertBefore =
2153
4
          &*Invoke->getUnwindDest()->getFirstInsertionPt();
2154
4
2155
4
      Instruction *NormalRematerializedValue = rematerializeChain(
2156
4
          NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2157
4
      Instruction *UnwindRematerializedValue = rematerializeChain(
2158
4
          UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2159
4
2160
4
      Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2161
4
      Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2162
4
    }
2163
36
  }
2164
324
2165
324
  // Remove rematerializaed values from the live set
2166
324
  for (auto LiveValue: LiveValuesToBeDeleted) {
2167
36
    Info.LiveSet.remove(LiveValue);
2168
36
  }
2169
324
}
2170
2171
static bool insertParsePoints(Function &F, DominatorTree &DT,
2172
                              TargetTransformInfo &TTI,
2173
279
                              SmallVectorImpl<CallBase *> &ToUpdate) {
2174
#ifndef NDEBUG
2175
  // sanity check the input
2176
  std::set<CallBase *> Uniqued;
2177
  Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2178
  assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2179
2180
  for (CallBase *Call : ToUpdate)
2181
    assert(Call->getFunction() == &F);
2182
#endif
2183
2184
279
  // When inserting gc.relocates for invokes, we need to be able to insert at
2185
279
  // the top of the successor blocks.  See the comment on
2186
279
  // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2187
279
  // may restructure the CFG.
2188
324
  for (CallBase *Call : ToUpdate) {
2189
324
    auto *II = dyn_cast<InvokeInst>(Call);
2190
324
    if (!II)
2191
290
      continue;
2192
34
    normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2193
34
    normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2194
34
  }
2195
279
2196
279
  // A list of dummy calls added to the IR to keep various values obviously
2197
279
  // live in the IR.  We'll remove all of these when done.
2198
279
  SmallVector<CallInst *, 64> Holders;
2199
279
2200
279
  // Insert a dummy call with all of the deopt operands we'll need for the
2201
279
  // actual safepoint insertion as arguments.  This ensures reference operands
2202
279
  // in the deopt argument list are considered live through the safepoint (and
2203
279
  // thus makes sure they get relocated.)
2204
324
  for (CallBase *Call : ToUpdate) {
2205
324
    SmallVector<Value *, 64> DeoptValues;
2206
324
2207
540
    for (Value *Arg : GetDeoptBundleOperands(Call)) {
2208
540
      assert(!isUnhandledGCPointerType(Arg->getType()) &&
2209
540
             "support for FCA unimplemented");
2210
540
      if (isHandledGCPointerType(Arg->getType()))
2211
18
        DeoptValues.push_back(Arg);
2212
540
    }
2213
324
2214
324
    insertUseHolderAfter(Call, DeoptValues, Holders);
2215
324
  }
2216
279
2217
279
  SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2218
279
2219
279
  // A) Identify all gc pointers which are statically live at the given call
2220
279
  // site.
2221
279
  findLiveReferences(F, DT, ToUpdate, Records);
2222
279
2223
279
  // B) Find the base pointers for each live pointer
2224
279
  /* scope for caching */ {
2225
279
    // Cache the 'defining value' relation used in the computation and
2226
279
    // insertion of base phis and selects.  This ensures that we don't insert
2227
279
    // large numbers of duplicate base_phis.
2228
279
    DefiningValueMapTy DVCache;
2229
279
2230
603
    for (size_t i = 0; i < Records.size(); 
i++324
) {
2231
324
      PartiallyConstructedSafepointRecord &info = Records[i];
2232
324
      findBasePointers(DT, DVCache, ToUpdate[i], info);
2233
324
    }
2234
279
  } // end of cache scope
2235
279
2236
279
  // The base phi insertion logic (for any safepoint) may have inserted new
2237
279
  // instructions which are now live at some safepoint.  The simplest such
2238
279
  // example is:
2239
279
  // loop:
2240
279
  //   phi a  <-- will be a new base_phi here
2241
279
  //   safepoint 1 <-- that needs to be live here
2242
279
  //   gep a + 1
2243
279
  //   safepoint 2
2244
279
  //   br loop
2245
279
  // We insert some dummy calls after each safepoint to definitely hold live
2246
279
  // the base pointers which were identified for that safepoint.  We'll then
2247
279
  // ask liveness for _every_ base inserted to see what is now live.  Then we
2248
279
  // remove the dummy calls.
2249
279
  Holders.reserve(Holders.size() + Records.size());
2250
603
  for (size_t i = 0; i < Records.size(); 
i++324
) {
2251
324
    PartiallyConstructedSafepointRecord &Info = Records[i];
2252
324
2253
324
    SmallVector<Value *, 128> Bases;
2254
324
    for (auto Pair : Info.PointerToBase)
2255
342
      Bases.push_back(Pair.second);
2256
324
2257
324
    insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2258
324
  }
2259
279
2260
279
  // By selecting base pointers, we've effectively inserted new uses. Thus, we
2261
279
  // need to rerun liveness.  We may *also* have inserted new defs, but that's
2262
279
  // not the key issue.
2263
279
  recomputeLiveInValues(F, DT, ToUpdate, Records);
2264
279
2265
279
  if (PrintBasePointers) {
2266
30
    for (auto &Info : Records) {
2267
30
      errs() << "Base Pairs: (w/Relocation)\n";
2268
56
      for (auto Pair : Info.PointerToBase) {
2269
56
        errs() << " derived ";
2270
56
        Pair.first->printAsOperand(errs(), false);
2271
56
        errs() << " base ";
2272
56
        Pair.second->printAsOperand(errs(), false);
2273
56
        errs() << "\n";
2274
56
      }
2275
30
    }
2276
26
  }
2277
279
2278
279
  // It is possible that non-constant live variables have a constant base.  For
2279
279
  // example, a GEP with a variable offset from a global.  In this case we can
2280
279
  // remove it from the liveset.  We already don't add constants to the liveset
2281
279
  // because we assume they won't move at runtime and the GC doesn't need to be
2282
279
  // informed about them.  The same reasoning applies if the base is constant.
2283
279
  // Note that the relocation placement code relies on this filtering for
2284
279
  // correctness as it expects the base to be in the liveset, which isn't true
2285
279
  // if the base is constant.
2286
279
  for (auto &Info : Records)
2287
324
    for (auto &BasePair : Info.PointerToBase)
2288
457
      if (isa<Constant>(BasePair.second))
2289
14
        Info.LiveSet.remove(BasePair.first);
2290
279
2291
279
  for (CallInst *CI : Holders)
2292
312
    CI->eraseFromParent();
2293
279
2294
279
  Holders.clear();
2295
279
2296
279
  // In order to reduce live set of statepoint we might choose to rematerialize
2297
279
  // some values instead of relocating them. This is purely an optimization and
2298
279
  // does not influence correctness.
2299
603
  for (size_t i = 0; i < Records.size(); 
i++324
)
2300
324
    rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2301
279
2302
279
  // We need this to safely RAUW and delete call or invoke return values that
2303
279
  // may themselves be live over a statepoint.  For details, please see usage in
2304
279
  // makeStatepointExplicitImpl.
2305
279
  std::vector<DeferredReplacement> Replacements;
2306
279
2307
279
  // Now run through and replace the existing statepoints with new ones with
2308
279
  // the live variables listed.  We do not yet update uses of the values being
2309
279
  // relocated. We have references to live variables that need to
2310
279
  // survive to the last iteration of this loop.  (By construction, the
2311
279
  // previous statepoint can not be a live variable, thus we can and remove
2312
279
  // the old statepoint calls as we go.)
2313
603
  for (size_t i = 0; i < Records.size(); 
i++324
)
2314
324
    makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
2315
279
2316
279
  ToUpdate.clear(); // prevent accident use of invalid calls.
2317
279
2318
279
  for (auto &PR : Replacements)
2319
324
    PR.doReplacement();
2320
279
2321
279
  Replacements.clear();
2322
279
2323
324
  for (auto &Info : Records) {
2324
324
    // These live sets may contain state Value pointers, since we replaced calls
2325
324
    // with operand bundles with calls wrapped in gc.statepoint, and some of
2326
324
    // those calls may have been def'ing live gc pointers.  Clear these out to
2327
324
    // avoid accidentally using them.
2328
324
    //
2329
324
    // TODO: We should create a separate data structure that does not contain
2330
324
    // these live sets, and migrate to using that data structure from this point
2331
324
    // onward.
2332
324
    Info.LiveSet.clear();
2333
324
    Info.PointerToBase.clear();
2334
324
  }
2335
279
2336
279
  // Do all the fixups of the original live variables to their relocated selves
2337
279
  SmallVector<Value *, 128> Live;
2338
603
  for (size_t i = 0; i < Records.size(); 
i++324
) {
2339
324
    PartiallyConstructedSafepointRecord &Info = Records[i];
2340
324
2341
324
    // We can't simply save the live set from the original insertion.  One of
2342
324
    // the live values might be the result of a call which needs a safepoint.
2343
324
    // That Value* no longer exists and we need to use the new gc_result.
2344
324
    // Thankfully, the live set is embedded in the statepoint (and updated), so
2345
324
    // we just grab that.
2346
324
    Statepoint Statepoint(Info.StatepointToken);
2347
324
    Live.insert(Live.end(), Statepoint.gc_args_begin(),
2348
324
                Statepoint.gc_args_end());
2349
#ifndef NDEBUG
2350
    // Do some basic sanity checks on our liveness results before performing
2351
    // relocation.  Relocation can and will turn mistakes in liveness results
2352
    // into non-sensical code which is must harder to debug.
2353
    // TODO: It would be nice to test consistency as well
2354
    assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2355
           "statepoint must be reachable or liveness is meaningless");
2356
    for (Value *V : Statepoint.gc_args()) {
2357
      if (!isa<Instruction>(V))
2358
        // Non-instruction values trivial dominate all possible uses
2359
        continue;
2360
      auto *LiveInst = cast<Instruction>(V);
2361
      assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2362
             "unreachable values should never be live");
2363
      assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2364
             "basic SSA liveness expectation violated by liveness analysis");
2365
    }
2366
#endif
2367
  }
2368
279
  unique_unsorted(Live);
2369
279
2370
#ifndef NDEBUG
2371
  // sanity check
2372
  for (auto *Ptr : Live)
2373
    assert(isHandledGCPointerType(Ptr->getType()) &&
2374
           "must be a gc pointer type");
2375
#endif
2376
2377
279
  relocationViaAlloca(F, DT, Live, Records);
2378
279
  return !Records.empty();
2379
279
}
2380
2381
// Handles both return values and arguments for Functions and calls.
2382
template <typename AttrHolder>
2383
static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2384
1.98k
                                      unsigned Index) {
2385
1.98k
  AttrBuilder R;
2386
1.98k
  if (AH.getDereferenceableBytes(Index))
2387
8
    R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2388
8
                                  AH.getDereferenceableBytes(Index)));
2389
1.98k
  if (AH.getDereferenceableOrNullBytes(Index))
2390
4
    R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2391
4
                                  AH.getDereferenceableOrNullBytes(Index)));
2392
1.98k
  if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
2393
8
    R.addAttribute(Attribute::NoAlias);
2394
1.98k
2395
1.98k
  if (!R.empty())
2396
18
    AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
2397
1.98k
}
RewriteStatepointsForGC.cpp:void RemoveNonValidAttrAtIndex<llvm::Function>(llvm::LLVMContext&, llvm::Function&, unsigned int)
Line
Count
Source
2384
666
                                      unsigned Index) {
2385
666
  AttrBuilder R;
2386
666
  if (AH.getDereferenceableBytes(Index))
2387
4
    R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2388
4
                                  AH.getDereferenceableBytes(Index)));
2389
666
  if (AH.getDereferenceableOrNullBytes(Index))
2390
2
    R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2391
2
                                  AH.getDereferenceableOrNullBytes(Index)));
2392
666
  if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
2393
4
    R.addAttribute(Attribute::NoAlias);
2394
666
2395
666
  if (!R.empty())
2396
10
    AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
2397
666
}
RewriteStatepointsForGC.cpp:void RemoveNonValidAttrAtIndex<llvm::CallBase>(llvm::LLVMContext&, llvm::CallBase&, unsigned int)
Line
Count
Source
2384
1.31k
                                      unsigned Index) {
2385
1.31k
  AttrBuilder R;
2386
1.31k
  if (AH.getDereferenceableBytes(Index))
2387
4
    R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2388
4
                                  AH.getDereferenceableBytes(Index)));
2389
1.31k
  if (AH.getDereferenceableOrNullBytes(Index))
2390
2
    R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2391
2
                                  AH.getDereferenceableOrNullBytes(Index)));
2392
1.31k
  if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
2393
4
    R.addAttribute(Attribute::NoAlias);
2394
1.31k
2395
1.31k
  if (!R.empty())
2396
8
    AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
2397
1.31k
}
2398
2399
797
static void stripNonValidAttributesFromPrototype(Function &F) {
2400
797
  LLVMContext &Ctx = F.getContext();
2401
797
2402
797
  for (Argument &A : F.args())
2403
1.31k
    if (isa<PointerType>(A.getType()))
2404
423
      RemoveNonValidAttrAtIndex(Ctx, F,
2405
423
                                A.getArgNo() + AttributeList::FirstArgIndex);
2406
797
2407
797
  if (isa<PointerType>(F.getReturnType()))
2408
243
    RemoveNonValidAttrAtIndex(Ctx, F, AttributeList::ReturnIndex);
2409
797
}
2410
2411
/// Certain metadata on instructions are invalid after running RS4GC.
2412
/// Optimizations that run after RS4GC can incorrectly use this metadata to
2413
/// optimize functions. We drop such metadata on the instruction.
2414
2.79k
static void stripInvalidMetadataFromInstruction(Instruction &I) {
2415
2.79k
  if (!isa<LoadInst>(I) && 
!isa<StoreInst>(I)2.73k
)
2416
2.72k
    return;
2417
76
  // These are the attributes that are still valid on loads and stores after
2418
76
  // RS4GC.
2419
76
  // The metadata implying dereferenceability and noalias are (conservatively)
2420
76
  // dropped.  This is because semantically, after RewriteStatepointsForGC runs,
2421
76
  // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2422
76
  // touch the entire heap including noalias objects. Note: The reasoning is
2423
76
  // same as stripping the dereferenceability and noalias attributes that are
2424
76
  // analogous to the metadata counterparts.
2425
76
  // We also drop the invariant.load metadata on the load because that metadata
2426
76
  // implies the address operand to the load points to memory that is never
2427
76
  // changed once it became dereferenceable. This is no longer true after RS4GC.
2428
76
  // Similar reasoning applies to invariant.group metadata, which applies to
2429
76
  // loads within a group.
2430
76
  unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2431
76
                         LLVMContext::MD_range,
2432
76
                         LLVMContext::MD_alias_scope,
2433
76
                         LLVMContext::MD_nontemporal,
2434
76
                         LLVMContext::MD_nonnull,
2435
76
                         LLVMContext::MD_align,
2436
76
                         LLVMContext::MD_type};
2437
76
2438
76
  // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2439
76
  I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
2440
76
}
2441
2442
797
static void stripNonValidDataFromBody(Function &F) {
2443
797
  if (F.empty())
2444
500
    return;
2445
297
2446
297
  LLVMContext &Ctx = F.getContext();
2447
297
  MDBuilder Builder(Ctx);
2448
297
2449
297
  // Set of invariantstart instructions that we need to remove.
2450
297
  // Use this to avoid invalidating the instruction iterator.
2451
297
  SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
2452
297
2453
2.80k
  for (Instruction &I : instructions(F)) {
2454
2.80k
    // invariant.start on memory location implies that the referenced memory
2455
2.80k
    // location is constant and unchanging. This is no longer true after
2456
2.80k
    // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
2457
2.80k
    // which frees the entire heap and the presence of invariant.start allows
2458
2.80k
    // the optimizer to sink the load of a memory location past a statepoint,
2459
2.80k
    // which is incorrect.
2460
2.80k
    if (auto *II = dyn_cast<IntrinsicInst>(&I))
2461
787
      if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2462
4
        InvariantStartInstructions.push_back(II);
2463
4
        continue;
2464
4
      }
2465
2.79k
2466
2.79k
    if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
2467
4
      MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
2468
4
      I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2469
4
    }
2470
2.79k
2471
2.79k
    stripInvalidMetadataFromInstruction(I);
2472
2.79k
2473
2.79k
    if (auto *Call = dyn_cast<CallBase>(&I)) {
2474
5.74k
      for (int i = 0, e = Call->arg_size(); i != e; 
i++4.79k
)
2475
4.79k
        if (isa<PointerType>(Call->getArgOperand(i)->getType()))
2476
853
          RemoveNonValidAttrAtIndex(Ctx, *Call,
2477
853
                                    i + AttributeList::FirstArgIndex);
2478
951
      if (isa<PointerType>(Call->getType()))
2479
461
        RemoveNonValidAttrAtIndex(Ctx, *Call, AttributeList::ReturnIndex);
2480
951
    }
2481
2.79k
  }
2482
297
2483
297
  // Delete the invariant.start instructions and RAUW undef.
2484
297
  for (auto *II : InvariantStartInstructions) {
2485
4
    II->replaceAllUsesWith(UndefValue::get(II->getType()));
2486
4
    II->eraseFromParent();
2487
4
  }
2488
297
}
2489
2490
/// Returns true if this function should be rewritten by this pass.  The main
2491
/// point of this function is as an extension point for custom logic.
2492
305
static bool shouldRewriteStatepointsIn(Function &F) {
2493
305
  // TODO: This should check the GCStrategy
2494
305
  if (F.hasGC()) {
2495
291
    const auto &FunctionGCName = F.getGC();
2496
291
    const StringRef StatepointExampleName("statepoint-example");
2497
291
    const StringRef CoreCLRName("coreclr");
2498
291
    return (StatepointExampleName == FunctionGCName) ||
2499
291
           
(CoreCLRName == FunctionGCName)4
;
2500
291
  } else
2501
14
    return false;
2502
305
}
2503
2504
87
static void stripNonValidData(Module &M) {
2505
#ifndef NDEBUG
2506
  assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
2507
#endif
2508
2509
87
  for (Function &F : M)
2510
797
    stripNonValidAttributesFromPrototype(F);
2511
87
2512
87
  for (Function &F : M)
2513
797
    stripNonValidDataFromBody(F);
2514
87
}
2515
2516
bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
2517
                                            TargetTransformInfo &TTI,
2518
289
                                            const TargetLibraryInfo &TLI) {
2519
289
  assert(!F.isDeclaration() && !F.empty() &&
2520
289
         "need function body to rewrite statepoints in");
2521
289
  assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
2522
289
2523
1.64k
  auto NeedsRewrite = [&TLI](Instruction &I) {
2524
1.64k
    if (const auto *Call = dyn_cast<CallBase>(&I))
2525
460
      return !callsGCLeafFunction(Call, TLI) && 
!isStatepoint(Call)324
;
2526
1.18k
    return false;
2527
1.18k
  };
2528
289
2529
289
  // Delete any unreachable statepoints so that we don't have unrewritten
2530
289
  // statepoints surviving this pass.  This makes testing easier and the
2531
289
  // resulting IR less confusing to human readers.
2532
289
  DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2533
289
  bool MadeChange = removeUnreachableBlocks(F, nullptr, &DTU);
2534
289
  // Flush the Dominator Tree.
2535
289
  DTU.getDomTree();
2536
289
2537
289
  // Gather all the statepoints which need rewritten.  Be careful to only
2538
289
  // consider those in reachable code since we need to ask dominance queries
2539
289
  // when rewriting.  We'll delete the unreachable ones in a moment.
2540
289
  SmallVector<CallBase *, 64> ParsePointNeeded;
2541
1.64k
  for (Instruction &I : instructions(F)) {
2542
1.64k
    // TODO: only the ones with the flag set!
2543
1.64k
    if (NeedsRewrite(I)) {
2544
324
      // NOTE removeUnreachableBlocks() is stronger than
2545
324
      // DominatorTree::isReachableFromEntry(). In other words
2546
324
      // removeUnreachableBlocks can remove some blocks for which
2547
324
      // isReachableFromEntry() returns true.
2548
324
      assert(DT.isReachableFromEntry(I.getParent()) &&
2549
324
            "no unreachable blocks expected");
2550
324
      ParsePointNeeded.push_back(cast<CallBase>(&I));
2551
324
    }
2552
1.64k
  }
2553
289
2554
289
  // Return early if no work to do.
2555
289
  if (ParsePointNeeded.empty())
2556
10
    return MadeChange;
2557
279
2558
279
  // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2559
279
  // These are created by LCSSA.  They have the effect of increasing the size
2560
279
  // of liveness sets for no good reason.  It may be harder to do this post
2561
279
  // insertion since relocations and base phis can confuse things.
2562
279
  for (BasicBlock &BB : F)
2563
677
    if (BB.getUniquePredecessor()) {
2564
266
      MadeChange = true;
2565
266
      FoldSingleEntryPHINodes(&BB);
2566
266
    }
2567
279
2568
279
  // Before we start introducing relocations, we want to tweak the IR a bit to
2569
279
  // avoid unfortunate code generation effects.  The main example is that we
2570
279
  // want to try to make sure the comparison feeding a branch is after any
2571
279
  // safepoints.  Otherwise, we end up with a comparison of pre-relocation
2572
279
  // values feeding a branch after relocation.  This is semantically correct,
2573
279
  // but results in extra register pressure since both the pre-relocation and
2574
279
  // post-relocation copies must be available in registers.  For code without
2575
279
  // relocations this is handled elsewhere, but teaching the scheduler to
2576
279
  // reverse the transform we're about to do would be slightly complex.
2577
279
  // Note: This may extend the live range of the inputs to the icmp and thus
2578
279
  // increase the liveset of any statepoint we move over.  This is profitable
2579
279
  // as long as all statepoints are in rare blocks.  If we had in-register
2580
279
  // lowering for live values this would be a much safer transform.
2581
677
  auto getConditionInst = [](Instruction *TI) -> Instruction * {
2582
677
    if (auto *BI = dyn_cast<BranchInst>(TI))
2583
324
      if (BI->isConditional())
2584
118
        return dyn_cast<Instruction>(BI->getCondition());
2585
559
    // TODO: Extend this to handle switches
2586
559
    return nullptr;
2587
559
  };
2588
677
  for (BasicBlock &BB : F) {
2589
677
    Instruction *TI = BB.getTerminator();
2590
677
    if (auto *Cond = getConditionInst(TI))
2591
34
      // TODO: Handle more than just ICmps here.  We should be able to move
2592
34
      // most instructions without side effects or memory access.
2593
34
      if (isa<ICmpInst>(Cond) && 
Cond->hasOneUse()30
) {
2594
14
        MadeChange = true;
2595
14
        Cond->moveBefore(TI);
2596
14
      }
2597
677
  }
2598
279
2599
279
  // Nasty workaround - The base computation code in the main algorithm doesn't
2600
279
  // consider the fact that a GEP can be used to convert a scalar to a vector.
2601
279
  // The right fix for this is to integrate GEPs into the base rewriting
2602
279
  // algorithm properly, this is just a short term workaround to prevent
2603
279
  // crashes by canonicalizing such GEPs into fully vector GEPs.
2604
1.62k
  for (Instruction &I : instructions(F)) {
2605
1.62k
    if (!isa<GetElementPtrInst>(I))
2606
1.46k
      continue;
2607
154
2608
154
    unsigned VF = 0;
2609
464
    for (unsigned i = 0; i < I.getNumOperands(); 
i++310
)
2610
310
      if (I.getOperand(i)->getType()->isVectorTy()) {
2611
16
        assert(VF == 0 ||
2612
16
               VF == I.getOperand(i)->getType()->getVectorNumElements());
2613
16
        VF = I.getOperand(i)->getType()->getVectorNumElements();
2614
16
      }
2615
154
2616
154
    // It's the vector to scalar traversal through the pointer operand which
2617
154
    // confuses base pointer rewriting, so limit ourselves to that case.
2618
154
    if (!I.getOperand(0)->getType()->isVectorTy() && 
VF != 0148
) {
2619
6
      IRBuilder<> B(&I);
2620
6
      auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
2621
6
      I.setOperand(0, Splat);
2622
6
      MadeChange = true;
2623
6
    }
2624
154
  }
2625
279
2626
279
  MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2627
279
  return MadeChange;
2628
279
}
2629
2630
// liveness computation via standard dataflow
2631
// -------------------------------------------------------------------
2632
2633
// TODO: Consider using bitvectors for liveness, the set of potentially
2634
// interesting values should be small and easy to pre-compute.
2635
2636
/// Compute the live-in set for the location rbegin starting from
2637
/// the live-out set of the basic block
2638
static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
2639
                                BasicBlock::reverse_iterator End,
2640
2.03k
                                SetVector<Value *> &LiveTmp) {
2641
5.53k
  for (auto &I : make_range(Begin, End)) {
2642
5.53k
    // KILL/Def - Remove this definition from LiveIn
2643
5.53k
    LiveTmp.remove(&I);
2644
5.53k
2645
5.53k
    // Don't consider *uses* in PHI nodes, we handle their contribution to
2646
5.53k
    // predecessor blocks when we seed the LiveOut sets
2647
5.53k
    if (isa<PHINode>(I))
2648
246
      continue;
2649
5.29k
2650
5.29k
    // USE - Add to the LiveIn set for this instruction
2651
10.3k
    
for (Value *V : I.operands())5.29k
{
2652
10.3k
      assert(!isUnhandledGCPointerType(V->getType()) &&
2653
10.3k
             "support for FCA unimplemented");
2654
10.3k
      if (isHandledGCPointerType(V->getType()) && 
!isa<Constant>(V)2.99k
) {
2655
2.73k
        // The choice to exclude all things constant here is slightly subtle.
2656
2.73k
        // There are two independent reasons:
2657
2.73k
        // - We assume that things which are constant (from LLVM's definition)
2658
2.73k
        // do not move at runtime.  For example, the address of a global
2659
2.73k
        // variable is fixed, even though it's contents may not be.
2660
2.73k
        // - Second, we can't disallow arbitrary inttoptr constants even
2661
2.73k
        // if the language frontend does.  Optimization passes are free to
2662
2.73k
        // locally exploit facts without respect to global reachability.  This
2663
2.73k
        // can create sections of code which are dynamically unreachable and
2664
2.73k
        // contain just about anything.  (see constants.ll in tests)
2665
2.73k
        LiveTmp.insert(V);
2666
2.73k
      }
2667
10.3k
    }
2668
5.29k
  }
2669
2.03k
}
2670
2671
1.39k
static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
2672
1.39k
  for (BasicBlock *Succ : successors(BB)) {
2673
1.63k
    for (auto &I : *Succ) {
2674
1.63k
      PHINode *PN = dyn_cast<PHINode>(&I);
2675
1.63k
      if (!PN)
2676
1.11k
        break;
2677
520
2678
520
      Value *V = PN->getIncomingValueForBlock(BB);
2679
520
      assert(!isUnhandledGCPointerType(V->getType()) &&
2680
520
             "support for FCA unimplemented");
2681
520
      if (isHandledGCPointerType(V->getType()) && 
!isa<Constant>(V)496
)
2682
440
        LiveTmp.insert(V);
2683
520
    }
2684
1.11k
  }
2685
1.39k
}
2686
2687
1.39k
static SetVector<Value *> computeKillSet(BasicBlock *BB) {
2688
1.39k
  SetVector<Value *> KillSet;
2689
1.39k
  for (Instruction &I : *BB)
2690
3.77k
    if (isHandledGCPointerType(I.getType()))
2691
1.09k
      KillSet.insert(&I);
2692
1.39k
  return KillSet;
2693
1.39k
}
2694
2695
#ifndef NDEBUG
2696
/// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2697
/// sanity check for the liveness computation.
2698
static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
2699
                          Instruction *TI, bool TermOkay = false) {
2700
  for (Value *V : Live) {
2701
    if (auto *I = dyn_cast<Instruction>(V)) {
2702
      // The terminator can be a member of the LiveOut set.  LLVM's definition
2703
      // of instruction dominance states that V does not dominate itself.  As
2704
      // such, we need to special case this to allow it.
2705
      if (TermOkay && TI == I)
2706
        continue;
2707
      assert(DT.dominates(I, TI) &&
2708
             "basic SSA liveness expectation violated by liveness analysis");
2709
    }
2710
  }
2711
}
2712
2713
/// Check that all the liveness sets used during the computation of liveness
2714
/// obey basic SSA properties.  This is useful for finding cases where we miss
2715
/// a def.
2716
static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2717
                          BasicBlock &BB) {
2718
  checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2719
  checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2720
  checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2721
}
2722
#endif
2723
2724
static void computeLiveInValues(DominatorTree &DT, Function &F,
2725
558
                                GCPtrLivenessData &Data) {
2726
558
  SmallSetVector<BasicBlock *, 32> Worklist;
2727
558
2728
558
  // Seed the liveness for each individual block
2729
1.39k
  for (BasicBlock &BB : F) {
2730
1.39k
    Data.KillSet[&BB] = computeKillSet(&BB);
2731
1.39k
    Data.LiveSet[&BB].clear();
2732
1.39k
    computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2733
1.39k
2734
#ifndef NDEBUG
2735
    for (Value *Kill : Data.KillSet[&BB])
2736
      assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2737
#endif
2738
2739
1.39k
    Data.LiveOut[&BB] = SetVector<Value *>();
2740
1.39k
    computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2741
1.39k
    Data.LiveIn[&BB] = Data.LiveSet[&BB];
2742
1.39k
    Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
2743
1.39k
    Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
2744
1.39k
    if (!Data.LiveIn[&BB].empty())
2745
779
      Worklist.insert(pred_begin(&BB), pred_end(&BB));
2746
1.39k
  }
2747
558
2748
558
  // Propagate that liveness until stable
2749
1.10k
  while (!Worklist.empty()) {
2750
548
    BasicBlock *BB = Worklist.pop_back_val();
2751
548
2752
548
    // Compute our new liveout set, then exit early if it hasn't changed despite
2753
548
    // the contribution of our successor.
2754
548
    SetVector<Value *> LiveOut = Data.LiveOut[BB];
2755
548
    const auto OldLiveOutSize = LiveOut.size();
2756
888
    for (BasicBlock *Succ : successors(BB)) {
2757
888
      assert(Data.LiveIn.count(Succ));
2758
888
      LiveOut.set_union(Data.LiveIn[Succ]);
2759
888
    }
2760
548
    // assert OutLiveOut is a subset of LiveOut
2761
548
    if (OldLiveOutSize == LiveOut.size()) {
2762
60
      // If the sets are the same size, then we didn't actually add anything
2763
60
      // when unioning our successors LiveIn.  Thus, the LiveIn of this block
2764
60
      // hasn't changed.
2765
60
      continue;
2766
60
    }
2767
488
    Data.LiveOut[BB] = LiveOut;
2768
488
2769
488
    // Apply the effects of this basic block
2770
488
    SetVector<Value *> LiveTmp = LiveOut;
2771
488
    LiveTmp.set_union(Data.LiveSet[BB]);
2772
488
    LiveTmp.set_subtract(Data.KillSet[BB]);
2773
488
2774
488
    assert(Data.LiveIn.count(BB));
2775
488
    const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
2776
488
    // assert: OldLiveIn is a subset of LiveTmp
2777
488
    if (OldLiveIn.size() != LiveTmp.size()) {
2778
274
      Data.LiveIn[BB] = LiveTmp;
2779
274
      Worklist.insert(pred_begin(BB), pred_end(BB));
2780
274
    }
2781
488
  } // while (!Worklist.empty())
2782
558
2783
#ifndef NDEBUG
2784
  // Sanity check our output against SSA properties.  This helps catch any
2785
  // missing kills during the above iteration.
2786
  for (BasicBlock &BB : F)
2787
    checkBasicSSA(DT, Data, BB);
2788
#endif
2789
}
2790
2791
static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2792
648
                              StatepointLiveSetTy &Out) {
2793
648
  BasicBlock *BB = Inst->getParent();
2794
648
2795
648
  // Note: The copy is intentional and required
2796
648
  assert(Data.LiveOut.count(BB));
2797
648
  SetVector<Value *> LiveOut = Data.LiveOut[BB];
2798
648
2799
648
  // We want to handle the statepoint itself oddly.  It's
2800
648
  // call result is not live (normal), nor are it's arguments
2801
648
  // (unless they're used again later).  This adjustment is
2802
648
  // specifically what we need to relocate
2803
648
  computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
2804
648
                      LiveOut);
2805
648
  LiveOut.remove(Inst);
2806
648
  Out.insert(LiveOut.begin(), LiveOut.end());
2807
648
}
2808
2809
static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2810
                                  CallBase *Call,
2811
324
                                  PartiallyConstructedSafepointRecord &Info) {
2812
324
  StatepointLiveSetTy Updated;
2813
324
  findLiveSetAtInst(Call, RevisedLivenessData, Updated);
2814
324
2815
324
  // We may have base pointers which are now live that weren't before.  We need
2816
324
  // to update the PointerToBase structure to reflect this.
2817
324
  for (auto V : Updated)
2818
457
    if (Info.PointerToBase.insert({V, V}).second) {
2819
115
      assert(isKnownBaseResult(V) &&
2820
115
             "Can't find base for unexpected live value!");
2821
115
      continue;
2822
115
    }
2823
324
2824
#ifndef NDEBUG
2825
  for (auto V : Updated)
2826
    assert(Info.PointerToBase.count(V) &&
2827
           "Must be able to find base for live value!");
2828
#endif
2829
2830
324
  // Remove any stale base mappings - this can happen since our liveness is
2831
324
  // more precise then the one inherent in the base pointer analysis.
2832
324
  DenseSet<Value *> ToErase;
2833
324
  for (auto KVPair : Info.PointerToBase)
2834
457
    if (!Updated.count(KVPair.first))
2835
0
      ToErase.insert(KVPair.first);
2836
324
2837
324
  for (auto *V : ToErase)
2838
0
    Info.PointerToBase.erase(V);
2839
324
2840
#ifndef NDEBUG
2841
  for (auto KVPair : Info.PointerToBase)
2842
    assert(Updated.count(KVPair.first) && "record for non-live value");
2843
#endif
2844
2845
324
  Info.LiveSet = Updated;
2846
324
}