Coverage Report

Created: 2018-10-23 03:11

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/CodeGen/BlockGenerators.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
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 implements the BlockGenerator and VectorBlockGenerator classes,
11
// which generate sequential code and vectorized code for a polyhedral
12
// statement, respectively.
13
//
14
//===----------------------------------------------------------------------===//
15
16
#include "polly/CodeGen/BlockGenerators.h"
17
#include "polly/CodeGen/CodeGeneration.h"
18
#include "polly/CodeGen/IslExprBuilder.h"
19
#include "polly/CodeGen/RuntimeDebugBuilder.h"
20
#include "polly/Options.h"
21
#include "polly/ScopInfo.h"
22
#include "polly/Support/GICHelper.h"
23
#include "polly/Support/SCEVValidator.h"
24
#include "polly/Support/ScopHelper.h"
25
#include "polly/Support/VirtualInstruction.h"
26
#include "llvm/Analysis/LoopInfo.h"
27
#include "llvm/Analysis/RegionInfo.h"
28
#include "llvm/Analysis/ScalarEvolution.h"
29
#include "llvm/IR/IntrinsicInst.h"
30
#include "llvm/IR/Module.h"
31
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
32
#include "llvm/Transforms/Utils/Local.h"
33
#include "isl/aff.h"
34
#include "isl/ast.h"
35
#include "isl/ast_build.h"
36
#include "isl/set.h"
37
#include <deque>
38
39
using namespace llvm;
40
using namespace polly;
41
42
static cl::opt<bool> Aligned("enable-polly-aligned",
43
                             cl::desc("Assumed aligned memory accesses."),
44
                             cl::Hidden, cl::init(false), cl::ZeroOrMore,
45
                             cl::cat(PollyCategory));
46
47
bool PollyDebugPrinting;
48
static cl::opt<bool, true> DebugPrintingX(
49
    "polly-codegen-add-debug-printing",
50
    cl::desc("Add printf calls that show the values loaded/stored."),
51
    cl::location(PollyDebugPrinting), cl::Hidden, cl::init(false),
52
    cl::ZeroOrMore, cl::cat(PollyCategory));
53
54
static cl::opt<bool> TraceStmts(
55
    "polly-codegen-trace-stmts",
56
    cl::desc("Add printf calls that print the statement being executed"),
57
    cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
58
59
static cl::opt<bool> TraceScalars(
60
    "polly-codegen-trace-scalars",
61
    cl::desc("Add printf calls that print the values of all scalar values "
62
             "used in a statement. Requires -polly-codegen-trace-stmts."),
63
    cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
64
65
BlockGenerator::BlockGenerator(
66
    PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT,
67
    AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap,
68
    ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
69
    : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
70
      EntryBB(nullptr), ScalarMap(ScalarMap), EscapeMap(EscapeMap),
71
293
      GlobalMap(GlobalMap), StartBlock(StartBlock) {}
72
73
Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
74
                                             ValueMapT &BBMap,
75
                                             LoopToScevMapT &LTS,
76
688
                                             Loop *L) const {
77
688
  if (!SE.isSCEVable(Old->getType()))
78
0
    return nullptr;
79
688
80
688
  const SCEV *Scev = SE.getSCEVAtScope(Old, L);
81
688
  if (!Scev)
82
0
    return nullptr;
83
688
84
688
  if (isa<SCEVCouldNotCompute>(Scev))
85
0
    return nullptr;
86
688
87
688
  const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE);
88
688
  ValueMapT VTV;
89
688
  VTV.insert(BBMap.begin(), BBMap.end());
90
688
  VTV.insert(GlobalMap.begin(), GlobalMap.end());
91
688
92
688
  Scop &S = *Stmt.getParent();
93
688
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
94
688
  auto IP = Builder.GetInsertPoint();
95
688
96
688
  assert(IP != Builder.GetInsertBlock()->end() &&
97
688
         "Only instructions can be insert points for SCEVExpander");
98
688
  Value *Expanded =
99
688
      expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV,
100
688
                    StartBlock->getSinglePredecessor());
101
688
102
688
  BBMap[Old] = Expanded;
103
688
  return Expanded;
104
688
}
105
106
Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
107
2.23k
                                   LoopToScevMapT &LTS, Loop *L) const {
108
2.23k
109
2.23k
  auto lookupGlobally = [this](Value *Old) -> Value * {
110
1.23k
    Value *New = GlobalMap.lookup(Old);
111
1.23k
    if (!New)
112
1.17k
      return nullptr;
113
53
114
53
    // Required by:
115
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded.ll
116
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_different_bb.ll
117
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_pass_only_needed.ll
118
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointers_preloaded.ll
119
53
    // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
120
53
    // * Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
121
53
    // GlobalMap should be a mapping from (value in original SCoP) to (copied
122
53
    // value in generated SCoP), without intermediate mappings, which might
123
53
    // easily require transitiveness as well.
124
53
    if (Value *NewRemapped = GlobalMap.lookup(New))
125
6
      New = NewRemapped;
126
53
127
53
    // No test case for this code.
128
53
    if (Old->getType()->getScalarSizeInBits() <
129
53
        New->getType()->getScalarSizeInBits())
130
0
      New = Builder.CreateTruncOrBitCast(New, Old->getType());
131
53
132
53
    return New;
133
53
  };
134
2.23k
135
2.23k
  Value *New = nullptr;
136
2.23k
  auto VUse = VirtualUse::create(&Stmt, L, Old, true);
137
2.23k
  switch (VUse.getKind()) {
138
2.23k
  case VirtualUse::Block:
139
143
    // BasicBlock are constants, but the BlockGenerator copies them.
140
143
    New = BBMap.lookup(Old);
141
143
    break;
142
2.23k
143
2.23k
  case VirtualUse::Constant:
144
399
    // Used by:
145
399
    // * Isl/CodeGen/OpenMP/reference-argument-from-non-affine-region.ll
146
399
    // Constants should not be redefined. In this case, the GlobalMap just
147
399
    // contains a mapping to the same constant, which is unnecessary, but
148
399
    // harmless.
149
399
    if ((New = lookupGlobally(Old)))
150
1
      break;
151
398
152
398
    assert(!BBMap.count(Old));
153
398
    New = Old;
154
398
    break;
155
398
156
398
  case VirtualUse::ReadOnly:
157
23
    assert(!GlobalMap.count(Old));
158
23
159
23
    // Required for:
160
23
    // * Isl/CodeGen/MemAccess/create_arrays.ll
161
23
    // * Isl/CodeGen/read-only-scalars.ll
162
23
    // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
163
23
    // For some reason these reload a read-only value. The reloaded value ends
164
23
    // up in BBMap, buts its value should be identical.
165
23
    //
166
23
    // Required for:
167
23
    // * Isl/CodeGen/OpenMP/single_loop_with_param.ll
168
23
    // The parallel subfunctions need to reference the read-only value from the
169
23
    // parent function, this is done by reloading them locally.
170
23
    if ((New = BBMap.lookup(Old)))
171
22
      break;
172
1
173
1
    New = Old;
174
1
    break;
175
1
176
788
  case VirtualUse::Synthesizable:
177
788
    // Used by:
178
788
    // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
179
788
    // * Isl/CodeGen/OpenMP/recomputed-srem.ll
180
788
    // * Isl/CodeGen/OpenMP/reference-other-bb.ll
181
788
    // * Isl/CodeGen/OpenMP/two-parallel-loops-reference-outer-indvar.ll
182
788
    // For some reason synthesizable values end up in GlobalMap. Their values
183
788
    // are the same as trySynthesizeNewValue would return. The legacy
184
788
    // implementation prioritized GlobalMap, so this is what we do here as well.
185
788
    // Ideally, synthesizable values should not end up in GlobalMap.
186
788
    if ((New = lookupGlobally(Old)))
187
7
      break;
188
781
189
781
    // Required for:
190
781
    // * Isl/CodeGen/RuntimeDebugBuilder/combine_different_values.ll
191
781
    // * Isl/CodeGen/getNumberOfIterations.ll
192
781
    // * Isl/CodeGen/non_affine_float_compare.ll
193
781
    // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
194
781
    // Ideally, synthesizable values are synthesized by trySynthesizeNewValue,
195
781
    // not precomputed (SCEVExpander has its own caching mechanism).
196
781
    // These tests fail without this, but I think trySynthesizeNewValue would
197
781
    // just re-synthesize the same instructions.
198
781
    if ((New = BBMap.lookup(Old)))
199
93
      break;
200
688
201
688
    New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L);
202
688
    break;
203
688
204
688
  case VirtualUse::Hoisted:
205
45
    // TODO: Hoisted invariant loads should be found in GlobalMap only, but not
206
45
    // redefined locally (which will be ignored anyway). That is, the following
207
45
    // assertion should apply: assert(!BBMap.count(Old))
208
45
209
45
    New = lookupGlobally(Old);
210
45
    break;
211
688
212
835
  case VirtualUse::Intra:
213
835
  case VirtualUse::Inter:
214
835
    assert(!GlobalMap.count(Old) &&
215
835
           "Intra and inter-stmt values are never global");
216
835
    New = BBMap.lookup(Old);
217
835
    break;
218
2.23k
  }
