1//===- OMP.cpp ------ Collection of helpers for OpenMP --------------------===//
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#include "llvm/Frontend/OpenMP/OMP.h"
10
11#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/SmallSet.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Demangle/Demangle.h"
16#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
17#include "llvm/Support/ErrorHandling.h"
18
19#include <algorithm>
20#include <cstdio>
21#include <iterator>
22#include <string>
23#include <type_traits>
24
25using namespace llvm;
26using namespace llvm::omp;
27
28#define GEN_DIRECTIVES_IMPL
29#include "llvm/Frontend/OpenMP/OMP.inc"
30
31static iterator_range<ArrayRef<Directive>::iterator>
32getFirstCompositeRange(iterator_range<ArrayRef<Directive>::iterator> Leafs) {
33 // OpenMP Spec 5.2: [17.3, 8-9]
34 // If directive-name-A and directive-name-B both correspond to loop-
35 // associated constructs then directive-name is a composite construct
36 // otherwise directive-name is a combined construct.
37 //
38 // In the list of leaf constructs, find the first loop-associated construct,
39 // this is the beginning of the returned range. Then, starting from the
40 // immediately following leaf construct, find the first sequence of adjacent
41 // loop-associated constructs. The last of those is the last one of the
42 // range, that is, the end of the range is one past that element.
43 // If such a sequence of adjacent loop-associated directives does not exist,
44 // return an empty range.
45 //
46 // The end of the returned range (including empty range) is intended to be
47 // a point from which the search for the next range could resume.
48 //
49 // Consequently, this function can't return a range with a single leaf
50 // construct in it.
51
52 auto firstLoopAssociated =
53 [](iterator_range<ArrayRef<Directive>::iterator> List) {
54 for (auto It = List.begin(), End = List.end(); It != End; ++It) {
55 if (getDirectiveAssociation(Dir: *It) == Association::LoopNest)
56 return It;
57 }
58 return List.end();
59 };
60
61 auto Empty = llvm::make_range(x: Leafs.end(), y: Leafs.end());
62
63 auto Begin = firstLoopAssociated(Leafs);
64 if (Begin == Leafs.end())
65 return Empty;
66
67 auto End =
68 firstLoopAssociated(llvm::make_range(x: std::next(x: Begin), y: Leafs.end()));
69 if (End == Leafs.end())
70 return Empty;
71
72 for (; End != Leafs.end(); ++End) {
73 if (getDirectiveAssociation(Dir: *End) != Association::LoopNest)
74 break;
75 }
76 return llvm::make_range(x: Begin, y: End);
77}
78
79static void
80collectPrivatizingConstructs(llvm::SmallSet<Directive, 16> &Constructs,
81 Version V) {
82 llvm::SmallSet<Clause, 16> Privatizing;
83 for (auto C : clauses()) {
84 if (isPrivatizingClause(C, V))
85 Privatizing.insert(V: C);
86 }
87
88 for (auto D : directives()) {
89 bool AllowsPrivatizing = llvm::any_of(Range&: Privatizing, P: [&](Clause C) {
90 return isAllowedClauseForDirective(D, C, V);
91 });
92 if (AllowsPrivatizing)
93 Constructs.insert(V: D);
94 }
95}
96
97namespace llvm::omp {
98ArrayRef<Directive> getLeafConstructs(Directive D) {
99 auto Idx = static_cast<std::size_t>(D);
100 if (Idx >= Directive_enumSize)
101 return {};
102 const auto *Row = LeafConstructTable[LeafConstructTableOrdering[Idx]];
103 return ArrayRef(&Row[2], static_cast<int>(Row[1]));
104}
105
106ArrayRef<Directive> getLeafConstructsOrSelf(Directive D) {
107 if (auto Leafs = getLeafConstructs(D); !Leafs.empty())
108 return Leafs;
109 auto Idx = static_cast<size_t>(D);
110 assert(Idx < Directive_enumSize && "Invalid directive");
111 const auto *Row = LeafConstructTable[LeafConstructTableOrdering[Idx]];
112 // The first entry in the row is the directive itself.
113 return ArrayRef(&Row[0], &Row[0] + 1);
114}
115
116ArrayRef<Directive>
117getLeafOrCompositeConstructs(Directive D, SmallVectorImpl<Directive> &Output) {
118 using ArrayTy = ArrayRef<Directive>;
119 using IteratorTy = ArrayTy::iterator;
120 ArrayRef<Directive> Leafs = getLeafConstructsOrSelf(D);
121
122 IteratorTy Iter = Leafs.begin();
123 do {
124 auto Range = getFirstCompositeRange(Leafs: llvm::make_range(x: Iter, y: Leafs.end()));
125 // All directives before the range are leaf constructs.
126 for (; Iter != Range.begin(); ++Iter)
127 Output.push_back(Elt: *Iter);
128 if (!Range.empty()) {
129 Directive Comp =
130 getCompoundConstruct(Parts: ArrayTy(Range.begin(), Range.end()));
131 assert(Comp != OMPD_unknown);
132 Output.push_back(Elt: Comp);
133 Iter = Range.end();
134 // As of now, a composite construct must contain all constituent leaf
135 // constructs from some point until the end of all constituent leaf
136 // constructs.
137 assert(Iter == Leafs.end() && "Malformed directive");
138 }
139 } while (Iter != Leafs.end());
140
141 return Output;
142}
143
144Directive getCompoundConstruct(ArrayRef<Directive> Parts) {
145 if (Parts.empty())
146 return OMPD_unknown;
147
148 // Parts don't have to be leafs, so expand them into leafs first.
149 // Store the expanded leafs in the same format as rows in the leaf
150 // table (generated by tablegen).
151 SmallVector<Directive> RawLeafs(2);
152 for (Directive P : Parts) {
153 ArrayRef<Directive> Ls = getLeafConstructs(D: P);
154 if (!Ls.empty())
155 RawLeafs.append(in_start: Ls.begin(), in_end: Ls.end());
156 else
157 RawLeafs.push_back(Elt: P);
158 }
159
160 // RawLeafs will be used as key in the binary search. The search doesn't
161 // guarantee that the exact same entry will be found (since RawLeafs may
162 // not correspond to any compound directive). Because of that, we will
163 // need to compare the search result with the given set of leafs.
164 // Also, if there is only one leaf in the list, it corresponds to itself,
165 // no search is necessary.
166 auto GivenLeafs{ArrayRef<Directive>(RawLeafs).drop_front(N: 2)};
167 if (GivenLeafs.size() == 1)
168 return GivenLeafs.front();
169 RawLeafs[1] = static_cast<Directive>(GivenLeafs.size());
170
171 auto Iter = std::lower_bound(
172 first: LeafConstructTable, last: LeafConstructTableEndDirective,
173 val: static_cast<std::decay_t<decltype(*LeafConstructTable)>>(RawLeafs.data()),
174 comp: [](const llvm::omp::Directive *RowA, const llvm::omp::Directive *RowB) {
175 const auto *BeginA = &RowA[2];
176 const auto *EndA = BeginA + static_cast<int>(RowA[1]);
177 const auto *BeginB = &RowB[2];
178 const auto *EndB = BeginB + static_cast<int>(RowB[1]);
179 if (BeginA == EndA && BeginB == EndB)
180 return static_cast<int>(RowA[0]) < static_cast<int>(RowB[0]);
181 return std::lexicographical_compare(first1: BeginA, last1: EndA, first2: BeginB, last2: EndB);
182 });
183
184 if (Iter == std::end(arr: LeafConstructTable))
185 return OMPD_unknown;
186
187 // Verify that we got a match.
188 Directive Found = (*Iter)[0];
189 ArrayRef<Directive> FoundLeafs = getLeafConstructs(D: Found);
190 if (FoundLeafs == GivenLeafs)
191 return Found;
192 return OMPD_unknown;
193}
194
195bool isLeafConstruct(Directive D) { return getLeafConstructs(D).empty(); }
196
197bool isCompositeConstruct(Directive D) {
198 ArrayRef<Directive> Leafs = getLeafConstructsOrSelf(D);
199 if (Leafs.size() <= 1)
200 return false;
201 auto Range = getFirstCompositeRange(Leafs);
202 return Range.begin() == Leafs.begin() && Range.end() == Leafs.end();
203}
204
205bool isCombinedConstruct(Directive D) {
206 // OpenMP Spec 5.2: [17.3, 9-10]
207 // Otherwise directive-name is a combined construct.
208 return !getLeafConstructs(D).empty() && !isCompositeConstruct(D);
209}
210
211ArrayRef<Version> getOpenMPVersions() {
212 static Version Versions[]{Version(31), Version(40), Version(45), Version(50),
213 Version(51), Version(52), Version(60), Version(61)};
214 return Versions;
215}
216
217bool isPrivatizingConstruct(Directive D, Version V) {
218 static llvm::SmallSet<Directive, 16> Privatizing;
219 [[maybe_unused]] static bool Init =
220 (collectPrivatizingConstructs(Constructs&: Privatizing, V), true);
221
222 // As of OpenMP 6.0, privatizing constructs (with the test being if they
223 // allow a privatizing clause) are: dispatch, distribute, do, for, loop,
224 // parallel, scope, sections, simd, single, target, target_data, task,
225 // taskgroup, taskloop, and teams.
226 return llvm::is_contained(Range&: Privatizing, Element: D);
227}
228
229ArrayRef<StringRef> getReservedLocatorNames() {
230 // All names must be lowercase.
231 static StringRef names[]{"omp_all_memory"};
232 return names;
233}
234
235std::string prettifyFunctionName(StringRef FunctionName) {
236 // Internalized functions have the right name, but simply a suffix.
237 if (FunctionName.ends_with(Suffix: ".internalized"))
238 return FunctionName.drop_back(N: sizeof("internalized")).str() +
239 " (internalized)";
240 unsigned LineNo = 0;
241 auto ParentName = deconstructOpenMPKernelName(KernelName: FunctionName, LineNo);
242 if (LineNo == 0)
243 return FunctionName.str();
244 return ("omp target in " + ParentName + " @ " + std::to_string(val: LineNo) +
245 " (" + FunctionName + ")")
246 .str();
247}
248
249std::string deconstructOpenMPKernelName(StringRef KernelName,
250 unsigned &LineNo) {
251
252 // Only handle functions with an OpenMP kernel prefix for now. Naming scheme:
253 // __omp_offloading_<hex_hash1>_<hex_hash2>_<name>_l<line>_[<count>_]<suffix>
254 if (!KernelName.starts_with(Prefix: TargetRegionEntryInfo::KernelNamePrefix))
255 return "";
256
257 auto PrettyName = KernelName.drop_front(
258 N: sizeof(TargetRegionEntryInfo::KernelNamePrefix) - /*'\0'*/ 1);
259 for (int I = 0; I < 3; ++I) {
260 PrettyName = PrettyName.drop_while(F: [](char c) { return c != '_'; });
261 PrettyName = PrettyName.drop_front();
262 }
263
264 // Look for the last '_l<line>'.
265 size_t LineIdx = PrettyName.rfind(Str: "_l");
266 if (LineIdx == StringRef::npos)
267 return "";
268 if (PrettyName.drop_front(N: LineIdx + 2).consumeInteger(Radix: 10, Result&: LineNo))
269 return "";
270 return demangle(MangledName: PrettyName.take_front(N: LineIdx));
271}
272} // namespace llvm::omp
273