Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- XCoreLowerThreadLocal - Lower thread local variables --------------===//
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
/// \file
10
/// This file contains a pass that lowers thread local variables on the
11
///        XCore.
12
///
13
//===----------------------------------------------------------------------===//
14
15
#include "XCore.h"
16
#include "llvm/IR/Constants.h"
17
#include "llvm/IR/DerivedTypes.h"
18
#include "llvm/IR/GlobalVariable.h"
19
#include "llvm/IR/IRBuilder.h"
20
#include "llvm/IR/Intrinsics.h"
21
#include "llvm/IR/Module.h"
22
#include "llvm/IR/NoFolder.h"
23
#include "llvm/IR/ValueHandle.h"
24
#include "llvm/Pass.h"
25
#include "llvm/Support/CommandLine.h"
26
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
27
28
#define DEBUG_TYPE "xcore-lower-thread-local"
29
30
using namespace llvm;
31
32
static cl::opt<unsigned> MaxThreads(
33
  "xcore-max-threads", cl::Optional,
34
  cl::desc("Maximum number of threads (for emulation thread-local storage)"),
35
  cl::Hidden, cl::value_desc("number"), cl::init(8));
36
37
namespace {
38
  /// Lowers thread local variables on the XCore. Each thread local variable is
39
  /// expanded to an array of n elements indexed by the thread ID where n is the
40
  /// fixed number hardware threads supported by the device.
41
  struct XCoreLowerThreadLocal : public ModulePass {
42
    static char ID;
43
44
70
    XCoreLowerThreadLocal() : ModulePass(ID) {
45
70
      initializeXCoreLowerThreadLocalPass(*PassRegistry::getPassRegistry());
46
70
    }
47
48
    bool lowerGlobal(GlobalVariable *GV);
49
50
    bool runOnModule(Module &M) override;
51
  };
52
}
53
54
char XCoreLowerThreadLocal::ID = 0;
55
56
INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
57
                "Lower thread local variables", false, false)
58
59
70
ModulePass *llvm::createXCoreLowerThreadLocalPass() {
60
70
  return new XCoreLowerThreadLocal();
61
70
}
62
63
5
static ArrayType *createLoweredType(Type *OriginalType) {
64
5
  return ArrayType::get(OriginalType, MaxThreads);
65
5
}
66
67
static Constant *
68
3
createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
69
3
  SmallVector<Constant *, 8> Elements(MaxThreads);
70
27
  for (unsigned i = 0; i != MaxThreads; 
++i24
) {
71
24
    Elements[i] = OriginalInitializer;
72
24
  }
73
3
  return ConstantArray::get(NewType, Elements);
74
3
}
75
76
static Instruction *
77
12
createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
78
12
  IRBuilder<NoFolder> Builder(Instr);
79
12
  unsigned OpCode = CE->getOpcode();
80
12
  switch (OpCode) {
81
12
    case Instruction::GetElementPtr: {
82
8
      SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end());
83
8
      ArrayRef<Value *> CEOps(CEOpVec);
84
8
      return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(
85
8
          cast<GEPOperator>(CE)->getSourceElementType(), CEOps[0],
86
8
          CEOps.slice(1)));
87
12
    }
88
12
    case Instruction::Add:
89
2
    case Instruction::Sub:
90
2
    case Instruction::Mul:
91
2
    case Instruction::UDiv:
92
2
    case Instruction::SDiv:
93
2
    case Instruction::FDiv:
94
2
    case Instruction::URem:
95
2
    case Instruction::SRem:
96
2
    case Instruction::FRem:
97
2
    case Instruction::Shl:
98
2
    case Instruction::LShr:
99
2
    case Instruction::AShr:
100
2
    case Instruction::And:
101
2
    case Instruction::Or:
102
2
    case Instruction::Xor:
103
2
      return dyn_cast<Instruction>(
104
2
                  Builder.CreateBinOp((Instruction::BinaryOps)OpCode,
105
2
                                      CE->getOperand(0), CE->getOperand(1),
106
2
                                      CE->getName()));
107
2
    case Instruction::Trunc:
108
2
    case Instruction::ZExt:
109
2
    case Instruction::SExt:
110
2
    case Instruction::FPToUI:
111
2
    case Instruction::FPToSI:
112
2
    case Instruction::UIToFP:
113
2
    case Instruction::SIToFP:
114
2
    case Instruction::FPTrunc:
115
2
    case Instruction::FPExt:
116
2
    case Instruction::PtrToInt:
117
2
    case Instruction::IntToPtr:
118
2
    case Instruction::BitCast:
119
2
      return dyn_cast<Instruction>(
120
2
                  Builder.CreateCast((Instruction::CastOps)OpCode,
121
2
                                     CE->getOperand(0), CE->getType(),
122
2
                                     CE->getName()));
123
2
    default:
124
0
      llvm_unreachable("Unhandled constant expression!\n");
125
12
  }
