Coverage Report

Created: 2019-02-23 12:57

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/include/polly/CodeGen/IslNodeBuilder.h
Line
Count
Source
1
//=- IslNodeBuilder.cpp - Translate an isl AST into a LLVM-IR AST -*- C++ -*-=//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file contains the IslNodeBuilder, a class to translate an isl AST into
10
// a LLVM-IR AST.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef POLLY_ISLNODEBUILDER_H
15
#define POLLY_ISLNODEBUILDER_H
16
17
#include "polly/CodeGen/BlockGenerators.h"
18
#include "polly/CodeGen/IslExprBuilder.h"
19
#include "polly/ScopDetectionDiagnostic.h"
20
#include "polly/Support/ScopHelper.h"
21
#include "llvm/ADT/ArrayRef.h"
22
#include "llvm/ADT/SetVector.h"
23
#include "llvm/ADT/SmallSet.h"
24
#include "llvm/ADT/SmallVector.h"
25
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
26
#include "llvm/IR/InstrTypes.h"
27
#include "isl/ctx.h"
28
#include "isl/isl-noexceptions.h"
29
#include <utility>
30
#include <vector>
31
32
using namespace llvm;
33
using namespace polly;
34
35
namespace llvm {
36
37
class BasicBlock;
38
class DataLayout;
39
class DominatorTree;
40
class Function;
41
class Instruction;
42
class Loop;
43
class LoopInfo;
44
class ScalarEvolution;
45
class SCEV;
46
class Type;
47
class Value;
48
} // namespace llvm
49
50
namespace polly {
51
52
struct InvariantEquivClassTy;
53
class MemoryAccess;
54
class Scop;
55
class ScopStmt;
56
} // namespace polly
57
58
struct isl_ast_node;
59
struct isl_ast_build;
60
struct isl_union_map;
61
62
struct SubtreeReferences {
63
  LoopInfo &LI;
64
  ScalarEvolution &SE;
65
  Scop &S;
66
  ValueMapT &GlobalMap;
67
  SetVector<Value *> &Values;
68
  SetVector<const SCEV *> &SCEVs;
69
  BlockGenerator &BlockGen;
70
  // In case an (optional) parameter space location is provided, parameter space
71
  // information is collected as well.
72
  isl::space *ParamSpace;
73
};
74
75
/// Extract the out-of-scop values and SCEVs referenced from a ScopStmt.
76
///
77
/// This includes the SCEVUnknowns referenced by the SCEVs used in the
78
/// statement and the base pointers of the memory accesses. For scalar
79
/// statements we force the generation of alloca memory locations and list
80
/// these locations in the set of out-of-scop values as well.
81
///
82
/// We also collect an isl::space that includes all parameter dimensions
83
/// used in the statement's memory accesses, in case the ParamSpace pointer
84
/// is non-null.
85
///
86
/// @param Stmt             The statement for which to extract the information.
87
/// @param UserPtr          A void pointer that can be casted to a
88
///                         SubtreeReferences structure.
89
/// @param CreateScalarRefs Should the result include allocas of scalar
90
///                         references?
91
void addReferencesFromStmt(const ScopStmt *Stmt, void *UserPtr,
92
                           bool CreateScalarRefs = true);
93
94
class IslNodeBuilder {
95
public:
96
  IslNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
97
                 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
98
                 DominatorTree &DT, Scop &S, BasicBlock *StartBlock)
99
      : S(S), Builder(Builder), Annotator(Annotator),
100
        ExprBuilder(S, Builder, IDToValue, ValueMap, DL, SE, DT, LI,
101
                    StartBlock),
102
        BlockGen(Builder, LI, SE, DT, ScalarMap, EscapeMap, ValueMap,
103
                 &ExprBuilder, StartBlock),
104
        RegionGen(BlockGen), DL(DL), LI(LI), SE(SE), DT(DT),
105
293
        StartBlock(StartBlock) {}
106
107
293
  virtual ~IslNodeBuilder() = default;
108
109
  void addParameters(__isl_take isl_set *Context);
110
111
  /// Create Values which hold the sizes of the outermost dimension of all
112
  /// Fortran arrays in the current scop.
113
  ///
114
  /// @returns False, if a problem occurred and a Fortran array was not
115
  /// materialized. True otherwise.
116
  bool materializeFortranArrayOutermostDimension();
117
118
  /// Generate code that evaluates @p Condition at run-time.
119
  ///
120
  /// This function is typically called to generate the LLVM-IR for the
121
  /// run-time condition of the scop, that verifies that all the optimistic
122
  /// assumptions we have taken during scop modeling and transformation
123
  /// hold at run-time.
124
  ///
125
  /// @param Condition The condition to evaluate
126
  ///
127
  /// @result An llvm::Value that is true if the condition holds and false
