Coverage Report

Created: 2017-06-27 13:53

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