Silencing a warning about control flow reaching the end of a non-void function.
[oota-llvm.git] / lib / Target / XCore / XCoreLowerThreadLocal.cpp
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"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/NoFolder.h"
26 #include "llvm/Support/ValueHandle.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     XCoreLowerThreadLocal() : ModulePass(ID) {
45       initializeXCoreLowerThreadLocalPass(*PassRegistry::getPassRegistry());
46     }
47
48     bool lowerGlobal(GlobalVariable *GV);
49
50     bool runOnModule(Module &M);
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 ModulePass *llvm::createXCoreLowerThreadLocalPass() {
60   return new XCoreLowerThreadLocal();
61 }
62
63 static ArrayType *createLoweredType(Type *OriginalType) {
64   return ArrayType::get(OriginalType, MaxThreads);
65 }
66
67 static Constant *
68 createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
69   SmallVector<Constant *, 8> Elements(MaxThreads);
70   for (unsigned i = 0; i != MaxThreads; ++i) {
71     Elements[i] = OriginalInitializer;
72   }
73   return ConstantArray::get(NewType, Elements);
74 }
75
76 static Instruction *
77 createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
78   IRBuilder<true,NoFolder> Builder(Instr);
79   unsigned OpCode = CE->getOpcode();
80   switch (OpCode) {
81     case Instruction::GetElementPtr: {
82       SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end());
83       ArrayRef<Value *> CEOps(CEOpVec);
84       return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(CEOps[0],
85                                                              CEOps.slice(1)));
86     }
87     case Instruction::Add:
88     case Instruction::Sub:
89     case Instruction::Mul:
90     case Instruction::UDiv:
91     case Instruction::SDiv:
92     case Instruction::FDiv:
93     case Instruction::URem:
94     case Instruction::SRem:
95     case Instruction::FRem:
96     case Instruction::Shl:
97     case Instruction::LShr:
98     case Instruction::AShr:
99     case Instruction::And:
100     case Instruction::Or:
101     case Instruction::Xor:
102       return dyn_cast<Instruction>(
103                   Builder.CreateBinOp((Instruction::BinaryOps)OpCode,
104                                       CE->getOperand(0), CE->getOperand(1),
105                                       CE->getName()));
106     case Instruction::Trunc:
107     case Instruction::ZExt:
108     case Instruction::SExt:
109     case Instruction::FPToUI:
110     case Instruction::FPToSI:
111     case Instruction::UIToFP:
112     case Instruction::SIToFP:
113     case Instruction::FPTrunc:
114     case Instruction::FPExt:
115     case Instruction::PtrToInt:
116     case Instruction::IntToPtr:
117     case Instruction::BitCast:
118       return dyn_cast<Instruction>(
119                   Builder.CreateCast((Instruction::CastOps)OpCode,
120                                      CE->getOperand(0), CE->getType(),
121                                      CE->getName()));
122     default:
123       assert(0 && "Unhandled constant expression!\n");
124   }
125   llvm_unreachable("Unhandled constant expression!\n");
126 }
127
128 static bool replaceConstantExprOp(ConstantExpr *CE) {
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     while (!WUsers.empty())
135       if (WeakVH WU = WUsers.pop_back_val()) {
136         if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
137           Instruction *NewInst = createReplacementInstr(CE, Instr);
138           assert(NewInst && "Must build an instruction\n");
139           // If NewInst uses a CE being handled in an earlier recursion the
140           // earlier recursion's do-while-hasNUsesOrMore(1) will run again.
141           Instr->replaceUsesOfWith(CE, NewInst);
142         } else {
143           ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
144           if (!CExpr || !replaceConstantExprOp(CExpr))
145             return false;
146         }
147       }
148   } while (CE->hasNUsesOrMore(1)); // Does a recursion's NewInst use CE?
149   CE->destroyConstant();
150   return true;
151 }
152
153 static bool rewriteNonInstructionUses(GlobalVariable *GV) {
154   SmallVector<WeakVH,8> WUsers;
155   for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
156     if (!isa<Instruction>(*I))
157       WUsers.push_back(WeakVH(*I));
158   while (!WUsers.empty())
159     if (WeakVH WU = WUsers.pop_back_val()) {
160       ConstantExpr *CE = dyn_cast<ConstantExpr>(WU);
161       if (!CE || !replaceConstantExprOp(CE))
162         return false;
163     }
164   return true;
165 }
166
167 static bool isZeroLengthArray(Type *Ty) {
168   ArrayType *AT = dyn_cast<ArrayType>(Ty);
169   return AT && (AT->getNumElements() == 0);
170 }
171
172 bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
173   Module *M = GV->getParent();
174   LLVMContext &Ctx = M->getContext();
175   if (!GV->isThreadLocal())
176     return false;
177
178   // Skip globals that we can't lower and leave it for the backend to error.
179   if (!rewriteNonInstructionUses(GV) ||
180       !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
181     return false;
182
183   // Create replacement global.
184   ArrayType *NewType = createLoweredType(GV->getType()->getElementType());
185   Constant *NewInitializer = 0;
186   if (GV->hasInitializer())
187     NewInitializer = createLoweredInitializer(NewType,
188                                               GV->getInitializer());
189   GlobalVariable *NewGV =
190     new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
191                        NewInitializer, "", 0, GlobalVariable::NotThreadLocal,
192                        GV->getType()->getAddressSpace(),
193                        GV->isExternallyInitialized());
194
195   // Update uses.
196   SmallVector<User *, 16> Users(GV->use_begin(), GV->use_end());
197   for (unsigned I = 0, E = Users.size(); I != E; ++I) {
198     User *U = Users[I];
199     Instruction *Inst = cast<Instruction>(U);
200     IRBuilder<> Builder(Inst);
201     Function *GetID = Intrinsic::getDeclaration(GV->getParent(),
202                                                 Intrinsic::xcore_getid);
203     Value *ThreadID = Builder.CreateCall(GetID);
204     SmallVector<Value *, 2> Indices;
205     Indices.push_back(Constant::getNullValue(Type::getInt64Ty(Ctx)));
206     Indices.push_back(ThreadID);
207     Value *Addr = Builder.CreateInBoundsGEP(NewGV, Indices);
208     U->replaceUsesOfWith(GV, Addr);
209   }
210
211   // Remove old global.
212   NewGV->takeName(GV);
213   GV->eraseFromParent();
214   return true;
215 }
216
217 bool XCoreLowerThreadLocal::runOnModule(Module &M) {
218   // Find thread local globals.
219   bool MadeChange = false;
220   SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
221   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
222        GVI != E; ++GVI) {
223     GlobalVariable *GV = GVI;
224     if (GV->isThreadLocal())
225       ThreadLocalGlobals.push_back(GV);
226   }
227   for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) {
228     MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);
229   }
230   return MadeChange;
231 }