128
  ///         otherwise.
129
  Value *createRTC(isl_ast_expr *Condition);
130
131
  void create(__isl_take isl_ast_node *Node);
132
133
  /// Allocate memory for all new arrays created by Polly.
134
  void allocateNewArrays(BBPair StartExitBlocks);
135
136
  /// Preload all memory loads that are invariant.
137
  bool preloadInvariantLoads();
138
139
  /// Finalize code generation.
140
  ///
141
  /// @see BlockGenerator::finalizeSCoP(Scop &S)
142
289
  virtual void finalize() { BlockGen.finalizeSCoP(S); }
143
144
289
  IslExprBuilder &getExprBuilder() { return ExprBuilder; }
145
146
  /// Get the associated block generator.
147
  ///
148
  /// @return A reference to the associated block generator.
149
30
  BlockGenerator &getBlockGenerator() { return BlockGen; }
150
151
  /// Return the parallel subfunctions that have been created.
152
293
  const ArrayRef<Function *> getParallelSubfunctions() const {
153
293
    return ParallelSubfunctions;
154
293
  }
155
156
protected:
157
  Scop &S;
158
  PollyIRBuilder &Builder;
159
  ScopAnnotator &Annotator;
160
161
  IslExprBuilder ExprBuilder;
162
163
  /// Maps used by the block and region generator to demote scalars.
164
  ///
165
  ///@{
166
167
  /// See BlockGenerator::ScalarMap.
168
  BlockGenerator::AllocaMapTy ScalarMap;
169
170
  /// See BlockGenerator::EscapeMap.
171
  BlockGenerator::EscapeUsersAllocaMapTy EscapeMap;
172
173
  ///@}
174
175
  /// The generator used to copy a basic block.
176
  BlockGenerator BlockGen;
177
178
  /// The generator used to copy a non-affine region.
179
  RegionGenerator RegionGen;
180
181
  const DataLayout &DL;
182
  LoopInfo &LI;
183
  ScalarEvolution &SE;
184
  DominatorTree &DT;
185
  BasicBlock *StartBlock;
186
187
  /// The current iteration of out-of-scop loops
188
  ///
189
  /// This map provides for a given loop a llvm::Value that contains the current
190
  /// loop iteration.
191
  LoopToScevMapT OutsideLoopIterations;
192
193
  // This maps an isl_id* to the Value* it has in the generated program. For now
194
  // on, the only isl_ids that are stored here are the newly calculated loop
195
  // ivs.
196
  IslExprBuilder::IDToValueTy IDToValue;
197
198
  /// A collection of all parallel subfunctions that have been created.
199
  SmallVector<Function *, 8> ParallelSubfunctions;
200
201
  /// Generate code for a given SCEV*
202
  ///
203
  /// This function generates code for a given SCEV expression. It generated
204
  /// code is emitted at the end of the basic block our Builder currently
205
  /// points to and the resulting value is returned.
206
  ///
207
  /// @param Expr The expression to code generate.
208
  Value *generateSCEV(const SCEV *Expr);
209
210
  /// A set of Value -> Value remappings to apply when generating new code.
211
  ///
212
  /// When generating new code for a ScopStmt this map is used to map certain
213
  /// llvm::Values to new llvm::Values.
214
  ValueMapT ValueMap;
215
216
  /// Materialize code for @p Id if it was not done before.
217
  ///
218
  /// @returns False, iff a problem occurred and the value was not materialized.
219
  bool materializeValue(__isl_take isl_id *Id);
220
221
  /// Materialize parameters of @p Set.
222
  ///
223
  /// @returns False, iff a problem occurred and the value was not materialized.
224
  bool materializeParameters(__isl_take isl_set *Set);
225
226
  /// Materialize all parameters in the current scop.
227
  ///
228
  /// @returns False, iff a problem occurred and the value was not materialized.
229
  bool materializeParameters();
230
231
  // Extract the upper bound of this loop
232
  //
233
  // The isl code generation can generate arbitrary expressions to check if the
234
  // upper bound of a loop is reached, but it provides an option to enforce
235
  // 'atomic' upper bounds. An 'atomic upper bound is always of the form
236
  // iv <= expr, where expr is an (arbitrary) expression not containing iv.
237
  //
238
  // This function extracts 'atomic' upper bounds. Polly, in general, requires
239
  // atomic upper bounds for the following reasons:
240
  //
241
  // 1. An atomic upper bound is loop invariant
242
  //
243
  //    It must not be calculated at each loop iteration and can often even be
244
  //    hoisted out further by the loop invariant code motion.
245
  //
246
  // 2. OpenMP needs a loop invariant upper bound to calculate the number
247
  //    of loop iterations.
248
  //
249
  // 3. With the existing code, upper bounds have been easier to implement.