219
2.23k
  assert(New && "Unexpected scalar dependence in region!");
220
2.23k
  return New;
221
2.23k
}
222
223
void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
224
560
                                    ValueMapT &BBMap, LoopToScevMapT &LTS) {
225
560
  // We do not generate debug intrinsics as we did not investigate how to
226
560
  // copy them correctly. At the current state, they just crash the code
227
560
  // generation as the meta-data operands are not correctly copied.
228
560
  if (isa<DbgInfoIntrinsic>(Inst))
229
0
    return;
230
560
231
560
  Instruction *NewInst = Inst->clone();
232
560
233
560
  // Replace old operands with the new ones.
234
1.05k
  for (Value *OldOperand : Inst->operands()) {
235
1.05k
    Value *NewOperand =
236
1.05k
        getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
237
1.05k
238
1.05k
    if (!NewOperand) {
239
0
      assert(!isa<StoreInst>(NewInst) &&
240
0
             "Store instructions are always needed!");
241
0
      NewInst->deleteValue();
242
0
      return;
243
0
    }
244
1.05k
245
1.05k
    NewInst->replaceUsesOfWith(OldOperand, NewOperand);
246
1.05k
  }
247
560
248
560
  Builder.Insert(NewInst);
249
560
  BBMap[Inst] = NewInst;
250
560
251
560
  // When copying the instruction onto the Module meant for the GPU,
252
560
  // debug metadata attached to an instruction causes all related
253
560
  // metadata to be pulled into the Module. This includes the DICompileUnit,
254
560
  // which will not be listed in llvm.dbg.cu of the Module since the Module
255
560
  // doesn't contain one. This fails the verification of the Module and the
256
560
  // subsequent generation of the ASM string.
257
560
  if (NewInst->getModule() != Inst->getModule())
258
0
    NewInst->setDebugLoc(llvm::DebugLoc());
259
560
260
560
  if (!NewInst->getType()->isVoidTy())
261
454
    NewInst->setName("p_" + Inst->getName());
262
560
}
263
264
Value *
265
BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
266
                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
267
805
                                         isl_id_to_ast_expr *NewAccesses) {
268
805
  const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
269
805
  return generateLocationAccessed(
270
805
      Stmt, getLoopForStmt(Stmt),
271
805
      Inst.isNull() ? 
nullptr0
: Inst.getPointerOperand(), BBMap, LTS,
272
805
      NewAccesses, MA.getId().release(), MA.getAccessValue()->getType());
273
805
}
274
275
Value *BlockGenerator::generateLocationAccessed(
276
    ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
277
    LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
278
833
    Type *ExpectedType) {
279
833
  isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
280
833
281
833
  if (AccessExpr) {
282
241
    AccessExpr = isl_ast_expr_address_of(AccessExpr);
283
241
    auto Address = ExprBuilder->create(AccessExpr);
284
241
285
241
    // Cast the address of this memory access to a pointer type that has the
286
241
    // same element type as the original access, but uses the address space of
287
241
    // the newly generated pointer.
288
241
    auto OldPtrTy = ExpectedType->getPointerTo();
289
241
    auto NewPtrTy = Address->getType();
290
241
    OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
291
241
                                NewPtrTy->getPointerAddressSpace());
292
241
293
241
    if (OldPtrTy != NewPtrTy)
294
4
      Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
295
241
    return Address;
296
241
  }
297
592
  assert(
298
592
      Pointer &&
299
592
      "If expression was not generated, must use the original pointer value");
300
592
  return getNewValue(Stmt, Pointer, BBMap, LTS, L);
301
592
}
302
303
Value *
304
BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
305
                                   LoopToScevMapT &LTS, ValueMapT &BBMap,
306
243
                                   __isl_keep isl_id_to_ast_expr *NewAccesses) {
307
243
  if (Access.isLatestArrayKind())
308
28
    return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
309
28
                                    LTS, NewAccesses, Access.getId().release(),
310
28
                                    Access.getAccessValue()->getType());
311
215
312
215
  return getOrCreateAlloca(Access);
313
215
}
314
315
3.95k
Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
316
3.95k
  auto *StmtBB = Stmt.getEntryBlock();
317
3.95k
  return LI.getLoopFor(StmtBB);
318
3.95k
}
319
320
Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load,
321
                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
322
383
                                         isl_id_to_ast_expr *NewAccesses) {
323
383
  if (Value *PreloadLoad = GlobalMap.lookup(Load))
324
30
    return PreloadLoad;
325
353
326
353
  Value *NewPointer =
327
353
      generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
328
353
  Value *ScalarLoad = Builder.CreateAlignedLoad(
329
353
      NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
330
353
331
353
  if (PollyDebugPrinting)
332
5
    RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
333
5
                                          ": ", ScalarLoad, "\n");
334
353
335
353
  return ScalarLoad;
336
353
}
337
338
void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
339
                                        ValueMapT &BBMap, LoopToScevMapT &LTS,
340
399
                                        isl_id_to_ast_expr *NewAccesses) {
341
399
  MemoryAccess &MA = Stmt.getArrayAccessFor(Store);
342
399
  isl::set AccDom = MA.getAccessRelation().domain();
343
399
  std::string Subject = MA.getId().get_name();
344
399
345
399
  generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() {
346
398
    Value *NewPointer =
347
398
        generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
348
398
    Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
349
398
                                      LTS, getLoopForStmt(Stmt));
350
398
351
398
    if (PollyDebugPrinting)
352
1
      RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to  ", NewPointer,
353
1
                                            ": ", ValueOperand, "\n");
354
398
355
398
    Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
356
398
  });
357
399
}
358
359
1.41k
bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
360
1.41k
  Loop *L = getLoopForStmt(Stmt);
361
1.41k
  return (Stmt.isBlockStmt() || 
!Stmt.getRegion()->contains(L)169
) &&
362
1.41k
         
canSynthesize(Inst, *Stmt.getParent(), &SE, L)1.40k
;
363
1.41k
}
364
365
void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
366
                                     ValueMapT &BBMap, LoopToScevMapT &LTS,
367
1.38k
                                     isl_id_to_ast_expr *NewAccesses) {
368
1.38k
  // Terminator instructions control the control flow. They are explicitly
369
1.38k
  // expressed in the clast and do not need to be copied.
370
1.38k
  if (Inst->isTerminator())
371
66
    return;
372
1.31k
373
1.31k
  // Synthesizable statements will be generated on-demand.
374
1.31k
  if (canSyntheziseInStmt(Stmt, Inst))
375
32
    return;
376
1.28k
377
1.28k
  if (auto *Load = dyn_cast<LoadInst>(Inst)) {
378
383
    Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
379
383
    // Compute NewLoad before its insertion in BBMap to make the insertion
380
383
    // deterministic.
381
383
    BBMap[Load] = NewLoad;
382
383
    return;
383
383
  }
384
902
385
902
  if (auto *Store = dyn_cast<StoreInst>(Inst)) {
386
399
    // Identified as redundant by -polly-simplify.
387
399
    if (!Stmt.getArrayAccessOrNULLFor(Store))
388
0
      return;
389
399
390
399
    generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
391
399
    return;
392
399
  }
393
503
394
503
  if (auto *PHI = dyn_cast<PHINode>(Inst)) {
395
44
    copyPHIInstruction(Stmt, PHI, BBMap, LTS);
396
44
    return;
397
44
  }
398
459
399
459
  // Skip some special intrinsics for which we do not adjust the semantics to
400
459
  // the new schedule. All others are handled like every other instruction.
401
459
  if (isIgnoredIntrinsic(Inst))
402
0
    return;
403
459
404
459
  copyInstScalar(Stmt, Inst, BBMap, LTS);
405
459
}
406
407
462
void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
408
462
  auto NewBB = Builder.GetInsertBlock();
409
4.21k
  for (auto I = NewBB->rbegin(); I != NewBB->rend(); 
I++3.75k
) {
410
3.75k
    Instruction *NewInst = &*I;
411
3.75k
412
3.75k
    if (!isInstructionTriviallyDead(NewInst))
413
3.71k
      continue;
414
40
415
40
    for (auto Pair : BBMap)
416
201
      if (Pair.second == NewInst) {
417
29
        BBMap.erase(Pair.first);
418
29
      }
419
40
420
40
    NewInst->eraseFromParent();
421
40
    I = NewBB->rbegin();
422
40
  }
423
462
}
424
425
void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
426
462
                              isl_id_to_ast_expr *NewAccesses) {
427
462
  assert(Stmt.isBlockStmt() &&
428
462
         "Only block statements can be copied by the block generator");
429
462
430
462
  ValueMapT BBMap;
431
462
432
462
  BasicBlock *BB = Stmt.getBasicBlock();
433
462
  copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
434
462
  removeDeadInstructions(BB, BBMap);
435
462
}
436
437
563
BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
438
563
  BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
439
563
                                  &*Builder.GetInsertPoint(), &DT, &LI);
440
563
  CopyBB->setName("polly.stmt." + BB->getName());
441
563
  return CopyBB;
