LLVM 24.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/ValueHandle.h"
24#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) {}
46
47 bool lowerGlobal(GlobalVariable *GV);
48
49 bool runOnModule(Module &M) override;
50 };
51}
52
53char XCoreLowerThreadLocal::ID = 0;
54
55INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
56 "Lower thread local variables", false, false)
57
59 return new XCoreLowerThreadLocal();
60}
61
62static ArrayType *createLoweredType(Type *OriginalType) {
63 return ArrayType::get(OriginalType, MaxThreads);
64}
65
66static Constant *
67createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
69 for (unsigned i = 0; i != MaxThreads; ++i) {
70 Elements[i] = OriginalInitializer;
71 }
72 return ConstantArray::get(NewType, Elements);
73}
74
75
77 do {
78 SmallVector<WeakTrackingVH, 8> WUsers(CE->users());
79 llvm::sort(WUsers);
80 WUsers.erase(llvm::unique(WUsers), WUsers.end());
81 while (!WUsers.empty())
82 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
83 if (PHINode *PN = dyn_cast<PHINode>(WU)) {
84 for (int I = 0, E = PN->getNumIncomingValues(); I < E; ++I)
85 if (PN->getIncomingValue(I) == CE) {
86 BasicBlock *PredBB = PN->getIncomingBlock(I);
87 if (PredBB->getTerminator()->getNumSuccessors() > 1)
88 PredBB = SplitEdge(PredBB, PN->getParent());
89 BasicBlock::iterator InsertPos =
90 PredBB->getTerminator()->getIterator();
91 Instruction *NewInst = CE->getAsInstruction();
92 NewInst->insertBefore(*PredBB, InsertPos);
93 PN->setOperand(I, NewInst);
94 }
95 } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
96 Instruction *NewInst = CE->getAsInstruction();
97 NewInst->insertBefore(*Instr->getParent(), Instr->getIterator());
98 Instr->replaceUsesOfWith(CE, NewInst);
99 } else {
101 if (!CExpr || !replaceConstantExprOp(CExpr, P))
102 return false;
103 }
104 }
105 } while (CE->hasNUsesOrMore(1)); // We need to check because a recursive
106 // sibling may have used 'CE' when getAsInstruction was called.
107 CE->destroyConstant();
108 return true;
109}
110
113 for (User *U : GV->users())
114 if (!isa<Instruction>(U))
115 WUsers.push_back(WeakTrackingVH(U));
116 while (!WUsers.empty())
117 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
119 if (!CE || !replaceConstantExprOp(CE, P))
120 return false;
121 }
122 return true;
123}
124
125bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
126 Module *M = GV->getParent();
127 if (!GV->isThreadLocal())
128 return false;
129
130 if (!rewriteNonInstructionUses(GV, this))
131 return false;
132
133 // The lowered representation needs an ArrayType of the value type, which
134 // requires a known per-element stride: reject anything that can't provide
135 // one now, with a clear diagnostic, rather than emitting a malformed GEP
136 // that only fails much later (and much less clearly) in instruction
137 // selection.
138 if (!GV->getValueType()->isSized() ||
139 GV->getGlobalSize(M->getDataLayout()) == 0)
140 reportFatalUsageError("Size of thread local object '" + GV->getName() +
141 "' is unknown");
142
143 // Create replacement global.
144 ArrayType *NewType = createLoweredType(GV->getValueType());
145 Constant *NewInitializer = nullptr;
146 if (GV->hasInitializer())
147 NewInitializer = createLoweredInitializer(NewType,
148 GV->getInitializer());
149 GlobalVariable *NewGV =
150 new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
151 NewInitializer, "", nullptr,
152 GlobalVariable::NotThreadLocal,
153 GV->getType()->getAddressSpace(),
155
156 // Update uses.
158 for (User *U : Users) {
160 IRBuilder<> Builder(Inst);
161 Value *ThreadID = Builder.CreateIntrinsic(Intrinsic::xcore_getid, {});
162 Value *Addr = Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV,
163 {Builder.getInt64(0), ThreadID});
164 U->replaceUsesOfWith(GV, Addr);
165 }
166
167 // Remove old global.
168 NewGV->takeName(GV);
169 GV->eraseFromParent();
170 return true;
171}
172
173bool XCoreLowerThreadLocal::runOnModule(Module &M) {
174 // Find thread local globals.
175 bool MadeChange = false;
176 SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
177 for (GlobalVariable &GV : M.globals())
178 if (GV.isThreadLocal())
179 ThreadLocalGlobals.push_back(&GV);
180 for (GlobalVariable *GV : ThreadLocalGlobals)
181 MadeChange |= lowerGlobal(GV);
182 return MadeChange;
183}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
iv Induction Variable Users
Definition IVUsers.cpp:48
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P)
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)
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
This is an important base class in LLVM.
Definition Constant.h:43
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
LinkageTypes getLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isExternallyInitialized() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
unsigned getAddressSpace() const
Return the address space of the Pointer type.
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Value handle that is nullable, but tries to track the Value.
self_iterator getIterator()
Definition ilist_node.h:123
initializer< Ty > init(const Ty &Val)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
ModulePass * createXCoreLowerThreadLocalPass()
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI 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...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177