1 //===- LowerEmuTLS.cpp - Add __emutls_[vt].* 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 // This transformation is required for targets depending on libgcc style
10 // emulated thread local storage variables. For every defined TLS variable xyz,
11 // an __emutls_v.xyz is generated. If there is non-zero initialized value
12 // an __emutls_t.xyz is also generated.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/TargetPassConfig.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/InitializePasses.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Target/TargetMachine.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "loweremutls"
28 
29 namespace {
30 
31 class LowerEmuTLS : public ModulePass {
32 public:
33   static char ID; // Pass identification, replacement for typeid
LowerEmuTLS()34   LowerEmuTLS() : ModulePass(ID) {
35     initializeLowerEmuTLSPass(*PassRegistry::getPassRegistry());
36   }
37 
38   bool runOnModule(Module &M) override;
39 private:
40   bool addEmuTlsVar(Module &M, const GlobalVariable *GV);
copyLinkageVisibility(Module & M,const GlobalVariable * from,GlobalVariable * to)41   static void copyLinkageVisibility(Module &M,
42                                     const GlobalVariable *from,
43                                     GlobalVariable *to) {
44     to->setLinkage(from->getLinkage());
45     to->setVisibility(from->getVisibility());
46     to->setDSOLocal(from->isDSOLocal());
47     if (from->hasComdat()) {
48       to->setComdat(M.getOrInsertComdat(to->getName()));
49       to->getComdat()->setSelectionKind(from->getComdat()->getSelectionKind());
50     }
51   }
52 };
53 }
54 
55 char LowerEmuTLS::ID = 0;
56 
57 INITIALIZE_PASS(LowerEmuTLS, DEBUG_TYPE,
58                 "Add __emutls_[vt]. variables for emultated TLS model", false,
59                 false)
60 
createLowerEmuTLSPass()61 ModulePass *llvm::createLowerEmuTLSPass() { return new LowerEmuTLS(); }
62 
runOnModule(Module & M)63 bool LowerEmuTLS::runOnModule(Module &M) {
64   if (skipModule(M))
65     return false;
66 
67   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
68   if (!TPC)
69     return false;
70 
71   auto &TM = TPC->getTM<TargetMachine>();
72   if (!TM.useEmulatedTLS())
73     return false;
74 
75   bool Changed = false;
76   SmallVector<const GlobalVariable*, 8> TlsVars;
77   for (const auto &G : M.globals()) {
78     if (G.isThreadLocal())
79       TlsVars.append({&G});
80   }
81   for (const auto *const G : TlsVars)
82     Changed |= addEmuTlsVar(M, G);
83   return Changed;
84 }
85 
addEmuTlsVar(Module & M,const GlobalVariable * GV)86 bool LowerEmuTLS::addEmuTlsVar(Module &M, const GlobalVariable *GV) {
87   LLVMContext &C = M.getContext();
88   PointerType *VoidPtrType = Type::getInt8PtrTy(C);
89 
90   std::string EmuTlsVarName = ("__emutls_v." + GV->getName()).str();
91   GlobalVariable *EmuTlsVar = M.getNamedGlobal(EmuTlsVarName);
92   if (EmuTlsVar)
93     return false;  // It has been added before.
94 
95   const DataLayout &DL = M.getDataLayout();
96   Constant *NullPtr = ConstantPointerNull::get(VoidPtrType);
97 
98   // Get non-zero initializer from GV's initializer.
99   const Constant *InitValue = nullptr;
100   if (GV->hasInitializer()) {
101     InitValue = GV->getInitializer();
102     const ConstantInt *InitIntValue = dyn_cast<ConstantInt>(InitValue);
103     // When GV's init value is all 0, omit the EmuTlsTmplVar and let
104     // the emutls library function to reset newly allocated TLS variables.
105     if (isa<ConstantAggregateZero>(InitValue) ||
106         (InitIntValue && InitIntValue->isZero()))
107       InitValue = nullptr;
108   }
109 
110   // Create the __emutls_v. symbol, whose type has 4 fields:
111   //     word size;   // size of GV in bytes
112   //     word align;  // alignment of GV
113   //     void *ptr;   // initialized to 0; set at run time per thread.
114   //     void *templ; // 0 or point to __emutls_t.*
115   // sizeof(word) should be the same as sizeof(void*) on target.
116   IntegerType *WordType = DL.getIntPtrType(C);
117   PointerType *InitPtrType = InitValue ?
118       PointerType::getUnqual(InitValue->getType()) : VoidPtrType;
119   Type *ElementTypes[4] = {WordType, WordType, VoidPtrType, InitPtrType};
120   ArrayRef<Type*> ElementTypeArray(ElementTypes, 4);
121   StructType *EmuTlsVarType = StructType::create(ElementTypeArray);
122   EmuTlsVar = cast<GlobalVariable>(
123       M.getOrInsertGlobal(EmuTlsVarName, EmuTlsVarType));
124   copyLinkageVisibility(M, GV, EmuTlsVar);
125 
126   // Define "__emutls_t.*" and "__emutls_v.*" only if GV is defined.
127   if (!GV->hasInitializer())
128     return true;
129 
130   Type *GVType = GV->getValueType();
131   Align GVAlignment = DL.getValueOrABITypeAlignment(GV->getAlign(), GVType);
132 
133   // Define "__emutls_t.*" if there is InitValue
134   GlobalVariable *EmuTlsTmplVar = nullptr;
135   if (InitValue) {
136     std::string EmuTlsTmplName = ("__emutls_t." + GV->getName()).str();
137     EmuTlsTmplVar = dyn_cast_or_null<GlobalVariable>(
138         M.getOrInsertGlobal(EmuTlsTmplName, GVType));
139     assert(EmuTlsTmplVar && "Failed to create emualted TLS initializer");
140     EmuTlsTmplVar->setConstant(true);
141     EmuTlsTmplVar->setInitializer(const_cast<Constant*>(InitValue));
142     EmuTlsTmplVar->setAlignment(GVAlignment);
143     copyLinkageVisibility(M, GV, EmuTlsTmplVar);
144   }
145 
146   // Define "__emutls_v.*" with initializer and alignment.
147   Constant *ElementValues[4] = {
148       ConstantInt::get(WordType, DL.getTypeStoreSize(GVType)),
149       ConstantInt::get(WordType, GVAlignment.value()), NullPtr,
150       EmuTlsTmplVar ? EmuTlsTmplVar : NullPtr};
151   ArrayRef<Constant*> ElementValueArray(ElementValues, 4);
152   EmuTlsVar->setInitializer(
153       ConstantStruct::get(EmuTlsVarType, ElementValueArray));
154   Align MaxAlignment =
155       std::max(DL.getABITypeAlign(WordType), DL.getABITypeAlign(VoidPtrType));
156   EmuTlsVar->setAlignment(MaxAlignment);
157   return true;
158 }
159