442
563
}
443
444
BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
445
                                   ValueMapT &BBMap, LoopToScevMapT &LTS,
446
462
                                   isl_id_to_ast_expr *NewAccesses) {
447
462
  BasicBlock *CopyBB = splitBB(BB);
448
462
  Builder.SetInsertPoint(&CopyBB->front());
449
462
  generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
450
462
  generateBeginStmtTrace(Stmt, LTS, BBMap);
451
462
452
462
  copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
453
462
454
462
  // After a basic block was copied store all scalars that escape this block in
455
462
  // their alloca.
456
462
  generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
457
462
  return CopyBB;
458
462
}
459
460
void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
461
                            ValueMapT &BBMap, LoopToScevMapT &LTS,
462
563
                            isl_id_to_ast_expr *NewAccesses) {
463
563
  EntryBB = &CopyBB->getParent()->getEntryBlock();
464
563
465
563
  // Block statements and the entry blocks of region statement are code
466
563
  // generated from instruction lists. This allow us to optimize the
467
563
  // instructions that belong to a certain scop statement. As the code
468
563
  // structure of region statements might be arbitrary complex, optimizing the
469
563
  // instruction list is not yet supported.
470
563
  if (Stmt.isBlockStmt() || 
(101
Stmt.isRegionStmt()101
&&
Stmt.getEntryBlock() == BB101
))
471
497
    for (Instruction *Inst : Stmt.getInstructions())
472
1.13k
      copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses);
473
66
  else
474
66
    for (Instruction &Inst : *BB)
475
169
      copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
476
563
}
477
478
218
Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
479
218
  assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
480
218
481
218
  return getOrCreateAlloca(Access.getLatestScopArrayInfo());
482
218
}
483
484
298
Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
485
298
  assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
486
298
487
298
  auto &Addr = ScalarMap[Array];
488
298
489
298
  if (Addr) {
490
169
    // Allow allocas to be (temporarily) redirected once by adding a new
491
169
    // old-alloca-addr to new-addr mapping to GlobalMap. This functionality
492
169
    // is used for example by the OpenMP code generation where a first use
493
169
    // of a scalar while still in the host code allocates a normal alloca with
494
169
    // getOrCreateAlloca. When the values of this scalar are accessed during
495
169
    // the generation of the parallel subfunction, these values are copied over
496
169
    // to the parallel subfunction and each request for a scalar alloca slot
497
169
    // must be forwarded to the temporary in-subfunction slot. This mapping is
498
169
    // removed when the subfunction has been generated and again normal host
499
169
    // code is generated. Due to the following reasons it is not possible to
500
169
    // perform the GlobalMap lookup right after creating the alloca below, but
501
169
    // instead we need to check GlobalMap at each call to getOrCreateAlloca:
502
169
    //
503
169
    //   1) GlobalMap may be changed multiple times (for each parallel loop),
504
169
    //   2) The temporary mapping is commonly only known after the initial
505
169
    //      alloca has already been generated, and
506
169
    //   3) The original alloca value must be restored after leaving the
507
169
    //      sub-function.
508
169
    if (Value *NewAddr = GlobalMap.lookup(&*Addr))
509
2
      return NewAddr;
510
167
    return Addr;
511
167
  }
512
129
513
129
  Type *Ty = Array->getElementType();
514
129
  Value *ScalarBase = Array->getBasePtr();
515
129
  std::string NameExt;
516
129
  if (Array->isPHIKind())
517
34
    NameExt = ".phiops";
518
95
  else
519
95
    NameExt = ".s2a";
520
129
521
129
  const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout();
522
129
523
129
  Addr = new AllocaInst(Ty, DL.getAllocaAddrSpace(),
524
129
                        ScalarBase->getName() + NameExt);
525
129
  EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
526
129
  Addr->insertBefore(&*EntryBB->getFirstInsertionPt());
527
129
528
129
  return Addr;
529
129
}
530
531
74
void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) {
532
74
  Instruction *Inst = cast<Instruction>(Array->getBasePtr());
533
74
534
74
  // If there are escape users we get the alloca for this instruction and put it
535
74
  // in the EscapeMap for later finalization. Lastly, if the instruction was
536
74
  // copied multiple times we already did this and can exit.
537
74
  if (EscapeMap.count(Inst))
538
6
    return;
539
68
540
68
  EscapeUserVectorTy EscapeUsers;
541
97
  for (User *U : Inst->users()) {
542
97
543
97
    // Non-instruction user will never escape.
544
97
    Instruction *UI = dyn_cast<Instruction>(U);
545
97
    if (!UI)
546
0
      continue;
547
97
548
97
    if (S.contains(UI))
549
59
      continue;
550
38
551
38
    EscapeUsers.push_back(UI);
552
38
  }
553
68
554
68
  // Exit if no escape uses were found.
555
68
  if (EscapeUsers.empty())
556
35
    return;
557
33
558
33
  // Get or create an escape alloca for this instruction.
559
33
  auto *ScalarAddr = getOrCreateAlloca(Array);
560
33
561
33
  // Remember that this instruction has escape uses and the escape alloca.
562
33
  EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
563
33
}
564
565
void BlockGenerator::generateScalarLoads(
566
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
567
497
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
568
976
  for (MemoryAccess *MA : Stmt) {
569
976
    if (MA->isOriginalArrayKind() || 
MA->isWrite()244
)
570
885
      continue;
571
91
572
#ifndef NDEBUG
573
    auto StmtDom =
574
        Stmt.getDomain().intersect_params(Stmt.getParent()->getContext());
575
    auto AccDom = MA->getAccessRelation().domain();
576
    assert(!StmtDom.is_subset(AccDom).is_false() &&
577
           "Scalar must be loaded in all statement instances");
578
#endif
579
580
91
    auto *Address =
581
91
        getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
582
91
    assert((!isa<Instruction>(Address) ||
583
91
            DT.dominates(cast<Instruction>(Address)->getParent(),
584
91
                         Builder.GetInsertBlock())) &&
585
91
           "Domination violation");
586
91
    BBMap[MA->getAccessValue()] =
587
91
        Builder.CreateLoad(Address, Address->getName() + ".reload");
588
91
  }
589
497
}
590
591
Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt,
592
10
                                              const isl::set &Subdomain) {
593
10
  isl::ast_build AstBuild = Stmt.getAstBuild();
594
10
  isl::set Domain = Stmt.getDomain();
595
10
596
10
  isl::union_map USchedule = AstBuild.get_schedule();
597
10
  USchedule = USchedule.intersect_domain(Domain);
598
10
599
10
  assert(!USchedule.is_empty());
600
10
  isl::map Schedule = isl::map::from_union_map(USchedule);
601
10
602
10
  isl::set ScheduledDomain = Schedule.range();
603
10
  isl::set ScheduledSet = Subdomain.apply(Schedule);
604
10
605
10
  isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
606
10
607
10
  isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
608
10
  Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
609
10
  IsInSetExpr = Builder.CreateICmpNE(
610
10
      IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
611
10
612
10
  return IsInSetExpr;
613
10
}
614
615
void BlockGenerator::generateConditionalExecution(
616
    ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
617
552
    const std::function<void()> &GenThenFunc) {
618
552
  isl::set StmtDom = Stmt.getDomain();
619
552
620
552
  // If the condition is a tautology, don't generate a condition around the
621
552
  // code.
622
552
  bool IsPartialWrite =
623
552
      !StmtDom.intersect_params(Stmt.getParent()->getContext())
624
552
           .is_subset(Subdomain);
625
552
  if (!IsPartialWrite) {
626
542
    GenThenFunc();
627
542
    return;
628
542
  }
629
10
630
10
  // Generate the condition.
631
10
  Value *Cond = buildContainsCondition(Stmt, Subdomain);
632
10
633
10
  // Don't call GenThenFunc if it is never executed. An ast index expression
634
10
  // might not be defined in this case.
635
10
  if (auto *Const = dyn_cast<ConstantInt>(Cond))
636
2
    if (Const->isZero())
637
2
      return;
638
8
639
8
  BasicBlock *HeadBlock = Builder.GetInsertBlock();
640
8
  StringRef BlockName = HeadBlock->getName();
641
8
642
8
  // Generate the conditional block.
643
8
  SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr,
644
8
                            &DT, &LI);
645
8
  BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator());
646
8
  BasicBlock *ThenBlock = Branch->getSuccessor(0);
647
8
  BasicBlock *TailBlock = Branch->getSuccessor(1);
648
8
649
8
  // Assign descriptive names.
650
8
  if (auto *CondInst = dyn_cast<Instruction>(Cond))
651
8
    CondInst->setName("polly." + Subject + ".cond");
652
8
  ThenBlock->setName(BlockName + "." + Subject + ".partial");
653
8
  TailBlock->setName(BlockName + ".cont");
654
8
655
8
  // Put the client code into the conditional block and continue in the merge
656
8
  // block afterwards.
657
8
  Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
658
8
  GenThenFunc();
659
8
  Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
