Coverage Report

Created: 2018-08-14 02:14

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