Coverage Report

Created: 2017-11-21 16:49

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