660
8
}
661
662
0
static std::string getInstName(Value *Val) {
663
0
  std::string Result;
664
0
  raw_string_ostream OS(Result);
665
0
  Val->printAsOperand(OS, false);
666
0
  return OS.str();
667
0
}
668
669
void BlockGenerator::generateBeginStmtTrace(ScopStmt &Stmt, LoopToScevMapT &LTS,
670
497
                                            ValueMapT &BBMap) {
671
497
  if (!TraceStmts)
672
496
    return;
673
1
674
1
  Scop *S = Stmt.getParent();
675
1
  const char *BaseName = Stmt.getBaseName();
676
1
677
1
  isl::ast_build AstBuild = Stmt.getAstBuild();
678
1
  isl::set Domain = Stmt.getDomain();
679
1
680
1
  isl::union_map USchedule = AstBuild.get_schedule().intersect_domain(Domain);
681
1
  isl::map Schedule = isl::map::from_union_map(USchedule);
682
1
  assert(Schedule.is_empty().is_false() &&
683
1
         "The stmt must have a valid instance");
684
1
685
1
  isl::multi_pw_aff ScheduleMultiPwAff =
686
1
      isl::pw_multi_aff::from_map(Schedule.reverse());
687
1
  isl::ast_build RestrictedBuild = AstBuild.restrict(Schedule.range());
688
1
689
1
  // Sequence of strings to print.
690
1
  SmallVector<llvm::Value *, 8> Values;
691
1
692
1
  // Print the name of the statement.
693
1
  // TODO: Indent by the depth of the statement instance in the schedule tree.
694
1
  Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, BaseName));
695
1
  Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "("));
696
1
697
1
  // Add the coordinate of the statement instance.
698
1
  int DomDims = ScheduleMultiPwAff.dim(isl::dim::out);
699
2
  for (int i = 0; i < DomDims; 
i += 11
) {
700
1
    if (i > 0)
701
0
      Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ","));
702
1
703
1
    isl::ast_expr IsInSet =
704
1
        RestrictedBuild.expr_from(ScheduleMultiPwAff.get_pw_aff(i));
705
1
    Values.push_back(ExprBuilder->create(IsInSet.copy()));
706
1
  }
707
1
708
1
  if (TraceScalars) {
709
1
    Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")"));
710
1
    DenseSet<Instruction *> Encountered;
711
1
712
1
    // Add the value of each scalar (and the result of PHIs) used in the
713
1
    // statement.
714
1
    // TODO: Values used in region-statements.
715
1
    for (Instruction *Inst : Stmt.insts()) {
716
1
      if (!RuntimeDebugBuilder::isPrintable(Inst->getType()))
717
1
        continue;
718
0
719
0
      if (isa<PHINode>(Inst)) {
720
0
        Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, " "));
721
0
        Values.push_back(RuntimeDebugBuilder::getPrintableString(
722
0
            Builder, getInstName(Inst)));
723
0
        Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "="));
724
0
        Values.push_back(getNewValue(Stmt, Inst, BBMap, LTS,
725
0
                                     LI.getLoopFor(Inst->getParent())));
726
0
      } else {
727
0
        for (Value *Op : Inst->operand_values()) {
728
0
          // Do not print values that cannot change during the execution of the
729
0
          // SCoP.
730
0
          auto *OpInst = dyn_cast<Instruction>(Op);
731
0
          if (!OpInst)
732
0
            continue;
733
0
          if (!S->contains(OpInst))
734
0
            continue;
735
0
736
0
          // Print each scalar at most once, and exclude values defined in the
737
0
          // statement itself.
738
0
          if (Encountered.count(OpInst))
739
0
            continue;
740
0
741
0
          Values.push_back(
742
0
              RuntimeDebugBuilder::getPrintableString(Builder, " "));
743
0
          Values.push_back(RuntimeDebugBuilder::getPrintableString(
744
0
              Builder, getInstName(OpInst)));
745
0
          Values.push_back(
746
0
              RuntimeDebugBuilder::getPrintableString(Builder, "="));
747
0
          Values.push_back(getNewValue(Stmt, OpInst, BBMap, LTS,
748
0
                                       LI.getLoopFor(Inst->getParent())));
749
0
          Encountered.insert(OpInst);
750
0
        }
751
0
      }
752
0
753
0
      Encountered.insert(Inst);
754
0
    }
755
1
756
1
    Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "\n"));
757
1
  } else {
758
0
    Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")\n"));
759
0
  }
760
1
761
1
  RuntimeDebugBuilder::createCPUPrinter(Builder, ArrayRef<Value *>(Values));
762
1
}
763
764
void BlockGenerator::generateScalarStores(
765
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
766
462
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
767
462
  Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
768
462
769
462
  assert(Stmt.isBlockStmt() &&
770
462
         "Region statements need to use the generateScalarStores() function in "
771
462
         "the RegionGenerator");
772
462
773
880
  for (MemoryAccess *MA : Stmt) {
774
880
    if (MA->isOriginalArrayKind() || 
MA->isRead()215
)
775
746
      continue;
776
134
777
134
    isl::set AccDom = MA->getAccessRelation().domain();
778
134
    std::string Subject = MA->getId().get_name();
779
134
780
134
    generateConditionalExecution(
781
134
        Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
782
133
          Value *Val = MA->getAccessValue();
783
133
          if (MA->isAnyPHIKind()) {
784
69
            assert(MA->getIncoming().size() >= 1 &&
785
69
                   "Block statements have exactly one exiting block, or "
786
69
                   "multiple but "
787
69
                   "with same incoming block and value");
788
69
            assert(std::all_of(MA->getIncoming().begin(),
789
69
                               MA->getIncoming().end(),
790
69
                               [&](std::pair<BasicBlock *, Value *> p) -> bool {
791
69
                                 return p.first == Stmt.getBasicBlock();
792
69
                               }) &&
793
69
                   "Incoming block must be statement's block");
794
69
            Val = MA->getIncoming()[0].second;
795
69
          }
796
133
          auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
797
133
                                            BBMap, NewAccesses);
798
133
799
133
          Val = getNewValue(Stmt, Val, BBMap, LTS, L);
800
133
          assert((!isa<Instruction>(Val) ||
801
133
                  DT.dominates(cast<Instruction>(Val)->getParent(),
802
133
                               Builder.GetInsertBlock())) &&
803
133
                 "Domination violation");
804
133
          assert((!isa<Instruction>(Address) ||
805
133
                  DT.dominates(cast<Instruction>(Address)->getParent(),
806
133
                               Builder.GetInsertBlock())) &&
807
133
                 "Domination violation");
808
133
809
133
          // The new Val might have a different type than the old Val due to
810
133
          // ScalarEvolution looking through bitcasts.
811
133
          if (Val->getType() != Address->getType()->getPointerElementType())
812
1
            Address = Builder.CreateBitOrPointerCast(
813
1
                Address, Val->getType()->getPointerTo());
814
133
815
133
          Builder.CreateStore(Val, Address);
816
133
        });
817
134
  }
818
462
}
819
820
289
void BlockGenerator::createScalarInitialization(Scop &S) {
821
289
  BasicBlock *ExitBB = S.getExit();
822
289
  BasicBlock *PreEntryBB = S.getEnteringBlock();
823
289
824
289
  Builder.SetInsertPoint(&*StartBlock->begin());
825
289
826
622
  for (auto &Array : S.arrays()) {
827
622
    if (Array->getNumberOfDimensions() != 0)
828
475
      continue;
829
147
    if (Array->isPHIKind()) {
830
38
      // For PHI nodes, the only values we need to store are the ones that
831
38
      // reach the PHI node from outside the region. In general there should
832
38
      // only be one such incoming edge and this edge should enter through
833
38
      // 'PreEntryBB'.
834
38
      auto PHI = cast<PHINode>(Array->getBasePtr());
835
38
836
113
      for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; 
BI++75
)
837
75
        if (!S.contains(*BI) && 
*BI != PreEntryBB13
)
838
75
          
llvm_unreachable0
("Incoming edges from outside the scop should always "
839
38
                           "come from PreEntryBB");
840
38
841
38
      int Idx = PHI->getBasicBlockIndex(PreEntryBB);
842
38
      if (Idx < 0)
843
25
        continue;
844
13
845
13
      Value *ScalarValue = PHI->getIncomingValue(Idx);
846
13
847
13
      Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
848
13
      continue;
849
13
    }
850
109
851
109
    auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
852
109
853
109
    if (Inst && 
S.contains(Inst)98
)
854
74
      continue;
855
35
856
35
    // PHI nodes that are not marked as such in their SAI object are either exit
857
35
    // PHI nodes we model as common scalars but without initialization, or
858
35
    // incoming phi nodes that need to be initialized. Check if the first is the
859
35
    // case for Inst and do not create and initialize memory if so.
860
35
    if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
861
23
      if (!S.hasSingleExitEdge() && 
PHI->getBasicBlockIndex(ExitBB) >= 022
)
862
22
        continue;
863
13
864
13
    Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
865
13
  }