250
  isl::ast_expr getUpperBound(isl::ast_node For, CmpInst::Predicate &Predicate);
251
252
  /// Return non-negative number of iterations in case of the following form
253
  /// of a loop and -1 otherwise.
254
  ///
255
  /// for (i = 0; i <= NumIter; i++) {
256
  ///   loop body;
257
  /// }
258
  ///
259
  /// NumIter is a non-negative integer value. Condition can have
260
  /// isl_ast_op_lt type.
261
  int getNumberOfIterations(isl::ast_node For);
262
263
  /// Compute the values and loops referenced in this subtree.
264
  ///
265
  /// This function looks at all ScopStmts scheduled below the provided For node
266
  /// and finds the llvm::Value[s] and llvm::Loops[s] which are referenced but
267
  /// not locally defined.
268
  ///
269
  /// Values that can be synthesized or that are available as globals are
270
  /// considered locally defined.
271
  ///
272
  /// Loops that contain the scop or that are part of the scop are considered
273
  /// locally defined. Loops that are before the scop, but do not contain the
274
  /// scop itself are considered not locally defined.
275
  ///
276
  /// @param For    The node defining the subtree.
277
  /// @param Values A vector that will be filled with the Values referenced in
278
  ///               this subtree.
279
  /// @param Loops  A vector that will be filled with the Loops referenced in
280
  ///               this subtree.
281
  void getReferencesInSubtree(__isl_keep isl_ast_node *For,
282
                              SetVector<Value *> &Values,
283
                              SetVector<const Loop *> &Loops);
284
285
  /// Change the llvm::Value(s) used for code generation.
286
  ///
287
  /// When generating code certain values (e.g., references to induction
288
  /// variables or array base pointers) in the original code may be replaced by
289
  /// new values. This function allows to (partially) update the set of values
290
  /// used. A typical use case for this function is the case when we continue
291
  /// code generation in a subfunction/kernel function and need to explicitly
292
  /// pass down certain values.
293
  ///
294
  /// @param NewValues A map that maps certain llvm::Values to new llvm::Values.
295
  void updateValues(ValueMapT &NewValues);
296
297
  /// Return the most up-to-date version of the llvm::Value for code generation.
298
  /// @param Original The Value to check for an up to date version.
299
  /// @returns A remapped `Value` from ValueMap, or `Original` if no mapping
300
  ///          exists.
301
  /// @see IslNodeBuilder::updateValues
302
  /// @see IslNodeBuilder::ValueMap
303
  Value *getLatestValue(Value *Original) const;
304
305
  /// Generate code for a marker now.
306
  ///
307
  /// For mark nodes with an unknown name, we just forward the code generation
308
  /// to its child. This is currently the only behavior implemented, as there is
309
  /// currently not special handling for marker nodes implemented.
310
  ///
311
  /// @param Mark The node we generate code for.
312
  virtual void createMark(__isl_take isl_ast_node *Marker);
313
314
  virtual void createFor(__isl_take isl_ast_node *For);
315
316
  /// Set to remember materialized invariant loads.
317
  ///
318
  /// An invariant load is identified by its pointer (the SCEV) and its type.
319
  SmallSet<std::pair<const SCEV *, Type *>, 16> PreloadedPtrs;
320
321
  /// Preload the memory access at @p AccessRange with @p Build.
322
  ///
323
  /// @returns The preloaded value casted to type @p Ty
324
  Value *preloadUnconditionally(__isl_take isl_set *AccessRange,
325
                                isl_ast_build *Build, Instruction *AccInst);
326
327
  /// Preload the memory load access @p MA.
328
  ///
329
  /// If @p MA is not always executed it will be conditionally loaded and
330
  /// merged with undef from the same type. Hence, if @p MA is executed only
331
  /// under condition C then the preload code will look like this:
332
  ///
333
  /// MA_preload = undef;
334
  /// if (C)
335
  ///   MA_preload = load MA;
336
  /// use MA_preload
337
  Value *preloadInvariantLoad(const MemoryAccess &MA,
338
                              __isl_take isl_set *Domain);
339
340
  /// Preload the invariant access equivalence class @p IAClass
341
  ///
342
  /// This function will preload the representing load from @p IAClass and
343
  /// map all members of @p IAClass to that preloaded value, potentially casted
344
  /// to the required type.
345
  ///
346
  /// @returns False, iff a problem occurred and the load was not preloaded.
347
  bool preloadInvariantEquivClass(InvariantEquivClassTy &IAClass);
348
349
  void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
350
  void createForSequential(isl::ast_node For, bool MarkParallel);
351
352
  /// Create LLVM-IR that executes a for node thread parallel.
353
  ///
354
  /// @param For The FOR isl_ast_node for which code is generated.
