LLVM 19.0.0git
XCoreLowerThreadLocal.cpp
Go to the documentation of this file.
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"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/Intrinsics.h"
21#include "llvm/IR/IntrinsicsXCore.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/NoFolder.h"
24#include "llvm/IR/ValueHandle.h"
25#include "llvm/Pass.h"
28
29#define DEBUG_TYPE "xcore-lower-thread-local"
30
31using 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
38namespace {
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) override;
52 };
53}
54
55char XCoreLowerThreadLocal::ID = 0;
56
57INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
58 "Lower thread local variables", false, false)
59
61 return new XCoreLowerThreadLocal();
62}
63
64static ArrayType *createLoweredType(Type *OriginalType) {
65 return ArrayType::get(OriginalType, MaxThreads);
66}
67
68static Constant *
69createLoweredInitializer(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
79 do {
80 SmallVector<WeakTrackingVH, 8> WUsers(CE->users());
81 llvm::sort(WUsers);
82 WUsers.erase(llvm::unique(WUsers), WUsers.end());
83 while (!WUsers.empty())
84 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
85 if (PHINode *PN = dyn_cast<PHINode>(WU)) {
86 for (int I = 0, E = PN->getNumIncomingValues(); I < E; ++I)
87 if (PN->getIncomingValue(I) == CE) {
88 BasicBlock *PredBB = PN->getIncomingBlock(I);
89 if (PredBB->getTerminator()->getNumSuccessors() > 1)
90 PredBB = SplitEdge(PredBB, PN->getParent());
91 BasicBlock::iterator InsertPos =
92 PredBB->getTerminator()->getIterator();
93 Instruction *NewInst = CE->getAsInstruction();
94 NewInst->insertBefore(*PredBB, InsertPos);
95 PN->setOperand(I, NewInst);
96 }
97 } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
98 Instruction *NewInst = CE->getAsInstruction();
99 NewInst->insertBefore(*Instr->getParent(), Instr->getIterator());
100 Instr->replaceUsesOfWith(CE, NewInst);
101 } else {
102 ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
103 if (!CExpr || !replaceConstantExprOp(CExpr, P))
104 return false;
105 }
106 }
107 } while (CE->hasNUsesOrMore(1)); // We need to check because a recursive
108 // sibling may have used 'CE' when getAsInstruction was called.
109 CE->destroyConstant();
110 return true;
111}
112
115 for (User *U : GV->users())
116 if (!isa<Instruction>(U))
117 WUsers.push_back(WeakTrackingVH(U));
118 while (!WUsers.empty())
119 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
120 ConstantExpr *CE = dyn_cast<ConstantExpr>(WU);
121 if (!CE || !replaceConstantExprOp(CE, P))
122 return false;
123 }
124 return true;
125}
126
127static bool isZeroLengthArray(Type *Ty) {
128 ArrayType *AT = dyn_cast<ArrayType>(Ty);
129 return AT && (AT->getNumElements() == 0);
130}
131
132bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
133 Module *M = GV->getParent();
134 if (!GV->isThreadLocal())
135 return false;
136
137 // Skip globals that we can't lower and leave it for the backend to error.
138 if (!rewriteNonInstructionUses(GV, this) ||
139 !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
140 return false;
141
142 // Create replacement global.
143 ArrayType *NewType = createLoweredType(GV->getValueType());
144 Constant *NewInitializer = nullptr;
145 if (GV->hasInitializer())
146 NewInitializer = createLoweredInitializer(NewType,
147 GV->getInitializer());
148 GlobalVariable *NewGV =
149 new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
150 NewInitializer, "", nullptr,
151 GlobalVariable::NotThreadLocal,
152 GV->getType()->getAddressSpace(),
154
155 // Update uses.
157 for (unsigned I = 0, E = Users.size(); I != E; ++I) {
158 User *U = Users[I];
159 Instruction *Inst = cast<Instruction>(U);
160 IRBuilder<> Builder(Inst);
162 Intrinsic::xcore_getid);
163 Value *ThreadID = Builder.CreateCall(GetID, {});
164 Value *Addr = Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV,
165 {Builder.getInt64(0), ThreadID});
166 U->replaceUsesOfWith(GV, Addr);
167 }
168
169 // Remove old global.
170 NewGV->takeName(GV);
171 GV->eraseFromParent();
172 return true;
173}
174
175bool XCoreLowerThreadLocal::runOnModule(Module &M) {
176 // Find thread local globals.
177 bool MadeChange = false;
178 SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
179 for (GlobalVariable &GV : M.globals())
180 if (GV.isThreadLocal())
181 ThreadLocalGlobals.push_back(&GV);
182 for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) {
183 MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);
184 }
185 return MadeChange;
186}
This file contains the declarations for the subclasses of Constant, which represent the different fla...
uint64_t Addr
iv Induction Variable Users
Definition: IVUsers.cpp:48
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P)
static bool isZeroLengthArray(Type *Ty)
static Constant * createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer)
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)
static ArrayType * createLoweredType(Type *OriginalType)
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:208
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:166
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:223
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1292
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1084
This is an important base class in LLVM.
Definition: Constant.h:41
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:262
LinkageTypes getLinkage() const
Definition: GlobalValue.h:545
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:293
Type * getValueType() const
Definition: GlobalValue.h:295
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isExternallyInitialized() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:477
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2664
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:92
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:679
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
iterator erase(const_iterator CI)
Definition: SmallVector.h:750
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
LLVM Value Representation.
Definition: Value.h:74
iterator_range< user_iterator > users()
Definition: Value.h:421
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
self_iterator getIterator()
Definition: ilist_node.h:132
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1474
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto unique(Range &&R, Predicate P)
Definition: STLExtras.h:2013
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
void initializeXCoreLowerThreadLocalPass(PassRegistry &p)
ModulePass * createXCoreLowerThreadLocalPass()
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...