866
289
}
867
868
289
void BlockGenerator::createScalarFinalization(Scop &S) {
869
289
  // The exit block of the __unoptimized__ region.
870
289
  BasicBlock *ExitBB = S.getExitingBlock();
871
289
  // The merge block __just after__ the region and the optimized region.
872
289
  BasicBlock *MergeBB = S.getExit();
873
289
874
289
  // The exit block of the __optimized__ region.
875
289
  BasicBlock *OptExitBB = *(pred_begin(MergeBB));
876
289
  if (OptExitBB == ExitBB)
877
0
    OptExitBB = *(++pred_begin(MergeBB));
878
289
879
289
  Builder.SetInsertPoint(OptExitBB->getTerminator());
880
289
  for (const auto &EscapeMapping : EscapeMap) {
881
39
    // Extract the escaping instruction and the escaping users as well as the
882
39
    // alloca the instruction was demoted to.
883
39
    Instruction *EscapeInst = EscapeMapping.first;
884
39
    const auto &EscapeMappingValue = EscapeMapping.second;
885
39
    const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
886
39
    Value *ScalarAddr = EscapeMappingValue.first;
887
39
888
39
    // Reload the demoted instruction in the optimized version of the SCoP.
889
39
    Value *EscapeInstReload =
890
39
        Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
891
39
    EscapeInstReload =
892
39
        Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
893
39
894
39
    // Create the merge PHI that merges the optimized and unoptimized version.
895
39
    PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
896
39
                                        EscapeInst->getName() + ".merge");
897
39
    MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
898
39
899
39
    // Add the respective values to the merge PHI.
900
39
    MergePHI->addIncoming(EscapeInstReload, OptExitBB);
901
39
    MergePHI->addIncoming(EscapeInst, ExitBB);
902
39
903
39
    // The information of scalar evolution about the escaping instruction needs
904
39
    // to be revoked so the new merged instruction will be used.
905
39
    if (SE.isSCEVable(EscapeInst->getType()))
906
32
      SE.forgetValue(EscapeInst);
907
39
908
39
    // Replace all uses of the demoted instruction with the merge PHI.
909
39
    for (Instruction *EUser : EscapeUsers)
910
45
      EUser->replaceUsesOfWith(EscapeInst, MergePHI);
911
39
  }
912
289
}
913
914
289
void BlockGenerator::findOutsideUsers(Scop &S) {
915
622
  for (auto &Array : S.arrays()) {
916
622
917
622
    if (Array->getNumberOfDimensions() != 0)
918
475
      continue;
919
147
920
147
    if (Array->isPHIKind())
921
38
      continue;
922
109
923
109
    auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
924
109
925
109
    if (!Inst)
926
11
      continue;
927
98
928
98
    // Scop invariant hoisting moves some of the base pointers out of the scop.
929
98
    // We can ignore these, as the invariant load hoisting already registers the
930
98
    // relevant outside users.
931
98
    if (!S.contains(Inst))
932
24
      continue;
933
74
934
74
    handleOutsideUsers(S, Array);
935
74
  }
936
289
}
937
938
289
void BlockGenerator::createExitPHINodeMerges(Scop &S) {
939
289
  if (S.hasSingleExitEdge())
940
232
    return;
941
57
942
57
  auto *ExitBB = S.getExitingBlock();
943
57
  auto *MergeBB = S.getExit();
944
57
  auto *AfterMergeBB = MergeBB->getSingleSuccessor();
945
57
  BasicBlock *OptExitBB = *(pred_begin(MergeBB));
946
57
  if (OptExitBB == ExitBB)
947
0
    OptExitBB = *(++pred_begin(MergeBB));
948
57
949
57
  Builder.SetInsertPoint(OptExitBB->getTerminator());
950
57
951
113
  for (auto &SAI : S.arrays()) {
952
113
    auto *Val = SAI->getBasePtr();
953
113
954
113
    // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
955
113
    // the original PHI's value or the reloaded incoming values from the
956
113
    // generated code. An llvm::Value is merged between the original code's
957
113
    // value or the generated one.
958
113
    if (!SAI->isExitPHIKind())
959
92
      continue;
960
21
961
21
    PHINode *PHI = dyn_cast<PHINode>(Val);
962
21
    if (!PHI)
963
0
      continue;
964
21
965
21
    if (PHI->getParent() != AfterMergeBB)
966
0
      continue;
967
21
968
21
    std::string Name = PHI->getName();
969
21
    Value *ScalarAddr = getOrCreateAlloca(SAI);
970
21
    Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
971
21
    Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
972
21
    Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
973
21
    assert((!isa<Instruction>(OriginalValue) ||
974
21
            cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
975
21
           "Original value must no be one we just generated.");
976
21
    auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
977
21
    MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
978
21
    MergePHI->addIncoming(Reload, OptExitBB);
979
21
    MergePHI->addIncoming(OriginalValue, ExitBB);
980
21
    int Idx = PHI->getBasicBlockIndex(MergeBB);
981
21
    PHI->setIncomingValue(Idx, MergePHI);
982
21
  }
983
57
}
984
985
289
void BlockGenerator::invalidateScalarEvolution(Scop &S) {
986
289
  for (auto &Stmt : S)
987
445
    if (Stmt.isCopyStmt())
988
4
      continue;
989
441
    else if (Stmt.isBlockStmt())
990
407
      for (auto &Inst : *Stmt.getBasicBlock())
991
3.23k
        SE.forgetValue(&Inst);
992
34
    else if (Stmt.isRegionStmt())
993
34
      for (auto *BB : Stmt.getRegion()->blocks())
994
98
        for (auto &Inst : *BB)
995
295
          SE.forgetValue(&Inst);
996
34
    else
997
34
      
llvm_unreachable0
("Unexpected statement type found");
998
289
999
289
  // Invalidate SCEV of loops surrounding the EscapeUsers.
1000
289
  for (const auto &EscapeMapping : EscapeMap) {
1001
39
    const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
1002
45
    for (Instruction *EUser : EscapeUsers) {
1003
45
      if (Loop *L = LI.getLoopFor(EUser->getParent()))
1004
34
        
while (17
L) {
1005
17
          SE.forgetLoop(L);
1006
17
          L = L->getParentLoop();
1007
17
        }
1008
45
    }
1009
39
  }
1010
289
}
1011
1012
289
void BlockGenerator::finalizeSCoP(Scop &S) {
1013
289
  findOutsideUsers(S);
1014
289
  createScalarInitialization(S);
1015
289
  createExitPHINodeMerges(S);
1016
289
  createScalarFinalization(S);
1017
289
  invalidateScalarEvolution(S);
1018
289
}
1019
1020
VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
1021
                                           std::vector<LoopToScevMapT> &VLTS,
1022
                                           isl_map *Schedule)
1023
20
    : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
1024
20
  assert(Schedule && "No statement domain provided");
1025
20
}
1026
1027
Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
1028
                                            ValueMapT &VectorMap,
1029
                                            VectorValueMapT &ScalarMaps,
1030
32
                                            Loop *L) {
1031
32
  if (Value *NewValue = VectorMap.lookup(Old))
1032
29
    return NewValue;
1033
3
1034
3
  int Width = getVectorWidth();
1035
3
1036
3
  Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
1037
3
1038
15
  for (int Lane = 0; Lane < Width; 
Lane++12
)
1039
12
    Vector = Builder.CreateInsertElement(
1040
12
        Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
1041
12
        Builder.getInt32(Lane));
1042
3
1043
3
  VectorMap[Old] = Vector;
1044
3
1045
3
  return Vector;
1046
3
}
1047
1048
27
Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
1049
27
  PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
1050
27
  assert(PointerTy && "PointerType expected");
1051
27
1052
27
  Type *ScalarType = PointerTy->getElementType();
1053
27
  VectorType *VectorType = VectorType::get(ScalarType, Width);
1054
27
1055
27
  return PointerType::getUnqual(VectorType);
1056
27
}
1057
1058
Value *VectorBlockGenerator::generateStrideOneLoad(
1059
    ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
1060
8
    __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
1061
8
  unsigned VectorWidth = getVectorWidth();
1062
8
  auto *Pointer = Load->getPointerOperand();
1063
8
  Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
1064
8
  unsigned Offset = NegativeStride ? 
VectorWidth - 11
:
07
;
1065
8
1066
8
  Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
1067
8
                                               VLTS[Offset], NewAccesses);
1068
8
  Value *VectorPtr =
1069
8
      Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
1070
8
  LoadInst *VecLoad =
1071
8
      Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
1072
8
  if (!Aligned)
1073
8
    VecLoad->setAlignment(8);
1074
8
1075
8
  if (NegativeStride) {
1076
1
    SmallVector<Constant *, 16> Indices;
1077
5
    for (int i = VectorWidth - 1; i >= 0; 
i--4
)
1078
4
      Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
1079
1
    Constant *SV = llvm::ConstantVector::get(Indices);
1080
1
    Value *RevVecLoad = Builder.CreateShuffleVector(
1081
1
        VecLoad, VecLoad, SV, Load->getName() + "_reverse");
1082
1
    return RevVecLoad;
1083
1
  }
1084
7
1085
7
  return VecLoad;
1086
7
}
1087
1088
Value *VectorBlockGenerator::generateStrideZeroLoad(
1089
    ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
1090
3
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
1091
3
  auto *Pointer = Load->getPointerOperand();
1092
3
  Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
1093
3
  Value *NewPointer =
1094
3
      generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
1095
3
  Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
1096
3
                                           Load->getName() + "_p_vec_p");
