LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
XCoreLowerThreadLocal.cpp
Go to the documentation of this file.
1 //===-- XCoreLowerThreadLocal - Lower thread local variables --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file contains a pass that lowers thread local variables on the
12 /// XCore.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "XCore.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Pass.h"
25 #include "llvm/Support/NoFolder.h"
28 
29 #define DEBUG_TYPE "xcore-lower-thread-local"
30 
31 using namespace llvm;
32 
34  "xcore-max-threads", cl::Optional,
35  cl::desc("Maximum number of threads (for emulation thread-local storage)"),
36  cl::Hidden, cl::value_desc("number"), cl::init(8));
37 
38 namespace {
39  /// Lowers thread local variables on the XCore. Each thread local variable is
40  /// expanded to an array of n elements indexed by the thread ID where n is the
41  /// fixed number hardware threads supported by the device.
42  struct XCoreLowerThreadLocal : public ModulePass {
43  static char ID;
44 
45  XCoreLowerThreadLocal() : ModulePass(ID) {
47  }
48 
49  bool lowerGlobal(GlobalVariable *GV);
50 
51  bool runOnModule(Module &M);
52  };
53 }
54 
56 
57 INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
58  "Lower thread local variables", false, false)
59 
61  return new XCoreLowerThreadLocal();
62 }
63 
64 static ArrayType *createLoweredType(Type *OriginalType) {
65  return ArrayType::get(OriginalType, MaxThreads);
66 }
67 
68 static Constant *
69 createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
71  for (unsigned i = 0; i != MaxThreads; ++i) {
72  Elements[i] = OriginalInitializer;
73  }
74  return ConstantArray::get(NewType, Elements);
75 }
76 
77 static Instruction *
79  IRBuilder<true,NoFolder> Builder(Instr);
80  unsigned OpCode = CE->getOpcode();
81  switch (OpCode) {
82  case Instruction::GetElementPtr: {
83  SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end());
84  ArrayRef<Value *> CEOps(CEOpVec);
85  return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(CEOps[0],
86  CEOps.slice(1)));
87  }
88  case Instruction::Add:
89  case Instruction::Sub:
90  case Instruction::Mul:
91  case Instruction::UDiv:
92  case Instruction::SDiv:
93  case Instruction::FDiv:
94  case Instruction::URem:
95  case Instruction::SRem:
96  case Instruction::FRem:
97  case Instruction::Shl:
98  case Instruction::LShr:
99  case Instruction::AShr:
100  case Instruction::And:
101  case Instruction::Or:
102  case Instruction::Xor:
103  return dyn_cast<Instruction>(
104  Builder.CreateBinOp((Instruction::BinaryOps)OpCode,
105  CE->getOperand(0), CE->getOperand(1),
106  CE->getName()));
107  case Instruction::Trunc:
108  case Instruction::ZExt:
109  case Instruction::SExt:
110  case Instruction::FPToUI:
111  case Instruction::FPToSI:
112  case Instruction::UIToFP:
113  case Instruction::SIToFP:
114  case Instruction::FPTrunc:
115  case Instruction::FPExt:
116  case Instruction::PtrToInt:
117  case Instruction::IntToPtr:
118  case Instruction::BitCast:
119  return dyn_cast<Instruction>(
120  Builder.CreateCast((Instruction::CastOps)OpCode,
121  CE->getOperand(0), CE->getType(),
122  CE->getName()));
123  default:
124  llvm_unreachable("Unhandled constant expression!\n");
125  }
126 }
127 
129  do {
130  SmallVector<WeakVH,8> WUsers;
131  for (Value::use_iterator I = CE->use_begin(), E = CE->use_end();
132  I != E; ++I)
133  WUsers.push_back(WeakVH(*I));
134  std::sort(WUsers.begin(), WUsers.end());
135  WUsers.erase(std::unique(WUsers.begin(), WUsers.end()), WUsers.end());
136  while (!WUsers.empty())
137  if (WeakVH WU = WUsers.pop_back_val()) {
138  if (PHINode *PN = dyn_cast<PHINode>(WU)) {
139  for (int I = 0, E = PN->getNumIncomingValues(); I < E; ++I)
140  if (PN->getIncomingValue(I) == CE) {
141  BasicBlock *PredBB = PN->getIncomingBlock(I);
142  if (PredBB->getTerminator()->getNumSuccessors() > 1)
143  PredBB = SplitEdge(PredBB, PN->getParent(), P);
144  Instruction *InsertPos = PredBB->getTerminator();
145  Instruction *NewInst = createReplacementInstr(CE, InsertPos);
146  PN->setOperand(I, NewInst);
147  }
148  } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
149  Instruction *NewInst = createReplacementInstr(CE, Instr);
150  Instr->replaceUsesOfWith(CE, NewInst);
151  } else {
152  ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
153  if (!CExpr || !replaceConstantExprOp(CExpr, P))
154  return false;
155  }
156  }
157  } while (CE->hasNUsesOrMore(1)); // We need to check becasue a recursive
158  // sibbling may have used 'CE' when createReplacementInstr was called.
159  CE->destroyConstant();
160  return true;
161 }
162 
164  SmallVector<WeakVH,8> WUsers;
165  for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
166  if (!isa<Instruction>(*I))
167  WUsers.push_back(WeakVH(*I));
168  while (!WUsers.empty())
169  if (WeakVH WU = WUsers.pop_back_val()) {
171  if (!CE || !replaceConstantExprOp(CE, P))
172  return false;
173  }
174  return true;
175 }
176 
177 static bool isZeroLengthArray(Type *Ty) {
178  ArrayType *AT = dyn_cast<ArrayType>(Ty);
179  return AT && (AT->getNumElements() == 0);
180 }
181 
182 bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
183  Module *M = GV->getParent();
184  LLVMContext &Ctx = M->getContext();
185  if (!GV->isThreadLocal())
186  return false;
187 
188  // Skip globals that we can't lower and leave it for the backend to error.
189  if (!rewriteNonInstructionUses(GV, this) ||
190  !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
191  return false;
192 
193  // Create replacement global.
194  ArrayType *NewType = createLoweredType(GV->getType()->getElementType());
195  Constant *NewInitializer = 0;
196  if (GV->hasInitializer())
197  NewInitializer = createLoweredInitializer(NewType,
198  GV->getInitializer());
199  GlobalVariable *NewGV =
200  new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
201  NewInitializer, "", 0, GlobalVariable::NotThreadLocal,
202  GV->getType()->getAddressSpace(),
204 
205  // Update uses.
207  for (unsigned I = 0, E = Users.size(); I != E; ++I) {
208  User *U = Users[I];
209  Instruction *Inst = cast<Instruction>(U);
210  IRBuilder<> Builder(Inst);
213  Value *ThreadID = Builder.CreateCall(GetID);
214  SmallVector<Value *, 2> Indices;
216  Indices.push_back(ThreadID);
217  Value *Addr = Builder.CreateInBoundsGEP(NewGV, Indices);
218  U->replaceUsesOfWith(GV, Addr);
219  }
220 
221  // Remove old global.
222  NewGV->takeName(GV);
223  GV->eraseFromParent();
224  return true;
225 }
226 
227 bool XCoreLowerThreadLocal::runOnModule(Module &M) {
228  // Find thread local globals.
229  bool MadeChange = false;
230  SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
231  for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
232  GVI != E; ++GVI) {
233  GlobalVariable *GV = GVI;
234  if (GV->isThreadLocal())
235  ThreadLocalGlobals.push_back(GV);
236  }
237  for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) {
238  MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);
239  }
240  return MadeChange;
241 }
use_iterator use_end()
Definition: Value.h:152
LinkageTypes getLinkage() const
Definition: GlobalValue.h:218
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1164
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, Pass *P)
static PassRegistry * getPassRegistry()
The main container class for the LLVM Intermediate Representation.
Definition: Module.h:112
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:116
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:445
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:242
iv Induction Variable Users
Definition: IVUsers.cpp:39
void initializeXCoreLowerThreadLocalPass(PassRegistry &p)
const Constant * getInitializer() const
unsigned getOpcode() const
getOpcode - Return the opcode at the root of this constant expression
Definition: Constants.h:1049
op_iterator op_begin()
Definition: User.h:116
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:111
StringRef getName() const
Definition: Value.cpp:167
ModulePass * createXCoreLowerThreadLocalPass()
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:430
#define llvm_unreachable(msg)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:421
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
global_iterator global_begin()
Definition: Module.h:521
virtual void destroyConstant()
Definition: Constants.cpp:2160
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:56
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Definition: Function.cpp:683
void takeName(Value *V)
Definition: Value.cpp:239
Type * getElementType() const
Definition: DerivedTypes.h:319
void replaceUsesOfWith(Value *From, Value *To)
Definition: User.cpp:26
unsigned getNumSuccessors() const
Definition: InstrTypes.h:59
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:314
bool isExternallyInitialized() const
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:834
INITIALIZE_PASS(XCoreLowerThreadLocal,"xcore-lower-thread-local","Lower thread local variables", false, false) ModulePass *llvm
LLVM Basic Block Representation.
Definition: BasicBlock.h:72
static bool isZeroLengthArray(Type *Ty)
LLVM Constant Representation.
Definition: Constant.h:41
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
Definition: APInt.h:1845
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:745
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Definition: APInt.h:1850
virtual void eraseFromParent()
Definition: Globals.cpp:142
op_iterator op_end()
Definition: User.h:118
uint64_t getNumElements() const
Definition: DerivedTypes.h:348
Value * getOperand(unsigned i) const
Definition: User.h:88
static Instruction * createReplacementInstr(ConstantExpr *CE, Instruction *Instr)
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:944
iterator erase(iterator I)
Definition: SmallVector.h:478
static ArrayType * createLoweredType(Type *OriginalType)
global_iterator global_end()
Definition: Module.h:523
Type * getType() const
Definition: Value.h:111
static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P)
bool hasInitializer() const
bool isConstant() const
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
Definition: APInt.h:1840
use_iterator use_begin()
Definition: Value.h:150
PointerType * getType() const
getType - Global values are always pointers.
Definition: GlobalValue.h:107
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
static ArrayType * get(Type *ElementType, uint64_t NumElements)
Definition: Type.cpp:679
static Constant * createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer)
bool hasNUsesOrMore(unsigned N) const
Definition: Value.cpp:103
static cl::opt< unsigned > MaxThreads("xcore-max-threads", cl::Optional, cl::desc("Maximum number of threads (for emulation thread-local storage)"), cl::Hidden, cl::value_desc("number"), cl::init(8))
static bool rewriteNonInstructionUses(GlobalVariable *GV, Pass *P)
Module * getParent()
Definition: GlobalValue.h:286
LLVM Value Representation.
Definition: Value.h:66
bool isSized() const
Definition: Type.h:278
LLVMContext & getContext() const
Definition: Module.h:249