aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/llvm16/lib/Transforms/Scalar/TLSVariableHoist.cpp
blob: 4ec7181ad85950bc7d78bb38da4c2cfbcdfd15f2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//===- TLSVariableHoist.cpp -------- Remove Redundant TLS Loads ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This pass identifies/eliminate Redundant TLS Loads if related option is set.
// The example: Please refer to the comment at the head of TLSVariableHoist.h.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/TLSVariableHoist.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <tuple>
#include <utility>

using namespace llvm;
using namespace tlshoist;

#define DEBUG_TYPE "tlshoist"

static cl::opt<bool> TLSLoadHoist(
    "tls-load-hoist", cl::init(false), cl::Hidden,
    cl::desc("hoist the TLS loads in PIC model to eliminate redundant "
             "TLS address calculation."));

namespace {

/// The TLS Variable hoist pass.
class TLSVariableHoistLegacyPass : public FunctionPass {
public:
  static char ID; // Pass identification, replacement for typeid

  TLSVariableHoistLegacyPass() : FunctionPass(ID) {
    initializeTLSVariableHoistLegacyPassPass(*PassRegistry::getPassRegistry());
  }

  bool runOnFunction(Function &Fn) override;

  StringRef getPassName() const override { return "TLS Variable Hoist"; }

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.setPreservesCFG();
    AU.addRequired<DominatorTreeWrapperPass>();
    AU.addRequired<LoopInfoWrapperPass>();
  }

private:
  TLSVariableHoistPass Impl;
};

} // end anonymous namespace

char TLSVariableHoistLegacyPass::ID = 0;

INITIALIZE_PASS_BEGIN(TLSVariableHoistLegacyPass, "tlshoist",
                      "TLS Variable Hoist", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(TLSVariableHoistLegacyPass, "tlshoist",
                    "TLS Variable Hoist", false, false)

FunctionPass *llvm::createTLSVariableHoistPass() {
  return new TLSVariableHoistLegacyPass();
}

/// Perform the TLS Variable Hoist optimization for the given function.
bool TLSVariableHoistLegacyPass::runOnFunction(Function &Fn) {
  if (skipFunction(Fn))
    return false;

  LLVM_DEBUG(dbgs() << "********** Begin TLS Variable Hoist **********\n");
  LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');

  bool MadeChange =
      Impl.runImpl(Fn, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
                   getAnalysis<LoopInfoWrapperPass>().getLoopInfo());

  if (MadeChange) {
    LLVM_DEBUG(dbgs() << "********** Function after TLS Variable Hoist: "
                      << Fn.getName() << '\n');
    LLVM_DEBUG(dbgs() << Fn);
  }
  LLVM_DEBUG(dbgs() << "********** End TLS Variable Hoist **********\n");

  return MadeChange;
}

void TLSVariableHoistPass::collectTLSCandidate(Instruction *Inst) {
  // Skip all cast instructions. They are visited indirectly later on.
  if (Inst->isCast())
    return;

  // Scan all operands.
  for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
    auto *GV = dyn_cast<GlobalVariable>(Inst->getOperand(Idx));
    if (!GV || !GV->isThreadLocal())
      continue;

    // Add Candidate to TLSCandMap (GV --> Candidate).
    TLSCandMap[GV].addUser(Inst, Idx);
  }
}

void TLSVariableHoistPass::collectTLSCandidates(Function &Fn) {
  // First, quickly check if there is TLS Variable.
  Module *M = Fn.getParent();

  bool HasTLS = llvm::any_of(
      M->globals(), [](GlobalVariable &GV) { return GV.isThreadLocal(); });

  // If non, directly return.
  if (!HasTLS)
    return;

  TLSCandMap.clear();

  // Then, collect TLS Variable info.
  for (BasicBlock &BB : Fn) {
    // Ignore unreachable basic blocks.
    if (!DT->isReachableFromEntry(&BB))
      continue;

    for (Instruction &Inst : BB)
      collectTLSCandidate(&Inst);
  }
}

static bool oneUseOutsideLoop(tlshoist::TLSCandidate &Cand, LoopInfo *LI) {
  if (Cand.Users.size() != 1)
    return false;

  BasicBlock *BB = Cand.Users[0].Inst->getParent();
  if (LI->getLoopFor(BB))
    return false;

  return true;
}