1097
3
  LoadInst *ScalarLoad =
1098
3
      Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
1099
3
1100
3
  if (!Aligned)
1101
3
    ScalarLoad->setAlignment(8);
1102
3
1103
3
  Constant *SplatVector = Constant::getNullValue(
1104
3
      VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1105
3
1106
3
  Value *VectorLoad = Builder.CreateShuffleVector(
1107
3
      ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
1108
3
  return VectorLoad;
1109
3
}
1110
1111
Value *VectorBlockGenerator::generateUnknownStrideLoad(
1112
    ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
1113
3
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
1114
3
  int VectorWidth = getVectorWidth();
1115
3
  auto *Pointer = Load->getPointerOperand();
1116
3
  VectorType *VectorType = VectorType::get(
1117
3
      dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
1118
3
1119
3
  Value *Vector = UndefValue::get(VectorType);
1120
3
1121
23
  for (int i = 0; i < VectorWidth; 
i++20
) {
1122
20
    Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
1123
20
                                                 VLTS[i], NewAccesses);
1124
20
    Value *ScalarLoad =
1125
20
        Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
1126
20
    Vector = Builder.CreateInsertElement(
1127
20
        Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
1128
20
  }
1129
3
1130
3
  return Vector;
1131
3
}
1132
1133
void VectorBlockGenerator::generateLoad(
1134
    ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
1135
20
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1136
20
  if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
1137
6
    VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
1138
6
                                                Load->getName() + "_p");
1139
6
    return;
1140
6
  }
1141
14
1142
14
  if (!VectorType::isValidElementType(Load->getType())) {
1143
0
    for (int i = 0; i < getVectorWidth(); i++)
1144
0
      ScalarMaps[i][Load] =
1145
0
          generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
1146
0
    return;
1147
0
  }
1148
14
1149
14
  const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
1150
14
1151
14
  // Make sure we have scalar values available to access the pointer to
1152
14
  // the data location.
1153
14
  extractScalarValues(Load, VectorMap, ScalarMaps);
1154
14
1155
14
  Value *NewLoad;
1156
14
  if (Access.isStrideZero(isl::manage_copy(Schedule)))
1157
3
    NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
1158
11
  else if (Access.isStrideOne(isl::manage_copy(Schedule)))
1159
7
    NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
1160
4
  else if (Access.isStrideX(isl::manage_copy(Schedule), -1))
1161
1
    NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
1162
3
  else
1163
3
    NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
1164
14
1165
14
  VectorMap[Load] = NewLoad;
1166
14
}
1167
1168
void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
1169
                                         ValueMapT &VectorMap,
1170
1
                                         VectorValueMapT &ScalarMaps) {
1171
1
  int VectorWidth = getVectorWidth();
1172
1
  Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
1173
1
                                     ScalarMaps, getLoopForStmt(Stmt));
1174
1
1175
1
  assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
1176
1
1177
1
  const CastInst *Cast = dyn_cast<CastInst>(Inst);
1178
1
  VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
1179
1
  VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
1180
1
}
1181
1182
void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
1183
                                          ValueMapT &VectorMap,
1184
7
                                          VectorValueMapT &ScalarMaps) {
1185
7
  Loop *L = getLoopForStmt(Stmt);
1186
7
  Value *OpZero = Inst->getOperand(0);
1187
7
  Value *OpOne = Inst->getOperand(1);
1188
7
1189
7
  Value *NewOpZero, *NewOpOne;
1190
7
  NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
1191
7
  NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
1192
7
1193
7
  Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
1194
7
                                       Inst->getName() + "p_vec");
1195
7
  VectorMap[Inst] = NewInst;
1196
7
}
1197
1198
void VectorBlockGenerator::copyStore(
1199
    ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
1200
17
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1201
17
  const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
1202
17
1203
17
  auto *Pointer = Store->getPointerOperand();
1204
17
  Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
1205
17
                                 ScalarMaps, getLoopForStmt(Stmt));
1206
17
1207
17
  // Make sure we have scalar values available to access the pointer to
1208
17
  // the data location.
1209
17
  extractScalarValues(Store, VectorMap, ScalarMaps);
1210
17
1211
17
  if (Access.isStrideOne(isl::manage_copy(Schedule))) {
1212
15
    Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
1213
15
    Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
1214
15
                                                 VLTS[0], NewAccesses);
1215
15
1216
15
    Value *VectorPtr =
1217
15
        Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
1218
15
    StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
1219
15
1220
15
    if (!Aligned)
1221
15
      Store->setAlignment(8);
1222
15
  } else {
1223
10
    for (unsigned i = 0; i < ScalarMaps.size(); 
i++8
) {
1224
8
      Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
1225
8
      Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
1226
8
                                                   VLTS[i], NewAccesses);
1227
8
      Builder.CreateStore(Scalar, NewPointer);
1228
8
    }
1229
2
  }
1230
17
}
1231
1232
bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
1233
40
                                             ValueMapT &VectorMap) {
1234
40
  for (Value *Operand : Inst->operands())
1235
51
    if (VectorMap.count(Operand))
1236
28
      return true;
1237
40
  
return false12
;
1238
40
}
1239
1240
bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
1241
                                               ValueMapT &VectorMap,
1242
46
                                               VectorValueMapT &ScalarMaps) {
1243
46
  bool HasVectorOperand = false;
1244
46
  int VectorWidth = getVectorWidth();
1245
46
1246
77
  for (Value *Operand : Inst->operands()) {
1247
77
    ValueMapT::iterator VecOp = VectorMap.find(Operand);
1248
77
1249
77
    if (VecOp == VectorMap.end())
1250
57
      continue;
1251
20
1252
20
    HasVectorOperand = true;
1253
20
    Value *NewVector = VecOp->second;
1254
20
1255
115
    for (int i = 0; i < VectorWidth; 
++i95
) {
1256
98
      ValueMapT &SM = ScalarMaps[i];
1257
98
1258
98
      // If there is one scalar extracted, all scalar elements should have
1259
98
      // already been extracted by the code here. So no need to check for the
1260
98
      // existence of all of them.
1261
98
      if (SM.count(Operand))
1262
3
        break;
1263
95
1264
95
      SM[Operand] =
1265
95
          Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
1266
95
    }
1267
20
  }
1268
46
1269
46
  return HasVectorOperand;
1270
46
}
1271
1272
void VectorBlockGenerator::copyInstScalarized(
1273
    ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1274
15
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1275
15
  bool HasVectorOperand;
1276
15
  int VectorWidth = getVectorWidth();
1277
15
1278
15
  HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
1279
15
1280
91
  for (int VectorLane = 0; VectorLane < getVectorWidth(); 
VectorLane++76
)
1281
76
    BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
1282
76
                                    VLTS[VectorLane], NewAccesses);
1283
15
1284
15
  if (!VectorType::isValidElementType(Inst->getType()) || 
!HasVectorOperand12
)
1285
12
    return;
1286
3
1287
3
  // Make the result available as vector value.
1288
3
  VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
1289
3
  Value *Vector = UndefValue::get(VectorType);
1290
3
1291
15
  for (int i = 0; i < VectorWidth; 
i++12
)
1292
12
    Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
1293
12
                                         Builder.getInt32(i));
1294
3
1295
3
  VectorMap[Inst] = Vector;
1296
3
}
1297
1298
212
int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
1299
1300
void VectorBlockGenerator::copyInstruction(
1301
    ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1302
122
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1303
122
  // Terminator instructions control the control flow. They are explicitly
1304
122
  // expressed in the clast and do not need to be copied.
1305
122
  if (Inst->isTerminator())
1306
20
    return;
1307
102
1308
102
  if (canSyntheziseInStmt(Stmt, Inst))
1309
42
    return;
1310
60
1311
60
  if (auto *Load = dyn_cast<LoadInst>(Inst)) {
1312
20
    generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
1313
20
    return;
1314
20
  }
1315
40
1316
40
  if (hasVectorOperands(Inst, VectorMap)) {
1317
28
    if (auto *Store = dyn_cast<StoreInst>(Inst)) {
1318
17
      // Identified as redundant by -polly-simplify.
1319
17
      if (!Stmt.getArrayAccessOrNULLFor(Store))
1320
0
        return;
1321
17
1322
17
      copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1323
17
      return;
1324
17
    }
1325
11
1326
11
    if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1327
1
      copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1328
1
      return;
1329
1
    }
1330
10
1331
10
    if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1332
7
      copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1333
7
      return;
1334
7
    }
1335
15
1336
15
    // Fallthrough: We generate scalar instructions, if we don't know how to
1337
15
    // generate vector code.
1338
15
  }
1339
15
1340
15
  copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1341
