Debian Codegraph @

suite/synctools/tablegen/include/llvm/Frontend/OpenMP/OMPIRBuilder.h

raw symbols SCIP
1 //===- IR/OpenMPIRBuilder.h - OpenMP encoding builder for LLVM IR - 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 defines the OpenMPIRBuilder class and helpers used as a convenient
10 // way to create LLVM instructions for OpenMP directives.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
15 #define LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
16
17 #include "llvm/Frontend/OpenMP/OMPConstants.h"
18 #include "llvm/IR/DebugLoc.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/Support/Allocator.h"
21 #include <forward_list>
22
23 namespace llvm {
24 class CanonicalLoopInfo;
25
26 /// An interface to create LLVM-IR for OpenMP directives.
27 ///
28 /// Each OpenMP directive has a corresponding public generator method.
29 class OpenMPIRBuilder {
30 public:
31 /// Create a new OpenMPIRBuilder operating on the given module \p M. This will
32 /// not have an effect on \p M (see initialize).
33 OpenMPIRBuilder(Module &M) : M(M), Builder(M.getContext()) {}
34 ~OpenMPIRBuilder();
35
36 /// Initialize the internal state, this will put structures types and
37 /// potentially other helpers into the underlying module. Must be called
38 /// before any other method and only once!
39 void initialize();
40
41 /// Finalize the underlying module, e.g., by outlining regions.
42 /// \param Fn The function to be finalized. If not used,
43 /// all functions are finalized.
44 void finalize(Function *Fn = nullptr);
45
46 /// Add attributes known for \p FnID to \p Fn.
47 void addAttributes(omp::RuntimeFunction FnID, Function &Fn);
48
49 /// Type used throughout for insertion points.
50 using InsertPointTy = IRBuilder<>::InsertPoint;
51
52 /// Callback type for variable finalization (think destructors).
53 ///
54 /// \param CodeGenIP is the insertion point at which the finalization code
55 /// should be placed.
56 ///
57 /// A finalize callback knows about all objects that need finalization, e.g.
58 /// destruction, when the scope of the currently generated construct is left
59 /// at the time, and location, the callback is invoked.
60 using FinalizeCallbackTy = std::function<void(InsertPointTy CodeGenIP)>;
61
62 struct FinalizationInfo {
63 /// The finalization callback provided by the last in-flight invocation of
64 /// createXXXX for the directive of kind DK.
65 FinalizeCallbackTy FiniCB;
66
67 /// The directive kind of the innermost directive that has an associated
68 /// region which might require finalization when it is left.
69 omp::Directive DK;
70
71 /// Flag to indicate if the directive is cancellable.
72 bool IsCancellable;
73 };
74
75 /// Push a finalization callback on the finalization stack.
76 ///
77 /// NOTE: Temporary solution until Clang CG is gone.
78 void pushFinalizationCB(const FinalizationInfo &FI) {
79 FinalizationStack.push_back(FI);
80 }
81
82 /// Pop the last finalization callback from the finalization stack.
83 ///
84 /// NOTE: Temporary solution until Clang CG is gone.
85 void popFinalizationCB() { FinalizationStack.pop_back(); }
86
87 /// Callback type for body (=inner region) code generation
88 ///
89 /// The callback takes code locations as arguments, each describing a
90 /// location at which code might need to be generated or a location that is
91 /// the target of control transfer.
92 ///
93 /// \param AllocaIP is the insertion point at which new alloca instructions
94 /// should be placed.
95 /// \param CodeGenIP is the insertion point at which the body code should be
96 /// placed.
97 /// \param ContinuationBB is the basic block target to leave the body.
98 ///
99 /// Note that all blocks pointed to by the arguments have terminators.
100 using BodyGenCallbackTy =
101 function_ref<void(InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
102 BasicBlock &ContinuationBB)>;
103
104 // This is created primarily for sections construct as llvm::function_ref
105 // (BodyGenCallbackTy) is not storable (as described in the comments of
106 // function_ref class - function_ref contains non-ownable reference
107 // to the callable.
108 using StorableBodyGenCallbackTy =
109 std::function<void(InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
110 BasicBlock &ContinuationBB)>;
111
112 /// Callback type for loop body code generation.
113 ///
114 /// \param CodeGenIP is the insertion point where the loop's body code must be
115 /// placed. This will be a dedicated BasicBlock with a
116 /// conditional branch from the loop condition check and
117 /// terminated with an unconditional branch to the loop
118 /// latch.
119 /// \param IndVar is the induction variable usable at the insertion point.
120 using LoopBodyGenCallbackTy =
121 function_ref<void(InsertPointTy CodeGenIP, Value *IndVar)>;
122
123 /// Callback type for variable privatization (think copy & default
124 /// constructor).
125 ///
126 /// \param AllocaIP is the insertion point at which new alloca instructions
127 /// should be placed.
128 /// \param CodeGenIP is the insertion point at which the privatization code
129 /// should be placed.
130 /// \param Original The value being copied/created, should not be used in the
131 /// generated IR.
132 /// \param Inner The equivalent of \p Original that should be used in the
133 /// generated IR; this is equal to \p Original if the value is
134 /// a pointer and can thus be passed directly, otherwise it is
135 /// an equivalent but different value.
136 /// \param ReplVal The replacement value, thus a copy or new created version
137 /// of \p Inner.
138 ///
139 /// \returns The new insertion point where code generation continues and
140 /// \p ReplVal the replacement value.
141 using PrivatizeCallbackTy = function_ref<InsertPointTy(
142 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original,
143 Value &Inner, Value *&ReplVal)>;
144
145 /// Description of a LLVM-IR insertion point (IP) and a debug/source location
146 /// (filename, line, column, ...).
147 struct LocationDescription {
148 template <typename T, typename U>
149 LocationDescription(const IRBuilder<T, U> &IRB)
150 : IP(IRB.saveIP()), DL(IRB.getCurrentDebugLocation()) {}
151 LocationDescription(const InsertPointTy &IP) : IP(IP) {}
152 LocationDescription(const InsertPointTy &IP, const DebugLoc &DL)
153 : IP(IP), DL(DL) {}
154 InsertPointTy IP;
155 DebugLoc DL;
156 };
157
158 /// Emitter methods for OpenMP directives.
159 ///
160 ///{
161
162 /// Generator for '#omp barrier'
163 ///
164 /// \param Loc The location where the barrier directive was encountered.
165 /// \param DK The kind of directive that caused the barrier.
166 /// \param ForceSimpleCall Flag to force a simple (=non-cancellation) barrier.
167 /// \param CheckCancelFlag Flag to indicate a cancel barrier return value
168 /// should be checked and acted upon.
169 ///
170 /// \returns The insertion point after the barrier.
171 InsertPointTy createBarrier(const LocationDescription &Loc, omp::Directive DK,
172 bool ForceSimpleCall = false,
173 bool CheckCancelFlag = true);
174
175 /// Generator for '#omp cancel'
176 ///
177 /// \param Loc The location where the directive was encountered.
178 /// \param IfCondition The evaluated 'if' clause expression, if any.
179 /// \param CanceledDirective The kind of directive that is cancled.
180 ///
181 /// \returns The insertion point after the barrier.
182 InsertPointTy createCancel(const LocationDescription &Loc, Value *IfCondition,
183 omp::Directive CanceledDirective);
184
185 /// Generator for '#omp parallel'
186 ///
187 /// \param Loc The insert and source location description.
188 /// \param AllocaIP The insertion points to be used for alloca instructions.
189 /// \param BodyGenCB Callback that will generate the region code.
190 /// \param PrivCB Callback to copy a given variable (think copy constructor).
191 /// \param FiniCB Callback to finalize variable copies.
192 /// \param IfCondition The evaluated 'if' clause expression, if any.
193 /// \param NumThreads The evaluated 'num_threads' clause expression, if any.
194 /// \param ProcBind The value of the 'proc_bind' clause (see ProcBindKind).
195 /// \param IsCancellable Flag to indicate a cancellable parallel region.
196 ///
197 /// \returns The insertion position *after* the parallel.
198 IRBuilder<>::InsertPoint
199 createParallel(const LocationDescription &Loc, InsertPointTy AllocaIP,
200 BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
201 FinalizeCallbackTy FiniCB, Value *IfCondition,
202 Value *NumThreads, omp::ProcBindKind ProcBind,
203 bool IsCancellable);
204
205 /// Generator for the control flow structure of an OpenMP canonical loop.
206 ///
207 /// This generator operates on the logical iteration space of the loop, i.e.
208 /// the caller only has to provide a loop trip count of the loop as defined by
209 /// base language semantics. The trip count is interpreted as an unsigned
210 /// integer. The induction variable passed to \p BodyGenCB will be of the same
211 /// type and run from 0 to \p TripCount - 1. It is up to the callback to
212 /// convert the logical iteration variable to the loop counter variable in the
213 /// loop body.
214 ///
215 /// \param Loc The insert and source location description. The insert
216 /// location can be between two instructions or the end of a
217 /// degenerate block (e.g. a BB under construction).
218 /// \param BodyGenCB Callback that will generate the loop body code.
219 /// \param TripCount Number of iterations the loop body is executed.
220 /// \param Name Base name used to derive BB and instruction names.
221 ///
222 /// \returns An object representing the created control flow structure which
223 /// can be used for loop-associated directives.
224 CanonicalLoopInfo *createCanonicalLoop(const LocationDescription &Loc,
225 LoopBodyGenCallbackTy BodyGenCB,
226 Value *TripCount,
227 const Twine &Name = "loop");
228
229 /// Generator for the control flow structure of an OpenMP canonical loop.
230 ///
231 /// Instead of a logical iteration space, this allows specifying user-defined
232 /// loop counter values using increment, upper- and lower bounds. To
233 /// disambiguate the terminology when counting downwards, instead of lower
234 /// bounds we use \p Start for the loop counter value in the first body
235 /// iteration.
236 ///
237 /// Consider the following limitations:
238 ///
239 /// * A loop counter space over all integer values of its bit-width cannot be
240 /// represented. E.g using uint8_t, its loop trip count of 256 cannot be
241 /// stored into an 8 bit integer):
242 ///
243 /// DO I = 0, 255, 1
244 ///
245 /// * Unsigned wrapping is only supported when wrapping only "once"; E.g.
246 /// effectively counting downwards:
247 ///
248 /// for (uint8_t i = 100u; i > 0; i += 127u)
249 ///
250 ///
251 /// TODO: May need to add additional parameters to represent:
252 ///
253 /// * Allow representing downcounting with unsigned integers.
254 ///
255 /// * Sign of the step and the comparison operator might disagree:
256 ///
257 /// for (int i = 0; i < 42; i -= 1u)
258 ///
259 //
260 /// \param Loc The insert and source location description.
261 /// \param BodyGenCB Callback that will generate the loop body code.
262 /// \param Start Value of the loop counter for the first iterations.
263 /// \param Stop Loop counter values past this will stop the loop.
264 /// \param Step Loop counter increment after each iteration; negative
265 /// means counting down.
266 /// \param IsSigned Whether Start, Stop and Step are signed integers.
267 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
268 /// counter.
269 /// \param ComputeIP Insertion point for instructions computing the trip
270 /// count. Can be used to ensure the trip count is available
271 /// at the outermost loop of a loop nest. If not set,
272 /// defaults to the preheader of the generated loop.
273 /// \param Name Base name used to derive BB and instruction names.
274 ///
275 /// \returns An object representing the created control flow structure which
276 /// can be used for loop-associated directives.
277 CanonicalLoopInfo *createCanonicalLoop(const LocationDescription &Loc,
278 LoopBodyGenCallbackTy BodyGenCB,
279 Value *Start, Value *Stop, Value *Step,
280 bool IsSigned, bool InclusiveStop,
281 InsertPointTy ComputeIP = {},
282 const Twine &Name = "loop");
283
284 /// Collapse a loop nest into a single loop.
285 ///
286 /// Merges loops of a loop nest into a single CanonicalLoopNest representation
287 /// that has the same number of innermost loop iterations as the origin loop
288 /// nest. The induction variables of the input loops are derived from the
289 /// collapsed loop's induction variable. This is intended to be used to
290 /// implement OpenMP's collapse clause. Before applying a directive,
291 /// collapseLoops normalizes a loop nest to contain only a single loop and the
292 /// directive's implementation does not need to handle multiple loops itself.
293 /// This does not remove the need to handle all loop nest handling by
294 /// directives, such as the ordered(<n>) clause or the simd schedule-clause
295 /// modifier of the worksharing-loop directive.
296 ///
297 /// Example:
298 /// \code
299 /// for (int i = 0; i < 7; ++i) // Canonical loop "i"
300 /// for (int j = 0; j < 9; ++j) // Canonical loop "j"
301 /// body(i, j);
302 /// \endcode
303 ///
304 /// After collapsing with Loops={i,j}, the loop is changed to
305 /// \code
306 /// for (int ij = 0; ij < 63; ++ij) {
307 /// int i = ij / 9;
308 /// int j = ij % 9;
309 /// body(i, j);
310 /// }
311 /// \endcode
312 ///
313 /// In the current implementation, the following limitations apply:
314 ///
315 /// * All input loops have an induction variable of the same type.
316 ///
317 /// * The collapsed loop will have the same trip count integer type as the
318 /// input loops. Therefore it is possible that the collapsed loop cannot
319 /// represent all iterations of the input loops. For instance, assuming a
320 /// 32 bit integer type, and two input loops both iterating 2^16 times, the
321 /// theoretical trip count of the collapsed loop would be 2^32 iteration,
322 /// which cannot be represented in an 32-bit integer. Behavior is undefined
323 /// in this case.
324 ///
325 /// * The trip counts of every input loop must be available at \p ComputeIP.
326 /// Non-rectangular loops are not yet supported.
327 ///
328 /// * At each nest level, code between a surrounding loop and its nested loop
329 /// is hoisted into the loop body, and such code will be executed more
330 /// often than before collapsing (or not at all if any inner loop iteration
331 /// has a trip count of 0). This is permitted by the OpenMP specification.
332 ///
333 /// \param DL Debug location for instructions added for collapsing,
334 /// such as instructions to compute/derive the input loop's
335 /// induction variables.
336 /// \param Loops Loops in the loop nest to collapse. Loops are specified
337 /// from outermost-to-innermost and every control flow of a
338 /// loop's body must pass through its directly nested loop.
339 /// \param ComputeIP Where additional instruction that compute the collapsed
340 /// trip count. If not set, defaults to before the generated
341 /// loop.
342 ///
343 /// \returns The CanonicalLoopInfo object representing the collapsed loop.
344 CanonicalLoopInfo *collapseLoops(DebugLoc DL,
345 ArrayRef<CanonicalLoopInfo *> Loops,
346 InsertPointTy ComputeIP);
347
348 /// Modifies the canonical loop to be a statically-scheduled workshare loop.
349 ///
350 /// This takes a \p LoopInfo representing a canonical loop, such as the one
351 /// created by \p createCanonicalLoop and emits additional instructions to
352 /// turn it into a workshare loop. In particular, it calls to an OpenMP
353 /// runtime function in the preheader to obtain the loop bounds to be used in
354 /// the current thread, updates the relevant instructions in the canonical
355 /// loop and calls to an OpenMP runtime finalization function after the loop.
356 ///
357 /// TODO: Workshare loops with static scheduling may contain up to two loops
358 /// that fulfill the requirements of an OpenMP canonical loop. One for
359 /// iterating over all iterations of a chunk and another one for iterating
360 /// over all chunks that are executed on the same thread. Returning
361 /// CanonicalLoopInfo objects representing them may eventually be useful for
362 /// the apply clause planned in OpenMP 6.0, but currently whether these are
363 /// canonical loops is irrelevant.
364 ///
365 /// \param DL Debug location for instructions added for the
366 /// workshare-loop construct itself.
367 /// \param CLI A descriptor of the canonical loop to workshare.
368 /// \param AllocaIP An insertion point for Alloca instructions usable in the
369 /// preheader of the loop.
370 /// \param NeedsBarrier Indicates whether a barrier must be inserted after
371 /// the loop.
372 /// \param Chunk The size of loop chunk considered as a unit when
373 /// scheduling. If \p nullptr, defaults to 1.
374 ///
375 /// \returns Point where to insert code after the workshare construct.
376 InsertPointTy applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
377 InsertPointTy AllocaIP,
378 bool NeedsBarrier,
379 Value *Chunk = nullptr);
380
381 /// Modifies the canonical loop to be a dynamically-scheduled workshare loop.
382 ///
383 /// This takes a \p LoopInfo representing a canonical loop, such as the one
384 /// created by \p createCanonicalLoop and emits additional instructions to
385 /// turn it into a workshare loop. In particular, it calls to an OpenMP
386 /// runtime function in the preheader to obtain, and then in each iteration
387 /// to update the loop counter.
388 ///
389 /// \param DL Debug location for instructions added for the
390 /// workshare-loop construct itself.
391 /// \param CLI A descriptor of the canonical loop to workshare.
392 /// \param AllocaIP An insertion point for Alloca instructions usable in the
393 /// preheader of the loop.
394 /// \param SchedType Type of scheduling to be passed to the init function.
395 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
396 /// the loop.
397 /// \param Chunk The size of loop chunk considered as a unit when
398 /// scheduling. If \p nullptr, defaults to 1.
399 ///
400 /// \returns Point where to insert code after the workshare construct.
401 InsertPointTy applyDynamicWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
402 InsertPointTy AllocaIP,
403 omp::OMPScheduleType SchedType,
404 bool NeedsBarrier,
405 Value *Chunk = nullptr);
406
407 /// Modifies the canonical loop to be a workshare loop.
408 ///
409 /// This takes a \p LoopInfo representing a canonical loop, such as the one
410 /// created by \p createCanonicalLoop and emits additional instructions to
411 /// turn it into a workshare loop. In particular, it calls to an OpenMP
412 /// runtime function in the preheader to obtain the loop bounds to be used in
413 /// the current thread, updates the relevant instructions in the canonical
414 /// loop and calls to an OpenMP runtime finalization function after the loop.
415 ///
416 /// \param DL Debug location for instructions added for the
417 /// workshare-loop construct itself.
418 /// \param CLI A descriptor of the canonical loop to workshare.
419 /// \param AllocaIP An insertion point for Alloca instructions usable in the
420 /// preheader of the loop.
421 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
422 /// the loop.
423 ///
424 /// \returns Point where to insert code after the workshare construct.
425 InsertPointTy applyWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
426 InsertPointTy AllocaIP, bool NeedsBarrier);
427
428 /// Tile a loop nest.
429 ///
430 /// Tiles the loops of \p Loops by the tile sizes in \p TileSizes. Loops in
431 /// \p/ Loops must be perfectly nested, from outermost to innermost loop
432 /// (i.e. Loops.front() is the outermost loop). The trip count llvm::Value
433 /// of every loop and every tile sizes must be usable in the outermost
434 /// loop's preheader. This implies that the loop nest is rectangular.
435 ///
436 /// Example:
437 /// \code
438 /// for (int i = 0; i < 15; ++i) // Canonical loop "i"
439 /// for (int j = 0; j < 14; ++j) // Canonical loop "j"
440 /// body(i, j);
441 /// \endcode
442 ///
443 /// After tiling with Loops={i,j} and TileSizes={5,7}, the loop is changed to
444 /// \code
445 /// for (int i1 = 0; i1 < 3; ++i1)
446 /// for (int j1 = 0; j1 < 2; ++j1)
447 /// for (int i2 = 0; i2 < 5; ++i2)
448 /// for (int j2 = 0; j2 < 7; ++j2)
449 /// body(i1*3+i2, j1*3+j2);
450 /// \endcode
451 ///
452 /// The returned vector are the loops {i1,j1,i2,j2}. The loops i1 and j1 are
453 /// referred to the floor, and the loops i2 and j2 are the tiles. Tiling also
454 /// handles non-constant trip counts, non-constant tile sizes and trip counts
455 /// that are not multiples of the tile size. In the latter case the tile loop
456 /// of the last floor-loop iteration will have fewer iterations than specified
457 /// as its tile size.
458 ///
459 ///
460 /// @param DL Debug location for instructions added by tiling, for
461 /// instance the floor- and tile trip count computation.
462 /// @param Loops Loops to tile. The CanonicalLoopInfo objects are
463 /// invalidated by this method, i.e. should not used after
464 /// tiling.
465 /// @param TileSizes For each loop in \p Loops, the tile size for that
466 /// dimensions.
467 ///
468 /// \returns A list of generated loops. Contains twice as many loops as the
469 /// input loop nest; the first half are the floor loops and the
470 /// second half are the tile loops.
471 std::vector<CanonicalLoopInfo *>
472 tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
473 ArrayRef<Value *> TileSizes);
474
475 /// Fully unroll a loop.
476 ///
477 /// Instead of unrolling the loop immediately (and duplicating its body
478 /// instructions), it is deferred to LLVM's LoopUnrollPass by adding loop
479 /// metadata.
480 ///
481 /// \param DL Debug location for instructions added by unrolling.
482 /// \param Loop The loop to unroll. The loop will be invalidated.
483 void unrollLoopFull(DebugLoc DL, CanonicalLoopInfo *Loop);
484
485 /// Fully or partially unroll a loop. How the loop is unrolled is determined
486 /// using LLVM's LoopUnrollPass.
487 ///
488 /// \param DL Debug location for instructions added by unrolling.
489 /// \param Loop The loop to unroll. The loop will be invalidated.
490 void unrollLoopHeuristic(DebugLoc DL, CanonicalLoopInfo *Loop);
491
492 /// Partially unroll a loop.
493 ///
494 /// The CanonicalLoopInfo of the unrolled loop for use with chained
495 /// loop-associated directive can be requested using \p UnrolledCLI. Not
496 /// needing the CanonicalLoopInfo allows more efficient code generation by
497 /// deferring the actual unrolling to the LoopUnrollPass using loop metadata.
498 /// A loop-associated directive applied to the unrolled loop needs to know the
499 /// new trip count which means that if using a heuristically determined unroll
500 /// factor (\p Factor == 0), that factor must be computed immediately. We are
501 /// using the same logic as the LoopUnrollPass to derived the unroll factor,
502 /// but which assumes that some canonicalization has taken place (e.g.
503 /// Mem2Reg, LICM, GVN, Inlining, etc.). That is, the heuristic will perform
504 /// better when the unrolled loop's CanonicalLoopInfo is not needed.
505 ///
506 /// \param DL Debug location for instructions added by unrolling.
507 /// \param Loop The loop to unroll. The loop will be invalidated.
508 /// \param Factor The factor to unroll the loop by. A factor of 0
509 /// indicates that a heuristic should be used to determine
510 /// the unroll-factor.
511 /// \param UnrolledCLI If non-null, receives the CanonicalLoopInfo of the
512 /// partially unrolled loop. Otherwise, uses loop metadata
513 /// to defer unrolling to the LoopUnrollPass.
514 void unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop, int32_t Factor,
515 CanonicalLoopInfo **UnrolledCLI);
516
517 /// Add metadata to simd-ize a loop.
518 ///
519 /// \param DL Debug location for instructions added by unrolling.
520 /// \param Loop The loop to simd-ize.
521 void applySimd(DebugLoc DL, CanonicalLoopInfo *Loop);
522
523 /// Generator for '#omp flush'
524 ///
525 /// \param Loc The location where the flush directive was encountered
526 void createFlush(const LocationDescription &Loc);
527
528 /// Generator for '#omp taskwait'
529 ///
530 /// \param Loc The location where the taskwait directive was encountered.
531 void createTaskwait(const LocationDescription &Loc);
532
533 /// Generator for '#omp taskyield'
534 ///
535 /// \param Loc The location where the taskyield directive was encountered.
536 void createTaskyield(const LocationDescription &Loc);
537
538 /// Functions used to generate reductions. Such functions take two Values
539 /// representing LHS and RHS of the reduction, respectively, and a reference
540 /// to the value that is updated to refer to the reduction result.
541 using ReductionGenTy =
542 function_ref<InsertPointTy(InsertPointTy, Value *, Value *, Value *&)>;
543
544 /// Functions used to generate atomic reductions. Such functions take two
545 /// Values representing pointers to LHS and RHS of the reduction, as well as
546 /// the element type of these pointers. They are expected to atomically
547 /// update the LHS to the reduced value.
548 using AtomicReductionGenTy =
549 function_ref<InsertPointTy(InsertPointTy, Type *, Value *, Value *)>;
550
551 /// Information about an OpenMP reduction.
552 struct ReductionInfo {
553 ReductionInfo(Type *ElementType, Value *Variable, Value *PrivateVariable,
554 ReductionGenTy ReductionGen,
555 AtomicReductionGenTy AtomicReductionGen)
556 : ElementType(ElementType), Variable(Variable),
557 PrivateVariable(PrivateVariable), ReductionGen(ReductionGen),
558 AtomicReductionGen(AtomicReductionGen) {
559 assert(cast<PointerType>(Variable->getType())
560 ->isOpaqueOrPointeeTypeMatches(ElementType) && "Invalid elem type");
561 }
562
563 /// Reduction element type, must match pointee type of variable.
564 Type *ElementType;
565
566 /// Reduction variable of pointer type.
567 Value *Variable;
568
569 /// Thread-private partial reduction variable.
570 Value *PrivateVariable;
571
572 /// Callback for generating the reduction body. The IR produced by this will
573 /// be used to combine two values in a thread-safe context, e.g., under
574 /// lock or within the same thread, and therefore need not be atomic.
575 ReductionGenTy ReductionGen;
576
577 /// Callback for generating the atomic reduction body, may be null. The IR
578 /// produced by this will be used to atomically combine two values during
579 /// reduction. If null, the implementation will use the non-atomic version
580 /// along with the appropriate synchronization mechanisms.
581 AtomicReductionGenTy AtomicReductionGen;
582 };
583
584 // TODO: provide atomic and non-atomic reduction generators for reduction
585 // operators defined by the OpenMP specification.
586
587 /// Generator for '#omp reduction'.
588 ///
589 /// Emits the IR instructing the runtime to perform the specific kind of
590 /// reductions. Expects reduction variables to have been privatized and
591 /// initialized to reduction-neutral values separately. Emits the calls to
592 /// runtime functions as well as the reduction function and the basic blocks
593 /// performing the reduction atomically and non-atomically.
594 ///
595 /// The code emitted for the following:
596 ///
597 /// \code
598 /// type var_1;
599 /// type var_2;
600 /// #pragma omp <directive> reduction(reduction-op:var_1,var_2)
601 /// /* body */;
602 /// \endcode
603 ///
604 /// corresponds to the following sketch.
605 ///
606 /// \code
607 /// void _outlined_par() {
608 /// // N is the number of different reductions.
609 /// void *red_array[] = {privatized_var_1, privatized_var_2, ...};
610 /// switch(__kmpc_reduce(..., N, /*size of data in red array*/, red_array,
611 /// _omp_reduction_func,
612 /// _gomp_critical_user.reduction.var)) {
613 /// case 1: {
614 /// var_1 = var_1 <reduction-op> privatized_var_1;
615 /// var_2 = var_2 <reduction-op> privatized_var_2;
616 /// // ...
617 /// __kmpc_end_reduce(...);
618 /// break;
619 /// }
620 /// case 2: {
621 /// _Atomic<ReductionOp>(var_1, privatized_var_1);
622 /// _Atomic<ReductionOp>(var_2, privatized_var_2);
623 /// // ...
624 /// break;
625 /// }
626 /// default: break;
627 /// }
628 /// }
629 ///
630 /// void _omp_reduction_func(void **lhs, void **rhs) {
631 /// *(type *)lhs[0] = *(type *)lhs[0] <reduction-op> *(type *)rhs[0];
632 /// *(type *)lhs[1] = *(type *)lhs[1] <reduction-op> *(type *)rhs[1];
633 /// // ...
634 /// }
635 /// \endcode
636 ///
637 /// \param Loc The location where the reduction was
638 /// encountered. Must be within the associate
639 /// directive and after the last local access to the
640 /// reduction variables.
641 /// \param AllocaIP An insertion point suitable for allocas usable
642 /// in reductions.
643 /// \param ReductionInfos A list of info on each reduction variable.
644 /// \param IsNoWait A flag set if the reduction is marked as nowait.
645 InsertPointTy createReductions(const LocationDescription &Loc,
646 InsertPointTy AllocaIP,
647 ArrayRef<ReductionInfo> ReductionInfos,
648 bool IsNoWait = false);
649
650 ///}
651
652 /// Return the insertion point used by the underlying IRBuilder.
653 InsertPointTy getInsertionPoint() { return Builder.saveIP(); }
654
655 /// Update the internal location to \p Loc.
656 bool updateToLocation(const LocationDescription &Loc) {
657 Builder.restoreIP(Loc.IP);
658 Builder.SetCurrentDebugLocation(Loc.DL);
659 return Loc.IP.getBlock() != nullptr;
660 }
661
662 /// Return the function declaration for the runtime function with \p FnID.
663 FunctionCallee getOrCreateRuntimeFunction(Module &M,
664 omp::RuntimeFunction FnID);
665
666 Function *getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID);
667
668 /// Return the (LLVM-IR) string describing the source location \p LocStr.
669 Constant *getOrCreateSrcLocStr(StringRef LocStr, uint32_t &SrcLocStrSize);
670
671 /// Return the (LLVM-IR) string describing the default source location.
672 Constant *getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize);
673
674 /// Return the (LLVM-IR) string describing the source location identified by
675 /// the arguments.
676 Constant *getOrCreateSrcLocStr(StringRef FunctionName, StringRef FileName,
677 unsigned Line, unsigned Column,
678 uint32_t &SrcLocStrSize);
679
680 /// Return the (LLVM-IR) string describing the DebugLoc \p DL. Use \p F as
681 /// fallback if \p DL does not specify the function name.
682 Constant *getOrCreateSrcLocStr(DebugLoc DL, uint32_t &SrcLocStrSize,
683 Function *F = nullptr);
684
685 /// Return the (LLVM-IR) string describing the source location \p Loc.
686 Constant *getOrCreateSrcLocStr(const LocationDescription &Loc,
687 uint32_t &SrcLocStrSize);
688
689 /// Return an ident_t* encoding the source location \p SrcLocStr and \p Flags.
690 /// TODO: Create a enum class for the Reserve2Flags
691 Constant *getOrCreateIdent(Constant *SrcLocStr, uint32_t SrcLocStrSize,
692 omp::IdentFlag Flags = omp::IdentFlag(0),
693 unsigned Reserve2Flags = 0);
694
695 /// Create a hidden global flag \p Name in the module with initial value \p
696 /// Value.
697 GlobalValue *createGlobalFlag(unsigned Value, StringRef Name);
698
699 /// Generate control flow and cleanup for cancellation.
700 ///
701 /// \param CancelFlag Flag indicating if the cancellation is performed.
702 /// \param CanceledDirective The kind of directive that is cancled.
703 /// \param ExitCB Extra code to be generated in the exit block.
704 void emitCancelationCheckImpl(Value *CancelFlag,
705 omp::Directive CanceledDirective,
706 FinalizeCallbackTy ExitCB = {});
707
708 /// Generate a barrier runtime call.
709 ///
710 /// \param Loc The location at which the request originated and is fulfilled.
711 /// \param DK The directive which caused the barrier
712 /// \param ForceSimpleCall Flag to force a simple (=non-cancellation) barrier.
713 /// \param CheckCancelFlag Flag to indicate a cancel barrier return value
714 /// should be checked and acted upon.
715 ///
716 /// \returns The insertion point after the barrier.
717 InsertPointTy emitBarrierImpl(const LocationDescription &Loc,
718 omp::Directive DK, bool ForceSimpleCall,
719 bool CheckCancelFlag);
720
721 /// Generate a flush runtime call.
722 ///
723 /// \param Loc The location at which the request originated and is fulfilled.
724 void emitFlush(const LocationDescription &Loc);
725
726 /// The finalization stack made up of finalize callbacks currently in-flight,
727 /// wrapped into FinalizationInfo objects that reference also the finalization
728 /// target block and the kind of cancellable directive.
729 SmallVector<FinalizationInfo, 8> FinalizationStack;
730
731 /// Return true if the last entry in the finalization stack is of kind \p DK
732 /// and cancellable.
733 bool isLastFinalizationInfoCancellable(omp::Directive DK) {
734 return !FinalizationStack.empty() &&
735 FinalizationStack.back().IsCancellable &&
736 FinalizationStack.back().DK == DK;
737 }
738
739 /// Generate a taskwait runtime call.
740 ///
741 /// \param Loc The location at which the request originated and is fulfilled.
742 void emitTaskwaitImpl(const LocationDescription &Loc);
743
744 /// Generate a taskyield runtime call.
745 ///
746 /// \param Loc The location at which the request originated and is fulfilled.
747 void emitTaskyieldImpl(const LocationDescription &Loc);
748
749 /// Return the current thread ID.
750 ///
751 /// \param Ident The ident (ident_t*) describing the query origin.
752 Value *getOrCreateThreadID(Value *Ident);
753
754 /// The underlying LLVM-IR module
755 Module &M;
756
757 /// The LLVM-IR Builder used to create IR.
758 IRBuilder<> Builder;
759
760 /// Map to remember source location strings
761 StringMap<Constant *> SrcLocStrMap;
762
763 /// Map to remember existing ident_t*.
764 DenseMap<std::pair<Constant *, uint64_t>, Constant *> IdentMap;
765
766 /// Helper that contains information about regions we need to outline
767 /// during finalization.
768 struct OutlineInfo {
769 using PostOutlineCBTy = std::function<void(Function &)>;
770 PostOutlineCBTy PostOutlineCB;
771 BasicBlock *EntryBB, *ExitBB;
772 SmallVector<Value *, 2> ExcludeArgsFromAggregate;
773
774 /// Collect all blocks in between EntryBB and ExitBB in both the given
775 /// vector and set.
776 void collectBlocks(SmallPtrSetImpl<BasicBlock *> &BlockSet,
777 SmallVectorImpl<BasicBlock *> &BlockVector);
778
779 /// Return the function that contains the region to be outlined.
780 Function *getFunction() const { return EntryBB->getParent(); }
781 };
782
783 /// Collection of regions that need to be outlined during finalization.
784 SmallVector<OutlineInfo, 16> OutlineInfos;
785
786 /// Collection of owned canonical loop objects that eventually need to be
787 /// free'd.
788 std::forward_list<CanonicalLoopInfo> LoopInfos;
789
790 /// Add a new region that will be outlined later.
791 void addOutlineInfo(OutlineInfo &&OI) { OutlineInfos.emplace_back(OI); }
792
793 /// An ordered map of auto-generated variables to their unique names.
794 /// It stores variables with the following names: 1) ".gomp_critical_user_" +
795 /// <critical_section_name> + ".var" for "omp critical" directives; 2)
796 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
797 /// variables.
798 StringMap<AssertingVH<Constant>, BumpPtrAllocator> InternalVars;
799
800 /// Create the global variable holding the offload mappings information.
801 GlobalVariable *createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
802 std::string VarName);
803
804 /// Create the global variable holding the offload names information.
805 GlobalVariable *
806 createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
807 std::string VarName);
808
809 struct MapperAllocas {
810 AllocaInst *ArgsBase = nullptr;
811 AllocaInst *Args = nullptr;
812 AllocaInst *ArgSizes = nullptr;
813 };
814
815 /// Create the allocas instruction used in call to mapper functions.
816 void createMapperAllocas(const LocationDescription &Loc,
817 InsertPointTy AllocaIP, unsigned NumOperands,
818 struct MapperAllocas &MapperAllocas);
819
820 /// Create the call for the target mapper function.
821 /// \param Loc The source location description.
822 /// \param MapperFunc Function to be called.
823 /// \param SrcLocInfo Source location information global.
824 /// \param MaptypesArg The argument types.
825 /// \param MapnamesArg The argument names.
826 /// \param MapperAllocas The AllocaInst used for the call.
827 /// \param DeviceID Device ID for the call.
828 /// \param NumOperands Number of operands in the call.
829 void emitMapperCall(const LocationDescription &Loc, Function *MapperFunc,
830 Value *SrcLocInfo, Value *MaptypesArg, Value *MapnamesArg,
831 struct MapperAllocas &MapperAllocas, int64_t DeviceID,
832 unsigned NumOperands);
833
834 public:
835 /// Generator for __kmpc_copyprivate
836 ///
837 /// \param Loc The source location description.
838 /// \param BufSize Number of elements in the buffer.
839 /// \param CpyBuf List of pointers to data to be copied.
840 /// \param CpyFn function to call for copying data.
841 /// \param DidIt flag variable; 1 for 'single' thread, 0 otherwise.
842 ///
843 /// \return The insertion position *after* the CopyPrivate call.
844
845 InsertPointTy createCopyPrivate(const LocationDescription &Loc,
846 llvm::Value *BufSize, llvm::Value *CpyBuf,
847 llvm::Value *CpyFn, llvm::Value *DidIt);
848
849 /// Generator for '#omp single'
850 ///
851 /// \param Loc The source location description.
852 /// \param BodyGenCB Callback that will generate the region code.
853 /// \param FiniCB Callback to finalize variable copies.
854 /// \param DidIt Local variable used as a flag to indicate 'single' thread
855 ///
856 /// \returns The insertion position *after* the single call.
857 InsertPointTy createSingle(const LocationDescription &Loc,
858 BodyGenCallbackTy BodyGenCB,
859 FinalizeCallbackTy FiniCB, llvm::Value *DidIt);
860
861 /// Generator for '#omp master'
862 ///
863 /// \param Loc The insert and source location description.
864 /// \param BodyGenCB Callback that will generate the region code.
865 /// \param FiniCB Callback to finalize variable copies.
866 ///
867 /// \returns The insertion position *after* the master.
868 InsertPointTy createMaster(const LocationDescription &Loc,
869 BodyGenCallbackTy BodyGenCB,
870 FinalizeCallbackTy FiniCB);
871
872 /// Generator for '#omp masked'
873 ///
874 /// \param Loc The insert and source location description.
875 /// \param BodyGenCB Callback that will generate the region code.
876 /// \param FiniCB Callback to finialize variable copies.
877 ///
878 /// \returns The insertion position *after* the masked.
879 InsertPointTy createMasked(const LocationDescription &Loc,
880 BodyGenCallbackTy BodyGenCB,
881 FinalizeCallbackTy FiniCB, Value *Filter);
882
883 /// Generator for '#omp critical'
884 ///
885 /// \param Loc The insert and source location description.
886 /// \param BodyGenCB Callback that will generate the region body code.
887 /// \param FiniCB Callback to finalize variable copies.
888 /// \param CriticalName name of the lock used by the critical directive
889 /// \param HintInst Hint Instruction for hint clause associated with critical
890 ///
891 /// \returns The insertion position *after* the critical.
892 InsertPointTy createCritical(const LocationDescription &Loc,
893 BodyGenCallbackTy BodyGenCB,
894 FinalizeCallbackTy FiniCB,
895 StringRef CriticalName, Value *HintInst);
896
897 /// Generator for '#omp ordered depend (source | sink)'
898 ///
899 /// \param Loc The insert and source location description.
900 /// \param AllocaIP The insertion point to be used for alloca instructions.
901 /// \param NumLoops The number of loops in depend clause.
902 /// \param StoreValues The value will be stored in vector address.
903 /// \param Name The name of alloca instruction.
904 /// \param IsDependSource If true, depend source; otherwise, depend sink.
905 ///
906 /// \return The insertion position *after* the ordered.
907 InsertPointTy createOrderedDepend(const LocationDescription &Loc,
908 InsertPointTy AllocaIP, unsigned NumLoops,
909 ArrayRef<llvm::Value *> StoreValues,
910 const Twine &Name, bool IsDependSource);
911
912 /// Generator for '#omp ordered [threads | simd]'
913 ///
914 /// \param Loc The insert and source location description.
915 /// \param BodyGenCB Callback that will generate the region code.
916 /// \param FiniCB Callback to finalize variable copies.
917 /// \param IsThreads If true, with threads clause or without clause;
918 /// otherwise, with simd clause;
919 ///
920 /// \returns The insertion position *after* the ordered.
921 InsertPointTy createOrderedThreadsSimd(const LocationDescription &Loc,
922 BodyGenCallbackTy BodyGenCB,
923 FinalizeCallbackTy FiniCB,
924 bool IsThreads);
925
926 /// Generator for '#omp sections'
927 ///
928 /// \param Loc The insert and source location description.
929 /// \param AllocaIP The insertion points to be used for alloca instructions.
930 /// \param SectionCBs Callbacks that will generate body of each section.
931 /// \param PrivCB Callback to copy a given variable (think copy constructor).
932 /// \param FiniCB Callback to finalize variable copies.
933 /// \param IsCancellable Flag to indicate a cancellable parallel region.
934 /// \param IsNowait If true, barrier - to ensure all sections are executed
935 /// before moving forward will not be generated.
936 /// \returns The insertion position *after* the sections.
937 InsertPointTy createSections(const LocationDescription &Loc,
938 InsertPointTy AllocaIP,
939 ArrayRef<StorableBodyGenCallbackTy> SectionCBs,
940 PrivatizeCallbackTy PrivCB,
941 FinalizeCallbackTy FiniCB, bool IsCancellable,
942 bool IsNowait);
943
944 /// Generator for '#omp section'
945 ///
946 /// \param Loc The insert and source location description.
947 /// \param BodyGenCB Callback that will generate the region body code.
948 /// \param FiniCB Callback to finalize variable copies.
949 /// \returns The insertion position *after* the section.
950 InsertPointTy createSection(const LocationDescription &Loc,
951 BodyGenCallbackTy BodyGenCB,
952 FinalizeCallbackTy FiniCB);
953
954 /// Generate conditional branch and relevant BasicBlocks through which private
955 /// threads copy the 'copyin' variables from Master copy to threadprivate
956 /// copies.
957 ///
958 /// \param IP insertion block for copyin conditional
959 /// \param MasterVarPtr a pointer to the master variable
960 /// \param PrivateVarPtr a pointer to the threadprivate variable
961 /// \param IntPtrTy Pointer size type
962 /// \param BranchtoEnd Create a branch between the copyin.not.master blocks
963 // and copy.in.end block
964 ///
965 /// \returns The insertion point where copying operation to be emitted.
966 InsertPointTy createCopyinClauseBlocks(InsertPointTy IP, Value *MasterAddr,
967 Value *PrivateAddr,
968 llvm::IntegerType *IntPtrTy,
969 bool BranchtoEnd = true);
970
971 /// Create a runtime call for kmpc_Alloc
972 ///
973 /// \param Loc The insert and source location description.
974 /// \param Size Size of allocated memory space
975 /// \param Allocator Allocator information instruction
976 /// \param Name Name of call Instruction for OMP_alloc
977 ///
978 /// \returns CallInst to the OMP_Alloc call
979 CallInst *createOMPAlloc(const LocationDescription &Loc, Value *Size,
980 Value *Allocator, std::string Name = "");
981
982 /// Create a runtime call for kmpc_free
983 ///
984 /// \param Loc The insert and source location description.
985 /// \param Addr Address of memory space to be freed
986 /// \param Allocator Allocator information instruction
987 /// \param Name Name of call Instruction for OMP_Free
988 ///
989 /// \returns CallInst to the OMP_Free call
990 CallInst *createOMPFree(const LocationDescription &Loc, Value *Addr,
991 Value *Allocator, std::string Name = "");
992
993 /// Create a runtime call for kmpc_threadprivate_cached
994 ///
995 /// \param Loc The insert and source location description.
996 /// \param Pointer pointer to data to be cached
997 /// \param Size size of data to be cached
998 /// \param Name Name of call Instruction for callinst
999 ///
1000 /// \returns CallInst to the thread private cache call.
1001 CallInst *createCachedThreadPrivate(const LocationDescription &Loc,
1002 llvm::Value *Pointer,
1003 llvm::ConstantInt *Size,
1004 const llvm::Twine &Name = Twine(""));
1005
1006 /// Create a runtime call for __tgt_interop_init
1007 ///
1008 /// \param Loc The insert and source location description.
1009 /// \param InteropVar variable to be allocated
1010 /// \param InteropType type of interop operation
1011 /// \param Device devide to which offloading will occur
1012 /// \param NumDependences number of dependence variables
1013 /// \param DependenceAddress pointer to dependence variables
1014 /// \param HaveNowaitClause does nowait clause exist
1015 ///
1016 /// \returns CallInst to the __tgt_interop_init call
1017 CallInst *createOMPInteropInit(const LocationDescription &Loc,
1018 Value *InteropVar,
1019 omp::OMPInteropType InteropType, Value *Device,
1020 Value *NumDependences,
1021 Value *DependenceAddress,
1022 bool HaveNowaitClause);
1023
1024 /// Create a runtime call for __tgt_interop_destroy
1025 ///
1026 /// \param Loc The insert and source location description.
1027 /// \param InteropVar variable to be allocated
1028 /// \param Device devide to which offloading will occur
1029 /// \param NumDependences number of dependence variables
1030 /// \param DependenceAddress pointer to dependence variables
1031 /// \param HaveNowaitClause does nowait clause exist
1032 ///
1033 /// \returns CallInst to the __tgt_interop_destroy call
1034 CallInst *createOMPInteropDestroy(const LocationDescription &Loc,
1035 Value *InteropVar, Value *Device,
1036 Value *NumDependences,
1037 Value *DependenceAddress,
1038 bool HaveNowaitClause);
1039
1040 /// Create a runtime call for __tgt_interop_use
1041 ///
1042 /// \param Loc The insert and source location description.
1043 /// \param InteropVar variable to be allocated
1044 /// \param Device devide to which offloading will occur
1045 /// \param NumDependences number of dependence variables
1046 /// \param DependenceAddress pointer to dependence variables
1047 /// \param HaveNowaitClause does nowait clause exist
1048 ///
1049 /// \returns CallInst to the __tgt_interop_use call
1050 CallInst *createOMPInteropUse(const LocationDescription &Loc,
1051 Value *InteropVar, Value *Device,
1052 Value *NumDependences, Value *DependenceAddress,
1053 bool HaveNowaitClause);
1054
1055 /// The `omp target` interface
1056 ///
1057 /// For more information about the usage of this interface,
1058 /// \see openmp/libomptarget/deviceRTLs/common/include/target.h
1059 ///
1060 ///{
1061
1062 /// Create a runtime call for kmpc_target_init
1063 ///
1064 /// \param Loc The insert and source location description.
1065 /// \param IsSPMD Flag to indicate if the kernel is an SPMD kernel or not.
1066 /// \param RequiresFullRuntime Indicate if a full device runtime is necessary.
1067 InsertPointTy createTargetInit(const LocationDescription &Loc, bool IsSPMD,
1068 bool RequiresFullRuntime);
1069
1070 /// Create a runtime call for kmpc_target_deinit
1071 ///
1072 /// \param Loc The insert and source location description.
1073 /// \param IsSPMD Flag to indicate if the kernel is an SPMD kernel or not.
1074 /// \param RequiresFullRuntime Indicate if a full device runtime is necessary.
1075 void createTargetDeinit(const LocationDescription &Loc, bool IsSPMD,
1076 bool RequiresFullRuntime);
1077
1078 ///}
1079
1080 /// Declarations for LLVM-IR types (simple, array, function and structure) are
1081 /// generated below. Their names are defined and used in OpenMPKinds.def. Here
1082 /// we provide the declarations, the initializeTypes function will provide the
1083 /// values.
1084 ///
1085 ///{
1086 #define OMP_TYPE(VarName, InitValue) Type *VarName = nullptr;
1087 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
1088 ArrayType *VarName##Ty = nullptr; \
1089 PointerType *VarName##PtrTy = nullptr;
1090 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
1091 FunctionType *VarName = nullptr; \
1092 PointerType *VarName##Ptr = nullptr;
1093 #define OMP_STRUCT_TYPE(VarName, StrName, ...) \
1094 StructType *VarName = nullptr; \
1095 PointerType *VarName##Ptr = nullptr;
1096 #include "llvm/Frontend/OpenMP/OMPKinds.def"
1097
1098 ///}
1099
1100 private:
1101 /// Create all simple and struct types exposed by the runtime and remember
1102 /// the llvm::PointerTypes of them for easy access later.
1103 void initializeTypes(Module &M);
1104
1105 /// Common interface for generating entry calls for OMP Directives.
1106 /// if the directive has a region/body, It will set the insertion
1107 /// point to the body
1108 ///
1109 /// \param OMPD Directive to generate entry blocks for
1110 /// \param EntryCall Call to the entry OMP Runtime Function
1111 /// \param ExitBB block where the region ends.
1112 /// \param Conditional indicate if the entry call result will be used
1113 /// to evaluate a conditional of whether a thread will execute
1114 /// body code or not.
1115 ///
1116 /// \return The insertion position in exit block
1117 InsertPointTy emitCommonDirectiveEntry(omp::Directive OMPD, Value *EntryCall,
1118 BasicBlock *ExitBB,
1119 bool Conditional = false);
1120
1121 /// Common interface to finalize the region
1122 ///
1123 /// \param OMPD Directive to generate exiting code for
1124 /// \param FinIP Insertion point for emitting Finalization code and exit call
1125 /// \param ExitCall Call to the ending OMP Runtime Function
1126 /// \param HasFinalize indicate if the directive will require finalization
1127 /// and has a finalization callback in the stack that
1128 /// should be called.
1129 ///
1130 /// \return The insertion position in exit block
1131 InsertPointTy emitCommonDirectiveExit(omp::Directive OMPD,
1132 InsertPointTy FinIP,
1133 Instruction *ExitCall,
1134 bool HasFinalize = true);
1135
1136 /// Common Interface to generate OMP inlined regions
1137 ///
1138 /// \param OMPD Directive to generate inlined region for
1139 /// \param EntryCall Call to the entry OMP Runtime Function
1140 /// \param ExitCall Call to the ending OMP Runtime Function
1141 /// \param BodyGenCB Body code generation callback.
1142 /// \param FiniCB Finalization Callback. Will be called when finalizing region
1143 /// \param Conditional indicate if the entry call result will be used
1144 /// to evaluate a conditional of whether a thread will execute
1145 /// body code or not.
1146 /// \param HasFinalize indicate if the directive will require finalization
1147 /// and has a finalization callback in the stack that
1148 /// should be called.
1149 /// \param IsCancellable if HasFinalize is set to true, indicate if the
1150 /// the directive should be cancellable.
1151 /// \return The insertion point after the region
1152
1153 InsertPointTy
1154 EmitOMPInlinedRegion(omp::Directive OMPD, Instruction *EntryCall,
1155 Instruction *ExitCall, BodyGenCallbackTy BodyGenCB,
1156 FinalizeCallbackTy FiniCB, bool Conditional = false,
1157 bool HasFinalize = true, bool IsCancellable = false);
1158
1159 /// Get the platform-specific name separator.
1160 /// \param Parts different parts of the final name that needs separation
1161 /// \param FirstSeparator First separator used between the initial two
1162 /// parts of the name.
1163 /// \param Separator separator used between all of the rest consecutive
1164 /// parts of the name
1165 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
1166 StringRef FirstSeparator,
1167 StringRef Separator);
1168
1169 /// Gets (if variable with the given name already exist) or creates
1170 /// internal global variable with the specified Name. The created variable has
1171 /// linkage CommonLinkage by default and is initialized by null value.
1172 /// \param Ty Type of the global variable. If it is exist already the type
1173 /// must be the same.
1174 /// \param Name Name of the variable.
1175 Constant *getOrCreateOMPInternalVariable(Type *Ty, const Twine &Name,
1176 unsigned AddressSpace = 0);
1177
1178 /// Returns corresponding lock object for the specified critical region
1179 /// name. If the lock object does not exist it is created, otherwise the
1180 /// reference to the existing copy is returned.
1181 /// \param CriticalName Name of the critical region.
1182 ///
1183 Value *getOMPCriticalRegionLock(StringRef CriticalName);
1184
1185 /// Callback type for Atomic Expression update
1186 /// ex:
1187 /// \code{.cpp}
1188 /// unsigned x = 0;
1189 /// #pragma omp atomic update
1190 /// x = Expr(x_old); //Expr() is any legal operation
1191 /// \endcode
1192 ///
1193 /// \param XOld the value of the atomic memory address to use for update
1194 /// \param IRB reference to the IRBuilder to use
1195 ///
1196 /// \returns Value to update X to.
1197 using AtomicUpdateCallbackTy =
1198 const function_ref<Value *(Value *XOld, IRBuilder<> &IRB)>;
1199
1200 private:
1201 enum AtomicKind { Read, Write, Update, Capture };
1202
1203 /// Determine whether to emit flush or not
1204 ///
1205 /// \param Loc The insert and source location description.
1206 /// \param AO The required atomic ordering
1207 /// \param AK The OpenMP atomic operation kind used.
1208 ///
1209 /// \returns wether a flush was emitted or not
1210 bool checkAndEmitFlushAfterAtomic(const LocationDescription &Loc,
1211 AtomicOrdering AO, AtomicKind AK);
1212
1213 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
1214 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
1215 /// Only Scalar data types.
1216 ///
1217 /// \param AllocIP Instruction to create AllocaInst before.
1218 /// \param X The target atomic pointer to be updated
1219 /// \param XElemTy The element type of the atomic pointer.
1220 /// \param Expr The value to update X with.
1221 /// \param AO Atomic ordering of the generated atomic
1222 /// instructions.
1223 /// \param RMWOp The binary operation used for update. If
1224 /// operation is not supported by atomicRMW,
1225 /// or belong to {FADD, FSUB, BAD_BINOP}.
1226 /// Then a `cmpExch` based atomic will be generated.
1227 /// \param UpdateOp Code generator for complex expressions that cannot be
1228 /// expressed through atomicrmw instruction.
1229 /// \param VolatileX true if \a X volatile?
1230 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
1231 /// update expression, false otherwise.
1232 /// (e.g. true for X = X BinOp Expr)
1233 ///
1234 /// \returns A pair of the old value of X before the update, and the value
1235 /// used for the update.
1236 std::pair<Value *, Value *>
1237 emitAtomicUpdate(Instruction *AllocIP, Value *X, Type *XElemTy, Value *Expr,
1238 AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
1239 AtomicUpdateCallbackTy &UpdateOp, bool VolatileX,
1240 bool IsXBinopExpr);
1241
1242 /// Emit the binary op. described by \p RMWOp, using \p Src1 and \p Src2 .
1243 ///
1244 /// \Return The instruction
1245 Value *emitRMWOpAsInstruction(Value *Src1, Value *Src2,
1246 AtomicRMWInst::BinOp RMWOp);
1247
1248 public:
1249 /// a struct to pack relevant information while generating atomic Ops
1250 struct AtomicOpValue {
1251 Value *Var = nullptr;
1252 Type *ElemTy = nullptr;
1253 bool IsSigned = false;
1254 bool IsVolatile = false;
1255 };
1256
1257 /// Emit atomic Read for : V = X --- Only Scalar data types.
1258 ///
1259 /// \param Loc The insert and source location description.
1260 /// \param X The target pointer to be atomically read
1261 /// \param V Memory address where to store atomically read
1262 /// value
1263 /// \param AO Atomic ordering of the generated atomic
1264 /// instructions.
1265 ///
1266 /// \return Insertion point after generated atomic read IR.
1267 InsertPointTy createAtomicRead(const LocationDescription &Loc,
1268 AtomicOpValue &X, AtomicOpValue &V,
1269 AtomicOrdering AO);
1270
1271 /// Emit atomic write for : X = Expr --- Only Scalar data types.
1272 ///
1273 /// \param Loc The insert and source location description.
1274 /// \param X The target pointer to be atomically written to
1275 /// \param Expr The value to store.
1276 /// \param AO Atomic ordering of the generated atomic
1277 /// instructions.
1278 ///
1279 /// \return Insertion point after generated atomic Write IR.
1280 InsertPointTy createAtomicWrite(const LocationDescription &Loc,
1281 AtomicOpValue &X, Value *Expr,
1282 AtomicOrdering AO);
1283
1284 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
1285 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
1286 /// Only Scalar data types.
1287 ///
1288 /// \param Loc The insert and source location description.
1289 /// \param AllocIP Instruction to create AllocaInst before.
1290 /// \param X The target atomic pointer to be updated
1291 /// \param Expr The value to update X with.
1292 /// \param AO Atomic ordering of the generated atomic instructions.
1293 /// \param RMWOp The binary operation used for update. If operation
1294 /// is not supported by atomicRMW, or belong to
1295 /// {FADD, FSUB, BAD_BINOP}. Then a `cmpExch` based
1296 /// atomic will be generated.
1297 /// \param UpdateOp Code generator for complex expressions that cannot be
1298 /// expressed through atomicrmw instruction.
1299 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
1300 /// update expression, false otherwise.
1301 /// (e.g. true for X = X BinOp Expr)
1302 ///
1303 /// \return Insertion point after generated atomic update IR.
1304 InsertPointTy createAtomicUpdate(const LocationDescription &Loc,
1305 Instruction *AllocIP, AtomicOpValue &X,
1306 Value *Expr, AtomicOrdering AO,
1307 AtomicRMWInst::BinOp RMWOp,
1308 AtomicUpdateCallbackTy &UpdateOp,
1309 bool IsXBinopExpr);
1310
1311 /// Emit atomic update for constructs: --- Only Scalar data types
1312 /// V = X; X = X BinOp Expr ,
1313 /// X = X BinOp Expr; V = X,
1314 /// V = X; X = Expr BinOp X,
1315 /// X = Expr BinOp X; V = X,
1316 /// V = X; X = UpdateOp(X),
1317 /// X = UpdateOp(X); V = X,
1318 ///
1319 /// \param Loc The insert and source location description.
1320 /// \param AllocIP Instruction to create AllocaInst before.
1321 /// \param X The target atomic pointer to be updated
1322 /// \param V Memory address where to store captured value
1323 /// \param Expr The value to update X with.
1324 /// \param AO Atomic ordering of the generated atomic instructions
1325 /// \param RMWOp The binary operation used for update. If
1326 /// operation is not supported by atomicRMW, or belong to
1327 /// {FADD, FSUB, BAD_BINOP}. Then a cmpExch based
1328 /// atomic will be generated.
1329 /// \param UpdateOp Code generator for complex expressions that cannot be
1330 /// expressed through atomicrmw instruction.
1331 /// \param UpdateExpr true if X is an in place update of the form
1332 /// X = X BinOp Expr or X = Expr BinOp X
1333 /// \param IsXBinopExpr true if X is Left H.S. in Right H.S. part of the
1334 /// update expression, false otherwise.
1335 /// (e.g. true for X = X BinOp Expr)
1336 /// \param IsPostfixUpdate true if original value of 'x' must be stored in
1337 /// 'v', not an updated one.
1338 ///
1339 /// \return Insertion point after generated atomic capture IR.
1340 InsertPointTy
1341 createAtomicCapture(const LocationDescription &Loc, Instruction *AllocIP,
1342 AtomicOpValue &X, AtomicOpValue &V, Value *Expr,
1343 AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
1344 AtomicUpdateCallbackTy &UpdateOp, bool UpdateExpr,
1345 bool IsPostfixUpdate, bool IsXBinopExpr);
1346
1347 /// Create the control flow structure of a canonical OpenMP loop.
1348 ///
1349 /// The emitted loop will be disconnected, i.e. no edge to the loop's
1350 /// preheader and no terminator in the AfterBB. The OpenMPIRBuilder's
1351 /// IRBuilder location is not preserved.
1352 ///
1353 /// \param DL DebugLoc used for the instructions in the skeleton.
1354 /// \param TripCount Value to be used for the trip count.
1355 /// \param F Function in which to insert the BasicBlocks.
1356 /// \param PreInsertBefore Where to insert BBs that execute before the body,
1357 /// typically the body itself.
1358 /// \param PostInsertBefore Where to insert BBs that execute after the body.
1359 /// \param Name Base name used to derive BB
1360 /// and instruction names.
1361 ///
1362 /// \returns The CanonicalLoopInfo that represents the emitted loop.
1363 CanonicalLoopInfo *createLoopSkeleton(DebugLoc DL, Value *TripCount,
1364 Function *F,
1365 BasicBlock *PreInsertBefore,
1366 BasicBlock *PostInsertBefore,
1367 const Twine &Name = {});
1368 };
1369
1370 /// Class to represented the control flow structure of an OpenMP canonical loop.
1371 ///
1372 /// The control-flow structure is standardized for easy consumption by
1373 /// directives associated with loops. For instance, the worksharing-loop
1374 /// construct may change this control flow such that each loop iteration is
1375 /// executed on only one thread. The constraints of a canonical loop in brief
1376 /// are:
1377 ///
1378 /// * The number of loop iterations must have been computed before entering the
1379 /// loop.
1380 ///
1381 /// * Has an (unsigned) logical induction variable that starts at zero and
1382 /// increments by one.
1383 ///
1384 /// * The loop's CFG itself has no side-effects. The OpenMP specification
1385 /// itself allows side-effects, but the order in which they happen, including
1386 /// how often or whether at all, is unspecified. We expect that the frontend
1387 /// will emit those side-effect instructions somewhere (e.g. before the loop)
1388 /// such that the CanonicalLoopInfo itself can be side-effect free.
1389 ///
1390 /// Keep in mind that CanonicalLoopInfo is meant to only describe a repeated
1391 /// execution of a loop body that satifies these constraints. It does NOT
1392 /// represent arbitrary SESE regions that happen to contain a loop. Do not use
1393 /// CanonicalLoopInfo for such purposes.
1394 ///
1395 /// The control flow can be described as follows:
1396 ///
1397 /// Preheader
1398 /// |
1399 /// /-> Header
1400 /// | |
1401 /// | Cond---\
1402 /// | | |
1403 /// | Body |
1404 /// | | | |
1405 /// | <...> |
1406 /// | | | |
1407 /// \--Latch |
1408 /// |
1409 /// Exit
1410 /// |
1411 /// After
1412 ///
1413 /// The loop is thought to start at PreheaderIP (at the Preheader's terminator,
1414 /// including) and end at AfterIP (at the After's first instruction, excluding).
1415 /// That is, instructions in the Preheader and After blocks (except the
1416 /// Preheader's terminator) are out of CanonicalLoopInfo's control and may have
1417 /// side-effects. Typically, the Preheader is used to compute the loop's trip
1418 /// count. The instructions from BodyIP (at the Body block's first instruction,
1419 /// excluding) until the Latch are also considered outside CanonicalLoopInfo's
1420 /// control and thus can have side-effects. The body block is the single entry
1421 /// point into the loop body, which may contain arbitrary control flow as long
1422 /// as all control paths eventually branch to the Latch block.
1423 ///
1424 /// TODO: Consider adding another standardized BasicBlock between Body CFG and
1425 /// Latch to guarantee that there is only a single edge to the latch. It would
1426 /// make loop transformations easier to not needing to consider multiple
1427 /// predecessors of the latch (See redirectAllPredecessorsTo) and would give us
1428 /// an equivalant to PreheaderIP, AfterIP and BodyIP for inserting code that
1429 /// executes after each body iteration.
1430 ///
1431 /// There must be no loop-carried dependencies through llvm::Values. This is
1432 /// equivalant to that the Latch has no PHINode and the Header's only PHINode is
1433 /// for the induction variable.
1434 ///
1435 /// All code in Header, Cond, Latch and Exit (plus the terminator of the
1436 /// Preheader) are CanonicalLoopInfo's responsibility and their build-up checked
1437 /// by assertOK(). They are expected to not be modified unless explicitly
1438 /// modifying the CanonicalLoopInfo through a methods that applies a OpenMP
1439 /// loop-associated construct such as applyWorkshareLoop, tileLoops, unrollLoop,
1440 /// etc. These methods usually invalidate the CanonicalLoopInfo and re-use its
1441 /// basic blocks. After invalidation, the CanonicalLoopInfo must not be used
1442 /// anymore as its underlying control flow may not exist anymore.
1443 /// Loop-transformation methods such as tileLoops, collapseLoops and unrollLoop
1444 /// may also return a new CanonicalLoopInfo that can be passed to other
1445 /// loop-associated construct implementing methods. These loop-transforming
1446 /// methods may either create a new CanonicalLoopInfo usually using
1447 /// createLoopSkeleton and invalidate the input CanonicalLoopInfo, or reuse and
1448 /// modify one of the input CanonicalLoopInfo and return it as representing the
1449 /// modified loop. What is done is an implementation detail of
1450 /// transformation-implementing method and callers should always assume that the
1451 /// CanonicalLoopInfo passed to it is invalidated and a new object is returned.
1452 /// Returned CanonicalLoopInfo have the same structure and guarantees as the one
1453 /// created by createCanonicalLoop, such that transforming methods do not have
1454 /// to special case where the CanonicalLoopInfo originated from.
1455 ///
1456 /// Generally, methods consuming CanonicalLoopInfo do not need an
1457 /// OpenMPIRBuilder::InsertPointTy as argument, but use the locations of the
1458 /// CanonicalLoopInfo to insert new or modify existing instructions. Unless
1459 /// documented otherwise, methods consuming CanonicalLoopInfo do not invalidate
1460 /// any InsertPoint that is outside CanonicalLoopInfo's control. Specifically,
1461 /// any InsertPoint in the Preheader, After or Block can still be used after
1462 /// calling such a method.
1463 ///
1464 /// TODO: Provide mechanisms for exception handling and cancellation points.
1465 ///
1466 /// Defined outside OpenMPIRBuilder because nested classes cannot be
1467 /// forward-declared, e.g. to avoid having to include the entire OMPIRBuilder.h.
1468 class CanonicalLoopInfo {
1469 friend class OpenMPIRBuilder;
1470
1471 private:
1472 BasicBlock *Header = nullptr;
1473 BasicBlock *Cond = nullptr;
1474 BasicBlock *Latch = nullptr;
1475 BasicBlock *Exit = nullptr;
1476
1477 /// Add the control blocks of this loop to \p BBs.
1478 ///
1479 /// This does not include any block from the body, including the one returned
1480 /// by getBody().
1481 ///
1482 /// FIXME: This currently includes the Preheader and After blocks even though
1483 /// their content is (mostly) not under CanonicalLoopInfo's control.
1484 /// Re-evaluated whether this makes sense.
1485 void collectControlBlocks(SmallVectorImpl<BasicBlock *> &BBs);
1486
1487 public:
1488 /// Returns whether this object currently represents the IR of a loop. If
1489 /// returning false, it may have been consumed by a loop transformation or not
1490 /// been intialized. Do not use in this case;
1491 bool isValid() const { return Header; }
1492
1493 /// The preheader ensures that there is only a single edge entering the loop.
1494 /// Code that must be execute before any loop iteration can be emitted here,
1495 /// such as computing the loop trip count and begin lifetime markers. Code in
1496 /// the preheader is not considered part of the canonical loop.
1497 BasicBlock *getPreheader() const;
1498
1499 /// The header is the entry for each iteration. In the canonical control flow,
1500 /// it only contains the PHINode for the induction variable.
1501 BasicBlock *getHeader() const {
1502 assert(isValid() && "Requires a valid canonical loop");
1503 return Header;
1504 }
1505
1506 /// The condition block computes whether there is another loop iteration. If
1507 /// yes, branches to the body; otherwise to the exit block.
1508 BasicBlock *getCond() const {
1509 assert(isValid() && "Requires a valid canonical loop");
1510 return Cond;
1511 }
1512
1513 /// The body block is the single entry for a loop iteration and not controlled
1514 /// by CanonicalLoopInfo. It can contain arbitrary control flow but must
1515 /// eventually branch to the \p Latch block.
1516 BasicBlock *getBody() const {
1517 assert(isValid() && "Requires a valid canonical loop");
1518 return cast<BranchInst>(Cond->getTerminator())->getSuccessor(0);
1519 }
1520
1521 /// Reaching the latch indicates the end of the loop body code. In the
1522 /// canonical control flow, it only contains the increment of the induction
1523 /// variable.
1524 BasicBlock *getLatch() const {
1525 assert(isValid() && "Requires a valid canonical loop");
1526 return Latch;
1527 }
1528
1529 /// Reaching the exit indicates no more iterations are being executed.
1530 BasicBlock *getExit() const {
1531 assert(isValid() && "Requires a valid canonical loop");
1532 return Exit;
1533 }
1534
1535 /// The after block is intended for clean-up code such as lifetime end
1536 /// markers. It is separate from the exit block to ensure, analogous to the
1537 /// preheader, it having just a single entry edge and being free from PHI
1538 /// nodes should there be multiple loop exits (such as from break
1539 /// statements/cancellations).
1540 BasicBlock *getAfter() const {
1541 assert(isValid() && "Requires a valid canonical loop");
1542 return Exit->getSingleSuccessor();
1543 }
1544
1545 /// Returns the llvm::Value containing the number of loop iterations. It must
1546 /// be valid in the preheader and always interpreted as an unsigned integer of
1547 /// any bit-width.
1548 Value *getTripCount() const {
1549 assert(isValid() && "Requires a valid canonical loop");
1550 Instruction *CmpI = &Cond->front();
1551 assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
1552 return CmpI->getOperand(1);
1553 }
1554
1555 /// Returns the instruction representing the current logical induction
1556 /// variable. Always unsigned, always starting at 0 with an increment of one.
1557 Instruction *getIndVar() const {
1558 assert(isValid() && "Requires a valid canonical loop");
1559 Instruction *IndVarPHI = &Header->front();
1560 assert(isa<PHINode>(IndVarPHI) && "First inst must be the IV PHI");
1561 return IndVarPHI;
1562 }
1563
1564 /// Return the type of the induction variable (and the trip count).
1565 Type *getIndVarType() const {
1566 assert(isValid() && "Requires a valid canonical loop");
1567 return getIndVar()->getType();
1568 }
1569
1570 /// Return the insertion point for user code before the loop.
1571 OpenMPIRBuilder::InsertPointTy getPreheaderIP() const {
1572 assert(isValid() && "Requires a valid canonical loop");
1573 BasicBlock *Preheader = getPreheader();
1574 return {Preheader, std::prev(Preheader->end())};
1575 };
1576
1577 /// Return the insertion point for user code in the body.
1578 OpenMPIRBuilder::InsertPointTy getBodyIP() const {
1579 assert(isValid() && "Requires a valid canonical loop");
1580 BasicBlock *Body = getBody();
1581 return {Body, Body->begin()};
1582 };
1583
1584 /// Return the insertion point for user code after the loop.
1585 OpenMPIRBuilder::InsertPointTy getAfterIP() const {
1586 assert(isValid() && "Requires a valid canonical loop");
1587 BasicBlock *After = getAfter();
1588 return {After, After->begin()};
1589 };
1590
1591 Function *getFunction() const {
1592 assert(isValid() && "Requires a valid canonical loop");
1593 return Header->getParent();
1594 }
1595
1596 /// Consistency self-check.
1597 void assertOK() const;
1598
1599 /// Invalidate this loop. That is, the underlying IR does not fulfill the
1600 /// requirements of an OpenMP canonical loop anymore.
1601 void invalidate();
1602 };
1603
1604 } // end namespace llvm
1605
1606 #endif // LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H