Coverage Report

Created: 2018-12-13 20:48

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/CodeGen/LoopGenerators.cpp
Line
Count
Source
1
//===------ LoopGenerators.cpp -  IR helper to create loops ---------------===//
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
// This file contains functions to create scalar and parallel loops as LLVM-IR.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "polly/CodeGen/LoopGenerators.h"
15
#include "polly/ScopDetection.h"
16
#include "llvm/Analysis/LoopInfo.h"
17
#include "llvm/IR/DataLayout.h"
18
#include "llvm/IR/Dominators.h"
19
#include "llvm/IR/Module.h"
20
#include "llvm/Support/CommandLine.h"
21
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
22
23
using namespace llvm;
24
using namespace polly;
25
26
static cl::opt<int>
27
    PollyNumThreads("polly-num-threads",
28
                    cl::desc("Number of threads to use (0 = auto)"), cl::Hidden,
29
                    cl::init(0));
30
31
// We generate a loop of either of the following structures:
32
//
33
//              BeforeBB                      BeforeBB
34
//                 |                             |
35
//                 v                             v
36
//              GuardBB                      PreHeaderBB
37
//              /      |                         |   _____
38
//     __  PreHeaderBB  |                        v  \/    |
39
//    /  \    /         |                     HeaderBB  latch
40
// latch  HeaderBB      |                        |\       |
41
//    \  /    \         /                        | \------/
42
//     <       \       /                         |
43
//              \     /                          v
44
//              ExitBB                         ExitBB
45
//
46
// depending on whether or not we know that it is executed at least once. If
47
// not, GuardBB checks if the loop is executed at least once. If this is the
48
// case we branch to PreHeaderBB and subsequently to the HeaderBB, which
49
// contains the loop iv 'polly.indvar', the incremented loop iv
50
// 'polly.indvar_next' as well as the condition to check if we execute another
51
// iteration of the loop. After the loop has finished, we branch to ExitBB.
52
// We expect the type of UB, LB, UB+Stride to be large enough for values that
53
// UB may take throughout the execution of the loop, including the computation
54
// of indvar + Stride before the final abort.
55
Value *polly::createLoop(Value *LB, Value *UB, Value *Stride,
56
                         PollyIRBuilder &Builder, LoopInfo &LI,
57
                         DominatorTree &DT, BasicBlock *&ExitBB,
58
                         ICmpInst::Predicate Predicate,
59
                         ScopAnnotator *Annotator, bool Parallel, bool UseGuard,
60
308
                         bool LoopVectDisabled) {
61
308
  Function *F = Builder.GetInsertBlock()->getParent();
62
308
  LLVMContext &Context = F->getContext();
63
308
64
308
  assert(LB->getType() == UB->getType() && "Types of loop bounds do not match");
65
308
  IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
66
308
  assert(LoopIVType && "UB is not integer?");
67
308
68
308
  BasicBlock *BeforeBB = Builder.GetInsertBlock();
69
308
  BasicBlock *GuardBB =
70
308
      UseGuard ? 
BasicBlock::Create(Context, "polly.loop_if", F)129
:
nullptr179
;
71
308
  BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
72
308
  BasicBlock *PreHeaderBB =
73
308
      BasicBlock::Create(Context, "polly.loop_preheader", F);
74
308
75
308
  // Update LoopInfo
76
308
  Loop *OuterLoop = LI.getLoopFor(BeforeBB);
77
308
  Loop *NewLoop = LI.AllocateLoop();
78
308
79
308
  if (OuterLoop)
80
94
    OuterLoop->addChildLoop(NewLoop);
81
214
  else
82
214
    LI.addTopLevelLoop(NewLoop);
83
308
84
308
  if (OuterLoop) {
85
94
    if (GuardBB)
86
45
      OuterLoop->addBasicBlockToLoop(GuardBB, LI);
87
94
    OuterLoop->addBasicBlockToLoop(PreHeaderBB, LI);
88
94
  }
89
308
90
308
  NewLoop->addBasicBlockToLoop(HeaderBB, LI);
91
308
92
308
  // Notify the annotator (if present) that we have a new loop, but only
93
308
  // after the header block is set.
94
308
  if (Annotator)
95
278
    Annotator->pushLoop(NewLoop, Parallel);
96
308
97
308
  // ExitBB
98
308
  ExitBB = SplitBlock(BeforeBB, &*Builder.GetInsertPoint(), &DT, &LI);
99
308
  ExitBB->setName("polly.loop_exit");
100
308
101
308
  // BeforeBB
102
308
  if (GuardBB) {
103
129
    BeforeBB->getTerminator()->setSuccessor(0, GuardBB);
104
129
    DT.addNewBlock(GuardBB, BeforeBB);
105
129
106
129
    // GuardBB
107
129
    Builder.SetInsertPoint(GuardBB);
108
129
    Value *LoopGuard;
109
129
    LoopGuard = Builder.CreateICmp(Predicate, LB, UB);
110
129
    LoopGuard->setName("polly.loop_guard");
111
129
    Builder.CreateCondBr(LoopGuard, PreHeaderBB, ExitBB);
112
129
    DT.addNewBlock(PreHeaderBB, GuardBB);
113
179
  } else {
114
179
    BeforeBB->getTerminator()->setSuccessor(0, PreHeaderBB);
115
179
    DT.addNewBlock(PreHeaderBB, BeforeBB);
116
179
  }
117
308
118
308
  // PreHeaderBB
119
308
  Builder.SetInsertPoint(PreHeaderBB);
120
308
  Builder.CreateBr(HeaderBB);
121
308
122
308
  // HeaderBB
123
308
  DT.addNewBlock(HeaderBB, PreHeaderBB);
124
308
  Builder.SetInsertPoint(HeaderBB);
125
308
  PHINode *IV = Builder.CreatePHI(LoopIVType, 2, "polly.indvar");
126
308
  IV->addIncoming(LB, PreHeaderBB);
127
308
  Stride = Builder.CreateZExtOrBitCast(Stride, LoopIVType);
128
308
  Value *IncrementedIV = Builder.CreateNSWAdd(IV, Stride, "polly.indvar_next");
129
308
  Value *LoopCondition =
130
308
      Builder.CreateICmp(Predicate, IncrementedIV, UB, "polly.loop_cond");
131
308
132
308
  // Create the loop latch and annotate it as such.
133
308
  BranchInst *B = Builder.CreateCondBr(LoopCondition, HeaderBB, ExitBB);
134
308
  if (Annotator)
135
278
    Annotator->annotateLoopLatch(B, NewLoop, Parallel, LoopVectDisabled);
136
308
137
308
  IV->addIncoming(IncrementedIV, HeaderBB);
138
308
  if (GuardBB)
139
129
    DT.changeImmediateDominator(ExitBB, GuardBB);
140
179
  else
141
179
    DT.changeImmediateDominator(ExitBB, HeaderBB);
142
308
143
308
  // The loop body should be added here.
144
308
  Builder.SetInsertPoint(HeaderBB->getFirstNonPHI());
145
308
  return IV;
146
308
}
147
148
Value *ParallelLoopGenerator::createParallelLoop(
149
    Value *LB, Value *UB, Value *Stride, SetVector<Value *> &UsedValues,
150
30
    ValueMapT &Map, BasicBlock::iterator *LoopBody) {
151
30
  Function *SubFn;
152
30
153
30
  AllocaInst *Struct = storeValuesIntoStruct(UsedValues);
154
30
  BasicBlock::iterator BeforeLoop = Builder.GetInsertPoint();
155
30
  Value *IV = createSubFn(Stride, Struct, UsedValues, Map, &SubFn);
156
30
  *LoopBody = Builder.GetInsertPoint();
157
30
  Builder.SetInsertPoint(&*BeforeLoop);
158
30
159
30
  Value *SubFnParam = Builder.CreateBitCast(Struct, Builder.getInt8PtrTy(),
160
30
                                            "polly.par.userContext");
161
30
162
30
  // Add one as the upper bound provided by OpenMP is a < comparison
163
30
  // whereas the codegenForSequential function creates a <= comparison.
164
30
  UB = Builder.CreateAdd(UB, ConstantInt::get(LongType, 1));
165
30
166
30
  // Tell the runtime we start a parallel loop
167
30
  createCallSpawnThreads(SubFn, SubFnParam, LB, UB, Stride);
168
30
  Builder.CreateCall(SubFn, SubFnParam);
169
30
  createCallJoinThreads();
170
30
171
30
  return IV;
172
30
}
173
174
void ParallelLoopGenerator::createCallSpawnThreads(Value *SubFn,
175
                                                   Value *SubFnParam, Value *LB,
176
30
                                                   Value *UB, Value *Stride) {
177
30
  const std::string Name = "GOMP_parallel_loop_runtime_start";
178
30
179
30
  Function *F = M->getFunction(Name);
180
30
181
30
  // If F is not available, declare it.
182
30
  if (!F) {
183
27
    GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
184
27
185
27
    Type *Params[] = {PointerType::getUnqual(FunctionType::get(
186
27
                          Builder.getVoidTy(), Builder.getInt8PtrTy(), false)),
187
27
                      Builder.getInt8PtrTy(),
188
27
                      Builder.getInt32Ty(),
189
27
                      LongType,
190
27
                      LongType,
191
27
                      LongType};
192
27
193
27
    FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
194
27
    F = Function::Create(Ty, Linkage, Name, M);
195
27
  }
196
30
197
30
  Value *NumberOfThreads = Builder.getInt32(PollyNumThreads);
198
30
  Value *Args[] = {SubFn, SubFnParam, NumberOfThreads, LB, UB, Stride};
199
30
200
30
  Builder.CreateCall(F, Args);
201
30
}
202
203
Value *ParallelLoopGenerator::createCallGetWorkItem(Value *LBPtr,
204
30
                                                    Value *UBPtr) {
205
30
  const std::string Name = "GOMP_loop_runtime_next";
206
30
207
30
  Function *F = M->getFunction(Name);
208
30
209
30
  // If F is not available, declare it.
210
30
  if (!F) {
211
27
    GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
212
27
    Type *Params[] = {LongType->getPointerTo(), LongType->getPointerTo()};
213
27
    FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
214
27
    F = Function::Create(Ty, Linkage, Name, M);
215
27
  }
216
30
217
30
  Value *Args[] = {LBPtr, UBPtr};
218
30
  Value *Return = Builder.CreateCall(F, Args);
219
30
  Return = Builder.CreateICmpNE(
220
30
      Return, Builder.CreateZExt(Builder.getFalse(), Return->getType()));
221
30
  return Return;
222
30
}
223
224
30
void ParallelLoopGenerator::createCallJoinThreads() {
225
30
  const std::string Name = "GOMP_parallel_end";
226
30
227
30
  Function *F = M->getFunction(Name);
228
30
229
30
  // If F is not available, declare it.
230
30
  if (!F) {
231
27
    GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
232
27
233
27
    FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
234
27
    F = Function::Create(Ty, Linkage, Name, M);
235
27
  }
236
30
237
30
  Builder.CreateCall(F, {});
238
30
}
239
240
30
void ParallelLoopGenerator::createCallCleanupThread() {
241
30
  const std::string Name = "GOMP_loop_end_nowait";
242
30
243
30
  Function *F = M->getFunction(Name);
244
30
245
30
  // If F is not available, declare it.
246
30
  if (!F) {
247
27
    GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
248
27
249
27
    FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
250
27
    F = Function::Create(Ty, Linkage, Name, M);
251
27
  }
252
30
253
30
  Builder.CreateCall(F, {});
254
30
}
255
256
30
Function *ParallelLoopGenerator::createSubFnDefinition() {
257
30
  Function *F = Builder.GetInsertBlock()->getParent();
258
30
  std::vector<Type *> Arguments(1, Builder.getInt8PtrTy());
259
30
  FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
260
30
  Function *SubFn = Function::Create(FT, Function::InternalLinkage,
261
30
                                     F->getName() + "_polly_subfn", M);
262
30
263
30
  // Certain backends (e.g., NVPTX) do not support '.'s in function names.
264
30
  // Hence, we ensure that all '.'s are replaced by '_'s.
265
30
  std::string FunctionName = SubFn->getName();
266
30
  std::replace(FunctionName.begin(), FunctionName.end(), '.', '_');
267
30
  SubFn->setName(FunctionName);
268
30
269
30
  // Do not run any polly pass on the new function.
270
30
  SubFn->addFnAttr(PollySkipFnAttr);
271
30
272
30
  Function::arg_iterator AI = SubFn->arg_begin();
273
30
  AI->setName("polly.par.userContext");
274
30
275
30
  return SubFn;
276
30
}
277
278
AllocaInst *
279
30
ParallelLoopGenerator::storeValuesIntoStruct(SetVector<Value *> &Values) {
280
30
  SmallVector<Type *, 8> Members;
281
30
282
30
  for (Value *V : Values)
283
74
    Members.push_back(V->getType());
284
30
285
30
  const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout();
286
30
287
30
  // We do not want to allocate the alloca inside any loop, thus we allocate it
288
30
  // in the entry block of the function and use annotations to denote the actual
289
30
  // live span (similar to clang).
290
30
  BasicBlock &EntryBB = Builder.GetInsertBlock()->getParent()->getEntryBlock();
291
30
  Instruction *IP = &*EntryBB.getFirstInsertionPt();
292
30
  StructType *Ty = StructType::get(Builder.getContext(), Members);
293
30
  AllocaInst *Struct = new AllocaInst(Ty, DL.getAllocaAddrSpace(), nullptr,
294
30
                                      "polly.par.userContext", IP);
295
30
296
104
  for (unsigned i = 0; i < Values.size(); 
i++74
) {
297
74
    Value *Address = Builder.CreateStructGEP(Ty, Struct, i);
298
74
    Address->setName("polly.subfn.storeaddr." + Values[i]->getName());
299
74
    Builder.CreateStore(Values[i], Address);
300
74
  }
301
30
302
30
  return Struct;
303
30
}
304
305
void ParallelLoopGenerator::extractValuesFromStruct(
306
30
    SetVector<Value *> OldValues, Type *Ty, Value *Struct, ValueMapT &Map) {
307
104
  for (unsigned i = 0; i < OldValues.size(); 
i++74
) {
308
74
    Value *Address = Builder.CreateStructGEP(Ty, Struct, i);
309
74
    Value *NewValue = Builder.CreateLoad(Address);
310
74
    NewValue->setName("polly.subfunc.arg." + OldValues[i]->getName());
311
74
    Map[OldValues[i]] = NewValue;
312
74
  }
313
30
}
314
315
Value *ParallelLoopGenerator::createSubFn(Value *Stride, AllocaInst *StructData,
316
                                          SetVector<Value *> Data,
317
30
                                          ValueMapT &Map, Function **SubFnPtr) {
318
30
  BasicBlock *PrevBB, *HeaderBB, *ExitBB, *CheckNextBB, *PreHeaderBB, *AfterBB;
319
30
  Value *LBPtr, *UBPtr, *UserContext, *Ret1, *HasNextSchedule, *LB, *UB, *IV;
320
30
  Function *SubFn = createSubFnDefinition();
321
30
  LLVMContext &Context = SubFn->getContext();
322
30
323
30
  // Store the previous basic block.
324
30
  PrevBB = Builder.GetInsertBlock();
325
30
326
30
  // Create basic blocks.
327
30
  HeaderBB = BasicBlock::Create(Context, "polly.par.setup", SubFn);
328
30
  ExitBB = BasicBlock::Create(Context, "polly.par.exit", SubFn);
329
30
  CheckNextBB = BasicBlock::Create(Context, "polly.par.checkNext", SubFn);
330
30
  PreHeaderBB = BasicBlock::Create(Context, "polly.par.loadIVBounds", SubFn);
331
30
332
30
  DT.addNewBlock(HeaderBB, PrevBB);
333
30
  DT.addNewBlock(ExitBB, HeaderBB);
334
30
  DT.addNewBlock(CheckNextBB, HeaderBB);
335
30
  DT.addNewBlock(PreHeaderBB, HeaderBB);
336
30
337
30
  // Fill up basic block HeaderBB.
338
30
  Builder.SetInsertPoint(HeaderBB);
339
30
  LBPtr = Builder.CreateAlloca(LongType, nullptr, "polly.par.LBPtr");
340
30
  UBPtr = Builder.CreateAlloca(LongType, nullptr, "polly.par.UBPtr");
341
30
  UserContext = Builder.CreateBitCast(
342
30
      &*SubFn->arg_begin(), StructData->getType(), "polly.par.userContext");
343
30
344
30
  extractValuesFromStruct(Data, StructData->getAllocatedType(), UserContext,
345
30
                          Map);
346
30
  Builder.CreateBr(CheckNextBB);
347
30
348
30
  // Add code to check if another set of iterations will be executed.
349
30
  Builder.SetInsertPoint(CheckNextBB);
350
30
  Ret1 = createCallGetWorkItem(LBPtr, UBPtr);
351
30
  HasNextSchedule = Builder.CreateTrunc(Ret1, Builder.getInt1Ty(),
352
30
                                        "polly.par.hasNextScheduleBlock");
353
30
  Builder.CreateCondBr(HasNextSchedule, PreHeaderBB, ExitBB);
354
30
355
30
  // Add code to load the iv bounds for this set of iterations.
356
30
  Builder.SetInsertPoint(PreHeaderBB);
357
30
  LB = Builder.CreateLoad(LBPtr, "polly.par.LB");
358
30
  UB = Builder.CreateLoad(UBPtr, "polly.par.UB");
359
30
360
30
  // Subtract one as the upper bound provided by OpenMP is a < comparison
361
30
  // whereas the codegenForSequential function creates a <= comparison.
362
30
  UB = Builder.CreateSub(UB, ConstantInt::get(LongType, 1),
363
30
                         "polly.par.UBAdjusted");
364
30
365
30
  Builder.CreateBr(CheckNextBB);
366
30
  Builder.SetInsertPoint(&*--Builder.GetInsertPoint());
367
30
  IV = createLoop(LB, UB, Stride, Builder, LI, DT, AfterBB, ICmpInst::ICMP_SLE,
368
30
                  nullptr, true, /* UseGuard */ false);
369
30
370
30
  BasicBlock::iterator LoopBody = Builder.GetInsertPoint();
371
30
372
30
  // Add code to terminate this subfunction.
373
30
  Builder.SetInsertPoint(ExitBB);
374
30
  createCallCleanupThread();
375
30
  Builder.CreateRetVoid();
376
30
377
30
  Builder.SetInsertPoint(&*LoopBody);
378
30
  *SubFnPtr = SubFn;
379
30
380
30
  return IV;
381
30
}