15
}
1342
1343
void VectorBlockGenerator::generateScalarVectorLoads(
1344
20
    ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1345
35
  for (MemoryAccess *MA : Stmt) {
1346
35
    if (MA->isArrayKind() || 
MA->isWrite()1
)
1347
34
      continue;
1348
1
1349
1
    auto *Address = getOrCreateAlloca(*MA);
1350
1
    Type *VectorPtrType = getVectorPtrTy(Address, 1);
1351
1
    Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1352
1
                                             Address->getName() + "_p_vec_p");
1353
1
    auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1354
1
    Constant *SplatVector = Constant::getNullValue(
1355
1
        VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1356
1
1357
1
    Value *VectorVal = Builder.CreateShuffleVector(
1358
1
        Val, Val, SplatVector, Address->getName() + "_p_splat");
1359
1
    VectorBlockMap[MA->getAccessValue()] = VectorVal;
1360
1
  }
1361
20
}
1362
1363
20
void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1364
35
  for (MemoryAccess *MA : Stmt) {
1365
35
    if (MA->isArrayKind() || 
MA->isRead()1
)
1366
35
      continue;
1367
0
1368
0
    llvm_unreachable("Scalar stores not expected in vector loop");
1369
0
  }
1370
20
}
1371
1372
void VectorBlockGenerator::copyStmt(
1373
20
    ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1374
20
  assert(Stmt.isBlockStmt() &&
1375
20
         "TODO: Only block statements can be copied by the vector block "
1376
20
         "generator");
1377
20
1378
20
  BasicBlock *BB = Stmt.getBasicBlock();
1379
20
  BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1380
20
                                  &*Builder.GetInsertPoint(), &DT, &LI);
1381
20
  CopyBB->setName("polly.stmt." + BB->getName());
1382
20
  Builder.SetInsertPoint(&CopyBB->front());
1383
20
1384
20
  // Create two maps that store the mapping from the original instructions of
1385
20
  // the old basic block to their copies in the new basic block. Those maps
1386
20
  // are basic block local.
1387
20
  //
1388
20
  // As vector code generation is supported there is one map for scalar values
1389
20
  // and one for vector values.
1390
20
  //
1391
20
  // In case we just do scalar code generation, the vectorMap is not used and
1392
20
  // the scalarMap has just one dimension, which contains the mapping.
1393
20
  //
1394
20
  // In case vector code generation is done, an instruction may either appear
1395
20
  // in the vector map once (as it is calculating >vectorwidth< values at a
1396
20
  // time. Or (if the values are calculated using scalar operations), it
1397
20
  // appears once in every dimension of the scalarMap.
1398
20
  VectorValueMapT ScalarBlockMap(getVectorWidth());
1399
20
  ValueMapT VectorBlockMap;
1400
20
1401
20
  generateScalarVectorLoads(Stmt, VectorBlockMap);
1402
20
1403
20
  for (Instruction &Inst : *BB)
1404
122
    copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1405
20
1406
20
  verifyNoScalarStores(Stmt);
1407
20
}
1408
1409
BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1410
101
                                             BasicBlock *BBCopy) {
1411
101
1412
101
  BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1413
101
  BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1414
101
1415
101
  if (BBCopyIDom)
1416
100
    DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1417
101
1418
101
  return StartBlockMap.lookup(BBIDom);
1419
101
}
1420
1421
// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1422
// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1423
// does not work in cases where the exit block has edges from outside the
1424
// region. In that case the llvm::Value would never be usable in in the exit
1425
// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1426
// for the subregion's exiting edges only. We need to determine whether an
1427
// llvm::Value is usable in there. We do this by checking whether it dominates
1428
// all exiting blocks individually.
1429
static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1430
101
                                      BasicBlock *BB) {
1431
188
  for (auto ExitingBB : predecessors(R->getExit())) {
1432
188
    // Check for non-subregion incoming edges.
1433
188
    if (!R->contains(ExitingBB))
1434
27
      continue;
1435
161
1436
161
    if (!DT.dominates(BB, ExitingBB))
1437
58
      return false;
1438
161
  }
1439
101
1440
101
  
return true43
;
1441
101
}
1442
1443
// Find the direct dominator of the subregion's exit block if the subregion was
1444
// simplified.
1445
35
static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1446
35
  BasicBlock *Common = nullptr;
1447
72
  for (auto ExitingBB : predecessors(R->getExit())) {
1448
72
    // Check for non-subregion incoming edges.
1449
72
    if (!R->contains(ExitingBB))
1450
9
      continue;
1451
63
1452
63
    // First exiting edge.
1453
63
    if (!Common) {
1454
35
      Common = ExitingBB;
1455
35
      continue;
1456
35
    }
1457
28
1458
28
    Common = DT.findNearestCommonDominator(Common, ExitingBB);
1459
28
  }
1460
35
1461
35
  assert(Common && R->contains(Common));
1462
35
  return Common;
1463
35
}
1464
1465
void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1466
35
                               isl_id_to_ast_expr *IdToAstExp) {
1467
35
  assert(Stmt.isRegionStmt() &&
1468
35
         "Only region statements can be copied by the region generator");
1469
35
1470
35
  // Forget all old mappings.
1471
35
  StartBlockMap.clear();
1472
35
  EndBlockMap.clear();
1473
35
  RegionMaps.clear();
1474
35
  IncompletePHINodeMap.clear();
1475
35
1476
35
  // Collection of all values related to this subregion.
1477
35
  ValueMapT ValueMap;
1478
35
1479
35
  // The region represented by the statement.
1480
35
  Region *R = Stmt.getRegion();
1481
35
1482
35
  // Create a dedicated entry for the region where we can reload all demoted
1483
35
  // inputs.
1484
35
  BasicBlock *EntryBB = R->getEntry();
1485
35
  BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1486
35
                                       &*Builder.GetInsertPoint(), &DT, &LI);
1487
35
  EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1488
35
  Builder.SetInsertPoint(&EntryBBCopy->front());
1489
35
1490
35
  ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1491
35
  generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1492
35
  generateBeginStmtTrace(Stmt, LTS, EntryBBMap);
1493
35
1494
85
  for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; 
++PI50
)
1495
50
    if (!R->contains(*PI)) {
1496
48
      StartBlockMap[*PI] = EntryBBCopy;
1497
48
      EndBlockMap[*PI] = EntryBBCopy;
1498
48
    }
1499
35
1500
35
  // Iterate over all blocks in the region in a breadth-first search.
1501
35
  std::deque<BasicBlock *> Blocks;
1502
35
  SmallSetVector<BasicBlock *, 8> SeenBlocks;
1503
35
  Blocks.push_back(EntryBB);
1504
35
  SeenBlocks.insert(EntryBB);
1505
35
1506
136
  while (!Blocks.empty()) {
1507
101
    BasicBlock *BB = Blocks.front();
1508
101
    Blocks.pop_front();
1509
101
1510
101
    // First split the block and update dominance information.
1511
101
    BasicBlock *BBCopy = splitBB(BB);
1512
101
    BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1513
101
1514
101
    // Get the mapping for this block and initialize it with either the scalar
1515
101
    // loads from the generated entering block (which dominates all blocks of
1516
101
    // this subregion) or the maps of the immediate dominator, if part of the
1517
101
    // subregion. The latter necessarily includes the former.
1518
101
    ValueMapT *InitBBMap;
1519
101
    if (BBCopyIDom) {
1520
100
      assert(RegionMaps.count(BBCopyIDom));
1521
100
      InitBBMap = &RegionMaps[BBCopyIDom];
1522
100
    } else
1523
1
      InitBBMap = &EntryBBMap;
1524
101
    auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1525
101
    ValueMapT &RegionMap = Inserted.first->second;
1526
101
1527
101
    // Copy the block with the BlockGenerator.
1528
101
    Builder.SetInsertPoint(&BBCopy->front());
1529
101
    copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1530
101
1531
101
    // In order to remap PHI nodes we store also basic block mappings.
1532
101
    StartBlockMap[BB] = BBCopy;
1533
101
    EndBlockMap[BB] = Builder.GetInsertBlock();
1534
101
1535
101
    // Add values to incomplete PHI nodes waiting for this block to be copied.
1536
101
    for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1537
3
      addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1538
101
    IncompletePHINodeMap[BB].clear();
1539
101
1540
101
    // And continue with new successors inside the region.
1541
244
    for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; 
SI++143
)
1542
143
      if (R->contains(*SI) && 
SeenBlocks.insert(*SI)80
)
1543
66
        Blocks.push_back(*SI);
1544
101
1545
101
    // Remember value in case it is visible after this subregion.
1546
101
    if (isDominatingSubregionExit(DT, R, BB))
1547
43
      ValueMap.insert(RegionMap.begin(), RegionMap.end());
1548
101
  }
1549
35
1550
35
  // Now create a new dedicated region exit block and add it to the region map.
1551
35
  BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1552
35
                                      &*Builder.GetInsertPoint(), &DT, &LI);
1553
35
  ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1554
35
  StartBlockMap[R->getExit()] = ExitBBCopy;
1555
35
  EndBlockMap[R->getExit()] = ExitBBCopy;
1556
35
1557
35
  BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
1558
35
  assert(ExitDomBBCopy &&
1559
35
         "Common exit dominator must be within region; at least the entry node "
1560
35
         "must match");
1561
35
  DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1562
35
1563
35
  // As the block generator doesn't handle control flow we need to add the
1564
35
  // region control flow by hand after all blocks have been copied.
