Coverage Report

Created: 2017-08-21 19:50

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