126
12
}
127
128
10
static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P) {
129
12
  do {
130
12
    SmallVector<WeakTrackingVH, 8> WUsers(CE->user_begin(), CE->user_end());
131
12
    llvm::sort(WUsers);
132
12
    WUsers.erase(std::unique(WUsers.begin(), WUsers.end()), WUsers.end());
133
24
    while (!WUsers.empty())
134
12
      if (WeakTrackingVH WU = WUsers.pop_back_val()) {
135
12
        if (PHINode *PN = dyn_cast<PHINode>(WU)) {
136
6
          for (int I = 0, E = PN->getNumIncomingValues(); I < E; 
++I4
)
137
4
            if (PN->getIncomingValue(I) == CE) {
138
4
              BasicBlock *PredBB = PN->getIncomingBlock(I);
139
4
              if (PredBB->getTerminator()->getNumSuccessors() > 1)
140
1
                PredBB = SplitEdge(PredBB, PN->getParent());
141
4
              Instruction *InsertPos = PredBB->getTerminator();
142
4
              Instruction *NewInst = createReplacementInstr(CE, InsertPos);
143
4
              PN->setOperand(I, NewInst);
144
4
            }
145
10
        } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
146
8
          Instruction *NewInst = createReplacementInstr(CE, Instr);
147
8
          Instr->replaceUsesOfWith(CE, NewInst);
148
8
        } else {
149
2
          ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
150
2
          if (!CExpr || !replaceConstantExprOp(CExpr, P))
151
0
            return false;
152
2
        }
153
12
      }
154
12
  } while (CE->hasNUsesOrMore(1)); // We need to check because a recursive
155
10
  // sibling may have used 'CE' when createReplacementInstr was called.
156
10
  CE->destroyConstant();
157
10
  return true;
158
10
}
159
160
5
static bool rewriteNonInstructionUses(GlobalVariable *GV, Pass *P) {
161
5
  SmallVector<WeakTrackingVH, 8> WUsers;
162
5
  for (User *U : GV->users())
163
9
    if (!isa<Instruction>(U))
164
8
      WUsers.push_back(WeakTrackingVH(U));
165
13
  while (!WUsers.empty())
166
8
    if (WeakTrackingVH WU = WUsers.pop_back_val()) {
167
8
      ConstantExpr *CE = dyn_cast<ConstantExpr>(WU);
168
8
      if (!CE || !replaceConstantExprOp(CE, P))
169
0
        return false;
170
8
    }
171
5
  return true;
172
5
}
173
174
5
static bool isZeroLengthArray(Type *Ty) {
175
5
  ArrayType *AT = dyn_cast<ArrayType>(Ty);
176
5
  return AT && 
(AT->getNumElements() == 0)0
;
177
5
}
178
179
5
bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
180
5
  Module *M = GV->getParent();
181
5
  if (!GV->isThreadLocal())
182
0
    return false;
183
5
184
5
  // Skip globals that we can't lower and leave it for the backend to error.
185
5
  if (!rewriteNonInstructionUses(GV, this) ||
186
5
      !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
187
0
    return false;
188
5
189
5
  // Create replacement global.
190
5
  ArrayType *NewType = createLoweredType(GV->getValueType());
191
5
  Constant *NewInitializer = nullptr;
192
5
  if (GV->hasInitializer())
193
3
    NewInitializer = createLoweredInitializer(NewType,
194
3
                                              GV->getInitializer());
195
5
  GlobalVariable *NewGV =
196
5
    new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
197
5
                       NewInitializer, "", nullptr,
198
5
                       GlobalVariable::NotThreadLocal,
199
5
                       GV->getType()->getAddressSpace(),
200
5
                       GV->isExternallyInitialized());
201
5
202
5
  // Update uses.
203
5
  SmallVector<User *, 16> Users(GV->user_begin(), GV->user_end());
204
16
  for (unsigned I = 0, E = Users.size(); I != E; 
++I11
) {
205
11
    User *U = Users[I];
206
11
    Instruction *Inst = cast<Instruction>(U);
207
11
    IRBuilder<> Builder(Inst);
208
11
    Function *GetID = Intrinsic::getDeclaration(GV->getParent(),
209
11
                                                Intrinsic::xcore_getid);
210
11
    Value *ThreadID = Builder.CreateCall(GetID, {});
211
11
    Value *Addr = Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV,
212
11
                                            {Builder.getInt64(0), ThreadID});
213
11
    U->replaceUsesOfWith(GV, Addr);
214
11
  }
215
5
216
5
  // Remove old global.
217
5
  NewGV->takeName(GV);
218
5
  GV->eraseFromParent();
219
5
  return true;
220
5
}
221
222
70
bool XCoreLowerThreadLocal::runOnModule(Module &M) {
223
70
  // Find thread local globals.
224
70
  bool MadeChange = false;
225
70
  SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
226
70
  for (GlobalVariable &GV : M.globals())
227
94
    if (GV.isThreadLocal())
228
5
      ThreadLocalGlobals.push_back(&GV);
229
75
  for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; 
++I5
) {
230
5
    MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);
231
5
  }
232
70
  return MadeChange;
233
70
}