1565
101
  for (BasicBlock *BB : SeenBlocks) {
1566
101
1567
101
    BasicBlock *BBCopyStart = StartBlockMap[BB];
1568
101
    BasicBlock *BBCopyEnd = EndBlockMap[BB];
1569
101
    Instruction *TI = BB->getTerminator();
1570
101
    if (isa<UnreachableInst>(TI)) {
1571
0
      while (!BBCopyEnd->empty())
1572
0
        BBCopyEnd->begin()->eraseFromParent();
1573
0
      new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1574
0
      continue;
1575
0
    }
1576
101
1577
101
    Instruction *BICopy = BBCopyEnd->getTerminator();
1578
101
1579
101
    ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1580
101
    RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end());
1581
101
1582
101
    Builder.SetInsertPoint(BICopy);
1583
101
    copyInstScalar(Stmt, TI, RegionMap, LTS);
1584
101
    BICopy->eraseFromParent();
1585
101
  }
1586
35
1587
35
  // Add counting PHI nodes to all loops in the region that can be used as
1588
35
  // replacement for SCEVs referring to the old loop.
1589
101
  for (BasicBlock *BB : SeenBlocks) {
1590
101
    Loop *L = LI.getLoopFor(BB);
1591
101
    if (L == nullptr || 
L->getHeader() != BB75
||
!R->contains(L)12
)
1592
99
      continue;
1593
2
1594
2
    BasicBlock *BBCopy = StartBlockMap[BB];
1595
2
    Value *NullVal = Builder.getInt32(0);
1596
2
    PHINode *LoopPHI =
1597
2
        PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1598
2
    Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1599
2
        LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1600
2
    LoopPHI->insertBefore(&BBCopy->front());
1601
2
    LoopPHIInc->insertBefore(BBCopy->getTerminator());
1602
2
1603
4
    for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1604
4
      if (!R->contains(PredBB))
1605
2
        continue;
1606
2
      if (L->contains(PredBB))
1607
2
        LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1608
0
      else
1609
0
        LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1610
2
    }
1611
2
1612
2
    for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1613
4
      if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1614
2
        LoopPHI->addIncoming(NullVal, PredBBCopy);
1615
2
1616
2
    LTS[L] = SE.getUnknown(LoopPHI);
1617
2
  }
1618
35
1619
35
  // Continue generating code in the exit block.
1620
35
  Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1621
35
1622
35
  // Write values visible to other statements.
1623
35
  generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1624
35
  StartBlockMap.clear();
1625
35
  EndBlockMap.clear();
1626
35
  RegionMaps.clear();
1627
35
  IncompletePHINodeMap.clear();
1628
35
}
1629
1630
PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1631
12
                                       ValueMapT &BBMap, Loop *L) {
1632
12
  ScopStmt *Stmt = MA->getStatement();
1633
12
  Region *SubR = Stmt->getRegion();
1634
12
  auto Incoming = MA->getIncoming();
1635
12
1636
12
  PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1637
12
  PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1638
12
  BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1639
12
1640
12
  // This can happen if the subregion is simplified after the ScopStmts
1641
12
  // have been created; simplification happens as part of CodeGeneration.
1642
12
  if (OrigPHI->getParent() != SubR->getExit()) {
1643
6
    BasicBlock *FormerExit = SubR->getExitingBlock();
1644
6
    if (FormerExit)
1645
4
      NewSubregionExit = StartBlockMap.lookup(FormerExit);
1646
6
  }
1647
12
1648
12
  PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1649
12
                                    "polly." + OrigPHI->getName(),
1650
12
                                    NewSubregionExit->getFirstNonPHI());
1651
12
1652
12
  // Add the incoming values to the PHI.
1653
26
  for (auto &Pair : Incoming) {
1654
26
    BasicBlock *OrigIncomingBlock = Pair.first;
1655
26
    BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1656
26
    BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1657
26
    Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator());
1658
26
    assert(RegionMaps.count(NewIncomingBlockStart));
1659
26
    assert(RegionMaps.count(NewIncomingBlockEnd));
1660
26
    ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1661
26
1662
26
    Value *OrigIncomingValue = Pair.second;
1663
26
    Value *NewIncomingValue =
1664
26
        getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1665
26
    NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1666
26
  }
1667
12
1668
12
  return NewPHI;
1669
12
}
1670
1671
Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1672
19
                                      ValueMapT &BBMap) {
1673
19
  ScopStmt *Stmt = MA->getStatement();
1674
19
1675
19
  // TODO: Add some test cases that ensure this is really the right choice.
1676
19
  Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1677
19
1678
19
  if (MA->isAnyPHIKind()) {
1679
12
    auto Incoming = MA->getIncoming();
1680
12
    assert(!Incoming.empty() &&
1681
12
           "PHI WRITEs must have originate from at least one incoming block");
1682
12
1683
12
    // If there is only one incoming value, we do not need to create a PHI.
1684
12
    if (Incoming.size() == 1) {
1685
0
      Value *OldVal = Incoming[0].second;
1686
0
      return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1687
0
    }
1688
12
1689
12
    return buildExitPHI(MA, LTS, BBMap, L);
1690
12
  }
1691
7
1692
7
  // MemoryKind::Value accesses leaving the subregion must dominate the exit
1693
7
  // block; just pass the copied value.
1694
7
  Value *OldVal = MA->getAccessValue();
1695
7
  return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1696
7
}
1697
1698
void RegionGenerator::generateScalarStores(
1699
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1700
35
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
1701
35
  assert(Stmt.getRegion() &&
1702
35
         "Block statements need to use the generateScalarStores() "
1703
35
         "function in the BlockGenerator");
1704
35
1705
96
  for (MemoryAccess *MA : Stmt) {
1706
96
    if (MA->isOriginalArrayKind() || 
MA->isRead()29
)
1707
77
      continue;
1708
19
1709
19
    isl::set AccDom = MA->getAccessRelation().domain();
1710
19
    std::string Subject = MA->getId().get_name();
1711
19
    generateConditionalExecution(
1712
19
        Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1713
19
          Value *NewVal = getExitScalar(MA, LTS, BBMap);
1714
19
          Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1715
19
                                              BBMap, NewAccesses);
1716
19
          assert((!isa<Instruction>(NewVal) ||
1717
19
                  DT.dominates(cast<Instruction>(NewVal)->getParent(),
1718
19
                               Builder.GetInsertBlock())) &&
1719
19
                 "Domination violation");
1720
19
          assert((!isa<Instruction>(Address) ||
1721
19
                  DT.dominates(cast<Instruction>(Address)->getParent(),
1722
19
                               Builder.GetInsertBlock())) &&
1723
19
                 "Domination violation");
1724
19
          Builder.CreateStore(NewVal, Address);
1725
19
        });
1726
19
  }
1727
35
}
1728
1729
void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1730
                                      PHINode *PHICopy, BasicBlock *IncomingBB,
1731
15
                                      LoopToScevMapT &LTS) {
1732
15
  // If the incoming block was not yet copied mark this PHI as incomplete.
1733
15
  // Once the block will be copied the incoming value will be added.
1734
15
  BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1735
15
  BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1736
15
  if (!BBCopyStart) {
1737
3
    assert(!BBCopyEnd);
1738
3
    assert(Stmt.represents(IncomingBB) &&
1739
3
           "Bad incoming block for PHI in non-affine region");
1740
3
    IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1741
3
    return;
1742
3
  }
1743
12
1744
12
  assert(RegionMaps.count(BBCopyStart) &&
1745
12
         "Incoming PHI block did not have a BBMap");
1746
12
  ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1747
12
1748
12
  Value *OpCopy = nullptr;
1749
12
1750
12
  if (Stmt.represents(IncomingBB)) {
1751
6
    Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1752
6
1753
6
    // If the current insert block is different from the PHIs incoming block
1754
6
    // change it, otherwise do not.
1755
6
    auto IP = Builder.GetInsertPoint();
1756
6
    if (IP->getParent() != BBCopyEnd)
1757
3
      Builder.SetInsertPoint(BBCopyEnd->getTerminator());
1758
6
    OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1759
6
    if (IP->getParent() != BBCopyEnd)
1760
3
      Builder.SetInsertPoint(&*IP);
1761
6
  } else {
1762
6
    // All edges from outside the non-affine region become a single edge
1763
6
    // in the new copy of the non-affine region. Make sure to only add the
1764
6
    // corresponding edge the first time we encounter a basic block from
1765
6
    // outside the non-affine region.
1766
6
    if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1767
1
      return;
1768
5
1769
5
    // Get the reloaded value.
1770
5
    OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1771
5
  }
1772
12
1773
12
  assert(OpCopy && "Incoming PHI value was not copied properly");
1774
11
  PHICopy->addIncoming(OpCopy, BBCopyEnd);
1775
11
}
1776
1777
void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1778
                                         ValueMapT &BBMap,
1779
7
                                         LoopToScevMapT &LTS) {
1780
7
  unsigned NumIncoming = PHI->getNumIncomingValues();
1781
7
  PHINode *PHICopy =
1782
7
      Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1783
7
  PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1784
7
  BBMap[PHI] = PHICopy;
1785
7
1786
7
  for (BasicBlock *IncomingBB : PHI->blocks())
1787
12
    addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1788
7
}