Coverage Report

Created: 2018-06-24 14:39

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