Instruction *TLSVariableHoistPass::getNearestLoopDomInst(BasicBlock *BB,
                                                         Loop *L) {
  assert(L && "Unexcepted Loop status!");

  // Get the outermost loop.
  while (Loop *Parent = L->getParentLoop())
    L = Parent;

  BasicBlock *PreHeader = L->getLoopPreheader();

  // There is unique predecessor outside the loop.
  if (PreHeader)
    return PreHeader->getTerminator();

  BasicBlock *Header = L->getHeader();
  BasicBlock *Dom = Header;
  for (BasicBlock *PredBB : predecessors(Header))
    Dom = DT->findNearestCommonDominator(Dom, PredBB);

  assert(Dom && "Not find dominator BB!");
  Instruction *Term = Dom->getTerminator();

  return Term;
}

Instruction *TLSVariableHoistPass::getDomInst(Instruction *I1,
                                              Instruction *I2) {
  if (!I1)
    return I2;
  return DT->findNearestCommonDominator(I1, I2);
}

BasicBlock::iterator TLSVariableHoistPass::findInsertPos(Function &Fn,
                                                         GlobalVariable *GV,
                                                         BasicBlock *&PosBB) {
  tlshoist::TLSCandidate &Cand = TLSCandMap[GV];

  // We should hoist the TLS use out of loop, so choose its nearest instruction
  // which dominate the loop and the outside loops (if exist).
  Instruction *LastPos = nullptr;
  for (auto &User : Cand.Users) {
    BasicBlock *BB = User.Inst->getParent();
    Instruction *Pos = User.Inst;
    if (Loop *L = LI->getLoopFor(BB)) {
      Pos = getNearestLoopDomInst(BB, L);
      assert(Pos && "Not find insert position out of loop!");
    }
    Pos = getDomInst(LastPos, Pos);
    LastPos = Pos;
  }

  assert(LastPos && "Unexpected insert position!");
  BasicBlock *Parent = LastPos->getParent();
  PosBB = Parent;
  return LastPos->getIterator();
}

// Generate a bitcast (no type change) to replace the uses of TLS Candidate.
Instruction *TLSVariableHoistPass::genBitCastInst(Function &Fn,
                                                  GlobalVariable *GV) {
  BasicBlock *PosBB = &Fn.getEntryBlock();
  BasicBlock::iterator Iter = findInsertPos(Fn, GV, PosBB);
  Type *Ty = GV->getType();
  auto *CastInst = new BitCastInst(GV, Ty, "tls_bitcast");
  CastInst->insertInto(PosBB, Iter);
  return CastInst;
}

bool TLSVariableHoistPass::tryReplaceTLSCandidate(Function &Fn,
                                                  GlobalVariable *GV) {

  tlshoist::TLSCandidate &Cand = TLSCandMap[GV];

  // If only used 1 time and not in loops, we no need to replace it.
  if (oneUseOutsideLoop(Cand, LI))
    return false;

  // Generate a bitcast (no type change)
  auto *CastInst = genBitCastInst(Fn, GV);

  // to replace the uses of TLS Candidate
  for (auto &User : Cand.Users)
    User.Inst->setOperand(User.OpndIdx, CastInst);

  return true;
}

bool TLSVariableHoistPass::tryReplaceTLSCandidates(Function &Fn) {
  if (TLSCandMap.empty())
    return false;

  bool Replaced = false;
  for (auto &GV2Cand : TLSCandMap) {
    GlobalVariable *GV = GV2Cand.first;
    Replaced |= tryReplaceTLSCandidate(Fn, GV);
  }

  return Replaced;
}

/// Optimize expensive TLS variables in the given function.
bool TLSVariableHoistPass::runImpl(Function &Fn, DominatorTree &DT,
                                   LoopInfo &LI) {
  if (Fn.hasOptNone())
    return false;

  if (!TLSLoadHoist && !Fn.getAttributes().hasFnAttr("tls-load-hoist"))
    return false;

  this->LI = &LI;
  this->DT = &DT;
  assert(this->LI && this->DT && "Unexcepted requirement!");

  // Collect all TLS variable candidates.
  collectTLSCandidates(Fn);

  bool MadeChange = tryReplaceTLSCandidates(Fn);

  return MadeChange;
}

PreservedAnalyses TLSVariableHoistPass::run(Function &F,
                                            FunctionAnalysisManager &AM) {

  auto &LI = AM.getResult<LoopAnalysis>(F);
  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);

  if (!runImpl(F, DT, LI))
    return PreservedAnalyses::all();

  PreservedAnalyses PA;
  PA.preserveSet<CFGAnalyses>();
  return PA;
}