355
  void createForParallel(__isl_take isl_ast_node *For);
356
357
  /// Create new access functions for modified memory accesses.
358
  ///
359
  /// In case the access function of one of the memory references in the Stmt
360
  /// has been modified, we generate a new isl_ast_expr that reflects the
361
  /// newly modified access function and return a map that maps from the
362
  /// individual memory references in the statement (identified by their id)
363
  /// to these newly generated ast expressions.
364
  ///
365
  /// @param Stmt  The statement for which to (possibly) generate new access
366
  ///              functions.
367
  /// @param Node  The ast node corresponding to the statement for us to extract
368
  ///              the local schedule from.
369
  /// @return A new hash table that contains remappings from memory ids to new
370
  ///         access expressions.
371
  __isl_give isl_id_to_ast_expr *
372
  createNewAccesses(ScopStmt *Stmt, __isl_keep isl_ast_node *Node);
373
374
  /// Generate LLVM-IR that computes the values of the original induction
375
  /// variables in function of the newly generated loop induction variables.
376
  ///
377
  /// Example:
378
  ///
379
  ///   // Original
380
  ///   for i
381
  ///     for j
382
  ///       S(i)
383
  ///
384
  ///   Schedule: [i,j] -> [i+j, j]
385
  ///
386
  ///   // New
387
  ///   for c0
388
  ///     for c1
389
  ///       S(c0 - c1, c1)
390
  ///
391
  /// Assuming the original code consists of two loops which are
392
  /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
393
  /// ast models the original statement as a call expression where each argument
394
  /// is an expression that computes the old induction variables from the new
395
  /// ones, ordered such that the first argument computes the value of induction
396
  /// variable that was outermost in the original code.
397
  ///
398
  /// @param Expr The call expression that represents the statement.
399
  /// @param Stmt The statement that is called.
400
  /// @param LTS  The loop to SCEV map in which the mapping from the original
401
  ///             loop to a SCEV representing the new loop iv is added. This
402
  ///             mapping does not require an explicit induction variable.
403
  ///             Instead, we think in terms of an implicit induction variable
404
  ///             that counts the number of times a loop is executed. For each
405
  ///             original loop this count, expressed in function of the new
406
  ///             induction variables, is added to the LTS map.
407
  void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
408
                           LoopToScevMapT &LTS);
409
  void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
410
                                 std::vector<LoopToScevMapT> &VLTS,
411
                                 std::vector<Value *> &IVS,
412
                                 __isl_take isl_id *IteratorID);
413
  virtual void createIf(__isl_take isl_ast_node *If);
414
  void createUserVector(__isl_take isl_ast_node *User,
415
                        std::vector<Value *> &IVS,
416
                        __isl_take isl_id *IteratorID,
417
                        __isl_take isl_union_map *Schedule);
418
  virtual void createUser(__isl_take isl_ast_node *User);
419
  virtual void createBlock(__isl_take isl_ast_node *Block);
420
421
  /// Get the schedule for a given AST node.
422
  ///
423
  /// This information is used to reason about parallelism of loops or the
424
  /// locality of memory accesses under a given schedule.
425
  ///
426
  /// @param Node The node we want to obtain the schedule for.
427
  /// @return Return an isl_union_map that maps from the statements executed
428
  ///         below this ast node to the scheduling vectors used to enumerate
429
  ///         them.
430
  ///
431
  virtual __isl_give isl_union_map *
432
  getScheduleForAstNode(__isl_take isl_ast_node *Node);
433
434
private:
435
  /// Create code for a copy statement.
436
  ///
437
  /// A copy statement is expected to have one read memory access and one write
438
  /// memory access (in this very order). Data is loaded from the location
439
  /// described by the read memory access and written to the location described
440
  /// by the write memory access. @p NewAccesses contains for each access
441
  /// the isl ast expression that describes the location accessed.
442
  ///
443
  /// @param Stmt The copy statement that contains the accesses.
444
  /// @param NewAccesses The hash table that contains remappings from memory
445
  ///                    ids to new access expressions.
446
  void generateCopyStmt(ScopStmt *Stmt,
447
                        __isl_keep isl_id_to_ast_expr *NewAccesses);
448
449
  /// Materialize a canonical loop induction variable for `L`, which is a loop
450
  /// that is *not* present in the Scop.
451
  ///
452
  /// Note that this is materialized at the point where the `Builder` is
453
  /// currently pointing.
454
  /// We also populate the `OutsideLoopIterations` map with `L`s SCEV to keep
455
  /// track of the induction variable.
456
  /// See [Code generation of induction variables of loops outside Scops]
457
  Value *materializeNonScopLoopInductionVariable(const Loop *L);
458
};
459
460
#endif // POLLY_ISLNODEBUILDER_H