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