Bug Summary

File:tools/clang/lib/Sema/SemaOpenMP.cpp
Warning:line 1342, column 38
Called C++ object pointer is null

Annotated Source Code

<
1//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
11/// clauses.
12///
13//===----------------------------------------------------------------------===//
14
15#include "TreeTransform.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclOpenMP.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/Basic/OpenMPKinds.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
30#include "clang/Sema/SemaInternal.h"
31#include "llvm/ADT/PointerEmbeddedInt.h"
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
38static Expr *CheckMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41 OpenMPClauseKind CKind);
42
43namespace {
44/// \brief Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
46 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55};
56
57/// \brief Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
59class DSAStackTy final {
60public:
61 struct DSAVarData final {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
66 SourceLocation ImplicitDSALoc;
67 DSAVarData() = default;
68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
72 };
73 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74 OperatorOffsetTy;
75
76private:
77 struct DSAInfo final {
78 OpenMPClauseKind Attributes = OMPC_unknown;
79 /// Pointer to a reference expression and a flag which shows that the
80 /// variable is marked as lastprivate(true) or not (false).
81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82 DeclRefExpr *PrivateCopy = nullptr;
83 };
84 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
86 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
88 /// Struct that associates a component with the clause kind where they are
89 /// found.
90 struct MappedExprComponentTy {
91 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92 OpenMPClauseKind Kind = OMPC_unknown;
93 };
94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
95 MappedExprComponentsTy;
96 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97 CriticalsWithHintsTy;
98 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99 DoacrossDependMapTy;
100 struct ReductionData {
101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
102 SourceRange ReductionRange;
103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
115
116 struct SharingMapTy final {
117 DeclSAMapTy SharingMap;
118 DeclReductionMapTy ReductionMap;
119 AlignedMapTy AlignedMap;
120 MappedExprComponentsTy MappedExprComponents;
121 LoopControlVariablesMapTy LCVMap;
122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
123 SourceLocation DefaultAttrLoc;
124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125 SourceLocation DefaultMapAttrLoc;
126 OpenMPDirectiveKind Directive = OMPD_unknown;
127 DeclarationNameInfo DirectiveName;
128 Scope *CurScope = nullptr;
129 SourceLocation ConstructLoc;
130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131 /// get the data (loop counters etc.) about enclosing loop-based construct.
132 /// This data is required during codegen.
133 DoacrossDependMapTy DoacrossDepends;
134 /// \brief first argument (Expr *) contains optional argument of the
135 /// 'ordered' clause, the second one is true if the regions has 'ordered'
136 /// clause, false otherwise.
137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
138 bool NowaitRegion = false;
139 bool CancelRegion = false;
140 unsigned AssociatedLoops = 1;
141 SourceLocation InnerTeamsRegionLoc;
142 /// Reference to the taskgroup task_reduction reference expression.
143 Expr *TaskgroupReductionRef = nullptr;
144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
145 Scope *CurScope, SourceLocation Loc)
146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147 ConstructLoc(Loc) {}
148 SharingMapTy() = default;
149 };
150
151 typedef SmallVector<SharingMapTy, 4> StackTy;
152
153 /// \brief Stack of used declaration and their data-sharing attributes.
154 DeclSAMapTy Threadprivates;
155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
157 /// \brief true, if check for DSA must be from parent directive, false, if
158 /// from current directive.
159 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
160 Sema &SemaRef;
161 bool ForceCapturing = false;
162 CriticalsWithHintsTy Criticals;
163
164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165
166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
167
168 /// \brief Checks if the variable is a local for OpenMP region.
169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
170
171 bool isStackEmpty() const {
172 return Stack.empty() ||
173 Stack.back().second != CurrentNonCapturingFunctionScope ||
174 Stack.back().first.empty();
175 }
176
177public:
178 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
179
180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
181 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
182
183 bool isForceVarCapturing() const { return ForceCapturing; }
184 void setForceVarCapturing(bool V) { ForceCapturing = V; }
185
186 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
187 Scope *CurScope, SourceLocation Loc) {
188 if (Stack.empty() ||
189 Stack.back().second != CurrentNonCapturingFunctionScope)
190 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
191 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
192 Stack.back().first.back().DefaultAttrLoc = Loc;
193 }
194
195 void pop() {
196 assert(!Stack.back().first.empty() &&((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 197, __PRETTY_FUNCTION__))
197 "Data-sharing attributes stack is empty!")((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 197, __PRETTY_FUNCTION__))
;
198 Stack.back().first.pop_back();
199 }
200
201 /// Start new OpenMP region stack in new non-capturing function.
202 void pushFunction() {
203 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
204 assert(!isa<CapturingScopeInfo>(CurFnScope))((!isa<CapturingScopeInfo>(CurFnScope)) ? static_cast<
void> (0) : __assert_fail ("!isa<CapturingScopeInfo>(CurFnScope)"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 204, __PRETTY_FUNCTION__))
;
205 CurrentNonCapturingFunctionScope = CurFnScope;
206 }
207 /// Pop region stack for non-capturing function.
208 void popFunction(const FunctionScopeInfo *OldFSI) {
209 if (!Stack.empty() && Stack.back().second == OldFSI) {
210 assert(Stack.back().first.empty())((Stack.back().first.empty()) ? static_cast<void> (0) :
__assert_fail ("Stack.back().first.empty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 210, __PRETTY_FUNCTION__))
;
211 Stack.pop_back();
212 }
213 CurrentNonCapturingFunctionScope = nullptr;
214 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
215 if (!isa<CapturingScopeInfo>(FSI)) {
216 CurrentNonCapturingFunctionScope = FSI;
217 break;
218 }
219 }
220 }
221
222 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
223 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
224 }
225 const std::pair<OMPCriticalDirective *, llvm::APSInt>
226 getCriticalWithHint(const DeclarationNameInfo &Name) const {
227 auto I = Criticals.find(Name.getAsString());
228 if (I != Criticals.end())
229 return I->second;
230 return std::make_pair(nullptr, llvm::APSInt());
231 }
232 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
233 /// add it and return NULL; otherwise return previous occurrence's expression
234 /// for diagnostics.
235 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
236
237 /// \brief Register specified variable as loop control variable.
238 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
239 /// \brief Check if the specified variable is a loop control variable for
240 /// current region.
241 /// \return The index of the loop control variable in the list of associated
242 /// for-loops (from outer to inner).
243 LCDeclInfo isLoopControlVariable(ValueDecl *D);
244 /// \brief Check if the specified variable is a loop control variable for
245 /// parent region.
246 /// \return The index of the loop control variable in the list of associated
247 /// for-loops (from outer to inner).
248 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
249 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
250 /// parent directive.
251 ValueDecl *getParentLoopControlVariable(unsigned I);
252
253 /// \brief Adds explicit data sharing attribute to the specified declaration.
254 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
255 DeclRefExpr *PrivateCopy = nullptr);
256
257 /// Adds additional information for the reduction items with the reduction id
258 /// represented as an operator.
259 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
260 BinaryOperatorKind BOK);
261 /// Adds additional information for the reduction items with the reduction id
262 /// represented as reduction identifier.
263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264 const Expr *ReductionRef);
265 /// Returns the location and reduction operation from the innermost parent
266 /// region for the given \p D.
267 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
268 BinaryOperatorKind &BOK,
269 Expr *&TaskgroupDescriptor);
270 /// Returns the location and reduction operation from the innermost parent
271 /// region for the given \p D.
272 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
273 const Expr *&ReductionRef,
274 Expr *&TaskgroupDescriptor);
275 /// Return reduction reference expression for the current taskgroup.
276 Expr *getTaskgroupReductionRef() const {
277 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&((Stack.back().first.back().Directive == OMPD_taskgroup &&
"taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"Stack.back().first.back().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 279, __PRETTY_FUNCTION__))
278 "taskgroup reference expression requested for non taskgroup "((Stack.back().first.back().Directive == OMPD_taskgroup &&
"taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"Stack.back().first.back().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 279, __PRETTY_FUNCTION__))
279 "directive.")((Stack.back().first.back().Directive == OMPD_taskgroup &&
"taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"Stack.back().first.back().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 279, __PRETTY_FUNCTION__))
;
280 return Stack.back().first.back().TaskgroupReductionRef;
281 }
282 /// Checks if the given \p VD declaration is actually a taskgroup reduction
283 /// descriptor variable at the \p Level of OpenMP regions.
284 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
285 return Stack.back().first[Level].TaskgroupReductionRef &&
286 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
287 ->getDecl() == VD;
288 }
289
290 /// \brief Returns data sharing attributes from top of the stack for the
291 /// specified declaration.
292 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
293 /// \brief Returns data-sharing attributes for the specified declaration.
294 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
295 /// \brief Checks if the specified variables has data-sharing attributes which
296 /// match specified \a CPred predicate in any directive which matches \a DPred
297 /// predicate.
298 DSAVarData hasDSA(ValueDecl *D,
299 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
300 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
301 bool FromParent);
302 /// \brief Checks if the specified variables has data-sharing attributes which
303 /// match specified \a CPred predicate in any innermost directive which
304 /// matches \a DPred predicate.
305 DSAVarData
306 hasInnermostDSA(ValueDecl *D,
307 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
308 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
309 bool FromParent);
310 /// \brief Checks if the specified variables has explicit data-sharing
311 /// attributes which match specified \a CPred predicate at the specified
312 /// OpenMP region.
313 bool hasExplicitDSA(ValueDecl *D,
314 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
315 unsigned Level, bool NotLastprivate = false);
316
317 /// \brief Returns true if the directive at level \Level matches in the
318 /// specified \a DPred predicate.
319 bool hasExplicitDirective(
320 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
321 unsigned Level);
322
323 /// \brief Finds a directive which matches specified \a DPred predicate.
324 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
325 const DeclarationNameInfo &,
326 SourceLocation)> &DPred,
327 bool FromParent);
328
329 /// \brief Returns currently analyzed directive.
330 OpenMPDirectiveKind getCurrentDirective() const {
331 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
332 }
333 /// \brief Returns parent directive.
334 OpenMPDirectiveKind getParentDirective() const {
335 if (isStackEmpty() || Stack.back().first.size() == 1)
336 return OMPD_unknown;
337 return std::next(Stack.back().first.rbegin())->Directive;
338 }
339
340 /// \brief Set default data sharing attribute to none.
341 void setDefaultDSANone(SourceLocation Loc) {
342 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 342, __PRETTY_FUNCTION__))
;
343 Stack.back().first.back().DefaultAttr = DSA_none;
344 Stack.back().first.back().DefaultAttrLoc = Loc;
345 }
346 /// \brief Set default data sharing attribute to shared.
347 void setDefaultDSAShared(SourceLocation Loc) {
348 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 348, __PRETTY_FUNCTION__))
;
349 Stack.back().first.back().DefaultAttr = DSA_shared;
350 Stack.back().first.back().DefaultAttrLoc = Loc;
351 }
352 /// Set default data mapping attribute to 'tofrom:scalar'.
353 void setDefaultDMAToFromScalar(SourceLocation Loc) {
354 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 354, __PRETTY_FUNCTION__))
;
355 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
356 Stack.back().first.back().DefaultMapAttrLoc = Loc;
357 }
358
359 DefaultDataSharingAttributes getDefaultDSA() const {
360 return isStackEmpty() ? DSA_unspecified
361 : Stack.back().first.back().DefaultAttr;
362 }
363 SourceLocation getDefaultDSALocation() const {
364 return isStackEmpty() ? SourceLocation()
365 : Stack.back().first.back().DefaultAttrLoc;
366 }
367 DefaultMapAttributes getDefaultDMA() const {
368 return isStackEmpty() ? DMA_unspecified
369 : Stack.back().first.back().DefaultMapAttr;
370 }
371 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
372 return Stack.back().first[Level].DefaultMapAttr;
373 }
374 SourceLocation getDefaultDMALocation() const {
375 return isStackEmpty() ? SourceLocation()
376 : Stack.back().first.back().DefaultMapAttrLoc;
377 }
378
379 /// \brief Checks if the specified variable is a threadprivate.
380 bool isThreadPrivate(VarDecl *D) {
381 DSAVarData DVar = getTopDSA(D, false);
382 return isOpenMPThreadPrivate(DVar.CKind);
383 }
384
385 /// \brief Marks current region as ordered (it has an 'ordered' clause).
386 void setOrderedRegion(bool IsOrdered, Expr *Param) {
387 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 387, __PRETTY_FUNCTION__))
;
388 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
389 Stack.back().first.back().OrderedRegion.setPointer(Param);
390 }
391 /// \brief Returns true, if parent region is ordered (has associated
392 /// 'ordered' clause), false - otherwise.
393 bool isParentOrderedRegion() const {
394 if (isStackEmpty() || Stack.back().first.size() == 1)
395 return false;
396 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
397 }
398 /// \brief Returns optional parameter for the ordered region.
399 Expr *getParentOrderedRegionParam() const {
400 if (isStackEmpty() || Stack.back().first.size() == 1)
401 return nullptr;
402 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
403 }
404 /// \brief Marks current region as nowait (it has a 'nowait' clause).
405 void setNowaitRegion(bool IsNowait = true) {
406 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 406, __PRETTY_FUNCTION__))
;
407 Stack.back().first.back().NowaitRegion = IsNowait;
408 }
409 /// \brief Returns true, if parent region is nowait (has associated
410 /// 'nowait' clause), false - otherwise.
411 bool isParentNowaitRegion() const {
412 if (isStackEmpty() || Stack.back().first.size() == 1)
413 return false;
414 return std::next(Stack.back().first.rbegin())->NowaitRegion;
415 }
416 /// \brief Marks parent region as cancel region.
417 void setParentCancelRegion(bool Cancel = true) {
418 if (!isStackEmpty() && Stack.back().first.size() > 1) {
419 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
420 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
421 }
422 }
423 /// \brief Return true if current region has inner cancel construct.
424 bool isCancelRegion() const {
425 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
426 }
427
428 /// \brief Set collapse value for the region.
429 void setAssociatedLoops(unsigned Val) {
430 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 430, __PRETTY_FUNCTION__))
;
431 Stack.back().first.back().AssociatedLoops = Val;
432 }
433 /// \brief Return collapse value for region.
434 unsigned getAssociatedLoops() const {
435 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
436 }
437
438 /// \brief Marks current target region as one with closely nested teams
439 /// region.
440 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
441 if (!isStackEmpty() && Stack.back().first.size() > 1) {
442 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
443 TeamsRegionLoc;
444 }
445 }
446 /// \brief Returns true, if current region has closely nested teams region.
447 bool hasInnerTeamsRegion() const {
448 return getInnerTeamsRegionLoc().isValid();
449 }
450 /// \brief Returns location of the nested teams region (if any).
451 SourceLocation getInnerTeamsRegionLoc() const {
452 return isStackEmpty() ? SourceLocation()
453 : Stack.back().first.back().InnerTeamsRegionLoc;
454 }
455
456 Scope *getCurScope() const {
457 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
458 }
459 Scope *getCurScope() {
460 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
461 }
462 SourceLocation getConstructLoc() {
463 return isStackEmpty() ? SourceLocation()
464 : Stack.back().first.back().ConstructLoc;
465 }
466
467 /// Do the check specified in \a Check to all component lists and return true
468 /// if any issue is found.
469 bool checkMappableExprComponentListsForDecl(
470 ValueDecl *VD, bool CurrentRegionOnly,
471 const llvm::function_ref<
472 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
473 OpenMPClauseKind)> &Check) {
474 if (isStackEmpty())
475 return false;
476 auto SI = Stack.back().first.rbegin();
477 auto SE = Stack.back().first.rend();
478
479 if (SI == SE)
480 return false;
481
482 if (CurrentRegionOnly) {
483 SE = std::next(SI);
484 } else {
485 ++SI;
486 }
487
488 for (; SI != SE; ++SI) {
489 auto MI = SI->MappedExprComponents.find(VD);
490 if (MI != SI->MappedExprComponents.end())
491 for (auto &L : MI->second.Components)
492 if (Check(L, MI->second.Kind))
493 return true;
494 }
495 return false;
496 }
497
498 /// Do the check specified in \a Check to all component lists at a given level
499 /// and return true if any issue is found.
500 bool checkMappableExprComponentListsForDeclAtLevel(
501 ValueDecl *VD, unsigned Level,
502 const llvm::function_ref<
503 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
504 OpenMPClauseKind)> &Check) {
505 if (isStackEmpty())
506 return false;
507
508 auto StartI = Stack.back().first.begin();
509 auto EndI = Stack.back().first.end();
510 if (std::distance(StartI, EndI) <= (int)Level)
511 return false;
512 std::advance(StartI, Level);
513
514 auto MI = StartI->MappedExprComponents.find(VD);
515 if (MI != StartI->MappedExprComponents.end())
516 for (auto &L : MI->second.Components)
517 if (Check(L, MI->second.Kind))
518 return true;
519 return false;
520 }
521
522 /// Create a new mappable expression component list associated with a given
523 /// declaration and initialize it with the provided list of components.
524 void addMappableExpressionComponents(
525 ValueDecl *VD,
526 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
527 OpenMPClauseKind WhereFoundClauseKind) {
528 assert(!isStackEmpty() &&((!isStackEmpty() && "Not expecting to retrieve components from a empty stack!"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Not expecting to retrieve components from a empty stack!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 529, __PRETTY_FUNCTION__))
529 "Not expecting to retrieve components from a empty stack!")((!isStackEmpty() && "Not expecting to retrieve components from a empty stack!"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Not expecting to retrieve components from a empty stack!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 529, __PRETTY_FUNCTION__))
;
530 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
531 // Create new entry and append the new components there.
532 MEC.Components.resize(MEC.Components.size() + 1);
533 MEC.Components.back().append(Components.begin(), Components.end());
534 MEC.Kind = WhereFoundClauseKind;
535 }
536
537 unsigned getNestingLevel() const {
538 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 538, __PRETTY_FUNCTION__))
;
539 return Stack.back().first.size() - 1;
540 }
541 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
542 assert(!isStackEmpty() && Stack.back().first.size() > 1)((!isStackEmpty() && Stack.back().first.size() > 1
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 542, __PRETTY_FUNCTION__))
;
543 auto &StackElem = *std::next(Stack.back().first.rbegin());
544 assert(isOpenMPWorksharingDirective(StackElem.Directive))((isOpenMPWorksharingDirective(StackElem.Directive)) ? static_cast
<void> (0) : __assert_fail ("isOpenMPWorksharingDirective(StackElem.Directive)"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 544, __PRETTY_FUNCTION__))
;
545 StackElem.DoacrossDepends.insert({C, OpsOffs});
546 }
547 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
548 getDoacrossDependClauses() const {
549 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 549, __PRETTY_FUNCTION__))
;
550 auto &StackElem = Stack.back().first.back();
551 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
552 auto &Ref = StackElem.DoacrossDepends;
553 return llvm::make_range(Ref.begin(), Ref.end());
554 }
555 return llvm::make_range(StackElem.DoacrossDepends.end(),
556 StackElem.DoacrossDepends.end());
557 }
558};
559bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
560 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
561 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
562}
563} // namespace
564
565static Expr *getExprAsWritten(Expr *E) {
566 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
567 E = ExprTemp->getSubExpr();
568
569 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
570 E = MTE->GetTemporaryExpr();
571
572 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
573 E = Binder->getSubExpr();
574
575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
576 E = ICE->getSubExprAsWritten();
577 return E->IgnoreParens();
578}
579
580static ValueDecl *getCanonicalDecl(ValueDecl *D) {
581 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
582 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
583 D = ME->getMemberDecl();
584 auto *VD = dyn_cast<VarDecl>(D);
585 auto *FD = dyn_cast<FieldDecl>(D);
586 if (VD != nullptr) {
587 VD = VD->getCanonicalDecl();
588 D = VD;
589 } else {
590 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 590, __PRETTY_FUNCTION__))
;
591 FD = FD->getCanonicalDecl();
592 D = FD;
593 }
594 return D;
595}
596
597DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
598 ValueDecl *D) {
599 D = getCanonicalDecl(D);
600 auto *VD = dyn_cast<VarDecl>(D);
601 auto *FD = dyn_cast<FieldDecl>(D);
602 DSAVarData DVar;
603 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
604 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
605 // in a region but not in construct]
606 // File-scope or namespace-scope variables referenced in called routines
607 // in the region are shared unless they appear in a threadprivate
608 // directive.
609 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
610 DVar.CKind = OMPC_shared;
611
612 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
613 // in a region but not in construct]
614 // Variables with static storage duration that are declared in called
615 // routines in the region are shared.
616 if (VD && VD->hasGlobalStorage())
617 DVar.CKind = OMPC_shared;
618
619 // Non-static data members are shared by default.
620 if (FD)
621 DVar.CKind = OMPC_shared;
622
623 return DVar;
624 }
625
626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
627 // in a Construct, C/C++, predetermined, p.1]
628 // Variables with automatic storage duration that are declared in a scope
629 // inside the construct are private.
630 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
631 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
632 DVar.CKind = OMPC_private;
633 return DVar;
634 }
635
636 DVar.DKind = Iter->Directive;
637 // Explicitly specified attributes and local variables with predetermined
638 // attributes.
639 if (Iter->SharingMap.count(D)) {
640 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
641 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
642 DVar.CKind = Iter->SharingMap[D].Attributes;
643 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
644 return DVar;
645 }
646
647 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
648 // in a Construct, C/C++, implicitly determined, p.1]
649 // In a parallel or task construct, the data-sharing attributes of these
650 // variables are determined by the default clause, if present.
651 switch (Iter->DefaultAttr) {
652 case DSA_shared:
653 DVar.CKind = OMPC_shared;
654 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
655 return DVar;
656 case DSA_none:
657 return DVar;
658 case DSA_unspecified:
659 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
660 // in a Construct, implicitly determined, p.2]
661 // In a parallel construct, if no default clause is present, these
662 // variables are shared.
663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
664 if (isOpenMPParallelDirective(DVar.DKind) ||
665 isOpenMPTeamsDirective(DVar.DKind)) {
666 DVar.CKind = OMPC_shared;
667 return DVar;
668 }
669
670 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
671 // in a Construct, implicitly determined, p.4]
672 // In a task construct, if no default clause is present, a variable that in
673 // the enclosing context is determined to be shared by all implicit tasks
674 // bound to the current team is shared.
675 if (isOpenMPTaskingDirective(DVar.DKind)) {
676 DSAVarData DVarTemp;
677 auto I = Iter, E = Stack.back().first.rend();
678 do {
679 ++I;
680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
681 // Referenced in a Construct, implicitly determined, p.6]
682 // In a task construct, if no default clause is present, a variable
683 // whose data-sharing attribute is not determined by the rules above is
684 // firstprivate.
685 DVarTemp = getDSA(I, D);
686 if (DVarTemp.CKind != OMPC_shared) {
687 DVar.RefExpr = nullptr;
688 DVar.CKind = OMPC_firstprivate;
689 return DVar;
690 }
691 } while (I != E && !isParallelOrTaskRegion(I->Directive));
692 DVar.CKind =
693 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
694 return DVar;
695 }
696 }
697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
698 // in a Construct, implicitly determined, p.3]
699 // For constructs other than task, if no default clause is present, these
700 // variables inherit their data-sharing attributes from the enclosing
701 // context.
702 return getDSA(++Iter, D);
703}
704
705Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
706 assert(!isStackEmpty() && "Data sharing attributes stack is empty")((!isStackEmpty() && "Data sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 706, __PRETTY_FUNCTION__))
;
707 D = getCanonicalDecl(D);
708 auto &StackElem = Stack.back().first.back();
709 auto It = StackElem.AlignedMap.find(D);
710 if (It == StackElem.AlignedMap.end()) {
711 assert(NewDE && "Unexpected nullptr expr to be added into aligned map")((NewDE && "Unexpected nullptr expr to be added into aligned map"
) ? static_cast<void> (0) : __assert_fail ("NewDE && \"Unexpected nullptr expr to be added into aligned map\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 711, __PRETTY_FUNCTION__))
;
712 StackElem.AlignedMap[D] = NewDE;
713 return nullptr;
714 } else {
715 assert(It->second && "Unexpected nullptr expr in the aligned map")((It->second && "Unexpected nullptr expr in the aligned map"
) ? static_cast<void> (0) : __assert_fail ("It->second && \"Unexpected nullptr expr in the aligned map\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 715, __PRETTY_FUNCTION__))
;
716 return It->second;
717 }
718 return nullptr;
719}
720
721void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
722 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 722, __PRETTY_FUNCTION__))
;
723 D = getCanonicalDecl(D);
724 auto &StackElem = Stack.back().first.back();
725 StackElem.LCVMap.insert(
726 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
727}
728
729DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
730 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 730, __PRETTY_FUNCTION__))
;
731 D = getCanonicalDecl(D);
732 auto &StackElem = Stack.back().first.back();
733 auto It = StackElem.LCVMap.find(D);
734 if (It != StackElem.LCVMap.end())
735 return It->second;
736 return {0, nullptr};
737}
738
739DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
740 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 741, __PRETTY_FUNCTION__))
741 "Data-sharing attributes stack is empty")((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 741, __PRETTY_FUNCTION__))
;
742 D = getCanonicalDecl(D);
743 auto &StackElem = *std::next(Stack.back().first.rbegin());
744 auto It = StackElem.LCVMap.find(D);
745 if (It != StackElem.LCVMap.end())
746 return It->second;
747 return {0, nullptr};
748}
749
750ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
751 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 752, __PRETTY_FUNCTION__))
752 "Data-sharing attributes stack is empty")((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 752, __PRETTY_FUNCTION__))
;
753 auto &StackElem = *std::next(Stack.back().first.rbegin());
754 if (StackElem.LCVMap.size() < I)
755 return nullptr;
756 for (auto &Pair : StackElem.LCVMap)
757 if (Pair.second.first == I)
758 return Pair.first;
759 return nullptr;
760}
761
762void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
763 DeclRefExpr *PrivateCopy) {
764 D = getCanonicalDecl(D);
765 if (A == OMPC_threadprivate) {
766 auto &Data = Threadprivates[D];
767 Data.Attributes = A;
768 Data.RefExpr.setPointer(E);
769 Data.PrivateCopy = nullptr;
770 } else {
771 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 771, __PRETTY_FUNCTION__))
;
772 auto &Data = Stack.back().first.back().SharingMap[D];
773 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 776, __PRETTY_FUNCTION__))
774 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 776, __PRETTY_FUNCTION__))
775 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 776, __PRETTY_FUNCTION__))
776 (isLoopControlVariable(D).first && A == OMPC_private))((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 776, __PRETTY_FUNCTION__))
;
777 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
778 Data.RefExpr.setInt(/*IntVal=*/true);
779 return;
780 }
781 const bool IsLastprivate =
782 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
783 Data.Attributes = A;
784 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
785 Data.PrivateCopy = PrivateCopy;
786 if (PrivateCopy) {
787 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
788 Data.Attributes = A;
789 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
790 Data.PrivateCopy = nullptr;
791 }
792 }
793}
794
795/// \brief Build a variable declaration for OpenMP loop iteration variable.
796static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
797 StringRef Name, const AttrVec *Attrs = nullptr) {
798 DeclContext *DC = SemaRef.CurContext;
799 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
800 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
801 VarDecl *Decl =
802 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
803 if (Attrs) {
804 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
805 I != E; ++I)
806 Decl->addAttr(*I);
807 }
808 Decl->setImplicit();
809 return Decl;
810}
811
812static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
813 SourceLocation Loc,
814 bool RefersToCapture = false) {
815 D->setReferenced();
816 D->markUsed(S.Context);
817 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
818 SourceLocation(), D, RefersToCapture, Loc, Ty,
819 VK_LValue);
820}
821
822void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
823 BinaryOperatorKind BOK) {
824 D = getCanonicalDecl(D);
825 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 825, __PRETTY_FUNCTION__))
;
826 assert(((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 828, __PRETTY_FUNCTION__))
827 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 828, __PRETTY_FUNCTION__))
828 "Additional reduction info may be specified only for reduction items.")((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 828, __PRETTY_FUNCTION__))
;
829 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
830 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 833, __PRETTY_FUNCTION__))
831 Stack.back().first.back().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 833, __PRETTY_FUNCTION__))
832 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 833, __PRETTY_FUNCTION__))
833 "items.")((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 833, __PRETTY_FUNCTION__))
;
834 ReductionData.set(BOK, SR);
835 Expr *&TaskgroupReductionRef =
836 Stack.back().first.back().TaskgroupReductionRef;
837 if (!TaskgroupReductionRef) {
838 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
839 SemaRef.Context.VoidPtrTy, ".task_red.");
840 TaskgroupReductionRef =
841 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
842 }
843}
844
845void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
846 const Expr *ReductionRef) {
847 D = getCanonicalDecl(D);
848 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 848, __PRETTY_FUNCTION__))
;
849 assert(((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 851, __PRETTY_FUNCTION__))
850 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 851, __PRETTY_FUNCTION__))
851 "Additional reduction info may be specified only for reduction items.")((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 851, __PRETTY_FUNCTION__))
;
852 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
853 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 856, __PRETTY_FUNCTION__))
854 Stack.back().first.back().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 856, __PRETTY_FUNCTION__))
855 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 856, __PRETTY_FUNCTION__))
856 "items.")((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 856, __PRETTY_FUNCTION__))
;
857 ReductionData.set(ReductionRef, SR);
858 Expr *&TaskgroupReductionRef =
859 Stack.back().first.back().TaskgroupReductionRef;
860 if (!TaskgroupReductionRef) {
861 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
862 ".task_red.");
863 TaskgroupReductionRef =
864 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
865 }
866}
867
868DSAStackTy::DSAVarData
869DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
870 BinaryOperatorKind &BOK,
871 Expr *&TaskgroupDescriptor) {
872 D = getCanonicalDecl(D);
873 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 873, __PRETTY_FUNCTION__))
;
874 if (Stack.back().first.empty())
875 return DSAVarData();
876 for (auto I = std::next(Stack.back().first.rbegin(), 1),
877 E = Stack.back().first.rend();
878 I != E; std::advance(I, 1)) {
879 auto &Data = I->SharingMap[D];
880 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
881 continue;
882 auto &ReductionData = I->ReductionMap[D];
883 if (!ReductionData.ReductionOp ||
884 ReductionData.ReductionOp.is<const Expr *>())
885 return DSAVarData();
886 SR = ReductionData.ReductionRange;
887 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
888 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 890, __PRETTY_FUNCTION__))
889 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 890, __PRETTY_FUNCTION__))
890 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 890, __PRETTY_FUNCTION__))
;
891 TaskgroupDescriptor = I->TaskgroupReductionRef;
892 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
893 Data.PrivateCopy, I->DefaultAttrLoc);
894 }
895 return DSAVarData();
896}
897
898DSAStackTy::DSAVarData
899DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
900 const Expr *&ReductionRef,
901 Expr *&TaskgroupDescriptor) {
902 D = getCanonicalDecl(D);
903 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 903, __PRETTY_FUNCTION__))
;
904 if (Stack.back().first.empty())
905 return DSAVarData();
906 for (auto I = std::next(Stack.back().first.rbegin(), 1),
907 E = Stack.back().first.rend();
908 I != E; std::advance(I, 1)) {
909 auto &Data = I->SharingMap[D];
910 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
911 continue;
912 auto &ReductionData = I->ReductionMap[D];
913 if (!ReductionData.ReductionOp ||
914 !ReductionData.ReductionOp.is<const Expr *>())
915 return DSAVarData();
916 SR = ReductionData.ReductionRange;
917 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
918 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 920, __PRETTY_FUNCTION__))
919 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 920, __PRETTY_FUNCTION__))
920 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 920, __PRETTY_FUNCTION__))
;
921 TaskgroupDescriptor = I->TaskgroupReductionRef;
922 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
923 Data.PrivateCopy, I->DefaultAttrLoc);
924 }
925 return DSAVarData();
926}
927
928bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
929 D = D->getCanonicalDecl();
930 if (!isStackEmpty() && Stack.back().first.size() > 1) {
931 reverse_iterator I = Iter, E = Stack.back().first.rend();
932 Scope *TopScope = nullptr;
933 while (I != E && !isParallelOrTaskRegion(I->Directive))
934 ++I;
935 if (I == E)
936 return false;
937 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
938 Scope *CurScope = getCurScope();
939 while (CurScope != TopScope && !CurScope->isDeclScope(D))
940 CurScope = CurScope->getParent();
941 return CurScope != TopScope;
942 }
943 return false;
944}
945
946DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
947 D = getCanonicalDecl(D);
948 DSAVarData DVar;
949
950 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
951 // in a Construct, C/C++, predetermined, p.1]
952 // Variables appearing in threadprivate directives are threadprivate.
953 auto *VD = dyn_cast<VarDecl>(D);
954 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
955 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
956 SemaRef.getLangOpts().OpenMPUseTLS &&
957 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
958 (VD && VD->getStorageClass() == SC_Register &&
959 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
960 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
961 D->getLocation()),
962 OMPC_threadprivate);
963 }
964 auto TI = Threadprivates.find(D);
965 if (TI != Threadprivates.end()) {
966 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
967 DVar.CKind = OMPC_threadprivate;
968 return DVar;
969 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
970 DVar.RefExpr = buildDeclRefExpr(
971 SemaRef, VD, D->getType().getNonReferenceType(),
972 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
973 DVar.CKind = OMPC_threadprivate;
974 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
975 }
976
977 if (isStackEmpty())
978 // Not in OpenMP execution region and top scope was already checked.
979 return DVar;
980
981 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
982 // in a Construct, C/C++, predetermined, p.4]
983 // Static data members are shared.
984 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
985 // in a Construct, C/C++, predetermined, p.7]
986 // Variables with static storage duration that are declared in a scope
987 // inside the construct are shared.
988 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
989 if (VD && VD->isStaticDataMember()) {
990 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
991 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
992 return DVar;
993
994 DVar.CKind = OMPC_shared;
995 return DVar;
996 }
997
998 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
999 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1000 Type = SemaRef.getASTContext().getBaseElementType(Type);
1001 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1002 // in a Construct, C/C++, predetermined, p.6]
1003 // Variables with const qualified type having no mutable member are
1004 // shared.
1005 CXXRecordDecl *RD =
1006 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1007 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1008 if (auto *CTD = CTSD->getSpecializedTemplate())
1009 RD = CTD->getTemplatedDecl();
1010 if (IsConstant &&
1011 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1012 RD->hasMutableFields())) {
1013 // Variables with const-qualified type having no mutable member may be
1014 // listed in a firstprivate clause, even if they are static data members.
1015 DSAVarData DVarTemp = hasDSA(
1016 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1017 MatchesAlways, FromParent);
1018 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1019 return DVar;
1020
1021 DVar.CKind = OMPC_shared;
1022 return DVar;
1023 }
1024
1025 // Explicitly specified attributes and local variables with predetermined
1026 // attributes.
1027 auto I = Stack.back().first.rbegin();
1028 auto EndI = Stack.back().first.rend();
1029 if (FromParent && I != EndI)
1030 std::advance(I, 1);
1031 if (I->SharingMap.count(D)) {
1032 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
1033 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
1034 DVar.CKind = I->SharingMap[D].Attributes;
1035 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1036 DVar.DKind = I->Directive;
1037 }
1038
1039 return DVar;
1040}
1041
1042DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1043 bool FromParent) {
1044 if (isStackEmpty()) {
1045 StackTy::reverse_iterator I;
1046 return getDSA(I, D);
1047 }
1048 D = getCanonicalDecl(D);
1049 auto StartI = Stack.back().first.rbegin();
1050 auto EndI = Stack.back().first.rend();
1051 if (FromParent && StartI != EndI)
1052 std::advance(StartI, 1);
1053 return getDSA(StartI, D);
1054}
1055
1056DSAStackTy::DSAVarData
1057DSAStackTy::hasDSA(ValueDecl *D,
1058 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1059 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1060 bool FromParent) {
1061 if (isStackEmpty())
1062 return {};
1063 D = getCanonicalDecl(D);
1064 auto I = Stack.back().first.rbegin();
1065 auto EndI = Stack.back().first.rend();
1066 if (FromParent && I != EndI)
1067 std::advance(I, 1);
1068 for (; I != EndI; std::advance(I, 1)) {
1069 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1070 continue;
1071 auto NewI = I;
1072 DSAVarData DVar = getDSA(NewI, D);
1073 if (I == NewI && CPred(DVar.CKind))
1074 return DVar;
1075 }
1076 return {};
1077}
1078
1079DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1080 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1081 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1082 bool FromParent) {
1083 if (isStackEmpty())
1084 return {};
1085 D = getCanonicalDecl(D);
1086 auto StartI = Stack.back().first.rbegin();
1087 auto EndI = Stack.back().first.rend();
1088 if (FromParent && StartI != EndI)
1089 std::advance(StartI, 1);
1090 if (StartI == EndI || !DPred(StartI->Directive))
1091 return {};
1092 auto NewI = StartI;
1093 DSAVarData DVar = getDSA(NewI, D);
1094 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1095}
1096
1097bool DSAStackTy::hasExplicitDSA(
1098 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1099 unsigned Level, bool NotLastprivate) {
1100 if (CPred(ClauseKindMode))
1101 return true;
1102 if (isStackEmpty())
1103 return false;
1104 D = getCanonicalDecl(D);
1105 auto StartI = Stack.back().first.begin();
1106 auto EndI = Stack.back().first.end();
1107 if (std::distance(StartI, EndI) <= (int)Level)
1108 return false;
1109 std::advance(StartI, Level);
1110 return (StartI->SharingMap.count(D) > 0) &&
1111 StartI->SharingMap[D].RefExpr.getPointer() &&
1112 CPred(StartI->SharingMap[D].Attributes) &&
1113 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
1114}
1115
1116bool DSAStackTy::hasExplicitDirective(
1117 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1118 unsigned Level) {
1119 if (isStackEmpty())
1120 return false;
1121 auto StartI = Stack.back().first.begin();
1122 auto EndI = Stack.back().first.end();
1123 if (std::distance(StartI, EndI) <= (int)Level)
1124 return false;
1125 std::advance(StartI, Level);
1126 return DPred(StartI->Directive);
1127}
1128
1129bool DSAStackTy::hasDirective(
1130 const llvm::function_ref<bool(OpenMPDirectiveKind,
1131 const DeclarationNameInfo &, SourceLocation)>
1132 &DPred,
1133 bool FromParent) {
1134 // We look only in the enclosing region.
1135 if (isStackEmpty())
1136 return false;
1137 auto StartI = std::next(Stack.back().first.rbegin());
1138 auto EndI = Stack.back().first.rend();
1139 if (FromParent && StartI != EndI)
1140 StartI = std::next(StartI);
1141 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1142 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1143 return true;
1144 }
1145 return false;
1146}
1147
1148void Sema::InitDataSharingAttributesStack() {
1149 VarDataSharingAttributesStack = new DSAStackTy(*this);
1150}
1151
1152#define DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1153
1154void Sema::pushOpenMPFunctionRegion() {
1155 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pushFunction();
1156}
1157
1158void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1159 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->popFunction(OldFSI);
1160}
1161
1162bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
1163 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1163, __PRETTY_FUNCTION__))
;
1164
1165 auto &Ctx = getASTContext();
1166 bool IsByRef = true;
1167
1168 // Find the directive that is associated with the provided scope.
1169 D = cast<ValueDecl>(D->getCanonicalDecl());
1170 auto Ty = D->getType();
1171
1172 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1173 // This table summarizes how a given variable should be passed to the device
1174 // given its type and the clauses where it appears. This table is based on
1175 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1176 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1177 //
1178 // =========================================================================
1179 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1180 // | |(tofrom:scalar)| | pvt | | | |
1181 // =========================================================================
1182 // | scl | | | | - | | bycopy|
1183 // | scl | | - | x | - | - | bycopy|
1184 // | scl | | x | - | - | - | null |
1185 // | scl | x | | | - | | byref |
1186 // | scl | x | - | x | - | - | bycopy|
1187 // | scl | x | x | - | - | - | null |
1188 // | scl | | - | - | - | x | byref |
1189 // | scl | x | - | - | - | x | byref |
1190 //
1191 // | agg | n.a. | | | - | | byref |
1192 // | agg | n.a. | - | x | - | - | byref |
1193 // | agg | n.a. | x | - | - | - | null |
1194 // | agg | n.a. | - | - | - | x | byref |
1195 // | agg | n.a. | - | - | - | x[] | byref |
1196 //
1197 // | ptr | n.a. | | | - | | bycopy|
1198 // | ptr | n.a. | - | x | - | - | bycopy|
1199 // | ptr | n.a. | x | - | - | - | null |
1200 // | ptr | n.a. | - | - | - | x | byref |
1201 // | ptr | n.a. | - | - | - | x[] | bycopy|
1202 // | ptr | n.a. | - | - | x | | bycopy|
1203 // | ptr | n.a. | - | - | x | x | bycopy|
1204 // | ptr | n.a. | - | - | x | x[] | bycopy|
1205 // =========================================================================
1206 // Legend:
1207 // scl - scalar
1208 // ptr - pointer
1209 // agg - aggregate
1210 // x - applies
1211 // - - invalid in this combination
1212 // [] - mapped with an array section
1213 // byref - should be mapped by reference
1214 // byval - should be mapped by value
1215 // null - initialize a local variable to null on the device
1216 //
1217 // Observations:
1218 // - All scalar declarations that show up in a map clause have to be passed
1219 // by reference, because they may have been mapped in the enclosing data
1220 // environment.
1221 // - If the scalar value does not fit the size of uintptr, it has to be
1222 // passed by reference, regardless the result in the table above.
1223 // - For pointers mapped by value that have either an implicit map or an
1224 // array section, the runtime library may pass the NULL value to the
1225 // device instead of the value passed to it by the compiler.
1226
1227 if (Ty->isReferenceType())
1228 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1229
1230 // Locate map clauses and see if the variable being captured is referred to
1231 // in any of those clauses. Here we only care about variables, not fields,
1232 // because fields are part of aggregates.
1233 bool IsVariableUsedInMapClause = false;
1234 bool IsVariableAssociatedWithSection = false;
1235
1236 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
1237 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
1238 MapExprComponents,
1239 OpenMPClauseKind WhereFoundClauseKind) {
1240 // Only the map clause information influences how a variable is
1241 // captured. E.g. is_device_ptr does not require changing the default
1242 // behavior.
1243 if (WhereFoundClauseKind != OMPC_map)
1244 return false;
1245
1246 auto EI = MapExprComponents.rbegin();
1247 auto EE = MapExprComponents.rend();
1248
1249 assert(EI != EE && "Invalid map expression!")((EI != EE && "Invalid map expression!") ? static_cast
<void> (0) : __assert_fail ("EI != EE && \"Invalid map expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1249, __PRETTY_FUNCTION__))
;
1250
1251 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1252 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1253
1254 ++EI;
1255 if (EI == EE)
1256 return false;
1257
1258 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1259 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1260 isa<MemberExpr>(EI->getAssociatedExpression())) {
1261 IsVariableAssociatedWithSection = true;
1262 // There is nothing more we need to know about this variable.
1263 return true;
1264 }
1265
1266 // Keep looking for more map info.
1267 return false;
1268 });
1269
1270 if (IsVariableUsedInMapClause) {
1271 // If variable is identified in a map clause it is always captured by
1272 // reference except if it is a pointer that is dereferenced somehow.
1273 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1274 } else {
1275 // By default, all the data that has a scalar type is mapped by copy.
1276 IsByRef = !Ty->isScalarType() ||
1277 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
1278 }
1279 }
1280
1281 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1282 IsByRef = !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1283 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1284 Level, /*NotLastprivate=*/true);
1285 }
1286
1287 // When passing data by copy, we need to make sure it fits the uintptr size
1288 // and alignment, because the runtime library only deals with uintptr types.
1289 // If it does not fit the uintptr size, we need to pass the data by reference
1290 // instead.
1291 if (!IsByRef &&
1292 (Ctx.getTypeSizeInChars(Ty) >
1293 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1294 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1295 IsByRef = true;
1296 }
1297
1298 return IsByRef;
1299}
1300
1301unsigned Sema::getOpenMPNestingLevel() const {
1302 assert(getLangOpts().OpenMP)((getLangOpts().OpenMP) ? static_cast<void> (0) : __assert_fail
("getLangOpts().OpenMP", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1302, __PRETTY_FUNCTION__))
;
1303 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel();
1304}
1305
1306VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
1307 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1307, __PRETTY_FUNCTION__))
;
1308 D = getCanonicalDecl(D);
1309
1310 // If we are attempting to capture a global variable in a directive with
1311 // 'target' we return true so that this global is also mapped to the device.
1312 //
1313 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1314 // then it should not be captured. Therefore, an extra check has to be
1315 // inserted here once support for 'declare target' is added.
1316 //
1317 auto *VD = dyn_cast<VarDecl>(D);
1318 if (VD && !VD->hasLocalStorage()) {
1319 if (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
1320 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode())
1321 return VD;
1322 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDirective(
1323 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1324 SourceLocation) -> bool {
1325 return isOpenMPTargetExecutionDirective(K);
1326 },
1327 false))
1328 return VD;
1329 }
1330
1331 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() != OMPD_unknown &&
1332 (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode() ||
1333 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective() != OMPD_unknown)) {
1334 auto &&Info = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D);
1335 if (Info.first ||
1336 (VD && VD->hasLocalStorage() &&
1337 isParallelOrTaskRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) ||
1338 (VD && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing()))
1339 return VD ? VD : Info.second;
1340 auto DVarPrivate = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
11
Within the expansion of the macro 'DSAStack':
a
Null pointer value stored to 'DVarPrivate.PrivateCopy'
1341 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
12
Assuming the condition is true
13
Taking true branch
1342 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
14
'?' condition is false
15
Called C++ object pointer is null
1343 DVarPrivate = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDSA(
1344 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1345 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
1346 if (DVarPrivate.CKind != OMPC_unknown)
1347 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1348 }
1349 return nullptr;
1350}
1351
1352bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1353 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1353, __PRETTY_FUNCTION__))
;
1354 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1355 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1356 Level) ||
1357 // Consider taskgroup reduction descriptor variable a private to avoid
1358 // possible capture in the region.
1359 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(
1360 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1361 Level) &&
1362 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isTaskgroupReductionRef(D, Level));
1363}
1364
1365void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1366 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1366, __PRETTY_FUNCTION__))
;
1367 D = getCanonicalDecl(D);
1368 OpenMPClauseKind OMPC = OMPC_unknown;
1369 for (unsigned I = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel() + 1; I > Level; --I) {
1370 const unsigned NewLevel = I - 1;
1371 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(D,
1372 [&OMPC](const OpenMPClauseKind K) {
1373 if (isOpenMPPrivate(K)) {
1374 OMPC = K;
1375 return true;
1376 }
1377 return false;
1378 },
1379 NewLevel))
1380 break;
1381 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
1382 D, NewLevel,
1383 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1384 OpenMPClauseKind) { return true; })) {
1385 OMPC = OMPC_map;
1386 break;
1387 }
1388 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1389 NewLevel)) {
1390 OMPC = OMPC_firstprivate;
1391 break;
1392 }
1393 }
1394 if (OMPC != OMPC_unknown)
1395 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1396}
1397
1398bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1399 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1399, __PRETTY_FUNCTION__))
;
1400 // Return true if the current level is no longer enclosed in a target region.
1401
1402 auto *VD = dyn_cast<VarDecl>(D);
1403 return VD && !VD->hasLocalStorage() &&
1404 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1405 Level);
1406}
1407
1408void Sema::DestroyDataSharingAttributesStack() { delete DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
; }
1409
1410void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1411 const DeclarationNameInfo &DirName,
1412 Scope *CurScope, SourceLocation Loc) {
1413 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->push(DKind, DirName, CurScope, Loc);
1414 PushExpressionEvaluationContext(
1415 ExpressionEvaluationContext::PotentiallyEvaluated);
1416}
1417
1418void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1419 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(K);
1420}
1421
1422void Sema::EndOpenMPClause() {
1423 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(/*K=*/OMPC_unknown);
1424}
1425
1426void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1427 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1428 // A variable of class type (or array thereof) that appears in a lastprivate
1429 // clause requires an accessible, unambiguous default constructor for the
1430 // class type, unless the list item is also specified in a firstprivate
1431 // clause.
1432 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1433 for (auto *C : D->clauses()) {
1434 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1435 SmallVector<Expr *, 8> PrivateCopies;
1436 for (auto *DE : Clause->varlists()) {
1437 if (DE->isValueDependent() || DE->isTypeDependent()) {
1438 PrivateCopies.push_back(nullptr);
1439 continue;
1440 }
1441 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1442 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1443 QualType Type = VD->getType().getNonReferenceType();
1444 auto DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, false);
1445 if (DVar.CKind == OMPC_lastprivate) {
1446 // Generate helper private variable and initialize it with the
1447 // default value. The address of the original variable is replaced
1448 // by the address of the new private variable in CodeGen. This new
1449 // variable is not added to IdResolver, so the code in the OpenMP
1450 // region uses original variable for proper diagnostics.
1451 auto *VDPrivate = buildVarDecl(
1452 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1453 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1454 ActOnUninitializedDecl(VDPrivate);
1455 if (VDPrivate->isInvalidDecl())
1456 continue;
1457 PrivateCopies.push_back(buildDeclRefExpr(
1458 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1459 } else {
1460 // The variable is also a firstprivate, so initialization sequence
1461 // for private copy is generated already.
1462 PrivateCopies.push_back(nullptr);
1463 }
1464 }
1465 // Set initializers to private copies if no errors were found.
1466 if (PrivateCopies.size() == Clause->varlist_size())
1467 Clause->setPrivateCopies(PrivateCopies);
1468 }
1469 }
1470 }
1471
1472 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pop();
1473 DiscardCleanupsInEvaluationContext();
1474 PopExpressionEvaluationContext();
1475}
1476
1477static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1478 Expr *NumIterations, Sema &SemaRef,
1479 Scope *S, DSAStackTy *Stack);
1480
1481namespace {
1482
1483class VarDeclFilterCCC : public CorrectionCandidateCallback {
1484private:
1485 Sema &SemaRef;
1486
1487public:
1488 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1489 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1490 NamedDecl *ND = Candidate.getCorrectionDecl();
1491 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1492 return VD->hasGlobalStorage() &&
1493 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1494 SemaRef.getCurScope());
1495 }
1496 return false;
1497 }
1498};
1499
1500class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1501private:
1502 Sema &SemaRef;
1503
1504public:
1505 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1506 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1507 NamedDecl *ND = Candidate.getCorrectionDecl();
1508 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1509 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1510 SemaRef.getCurScope());
1511 }
1512 return false;
1513 }
1514};
1515
1516} // namespace
1517
1518ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1519 CXXScopeSpec &ScopeSpec,
1520 const DeclarationNameInfo &Id) {
1521 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1522 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1523
1524 if (Lookup.isAmbiguous())
1525 return ExprError();
1526
1527 VarDecl *VD;
1528 if (!Lookup.isSingleResult()) {
1529 if (TypoCorrection Corrected = CorrectTypo(
1530 Id, LookupOrdinaryName, CurScope, nullptr,
1531 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1532 diagnoseTypo(Corrected,
1533 PDiag(Lookup.empty()
1534 ? diag::err_undeclared_var_use_suggest
1535 : diag::err_omp_expected_var_arg_suggest)
1536 << Id.getName());
1537 VD = Corrected.getCorrectionDeclAs<VarDecl>();
1538 } else {
1539 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1540 : diag::err_omp_expected_var_arg)
1541 << Id.getName();
1542 return ExprError();
1543 }
1544 } else {
1545 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1546 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1547 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1548 return ExprError();
1549 }
1550 }
1551 Lookup.suppressDiagnostics();
1552
1553 // OpenMP [2.9.2, Syntax, C/C++]
1554 // Variables must be file-scope, namespace-scope, or static block-scope.
1555 if (!VD->hasGlobalStorage()) {
1556 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1557 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1558 bool IsDecl =
1559 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1560 Diag(VD->getLocation(),
1561 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1562 << VD;
1563 return ExprError();
1564 }
1565
1566 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1567 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1568 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1569 // A threadprivate directive for file-scope variables must appear outside
1570 // any definition or declaration.
1571 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1572 !getCurLexicalContext()->isTranslationUnit()) {
1573 Diag(Id.getLoc(), diag::err_omp_var_scope)
1574 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1575 bool IsDecl =
1576 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1577 Diag(VD->getLocation(),
1578 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1579 << VD;
1580 return ExprError();
1581 }
1582 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1583 // A threadprivate directive for static class member variables must appear
1584 // in the class definition, in the same scope in which the member
1585 // variables are declared.
1586 if (CanonicalVD->isStaticDataMember() &&
1587 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1588 Diag(Id.getLoc(), diag::err_omp_var_scope)
1589 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1590 bool IsDecl =
1591 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1592 Diag(VD->getLocation(),
1593 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1594 << VD;
1595 return ExprError();
1596 }
1597 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1598 // A threadprivate directive for namespace-scope variables must appear
1599 // outside any definition or declaration other than the namespace
1600 // definition itself.
1601 if (CanonicalVD->getDeclContext()->isNamespace() &&
1602 (!getCurLexicalContext()->isFileContext() ||
1603 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1604 Diag(Id.getLoc(), diag::err_omp_var_scope)
1605 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1606 bool IsDecl =
1607 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1608 Diag(VD->getLocation(),
1609 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1610 << VD;
1611 return ExprError();
1612 }
1613 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1614 // A threadprivate directive for static block-scope variables must appear
1615 // in the scope of the variable and not in a nested scope.
1616 if (CanonicalVD->isStaticLocal() && CurScope &&
1617 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1618 Diag(Id.getLoc(), diag::err_omp_var_scope)
1619 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1620 bool IsDecl =
1621 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1622 Diag(VD->getLocation(),
1623 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1624 << VD;
1625 return ExprError();
1626 }
1627
1628 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1629 // A threadprivate directive must lexically precede all references to any
1630 // of the variables in its list.
1631 if (VD->isUsed() && !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
1632 Diag(Id.getLoc(), diag::err_omp_var_used)
1633 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1634 return ExprError();
1635 }
1636
1637 QualType ExprType = VD->getType().getNonReferenceType();
1638 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1639 SourceLocation(), VD,
1640 /*RefersToEnclosingVariableOrCapture=*/false,
1641 Id.getLoc(), ExprType, VK_LValue);
1642}
1643
1644Sema::DeclGroupPtrTy
1645Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1646 ArrayRef<Expr *> VarList) {
1647 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1648 CurContext->addDecl(D);
1649 return DeclGroupPtrTy::make(DeclGroupRef(D));
1650 }
1651 return nullptr;
1652}
1653
1654namespace {
1655class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1656 Sema &SemaRef;
1657
1658public:
1659 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1660 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1661 if (VD->hasLocalStorage()) {
1662 SemaRef.Diag(E->getLocStart(),
1663 diag::err_omp_local_var_in_threadprivate_init)
1664 << E->getSourceRange();
1665 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1666 << VD << VD->getSourceRange();
1667 return true;
1668 }
1669 }
1670 return false;
1671 }
1672 bool VisitStmt(const Stmt *S) {
1673 for (auto Child : S->children()) {
1674 if (Child && Visit(Child))
1675 return true;
1676 }
1677 return false;
1678 }
1679 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1680};
1681} // namespace
1682
1683OMPThreadPrivateDecl *
1684Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1685 SmallVector<Expr *, 8> Vars;
1686 for (auto &RefExpr : VarList) {
1687 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1688 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1689 SourceLocation ILoc = DE->getExprLoc();
1690
1691 // Mark variable as used.
1692 VD->setReferenced();
1693 VD->markUsed(Context);
1694
1695 QualType QType = VD->getType();
1696 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1697 // It will be analyzed later.
1698 Vars.push_back(DE);
1699 continue;
1700 }
1701
1702 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1703 // A threadprivate variable must not have an incomplete type.
1704 if (RequireCompleteType(ILoc, VD->getType(),
1705 diag::err_omp_threadprivate_incomplete_type)) {
1706 continue;
1707 }
1708
1709 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1710 // A threadprivate variable must not have a reference type.
1711 if (VD->getType()->isReferenceType()) {
1712 Diag(ILoc, diag::err_omp_ref_type_arg)
1713 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1714 bool IsDecl =
1715 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1716 Diag(VD->getLocation(),
1717 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1718 << VD;
1719 continue;
1720 }
1721
1722 // Check if this is a TLS variable. If TLS is not being supported, produce
1723 // the corresponding diagnostic.
1724 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1725 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1726 getLangOpts().OpenMPUseTLS &&
1727 getASTContext().getTargetInfo().isTLSSupported())) ||
1728 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1729 !VD->isLocalVarDecl())) {
1730 Diag(ILoc, diag::err_omp_var_thread_local)
1731 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1732 bool IsDecl =
1733 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1734 Diag(VD->getLocation(),
1735 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1736 << VD;
1737 continue;
1738 }
1739
1740 // Check if initial value of threadprivate variable reference variable with
1741 // local storage (it is not supported by runtime).
1742 if (auto Init = VD->getAnyInitializer()) {
1743 LocalVarRefChecker Checker(*this);
1744 if (Checker.Visit(Init))
1745 continue;
1746 }
1747
1748 Vars.push_back(RefExpr);
1749 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(VD, DE, OMPC_threadprivate);
1750 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1751 Context, SourceRange(Loc, Loc)));
1752 if (auto *ML = Context.getASTMutationListener())
1753 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1754 }
1755 OMPThreadPrivateDecl *D = nullptr;
1756 if (!Vars.empty()) {
1757 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1758 Vars);
1759 D->setAccess(AS_public);
1760 }
1761 return D;
1762}
1763
1764static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1765 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1766 bool IsLoopIterVar = false) {
1767 if (DVar.RefExpr) {
1768 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1769 << getOpenMPClauseName(DVar.CKind);
1770 return;
1771 }
1772 enum {
1773 PDSA_StaticMemberShared,
1774 PDSA_StaticLocalVarShared,
1775 PDSA_LoopIterVarPrivate,
1776 PDSA_LoopIterVarLinear,
1777 PDSA_LoopIterVarLastprivate,
1778 PDSA_ConstVarShared,
1779 PDSA_GlobalVarShared,
1780 PDSA_TaskVarFirstprivate,
1781 PDSA_LocalVarPrivate,
1782 PDSA_Implicit
1783 } Reason = PDSA_Implicit;
1784 bool ReportHint = false;
1785 auto ReportLoc = D->getLocation();
1786 auto *VD = dyn_cast<VarDecl>(D);
1787 if (IsLoopIterVar) {
1788 if (DVar.CKind == OMPC_private)
1789 Reason = PDSA_LoopIterVarPrivate;
1790 else if (DVar.CKind == OMPC_lastprivate)
1791 Reason = PDSA_LoopIterVarLastprivate;
1792 else
1793 Reason = PDSA_LoopIterVarLinear;
1794 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1795 DVar.CKind == OMPC_firstprivate) {
1796 Reason = PDSA_TaskVarFirstprivate;
1797 ReportLoc = DVar.ImplicitDSALoc;
1798 } else if (VD && VD->isStaticLocal())
1799 Reason = PDSA_StaticLocalVarShared;
1800 else if (VD && VD->isStaticDataMember())
1801 Reason = PDSA_StaticMemberShared;
1802 else if (VD && VD->isFileVarDecl())
1803 Reason = PDSA_GlobalVarShared;
1804 else if (D->getType().isConstant(SemaRef.getASTContext()))
1805 Reason = PDSA_ConstVarShared;
1806 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1807 ReportHint = true;
1808 Reason = PDSA_LocalVarPrivate;
1809 }
1810 if (Reason != PDSA_Implicit) {
1811 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1812 << Reason << ReportHint
1813 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1814 } else if (DVar.ImplicitDSALoc.isValid()) {
1815 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1816 << getOpenMPClauseName(DVar.CKind);
1817 }
1818}
1819
1820namespace {
1821class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1822 DSAStackTy *Stack;
1823 Sema &SemaRef;
1824 bool ErrorFound;
1825 CapturedStmt *CS;
1826 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1827 llvm::SmallVector<Expr *, 8> ImplicitMap;
1828 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1829 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
1830
1831public:
1832 void VisitDeclRefExpr(DeclRefExpr *E) {
1833 if (E->isTypeDependent() || E->isValueDependent() ||
1834 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1835 return;
1836 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1837 VD = VD->getCanonicalDecl();
1838 // Skip internally declared variables.
1839 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
1840 return;
1841
1842 auto DVar = Stack->getTopDSA(VD, false);
1843 // Check if the variable has explicit DSA set and stop analysis if it so.
1844 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
1845 return;
1846
1847 // Skip internally declared static variables.
1848 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1849 return;
1850
1851 auto ELoc = E->getExprLoc();
1852 auto DKind = Stack->getCurrentDirective();
1853 // The default(none) clause requires that each variable that is referenced
1854 // in the construct, and does not have a predetermined data-sharing
1855 // attribute, must have its data-sharing attribute explicitly determined
1856 // by being listed in a data-sharing attribute clause.
1857 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1858 isParallelOrTaskRegion(DKind) &&
1859 VarsWithInheritedDSA.count(VD) == 0) {
1860 VarsWithInheritedDSA[VD] = E;
1861 return;
1862 }
1863
1864 if (isOpenMPTargetExecutionDirective(DKind) &&
1865 !Stack->isLoopControlVariable(VD).first) {
1866 if (!Stack->checkMappableExprComponentListsForDecl(
1867 VD, /*CurrentRegionOnly=*/true,
1868 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1869 StackComponents,
1870 OpenMPClauseKind) {
1871 // Variable is used if it has been marked as an array, array
1872 // section or the variable iself.
1873 return StackComponents.size() == 1 ||
1874 std::all_of(
1875 std::next(StackComponents.rbegin()),
1876 StackComponents.rend(),
1877 [](const OMPClauseMappableExprCommon::
1878 MappableComponent &MC) {
1879 return MC.getAssociatedDeclaration() ==
1880 nullptr &&
1881 (isa<OMPArraySectionExpr>(
1882 MC.getAssociatedExpression()) ||
1883 isa<ArraySubscriptExpr>(
1884 MC.getAssociatedExpression()));
1885 });
1886 })) {
1887 bool IsFirstprivate = false;
1888 // By default lambdas are captured as firstprivates.
1889 if (const auto *RD =
1890 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
1891 IsFirstprivate = RD->isLambda();
1892 IsFirstprivate =
1893 IsFirstprivate ||
1894 (VD->getType().getNonReferenceType()->isScalarType() &&
1895 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1896 if (IsFirstprivate)
1897 ImplicitFirstprivate.emplace_back(E);
1898 else
1899 ImplicitMap.emplace_back(E);
1900 return;
1901 }
1902 }
1903
1904 // OpenMP [2.9.3.6, Restrictions, p.2]
1905 // A list item that appears in a reduction clause of the innermost
1906 // enclosing worksharing or parallel construct may not be accessed in an
1907 // explicit task.
1908 DVar = Stack->hasInnermostDSA(
1909 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1910 [](OpenMPDirectiveKind K) -> bool {
1911 return isOpenMPParallelDirective(K) ||
1912 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1913 },
1914 /*FromParent=*/true);
1915 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1916 ErrorFound = true;
1917 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1918 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1919 return;
1920 }
1921
1922 // Define implicit data-sharing attributes for task.
1923 DVar = Stack->getImplicitDSA(VD, false);
1924 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1925 !Stack->isLoopControlVariable(VD).first)
1926 ImplicitFirstprivate.push_back(E);
1927 }
1928 }
1929 void VisitMemberExpr(MemberExpr *E) {
1930 if (E->isTypeDependent() || E->isValueDependent() ||
1931 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1932 return;
1933 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1934 if (!FD)
1935 return;
1936 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
1937 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1938 auto DVar = Stack->getTopDSA(FD, false);
1939 // Check if the variable has explicit DSA set and stop analysis if it
1940 // so.
1941 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1942 return;
1943
1944 if (isOpenMPTargetExecutionDirective(DKind) &&
1945 !Stack->isLoopControlVariable(FD).first &&
1946 !Stack->checkMappableExprComponentListsForDecl(
1947 FD, /*CurrentRegionOnly=*/true,
1948 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1949 StackComponents,
1950 OpenMPClauseKind) {
1951 return isa<CXXThisExpr>(
1952 cast<MemberExpr>(
1953 StackComponents.back().getAssociatedExpression())
1954 ->getBase()
1955 ->IgnoreParens());
1956 })) {
1957 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1958 // A bit-field cannot appear in a map clause.
1959 //
1960 if (FD->isBitField()) {
1961 SemaRef.Diag(E->getMemberLoc(),
1962 diag::err_omp_bit_fields_forbidden_in_clause)
1963 << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
1964 return;
1965 }
1966 ImplicitMap.emplace_back(E);
1967 return;
1968 }
1969
1970 auto ELoc = E->getExprLoc();
1971 // OpenMP [2.9.3.6, Restrictions, p.2]
1972 // A list item that appears in a reduction clause of the innermost
1973 // enclosing worksharing or parallel construct may not be accessed in
1974 // an explicit task.
1975 DVar = Stack->hasInnermostDSA(
1976 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1977 [](OpenMPDirectiveKind K) -> bool {
1978 return isOpenMPParallelDirective(K) ||
1979 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1980 },
1981 /*FromParent=*/true);
1982 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1983 ErrorFound = true;
1984 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1985 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1986 return;
1987 }
1988
1989 // Define implicit data-sharing attributes for task.
1990 DVar = Stack->getImplicitDSA(FD, false);
1991 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1992 !Stack->isLoopControlVariable(FD).first)
1993 ImplicitFirstprivate.push_back(E);
1994 return;
1995 }
1996 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
1997 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
1998 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
1999 auto *VD = cast<ValueDecl>(
2000 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2001 if (!Stack->checkMappableExprComponentListsForDecl(
2002 VD, /*CurrentRegionOnly=*/true,
2003 [&CurComponents](
2004 OMPClauseMappableExprCommon::MappableExprComponentListRef
2005 StackComponents,
2006 OpenMPClauseKind) {
2007 auto CCI = CurComponents.rbegin();
2008 auto CCE = CurComponents.rend();
2009 for (const auto &SC : llvm::reverse(StackComponents)) {
2010 // Do both expressions have the same kind?
2011 if (CCI->getAssociatedExpression()->getStmtClass() !=
2012 SC.getAssociatedExpression()->getStmtClass())
2013 if (!(isa<OMPArraySectionExpr>(
2014 SC.getAssociatedExpression()) &&
2015 isa<ArraySubscriptExpr>(
2016 CCI->getAssociatedExpression())))
2017 return false;
2018
2019 Decl *CCD = CCI->getAssociatedDeclaration();
2020 Decl *SCD = SC.getAssociatedDeclaration();
2021 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2022 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2023 if (SCD != CCD)
2024 return false;
2025 std::advance(CCI, 1);
2026 if (CCI == CCE)
2027 break;
2028 }
2029 return true;
2030 })) {
2031 Visit(E->getBase());
2032 }
2033 } else
2034 Visit(E->getBase());
2035 }
2036 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2037 for (auto *C : S->clauses()) {
2038 // Skip analysis of arguments of implicitly defined firstprivate clause
2039 // for task|target directives.
2040 // Skip analysis of arguments of implicitly defined map clause for target
2041 // directives.
2042 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2043 C->isImplicit())) {
2044 for (auto *CC : C->children()) {
2045 if (CC)
2046 Visit(CC);
2047 }
2048 }
2049 }
2050 }
2051 void VisitStmt(Stmt *S) {
2052 for (auto *C : S->children()) {
2053 if (C && !isa<OMPExecutableDirective>(C))
2054 Visit(C);
2055 }
2056 }
2057
2058 bool isErrorFound() { return ErrorFound; }
2059 ArrayRef<Expr *> getImplicitFirstprivate() const {
2060 return ImplicitFirstprivate;
2061 }
2062 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2063 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
2064 return VarsWithInheritedDSA;
2065 }
2066
2067 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2068 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2069};
2070} // namespace
2071
2072void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2073 switch (DKind) {
2074 case OMPD_parallel:
2075 case OMPD_parallel_for:
2076 case OMPD_parallel_for_simd:
2077 case OMPD_parallel_sections:
2078 case OMPD_teams:
2079 case OMPD_teams_distribute: {
2080 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2081 QualType KmpInt32PtrTy =
2082 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2083 Sema::CapturedParamNameType Params[] = {
2084 std::make_pair(".global_tid.", KmpInt32PtrTy),
2085 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2086 std::make_pair(StringRef(), QualType()) // __context with shared vars
2087 };
2088 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2089 Params);
2090 break;
2091 }
2092 case OMPD_target_teams:
2093 case OMPD_target_parallel:
2094 case OMPD_target_parallel_for:
2095 case OMPD_target_parallel_for_simd: {
2096 Sema::CapturedParamNameType ParamsTarget[] = {
2097 std::make_pair(StringRef(), QualType()) // __context with shared vars
2098 };
2099 // Start a captured region for 'target' with no implicit parameters.
2100 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2101 ParamsTarget);
2102 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2103 QualType KmpInt32PtrTy =
2104 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2105 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2106 std::make_pair(".global_tid.", KmpInt32PtrTy),
2107 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2108 std::make_pair(StringRef(), QualType()) // __context with shared vars
2109 };
2110 // Start a captured region for 'teams' or 'parallel'. Both regions have
2111 // the same implicit parameters.
2112 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2113 ParamsTeamsOrParallel);
2114 break;
2115 }
2116 case OMPD_simd:
2117 case OMPD_for:
2118 case OMPD_for_simd:
2119 case OMPD_sections:
2120 case OMPD_section:
2121 case OMPD_single:
2122 case OMPD_master:
2123 case OMPD_critical:
2124 case OMPD_taskgroup:
2125 case OMPD_distribute:
2126 case OMPD_ordered:
2127 case OMPD_atomic:
2128 case OMPD_target_data:
2129 case OMPD_target:
2130 case OMPD_target_simd: {
2131 Sema::CapturedParamNameType Params[] = {
2132 std::make_pair(StringRef(), QualType()) // __context with shared vars
2133 };
2134 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2135 Params);
2136 break;
2137 }
2138 case OMPD_task: {
2139 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2140 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2141 FunctionProtoType::ExtProtoInfo EPI;
2142 EPI.Variadic = true;
2143 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2144 Sema::CapturedParamNameType Params[] = {
2145 std::make_pair(".global_tid.", KmpInt32Ty),
2146 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2147 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2148 std::make_pair(".copy_fn.",
2149 Context.getPointerType(CopyFnType).withConst()),
2150 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2151 std::make_pair(StringRef(), QualType()) // __context with shared vars
2152 };
2153 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2154 Params);
2155 // Mark this captured region as inlined, because we don't use outlined
2156 // function directly.
2157 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2158 AlwaysInlineAttr::CreateImplicit(
2159 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2160 break;
2161 }
2162 case OMPD_taskloop:
2163 case OMPD_taskloop_simd: {
2164 QualType KmpInt32Ty =
2165 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2166 QualType KmpUInt64Ty =
2167 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2168 QualType KmpInt64Ty =
2169 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2170 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2171 FunctionProtoType::ExtProtoInfo EPI;
2172 EPI.Variadic = true;
2173 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2174 Sema::CapturedParamNameType Params[] = {
2175 std::make_pair(".global_tid.", KmpInt32Ty),
2176 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2177 std::make_pair(".privates.",
2178 Context.VoidPtrTy.withConst().withRestrict()),
2179 std::make_pair(
2180 ".copy_fn.",
2181 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2182 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2183 std::make_pair(".lb.", KmpUInt64Ty),
2184 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2185 std::make_pair(".liter.", KmpInt32Ty),
2186 std::make_pair(".reductions.",
2187 Context.VoidPtrTy.withConst().withRestrict()),
2188 std::make_pair(StringRef(), QualType()) // __context with shared vars
2189 };
2190 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2191 Params);
2192 // Mark this captured region as inlined, because we don't use outlined
2193 // function directly.
2194 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2195 AlwaysInlineAttr::CreateImplicit(
2196 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2197 break;
2198 }
2199 case OMPD_distribute_parallel_for_simd:
2200 case OMPD_distribute_simd:
2201 case OMPD_distribute_parallel_for:
2202 case OMPD_teams_distribute_simd:
2203 case OMPD_teams_distribute_parallel_for_simd:
2204 case OMPD_teams_distribute_parallel_for:
2205 case OMPD_target_teams_distribute:
2206 case OMPD_target_teams_distribute_parallel_for:
2207 case OMPD_target_teams_distribute_parallel_for_simd:
2208 case OMPD_target_teams_distribute_simd: {
2209 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2210 QualType KmpInt32PtrTy =
2211 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2212 Sema::CapturedParamNameType Params[] = {
2213 std::make_pair(".global_tid.", KmpInt32PtrTy),
2214 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2215 std::make_pair(".previous.lb.", Context.getSizeType()),
2216 std::make_pair(".previous.ub.", Context.getSizeType()),
2217 std::make_pair(StringRef(), QualType()) // __context with shared vars
2218 };
2219 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2220 Params);
2221 break;
2222 }
2223 case OMPD_threadprivate:
2224 case OMPD_taskyield:
2225 case OMPD_barrier:
2226 case OMPD_taskwait:
2227 case OMPD_cancellation_point:
2228 case OMPD_cancel:
2229 case OMPD_flush:
2230 case OMPD_target_enter_data:
2231 case OMPD_target_exit_data:
2232 case OMPD_declare_reduction:
2233 case OMPD_declare_simd:
2234 case OMPD_declare_target:
2235 case OMPD_end_declare_target:
2236 case OMPD_target_update:
2237 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2237)
;
2238 case OMPD_unknown:
2239 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2239)
;
2240 }
2241}
2242
2243int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2244 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2245 getOpenMPCaptureRegions(CaptureRegions, DKind);
2246 return CaptureRegions.size();
2247}
2248
2249static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2250 Expr *CaptureExpr, bool WithInit,
2251 bool AsExpression) {
2252 assert(CaptureExpr)((CaptureExpr) ? static_cast<void> (0) : __assert_fail (
"CaptureExpr", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2252, __PRETTY_FUNCTION__))
;
2253 ASTContext &C = S.getASTContext();
2254 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2255 QualType Ty = Init->getType();
2256 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2257 if (S.getLangOpts().CPlusPlus)
2258 Ty = C.getLValueReferenceType(Ty);
2259 else {
2260 Ty = C.getPointerType(Ty);
2261 ExprResult Res =
2262 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2263 if (!Res.isUsable())
2264 return nullptr;
2265 Init = Res.get();
2266 }
2267 WithInit = true;
2268 }
2269 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2270 CaptureExpr->getLocStart());
2271 if (!WithInit)
2272 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
2273 S.CurContext->addHiddenDecl(CED);
2274 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2275 return CED;
2276}
2277
2278static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2279 bool WithInit) {
2280 OMPCapturedExprDecl *CD;
2281 if (auto *VD = S.IsOpenMPCapturedDecl(D))
10
Calling 'Sema::IsOpenMPCapturedDecl'
2282 CD = cast<OMPCapturedExprDecl>(VD);
2283 else
2284 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2285 /*AsExpression=*/false);
2286 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2287 CaptureExpr->getExprLoc());
2288}
2289
2290static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2291 if (!Ref) {
2292 auto *CD =
2293 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2294 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2295 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2296 CaptureExpr->getExprLoc());
2297 }
2298 ExprResult Res = Ref;
2299 if (!S.getLangOpts().CPlusPlus &&
2300 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2301 Ref->getType()->isPointerType())
2302 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2303 if (!Res.isUsable())
2304 return ExprError();
2305 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
2306}
2307
2308namespace {
2309// OpenMP directives parsed in this section are represented as a
2310// CapturedStatement with an associated statement. If a syntax error
2311// is detected during the parsing of the associated statement, the
2312// compiler must abort processing and close the CapturedStatement.
2313//
2314// Combined directives such as 'target parallel' have more than one
2315// nested CapturedStatements. This RAII ensures that we unwind out
2316// of all the nested CapturedStatements when an error is found.
2317class CaptureRegionUnwinderRAII {
2318private:
2319 Sema &S;
2320 bool &ErrorFound;
2321 OpenMPDirectiveKind DKind;
2322
2323public:
2324 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2325 OpenMPDirectiveKind DKind)
2326 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2327 ~CaptureRegionUnwinderRAII() {
2328 if (ErrorFound) {
2329 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2330 while (--ThisCaptureLevel >= 0)
2331 S.ActOnCapturedRegionError();
2332 }
2333 }
2334};
2335} // namespace
2336
2337StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2338 ArrayRef<OMPClause *> Clauses) {
2339 bool ErrorFound = false;
2340 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2341 *this, ErrorFound, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
2342 if (!S.isUsable()) {
2343 ErrorFound = true;
2344 return StmtError();
2345 }
2346
2347 OMPOrderedClause *OC = nullptr;
2348 OMPScheduleClause *SC = nullptr;
2349 SmallVector<OMPLinearClause *, 4> LCs;
2350 SmallVector<OMPClauseWithPreInit *, 8> PICs;
2351 // This is required for proper codegen.
2352 for (auto *Clause : Clauses) {
2353 if (isOpenMPTaskingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
2354 Clause->getClauseKind() == OMPC_in_reduction) {
2355 // Capture taskgroup task_reduction descriptors inside the tasking regions
2356 // with the corresponding in_reduction items.
2357 auto *IRC = cast<OMPInReductionClause>(Clause);
2358 for (auto *E : IRC->taskgroup_descriptors())
2359 if (E)
2360 MarkDeclarationsReferencedInExpr(E);
2361 }
2362 if (isOpenMPPrivate(Clause->getClauseKind()) ||
2363 Clause->getClauseKind() == OMPC_copyprivate ||
2364 (getLangOpts().OpenMPUseTLS &&
2365 getASTContext().getTargetInfo().isTLSSupported() &&
2366 Clause->getClauseKind() == OMPC_copyin)) {
2367 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2368 // Mark all variables in private list clauses as used in inner region.
2369 for (auto *VarRef : Clause->children()) {
2370 if (auto *E = cast_or_null<Expr>(VarRef)) {
2371 MarkDeclarationsReferencedInExpr(E);
2372 }
2373 }
2374 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(/*V=*/false);
2375 } else if (isParallelOrTaskRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
2376 if (auto *C = OMPClauseWithPreInit::get(Clause))
2377 PICs.push_back(C);
2378 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2379 if (auto *E = C->getPostUpdateExpr())
2380 MarkDeclarationsReferencedInExpr(E);
2381 }
2382 }
2383 if (Clause->getClauseKind() == OMPC_schedule)
2384 SC = cast<OMPScheduleClause>(Clause);
2385 else if (Clause->getClauseKind() == OMPC_ordered)
2386 OC = cast<OMPOrderedClause>(Clause);
2387 else if (Clause->getClauseKind() == OMPC_linear)
2388 LCs.push_back(cast<OMPLinearClause>(Clause));
2389 }
2390 // OpenMP, 2.7.1 Loop Construct, Restrictions
2391 // The nonmonotonic modifier cannot be specified if an ordered clause is
2392 // specified.
2393 if (SC &&
2394 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2395 SC->getSecondScheduleModifier() ==
2396 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2397 OC) {
2398 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2399 ? SC->getFirstScheduleModifierLoc()
2400 : SC->getSecondScheduleModifierLoc(),
2401 diag::err_omp_schedule_nonmonotonic_ordered)
2402 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2403 ErrorFound = true;
2404 }
2405 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2406 for (auto *C : LCs) {
2407 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2408 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2409 }
2410 ErrorFound = true;
2411 }
2412 if (isOpenMPWorksharingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
2413 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) && OC &&
2414 OC->getNumForLoops()) {
2415 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2416 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
2417 ErrorFound = true;
2418 }
2419 if (ErrorFound) {
2420 return StmtError();
2421 }
2422 StmtResult SR = S;
2423 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2424 getOpenMPCaptureRegions(CaptureRegions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
2425 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2426 // Mark all variables in private list clauses as used in inner region.
2427 // Required for proper codegen of combined directives.
2428 // TODO: add processing for other clauses.
2429 if (isParallelOrTaskRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
2430 for (auto *C : PICs) {
2431 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2432 // Find the particular capture region for the clause if the
2433 // directive is a combined one with multiple capture regions.
2434 // If the directive is not a combined one, the capture region
2435 // associated with the clause is OMPD_unknown and is generated
2436 // only once.
2437 if (CaptureRegion == ThisCaptureRegion ||
2438 CaptureRegion == OMPD_unknown) {
2439 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2440 for (auto *D : DS->decls())
2441 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2442 }
2443 }
2444 }
2445 }
2446 SR = ActOnCapturedRegionEnd(SR.get());
2447 }
2448 return SR;
2449}
2450
2451static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2452 OpenMPDirectiveKind CancelRegion,
2453 SourceLocation StartLoc) {
2454 // CancelRegion is only needed for cancel and cancellation_point.
2455 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2456 return false;
2457
2458 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2459 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2460 return false;
2461
2462 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2463 << getOpenMPDirectiveName(CancelRegion);
2464 return true;
2465}
2466
2467static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
2468 OpenMPDirectiveKind CurrentRegion,
2469 const DeclarationNameInfo &CurrentName,
2470 OpenMPDirectiveKind CancelRegion,
2471 SourceLocation StartLoc) {
2472 if (Stack->getCurScope()) {
2473 auto ParentRegion = Stack->getParentDirective();
2474 auto OffendingRegion = ParentRegion;
2475 bool NestingProhibited = false;
2476 bool CloseNesting = true;
2477 bool OrphanSeen = false;
2478 enum {
2479 NoRecommend,
2480 ShouldBeInParallelRegion,
2481 ShouldBeInOrderedRegion,
2482 ShouldBeInTargetRegion,
2483 ShouldBeInTeamsRegion
2484 } Recommend = NoRecommend;
2485 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2486 // OpenMP [2.16, Nesting of Regions]
2487 // OpenMP constructs may not be nested inside a simd region.
2488 // OpenMP [2.8.1,simd Construct, Restrictions]
2489 // An ordered construct with the simd clause is the only OpenMP
2490 // construct that can appear in the simd region.
2491 // Allowing a SIMD construct nested in another SIMD construct is an
2492 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2493 // message.
2494 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2495 ? diag::err_omp_prohibited_region_simd
2496 : diag::warn_omp_nesting_simd);
2497 return CurrentRegion != OMPD_simd;
2498 }
2499 if (ParentRegion == OMPD_atomic) {
2500 // OpenMP [2.16, Nesting of Regions]
2501 // OpenMP constructs may not be nested inside an atomic region.
2502 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2503 return true;
2504 }
2505 if (CurrentRegion == OMPD_section) {
2506 // OpenMP [2.7.2, sections Construct, Restrictions]
2507 // Orphaned section directives are prohibited. That is, the section
2508 // directives must appear within the sections construct and must not be
2509 // encountered elsewhere in the sections region.
2510 if (ParentRegion != OMPD_sections &&
2511 ParentRegion != OMPD_parallel_sections) {
2512 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2513 << (ParentRegion != OMPD_unknown)
2514 << getOpenMPDirectiveName(ParentRegion);
2515 return true;
2516 }
2517 return false;
2518 }
2519 // Allow some constructs (except teams) to be orphaned (they could be
2520 // used in functions, called from OpenMP regions with the required
2521 // preconditions).
2522 if (ParentRegion == OMPD_unknown &&
2523 !isOpenMPNestingTeamsDirective(CurrentRegion))
2524 return false;
2525 if (CurrentRegion == OMPD_cancellation_point ||
2526 CurrentRegion == OMPD_cancel) {
2527 // OpenMP [2.16, Nesting of Regions]
2528 // A cancellation point construct for which construct-type-clause is
2529 // taskgroup must be nested inside a task construct. A cancellation
2530 // point construct for which construct-type-clause is not taskgroup must
2531 // be closely nested inside an OpenMP construct that matches the type
2532 // specified in construct-type-clause.
2533 // A cancel construct for which construct-type-clause is taskgroup must be
2534 // nested inside a task construct. A cancel construct for which
2535 // construct-type-clause is not taskgroup must be closely nested inside an
2536 // OpenMP construct that matches the type specified in
2537 // construct-type-clause.
2538 NestingProhibited =
2539 !((CancelRegion == OMPD_parallel &&
2540 (ParentRegion == OMPD_parallel ||
2541 ParentRegion == OMPD_target_parallel)) ||
2542 (CancelRegion == OMPD_for &&
2543 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2544 ParentRegion == OMPD_target_parallel_for)) ||
2545 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2546 (CancelRegion == OMPD_sections &&
2547 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2548 ParentRegion == OMPD_parallel_sections)));
2549 } else if (CurrentRegion == OMPD_master) {
2550 // OpenMP [2.16, Nesting of Regions]
2551 // A master region may not be closely nested inside a worksharing,
2552 // atomic, or explicit task region.
2553 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2554 isOpenMPTaskingDirective(ParentRegion);
2555 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2556 // OpenMP [2.16, Nesting of Regions]
2557 // A critical region may not be nested (closely or otherwise) inside a
2558 // critical region with the same name. Note that this restriction is not
2559 // sufficient to prevent deadlock.
2560 SourceLocation PreviousCriticalLoc;
2561 bool DeadLock = Stack->hasDirective(
2562 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2563 const DeclarationNameInfo &DNI,
2564 SourceLocation Loc) -> bool {
2565 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2566 PreviousCriticalLoc = Loc;
2567 return true;
2568 } else
2569 return false;
2570 },
2571 false /* skip top directive */);
2572 if (DeadLock) {
2573 SemaRef.Diag(StartLoc,
2574 diag::err_omp_prohibited_region_critical_same_name)
2575 << CurrentName.getName();
2576 if (PreviousCriticalLoc.isValid())
2577 SemaRef.Diag(PreviousCriticalLoc,
2578 diag::note_omp_previous_critical_region);
2579 return true;
2580 }
2581 } else if (CurrentRegion == OMPD_barrier) {
2582 // OpenMP [2.16, Nesting of Regions]
2583 // A barrier region may not be closely nested inside a worksharing,
2584 // explicit task, critical, ordered, atomic, or master region.
2585 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2586 isOpenMPTaskingDirective(ParentRegion) ||
2587 ParentRegion == OMPD_master ||
2588 ParentRegion == OMPD_critical ||
2589 ParentRegion == OMPD_ordered;
2590 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2591 !isOpenMPParallelDirective(CurrentRegion) &&
2592 !isOpenMPTeamsDirective(CurrentRegion)) {
2593 // OpenMP [2.16, Nesting of Regions]
2594 // A worksharing region may not be closely nested inside a worksharing,
2595 // explicit task, critical, ordered, atomic, or master region.
2596 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2597 isOpenMPTaskingDirective(ParentRegion) ||
2598 ParentRegion == OMPD_master ||
2599 ParentRegion == OMPD_critical ||
2600 ParentRegion == OMPD_ordered;
2601 Recommend = ShouldBeInParallelRegion;
2602 } else if (CurrentRegion == OMPD_ordered) {
2603 // OpenMP [2.16, Nesting of Regions]
2604 // An ordered region may not be closely nested inside a critical,
2605 // atomic, or explicit task region.
2606 // An ordered region must be closely nested inside a loop region (or
2607 // parallel loop region) with an ordered clause.
2608 // OpenMP [2.8.1,simd Construct, Restrictions]
2609 // An ordered construct with the simd clause is the only OpenMP construct
2610 // that can appear in the simd region.
2611 NestingProhibited = ParentRegion == OMPD_critical ||
2612 isOpenMPTaskingDirective(ParentRegion) ||
2613 !(isOpenMPSimdDirective(ParentRegion) ||
2614 Stack->isParentOrderedRegion());
2615 Recommend = ShouldBeInOrderedRegion;
2616 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2617 // OpenMP [2.16, Nesting of Regions]
2618 // If specified, a teams construct must be contained within a target
2619 // construct.
2620 NestingProhibited = ParentRegion != OMPD_target;
2621 OrphanSeen = ParentRegion == OMPD_unknown;
2622 Recommend = ShouldBeInTargetRegion;
2623 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2624 }
2625 if (!NestingProhibited &&
2626 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2627 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2628 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2629 // OpenMP [2.16, Nesting of Regions]
2630 // distribute, parallel, parallel sections, parallel workshare, and the
2631 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2632 // constructs that can be closely nested in the teams region.
2633 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2634 !isOpenMPDistributeDirective(CurrentRegion);
2635 Recommend = ShouldBeInParallelRegion;
2636 }
2637 if (!NestingProhibited &&
2638 isOpenMPNestingDistributeDirective(CurrentRegion)) {
2639 // OpenMP 4.5 [2.17 Nesting of Regions]
2640 // The region associated with the distribute construct must be strictly
2641 // nested inside a teams region
2642 NestingProhibited =
2643 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2644 Recommend = ShouldBeInTeamsRegion;
2645 }
2646 if (!NestingProhibited &&
2647 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2648 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2649 // OpenMP 4.5 [2.17 Nesting of Regions]
2650 // If a target, target update, target data, target enter data, or
2651 // target exit data construct is encountered during execution of a
2652 // target region, the behavior is unspecified.
2653 NestingProhibited = Stack->hasDirective(
2654 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2655 SourceLocation) -> bool {
2656 if (isOpenMPTargetExecutionDirective(K)) {
2657 OffendingRegion = K;
2658 return true;
2659 } else
2660 return false;
2661 },
2662 false /* don't skip top directive */);
2663 CloseNesting = false;
2664 }
2665 if (NestingProhibited) {
2666 if (OrphanSeen) {
2667 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2668 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2669 } else {
2670 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2671 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2672 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2673 }
2674 return true;
2675 }
2676 }
2677 return false;
2678}
2679
2680static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2681 ArrayRef<OMPClause *> Clauses,
2682 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2683 bool ErrorFound = false;
2684 unsigned NamedModifiersNumber = 0;
2685 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2686 OMPD_unknown + 1);
2687 SmallVector<SourceLocation, 4> NameModifierLoc;
2688 for (const auto *C : Clauses) {
2689 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2690 // At most one if clause without a directive-name-modifier can appear on
2691 // the directive.
2692 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2693 if (FoundNameModifiers[CurNM]) {
2694 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2695 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2696 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2697 ErrorFound = true;
2698 } else if (CurNM != OMPD_unknown) {
2699 NameModifierLoc.push_back(IC->getNameModifierLoc());
2700 ++NamedModifiersNumber;
2701 }
2702 FoundNameModifiers[CurNM] = IC;
2703 if (CurNM == OMPD_unknown)
2704 continue;
2705 // Check if the specified name modifier is allowed for the current
2706 // directive.
2707 // At most one if clause with the particular directive-name-modifier can
2708 // appear on the directive.
2709 bool MatchFound = false;
2710 for (auto NM : AllowedNameModifiers) {
2711 if (CurNM == NM) {
2712 MatchFound = true;
2713 break;
2714 }
2715 }
2716 if (!MatchFound) {
2717 S.Diag(IC->getNameModifierLoc(),
2718 diag::err_omp_wrong_if_directive_name_modifier)
2719 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2720 ErrorFound = true;
2721 }
2722 }
2723 }
2724 // If any if clause on the directive includes a directive-name-modifier then
2725 // all if clauses on the directive must include a directive-name-modifier.
2726 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2727 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2728 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2729 diag::err_omp_no_more_if_clause);
2730 } else {
2731 std::string Values;
2732 std::string Sep(", ");
2733 unsigned AllowedCnt = 0;
2734 unsigned TotalAllowedNum =
2735 AllowedNameModifiers.size() - NamedModifiersNumber;
2736 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2737 ++Cnt) {
2738 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2739 if (!FoundNameModifiers[NM]) {
2740 Values += "'";
2741 Values += getOpenMPDirectiveName(NM);
2742 Values += "'";
2743 if (AllowedCnt + 2 == TotalAllowedNum)
2744 Values += " or ";
2745 else if (AllowedCnt + 1 != TotalAllowedNum)
2746 Values += Sep;
2747 ++AllowedCnt;
2748 }
2749 }
2750 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2751 diag::err_omp_unnamed_if_clause)
2752 << (TotalAllowedNum > 1) << Values;
2753 }
2754 for (auto Loc : NameModifierLoc) {
2755 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2756 }
2757 ErrorFound = true;
2758 }
2759 return ErrorFound;
2760}
2761
2762StmtResult Sema::ActOnOpenMPExecutableDirective(
2763 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2764 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2765 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2766 StmtResult Res = StmtError();
2767 // First check CancelRegion which is then used in checkNestingOfRegions.
2768 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2769 checkNestingOfRegions(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Kind, DirName, CancelRegion,
2770 StartLoc))
2771 return StmtError();
2772
2773 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2774 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2775 bool ErrorFound = false;
2776 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2777 if (AStmt && !CurContext->isDependentContext()) {
2778 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2778, __PRETTY_FUNCTION__))
;
2779
2780 // Check default data sharing attributes for referenced variables.
2781 DSAAttrChecker DSAChecker(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, *this, cast<CapturedStmt>(AStmt));
2782 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2783 Stmt *S = AStmt;
2784 while (--ThisCaptureLevel >= 0)
2785 S = cast<CapturedStmt>(S)->getCapturedStmt();
2786 DSAChecker.Visit(S);
2787 if (DSAChecker.isErrorFound())
2788 return StmtError();
2789 // Generate list of implicitly defined firstprivate variables.
2790 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2791
2792 SmallVector<Expr *, 4> ImplicitFirstprivates(
2793 DSAChecker.getImplicitFirstprivate().begin(),
2794 DSAChecker.getImplicitFirstprivate().end());
2795 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2796 DSAChecker.getImplicitMap().end());
2797 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2798 for (auto *C : Clauses) {
2799 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2800 for (auto *E : IRC->taskgroup_descriptors())
2801 if (E)
2802 ImplicitFirstprivates.emplace_back(E);
2803 }
2804 }
2805 if (!ImplicitFirstprivates.empty()) {
2806 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2807 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2808 SourceLocation())) {
2809 ClausesWithImplicit.push_back(Implicit);
2810 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2811 ImplicitFirstprivates.size();
2812 } else
2813 ErrorFound = true;
2814 }
2815 if (!ImplicitMaps.empty()) {
2816 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2817 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2818 SourceLocation(), SourceLocation(), ImplicitMaps,
2819 SourceLocation(), SourceLocation(), SourceLocation())) {
2820 ClausesWithImplicit.emplace_back(Implicit);
2821 ErrorFound |=
2822 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2823 } else
2824 ErrorFound = true;
2825 }
2826 }
2827
2828 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2829 switch (Kind) {
2830 case OMPD_parallel:
2831 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2832 EndLoc);
2833 AllowedNameModifiers.push_back(OMPD_parallel);
2834 break;
2835 case OMPD_simd:
2836 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2837 VarsWithInheritedDSA);
2838 break;
2839 case OMPD_for:
2840 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2841 VarsWithInheritedDSA);
2842 break;
2843 case OMPD_for_simd:
2844 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2845 EndLoc, VarsWithInheritedDSA);
2846 break;
2847 case OMPD_sections:
2848 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2849 EndLoc);
2850 break;
2851 case OMPD_section:
2852 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp section' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2853, __PRETTY_FUNCTION__))
2853 "No clauses are allowed for 'omp section' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp section' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2853, __PRETTY_FUNCTION__))
;
2854 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2855 break;
2856 case OMPD_single:
2857 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2858 EndLoc);
2859 break;
2860 case OMPD_master:
2861 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp master' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2862, __PRETTY_FUNCTION__))
2862 "No clauses are allowed for 'omp master' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp master' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2862, __PRETTY_FUNCTION__))
;
2863 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2864 break;
2865 case OMPD_critical:
2866 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2867 StartLoc, EndLoc);
2868 break;
2869 case OMPD_parallel_for:
2870 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2871 EndLoc, VarsWithInheritedDSA);
2872 AllowedNameModifiers.push_back(OMPD_parallel);
2873 break;
2874 case OMPD_parallel_for_simd:
2875 Res = ActOnOpenMPParallelForSimdDirective(
2876 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2877 AllowedNameModifiers.push_back(OMPD_parallel);
2878 break;
2879 case OMPD_parallel_sections:
2880 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2881 StartLoc, EndLoc);
2882 AllowedNameModifiers.push_back(OMPD_parallel);
2883 break;
2884 case OMPD_task:
2885 Res =
2886 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2887 AllowedNameModifiers.push_back(OMPD_task);
2888 break;
2889 case OMPD_taskyield:
2890 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2891, __PRETTY_FUNCTION__))
2891 "No clauses are allowed for 'omp taskyield' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2891, __PRETTY_FUNCTION__))
;
2892 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2893, __PRETTY_FUNCTION__))
2893 "No associated statement allowed for 'omp taskyield' directive")((AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2893, __PRETTY_FUNCTION__))
;
2894 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2895 break;
2896 case OMPD_barrier:
2897 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2898, __PRETTY_FUNCTION__))
2898 "No clauses are allowed for 'omp barrier' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2898, __PRETTY_FUNCTION__))
;
2899 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2900, __PRETTY_FUNCTION__))
2900 "No associated statement allowed for 'omp barrier' directive")((AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2900, __PRETTY_FUNCTION__))
;
2901 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2902 break;
2903 case OMPD_taskwait:
2904 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2905, __PRETTY_FUNCTION__))
2905 "No clauses are allowed for 'omp taskwait' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2905, __PRETTY_FUNCTION__))
;
2906 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2907, __PRETTY_FUNCTION__))
2907 "No associated statement allowed for 'omp taskwait' directive")((AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2907, __PRETTY_FUNCTION__))
;
2908 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2909 break;
2910 case OMPD_taskgroup:
2911 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2912 EndLoc);
2913 break;
2914 case OMPD_flush:
2915 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp flush' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2916, __PRETTY_FUNCTION__))
2916 "No associated statement allowed for 'omp flush' directive")((AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp flush' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2916, __PRETTY_FUNCTION__))
;
2917 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2918 break;
2919 case OMPD_ordered:
2920 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2921 EndLoc);
2922 break;
2923 case OMPD_atomic:
2924 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2925 EndLoc);
2926 break;
2927 case OMPD_teams:
2928 Res =
2929 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2930 break;
2931 case OMPD_target:
2932 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2933 EndLoc);
2934 AllowedNameModifiers.push_back(OMPD_target);
2935 break;
2936 case OMPD_target_parallel:
2937 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2938 StartLoc, EndLoc);
2939 AllowedNameModifiers.push_back(OMPD_target);
2940 AllowedNameModifiers.push_back(OMPD_parallel);
2941 break;
2942 case OMPD_target_parallel_for:
2943 Res = ActOnOpenMPTargetParallelForDirective(
2944 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2945 AllowedNameModifiers.push_back(OMPD_target);
2946 AllowedNameModifiers.push_back(OMPD_parallel);
2947 break;
2948 case OMPD_cancellation_point:
2949 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2950, __PRETTY_FUNCTION__))
2950 "No clauses are allowed for 'omp cancellation point' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2950, __PRETTY_FUNCTION__))
;
2951 assert(AStmt == nullptr && "No associated statement allowed for 'omp "((AStmt == nullptr && "No associated statement allowed for 'omp "
"cancellation point' directive") ? static_cast<void> (
0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp \" \"cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2952, __PRETTY_FUNCTION__))
2952 "cancellation point' directive")((AStmt == nullptr && "No associated statement allowed for 'omp "
"cancellation point' directive") ? static_cast<void> (
0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp \" \"cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2952, __PRETTY_FUNCTION__))
;
2953 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2954 break;
2955 case OMPD_cancel:
2956 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp cancel' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2957, __PRETTY_FUNCTION__))
2957 "No associated statement allowed for 'omp cancel' directive")((AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp cancel' directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2957, __PRETTY_FUNCTION__))
;
2958 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2959 CancelRegion);
2960 AllowedNameModifiers.push_back(OMPD_cancel);
2961 break;
2962 case OMPD_target_data:
2963 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2964 EndLoc);
2965 AllowedNameModifiers.push_back(OMPD_target_data);
2966 break;
2967 case OMPD_target_enter_data:
2968 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2969 EndLoc);
2970 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2971 break;
2972 case OMPD_target_exit_data:
2973 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2974 EndLoc);
2975 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2976 break;
2977 case OMPD_taskloop:
2978 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2979 EndLoc, VarsWithInheritedDSA);
2980 AllowedNameModifiers.push_back(OMPD_taskloop);
2981 break;
2982 case OMPD_taskloop_simd:
2983 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2984 EndLoc, VarsWithInheritedDSA);
2985 AllowedNameModifiers.push_back(OMPD_taskloop);
2986 break;
2987 case OMPD_distribute:
2988 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2989 EndLoc, VarsWithInheritedDSA);
2990 break;
2991 case OMPD_target_update:
2992 assert(!AStmt && "Statement is not allowed for target update")((!AStmt && "Statement is not allowed for target update"
) ? static_cast<void> (0) : __assert_fail ("!AStmt && \"Statement is not allowed for target update\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2992, __PRETTY_FUNCTION__))
;
2993 Res =
2994 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2995 AllowedNameModifiers.push_back(OMPD_target_update);
2996 break;
2997 case OMPD_distribute_parallel_for:
2998 Res = ActOnOpenMPDistributeParallelForDirective(
2999 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3000 AllowedNameModifiers.push_back(OMPD_parallel);
3001 break;
3002 case OMPD_distribute_parallel_for_simd:
3003 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3004 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3005 AllowedNameModifiers.push_back(OMPD_parallel);
3006 break;
3007 case OMPD_distribute_simd:
3008 Res = ActOnOpenMPDistributeSimdDirective(
3009 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3010 break;
3011 case OMPD_target_parallel_for_simd:
3012 Res = ActOnOpenMPTargetParallelForSimdDirective(
3013 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3014 AllowedNameModifiers.push_back(OMPD_target);
3015 AllowedNameModifiers.push_back(OMPD_parallel);
3016 break;
3017 case OMPD_target_simd:
3018 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3019 EndLoc, VarsWithInheritedDSA);
3020 AllowedNameModifiers.push_back(OMPD_target);
3021 break;
3022 case OMPD_teams_distribute:
3023 Res = ActOnOpenMPTeamsDistributeDirective(
3024 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3025 break;
3026 case OMPD_teams_distribute_simd:
3027 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3028 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3029 break;
3030 case OMPD_teams_distribute_parallel_for_simd:
3031 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3032 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3033 AllowedNameModifiers.push_back(OMPD_parallel);
3034 break;
3035 case OMPD_teams_distribute_parallel_for:
3036 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3037 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3038 AllowedNameModifiers.push_back(OMPD_parallel);
3039 break;
3040 case OMPD_target_teams:
3041 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3042 EndLoc);
3043 AllowedNameModifiers.push_back(OMPD_target);
3044 break;
3045 case OMPD_target_teams_distribute:
3046 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3047 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3048 AllowedNameModifiers.push_back(OMPD_target);
3049 break;
3050 case OMPD_target_teams_distribute_parallel_for:
3051 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3052 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3053 AllowedNameModifiers.push_back(OMPD_target);
3054 AllowedNameModifiers.push_back(OMPD_parallel);
3055 break;
3056 case OMPD_target_teams_distribute_parallel_for_simd:
3057 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3059 AllowedNameModifiers.push_back(OMPD_target);
3060 AllowedNameModifiers.push_back(OMPD_parallel);
3061 break;
3062 case OMPD_target_teams_distribute_simd:
3063 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3064 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3065 AllowedNameModifiers.push_back(OMPD_target);
3066 break;
3067 case OMPD_declare_target:
3068 case OMPD_end_declare_target:
3069 case OMPD_threadprivate:
3070 case OMPD_declare_reduction:
3071 case OMPD_declare_simd:
3072 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3072)
;
3073 case OMPD_unknown:
3074 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3074)
;
3075 }
3076
3077 for (auto P : VarsWithInheritedDSA) {
3078 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3079 << P.first << P.second->getSourceRange();
3080 }
3081 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3082
3083 if (!AllowedNameModifiers.empty())
3084 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3085 ErrorFound;
3086
3087 if (ErrorFound)
3088 return StmtError();
3089 return Res;
3090}
3091
3092Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3093 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3094 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3095 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3096 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3097 assert(Aligneds.size() == Alignments.size())((Aligneds.size() == Alignments.size()) ? static_cast<void
> (0) : __assert_fail ("Aligneds.size() == Alignments.size()"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3097, __PRETTY_FUNCTION__))
;
3098 assert(Linears.size() == LinModifiers.size())((Linears.size() == LinModifiers.size()) ? static_cast<void
> (0) : __assert_fail ("Linears.size() == LinModifiers.size()"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3098, __PRETTY_FUNCTION__))
;
3099 assert(Linears.size() == Steps.size())((Linears.size() == Steps.size()) ? static_cast<void> (
0) : __assert_fail ("Linears.size() == Steps.size()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3099, __PRETTY_FUNCTION__))
;
3100 if (!DG || DG.get().isNull())
3101 return DeclGroupPtrTy();
3102
3103 if (!DG.get().isSingleDecl()) {
3104 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3105 return DG;
3106 }
3107 auto *ADecl = DG.get().getSingleDecl();
3108 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3109 ADecl = FTD->getTemplatedDecl();
3110
3111 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3112 if (!FD) {
3113 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3114 return DeclGroupPtrTy();
3115 }
3116
3117 // OpenMP [2.8.2, declare simd construct, Description]
3118 // The parameter of the simdlen clause must be a constant positive integer
3119 // expression.
3120 ExprResult SL;
3121 if (Simdlen)
3122 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3123 // OpenMP [2.8.2, declare simd construct, Description]
3124 // The special this pointer can be used as if was one of the arguments to the
3125 // function in any of the linear, aligned, or uniform clauses.
3126 // The uniform clause declares one or more arguments to have an invariant
3127 // value for all concurrent invocations of the function in the execution of a
3128 // single SIMD loop.
3129 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3130 Expr *UniformedLinearThis = nullptr;
3131 for (auto *E : Uniforms) {
3132 E = E->IgnoreParenImpCasts();
3133 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3134 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3135 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3136 FD->getParamDecl(PVD->getFunctionScopeIndex())
3137 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3138 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
3139 continue;
3140 }
3141 if (isa<CXXThisExpr>(E)) {
3142 UniformedLinearThis = E;
3143 continue;
3144 }
3145 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3146 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3147 }
3148 // OpenMP [2.8.2, declare simd construct, Description]
3149 // The aligned clause declares that the object to which each list item points
3150 // is aligned to the number of bytes expressed in the optional parameter of
3151 // the aligned clause.
3152 // The special this pointer can be used as if was one of the arguments to the
3153 // function in any of the linear, aligned, or uniform clauses.
3154 // The type of list items appearing in the aligned clause must be array,
3155 // pointer, reference to array, or reference to pointer.
3156 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3157 Expr *AlignedThis = nullptr;
3158 for (auto *E : Aligneds) {
3159 E = E->IgnoreParenImpCasts();
3160 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3161 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3162 auto *CanonPVD = PVD->getCanonicalDecl();
3163 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3164 FD->getParamDecl(PVD->getFunctionScopeIndex())
3165 ->getCanonicalDecl() == CanonPVD) {
3166 // OpenMP [2.8.1, simd construct, Restrictions]
3167 // A list-item cannot appear in more than one aligned clause.
3168 if (AlignedArgs.count(CanonPVD) > 0) {
3169 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3170 << 1 << E->getSourceRange();
3171 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3172 diag::note_omp_explicit_dsa)
3173 << getOpenMPClauseName(OMPC_aligned);
3174 continue;
3175 }
3176 AlignedArgs[CanonPVD] = E;
3177 QualType QTy = PVD->getType()
3178 .getNonReferenceType()
3179 .getUnqualifiedType()
3180 .getCanonicalType();
3181 const Type *Ty = QTy.getTypePtrOrNull();
3182 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3183 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3184 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3185 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3186 }
3187 continue;
3188 }
3189 }
3190 if (isa<CXXThisExpr>(E)) {
3191 if (AlignedThis) {
3192 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3193 << 2 << E->getSourceRange();
3194 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3195 << getOpenMPClauseName(OMPC_aligned);
3196 }
3197 AlignedThis = E;
3198 continue;
3199 }
3200 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3201 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3202 }
3203 // The optional parameter of the aligned clause, alignment, must be a constant
3204 // positive integer expression. If no optional parameter is specified,
3205 // implementation-defined default alignments for SIMD instructions on the
3206 // target platforms are assumed.
3207 SmallVector<Expr *, 4> NewAligns;
3208 for (auto *E : Alignments) {
3209 ExprResult Align;
3210 if (E)
3211 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3212 NewAligns.push_back(Align.get());
3213 }
3214 // OpenMP [2.8.2, declare simd construct, Description]
3215 // The linear clause declares one or more list items to be private to a SIMD
3216 // lane and to have a linear relationship with respect to the iteration space
3217 // of a loop.
3218 // The special this pointer can be used as if was one of the arguments to the
3219 // function in any of the linear, aligned, or uniform clauses.
3220 // When a linear-step expression is specified in a linear clause it must be
3221 // either a constant integer expression or an integer-typed parameter that is
3222 // specified in a uniform clause on the directive.
3223 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3224 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3225 auto MI = LinModifiers.begin();
3226 for (auto *E : Linears) {
3227 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3228 ++MI;
3229 E = E->IgnoreParenImpCasts();
3230 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3231 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3232 auto *CanonPVD = PVD->getCanonicalDecl();
3233 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3234 FD->getParamDecl(PVD->getFunctionScopeIndex())
3235 ->getCanonicalDecl() == CanonPVD) {
3236 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3237 // A list-item cannot appear in more than one linear clause.
3238 if (LinearArgs.count(CanonPVD) > 0) {
3239 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3240 << getOpenMPClauseName(OMPC_linear)
3241 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3242 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3243 diag::note_omp_explicit_dsa)
3244 << getOpenMPClauseName(OMPC_linear);
3245 continue;
3246 }
3247 // Each argument can appear in at most one uniform or linear clause.
3248 if (UniformedArgs.count(CanonPVD) > 0) {
3249 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3250 << getOpenMPClauseName(OMPC_linear)
3251 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3252 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3253 diag::note_omp_explicit_dsa)
3254 << getOpenMPClauseName(OMPC_uniform);
3255 continue;
3256 }
3257 LinearArgs[CanonPVD] = E;
3258 if (E->isValueDependent() || E->isTypeDependent() ||
3259 E->isInstantiationDependent() ||
3260 E->containsUnexpandedParameterPack())
3261 continue;
3262 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3263 PVD->getOriginalType());
3264 continue;
3265 }
3266 }
3267 if (isa<CXXThisExpr>(E)) {
3268 if (UniformedLinearThis) {
3269 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3270 << getOpenMPClauseName(OMPC_linear)
3271 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3272 << E->getSourceRange();
3273 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3274 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3275 : OMPC_linear);
3276 continue;
3277 }
3278 UniformedLinearThis = E;
3279 if (E->isValueDependent() || E->isTypeDependent() ||
3280 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3281 continue;
3282 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3283 E->getType());
3284 continue;
3285 }
3286 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3287 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3288 }
3289 Expr *Step = nullptr;
3290 Expr *NewStep = nullptr;
3291 SmallVector<Expr *, 4> NewSteps;
3292 for (auto *E : Steps) {
3293 // Skip the same step expression, it was checked already.
3294 if (Step == E || !E) {
3295 NewSteps.push_back(E ? NewStep : nullptr);
3296 continue;
3297 }
3298 Step = E;
3299 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3300 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3301 auto *CanonPVD = PVD->getCanonicalDecl();
3302 if (UniformedArgs.count(CanonPVD) == 0) {
3303 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3304 << Step->getSourceRange();
3305 } else if (E->isValueDependent() || E->isTypeDependent() ||
3306 E->isInstantiationDependent() ||
3307 E->containsUnexpandedParameterPack() ||
3308 CanonPVD->getType()->hasIntegerRepresentation())
3309 NewSteps.push_back(Step);
3310 else {
3311 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3312 << Step->getSourceRange();
3313 }
3314 continue;
3315 }
3316 NewStep = Step;
3317 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3318 !Step->isInstantiationDependent() &&
3319 !Step->containsUnexpandedParameterPack()) {
3320 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3321 .get();
3322 if (NewStep)
3323 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3324 }
3325 NewSteps.push_back(NewStep);
3326 }
3327 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3328 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3329 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3330 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3331 const_cast<Expr **>(Linears.data()), Linears.size(),
3332 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3333 NewSteps.data(), NewSteps.size(), SR);
3334 ADecl->addAttr(NewAttr);
3335 return ConvertDeclToDeclGroup(ADecl);
3336}
3337
3338StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3339 Stmt *AStmt,
3340 SourceLocation StartLoc,
3341 SourceLocation EndLoc) {
3342 if (!AStmt)
3343 return StmtError();
3344
3345 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3346 // 1.2.2 OpenMP Language Terminology
3347 // Structured block - An executable statement with a single entry at the
3348 // top and a single exit at the bottom.
3349 // The point of exit cannot be a branch out of the structured block.
3350 // longjmp() and throw() must not violate the entry/exit criteria.
3351 CS->getCapturedDecl()->setNothrow();
3352
3353 getCurFunction()->setHasBranchProtectedScope();
3354
3355 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3356 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
3357}
3358
3359namespace {
3360/// \brief Helper class for checking canonical form of the OpenMP loops and
3361/// extracting iteration space of each loop in the loop nest, that will be used
3362/// for IR generation.
3363class OpenMPIterationSpaceChecker {
3364 /// \brief Reference to Sema.
3365 Sema &SemaRef;
3366 /// \brief A location for diagnostics (when there is no some better location).
3367 SourceLocation DefaultLoc;
3368 /// \brief A location for diagnostics (when increment is not compatible).
3369 SourceLocation ConditionLoc;
3370 /// \brief A source location for referring to loop init later.
3371 SourceRange InitSrcRange;
3372 /// \brief A source location for referring to condition later.
3373 SourceRange ConditionSrcRange;
3374 /// \brief A source location for referring to increment later.
3375 SourceRange IncrementSrcRange;
3376 /// \brief Loop variable.
3377 ValueDecl *LCDecl = nullptr;
3378 /// \brief Reference to loop variable.
3379 Expr *LCRef = nullptr;
3380 /// \brief Lower bound (initializer for the var).
3381 Expr *LB = nullptr;
3382 /// \brief Upper bound.
3383 Expr *UB = nullptr;
3384 /// \brief Loop step (increment).
3385 Expr *Step = nullptr;
3386 /// \brief This flag is true when condition is one of:
3387 /// Var < UB
3388 /// Var <= UB
3389 /// UB > Var
3390 /// UB >= Var
3391 bool TestIsLessOp = false;
3392 /// \brief This flag is true when condition is strict ( < or > ).
3393 bool TestIsStrictOp = false;
3394 /// \brief This flag is true when step is subtracted on each iteration.
3395 bool SubtractStep = false;
3396
3397public:
3398 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3399 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3400 /// \brief Check init-expr for canonical loop form and save loop counter
3401 /// variable - #Var and its initialization value - #LB.
3402 bool CheckInit(Stmt *S, bool EmitDiags = true);
3403 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3404 /// for less/greater and for strict/non-strict comparison.
3405 bool CheckCond(Expr *S);
3406 /// \brief Check incr-expr for canonical loop form and return true if it
3407 /// does not conform, otherwise save loop step (#Step).
3408 bool CheckInc(Expr *S);
3409 /// \brief Return the loop counter variable.
3410 ValueDecl *GetLoopDecl() const { return LCDecl; }
3411 /// \brief Return the reference expression to loop counter variable.
3412 Expr *GetLoopDeclRefExpr() const { return LCRef; }
3413 /// \brief Source range of the loop init.
3414 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3415 /// \brief Source range of the loop condition.
3416 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3417 /// \brief Source range of the loop increment.
3418 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3419 /// \brief True if the step should be subtracted.
3420 bool ShouldSubtractStep() const { return SubtractStep; }
3421 /// \brief Build the expression to calculate the number of iterations.
3422 Expr *
3423 BuildNumIterations(Scope *S, const bool LimitedType,
3424 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3425 /// \brief Build the precondition expression for the loops.
3426 Expr *BuildPreCond(Scope *S, Expr *Cond,
3427 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3428 /// \brief Build reference expression to the counter be used for codegen.
3429 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3430 DSAStackTy &DSA) const;
3431 /// \brief Build reference expression to the private counter be used for
3432 /// codegen.
3433 Expr *BuildPrivateCounterVar() const;
3434 /// \brief Build initialization of the counter be used for codegen.
3435 Expr *BuildCounterInit() const;
3436 /// \brief Build step of the counter be used for codegen.
3437 Expr *BuildCounterStep() const;
3438 /// \brief Return true if any expression is dependent.
3439 bool Dependent() const;
3440
3441private:
3442 /// \brief Check the right-hand side of an assignment in the increment
3443 /// expression.
3444 bool CheckIncRHS(Expr *RHS);
3445 /// \brief Helper to set loop counter variable and its initializer.
3446 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3447 /// \brief Helper to set upper bound.
3448 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3449 SourceLocation SL);
3450 /// \brief Helper to set loop increment.
3451 bool SetStep(Expr *NewStep, bool Subtract);
3452};
3453
3454bool OpenMPIterationSpaceChecker::Dependent() const {
3455 if (!LCDecl) {
3456 assert(!LB && !UB && !Step)((!LB && !UB && !Step) ? static_cast<void>
(0) : __assert_fail ("!LB && !UB && !Step", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3456, __PRETTY_FUNCTION__))
;
3457 return false;
3458 }
3459 return LCDecl->getType()->isDependentType() ||
3460 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3461 (Step && Step->isValueDependent());
3462}
3463
3464bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3465 Expr *NewLCRefExpr,
3466 Expr *NewLB) {
3467 // State consistency checking to ensure correct usage.
3468 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3469, __PRETTY_FUNCTION__))
3469 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3469, __PRETTY_FUNCTION__))
;
3470 if (!NewLCDecl || !NewLB)
3471 return true;
3472 LCDecl = getCanonicalDecl(NewLCDecl);
3473 LCRef = NewLCRefExpr;
3474 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3475 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3476 if ((Ctor->isCopyOrMoveConstructor() ||
3477 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3478 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3479 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3480 LB = NewLB;
3481 return false;
3482}
3483
3484bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3485 SourceRange SR, SourceLocation SL) {
3486 // State consistency checking to ensure correct usage.
3487 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3488, __PRETTY_FUNCTION__))
3488 Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3488, __PRETTY_FUNCTION__))
;
3489 if (!NewUB)
3490 return true;
3491 UB = NewUB;
3492 TestIsLessOp = LessOp;
3493 TestIsStrictOp = StrictOp;
3494 ConditionSrcRange = SR;
3495 ConditionLoc = SL;
3496 return false;
3497}
3498
3499bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3500 // State consistency checking to ensure correct usage.
3501 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr)((LCDecl != nullptr && LB != nullptr && Step ==
nullptr) ? static_cast<void> (0) : __assert_fail ("LCDecl != nullptr && LB != nullptr && Step == nullptr"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3501, __PRETTY_FUNCTION__))
;
3502 if (!NewStep)
3503 return true;
3504 if (!NewStep->isValueDependent()) {
3505 // Check that the step is integer expression.
3506 SourceLocation StepLoc = NewStep->getLocStart();
3507 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3508 StepLoc, getExprAsWritten(NewStep));
3509 if (Val.isInvalid())
3510 return true;
3511 NewStep = Val.get();
3512
3513 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3514 // If test-expr is of form var relational-op b and relational-op is < or
3515 // <= then incr-expr must cause var to increase on each iteration of the
3516 // loop. If test-expr is of form var relational-op b and relational-op is
3517 // > or >= then incr-expr must cause var to decrease on each iteration of
3518 // the loop.
3519 // If test-expr is of form b relational-op var and relational-op is < or
3520 // <= then incr-expr must cause var to decrease on each iteration of the
3521 // loop. If test-expr is of form b relational-op var and relational-op is
3522 // > or >= then incr-expr must cause var to increase on each iteration of
3523 // the loop.
3524 llvm::APSInt Result;
3525 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3526 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3527 bool IsConstNeg =
3528 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3529 bool IsConstPos =
3530 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3531 bool IsConstZero = IsConstant && !Result.getBoolValue();
3532 if (UB && (IsConstZero ||
3533 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3534 : (IsConstPos || (IsUnsigned && !Subtract))))) {
3535 SemaRef.Diag(NewStep->getExprLoc(),
3536 diag::err_omp_loop_incr_not_compatible)
3537 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3538 SemaRef.Diag(ConditionLoc,
3539 diag::note_omp_loop_cond_requres_compatible_incr)
3540 << TestIsLessOp << ConditionSrcRange;
3541 return true;
3542 }
3543 if (TestIsLessOp == Subtract) {
3544 NewStep =
3545 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3546 .get();
3547 Subtract = !Subtract;
3548 }
3549 }
3550
3551 Step = NewStep;
3552 SubtractStep = Subtract;
3553 return false;
3554}
3555
3556bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3557 // Check init-expr for canonical loop form and save loop counter
3558 // variable - #Var and its initialization value - #LB.
3559 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3560 // var = lb
3561 // integer-type var = lb
3562 // random-access-iterator-type var = lb
3563 // pointer-type var = lb
3564 //
3565 if (!S) {
3566 if (EmitDiags) {
3567 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3568 }
3569 return true;
3570 }
3571 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3572 if (!ExprTemp->cleanupsHaveSideEffects())
3573 S = ExprTemp->getSubExpr();
3574
3575 InitSrcRange = S->getSourceRange();
3576 if (Expr *E = dyn_cast<Expr>(S))
3577 S = E->IgnoreParens();
3578 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3579 if (BO->getOpcode() == BO_Assign) {
3580 auto *LHS = BO->getLHS()->IgnoreParens();
3581 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3582 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3583 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3584 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3585 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3586 }
3587 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3588 if (ME->isArrow() &&
3589 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3590 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3591 }
3592 }
3593 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3594 if (DS->isSingleDecl()) {
3595 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3596 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3597 // Accept non-canonical init form here but emit ext. warning.
3598 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3599 SemaRef.Diag(S->getLocStart(),
3600 diag::ext_omp_loop_not_canonical_init)
3601 << S->getSourceRange();
3602 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3603 }
3604 }
3605 }
3606 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3607 if (CE->getOperator() == OO_Equal) {
3608 auto *LHS = CE->getArg(0);
3609 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3610 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3611 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3612 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3613 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3614 }
3615 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3616 if (ME->isArrow() &&
3617 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3618 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3619 }
3620 }
3621 }
3622
3623 if (Dependent() || SemaRef.CurContext->isDependentContext())
3624 return false;
3625 if (EmitDiags) {
3626 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3627 << S->getSourceRange();
3628 }
3629 return true;
3630}
3631
3632/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3633/// variable (which may be the loop variable) if possible.
3634static const ValueDecl *GetInitLCDecl(Expr *E) {
3635 if (!E)
3636 return nullptr;
3637 E = getExprAsWritten(E);
3638 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3639 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3640 if ((Ctor->isCopyOrMoveConstructor() ||
3641 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3642 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3643 E = CE->getArg(0)->IgnoreParenImpCasts();
3644 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3645 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3646 return getCanonicalDecl(VD);
3647 }
3648 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3649 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3650 return getCanonicalDecl(ME->getMemberDecl());
3651 return nullptr;
3652}
3653
3654bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3655 // Check test-expr for canonical form, save upper-bound UB, flags for
3656 // less/greater and for strict/non-strict comparison.
3657 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3658 // var relational-op b
3659 // b relational-op var
3660 //
3661 if (!S) {
3662 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3663 return true;
3664 }
3665 S = getExprAsWritten(S);
3666 SourceLocation CondLoc = S->getLocStart();
3667 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3668 if (BO->isRelationalOp()) {
3669 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3670 return SetUB(BO->getRHS(),
3671 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3672 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3673 BO->getSourceRange(), BO->getOperatorLoc());
3674 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3675 return SetUB(BO->getLHS(),
3676 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3677 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3678 BO->getSourceRange(), BO->getOperatorLoc());
3679 }
3680 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3681 if (CE->getNumArgs() == 2) {
3682 auto Op = CE->getOperator();
3683 switch (Op) {
3684 case OO_Greater:
3685 case OO_GreaterEqual:
3686 case OO_Less:
3687 case OO_LessEqual:
3688 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3689 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3690 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3691 CE->getOperatorLoc());
3692 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3693 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3694 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3695 CE->getOperatorLoc());
3696 break;
3697 default:
3698 break;
3699 }
3700 }
3701 }
3702 if (Dependent() || SemaRef.CurContext->isDependentContext())
3703 return false;
3704 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3705 << S->getSourceRange() << LCDecl;
3706 return true;
3707}
3708
3709bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3710 // RHS of canonical loop form increment can be:
3711 // var + incr
3712 // incr + var
3713 // var - incr
3714 //
3715 RHS = RHS->IgnoreParenImpCasts();
3716 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3717 if (BO->isAdditiveOp()) {
3718 bool IsAdd = BO->getOpcode() == BO_Add;
3719 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3720 return SetStep(BO->getRHS(), !IsAdd);
3721 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3722 return SetStep(BO->getLHS(), false);
3723 }
3724 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3725 bool IsAdd = CE->getOperator() == OO_Plus;
3726 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3727 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3728 return SetStep(CE->getArg(1), !IsAdd);
3729 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3730 return SetStep(CE->getArg(0), false);
3731 }
3732 }
3733 if (Dependent() || SemaRef.CurContext->isDependentContext())
3734 return false;
3735 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3736 << RHS->getSourceRange() << LCDecl;
3737 return true;
3738}
3739
3740bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3741 // Check incr-expr for canonical loop form and return true if it
3742 // does not conform.
3743 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3744 // ++var
3745 // var++
3746 // --var
3747 // var--
3748 // var += incr
3749 // var -= incr
3750 // var = var + incr
3751 // var = incr + var
3752 // var = var - incr
3753 //
3754 if (!S) {
3755 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3756 return true;
3757 }
3758 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3759 if (!ExprTemp->cleanupsHaveSideEffects())
3760 S = ExprTemp->getSubExpr();
3761
3762 IncrementSrcRange = S->getSourceRange();
3763 S = S->IgnoreParens();
3764 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3765 if (UO->isIncrementDecrementOp() &&
3766 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3767 return SetStep(SemaRef
3768 .ActOnIntegerConstant(UO->getLocStart(),
3769 (UO->isDecrementOp() ? -1 : 1))
3770 .get(),
3771 false);
3772 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3773 switch (BO->getOpcode()) {
3774 case BO_AddAssign:
3775 case BO_SubAssign:
3776 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3777 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3778 break;
3779 case BO_Assign:
3780 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3781 return CheckIncRHS(BO->getRHS());
3782 break;
3783 default:
3784 break;
3785 }
3786 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3787 switch (CE->getOperator()) {
3788 case OO_PlusPlus:
3789 case OO_MinusMinus:
3790 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3791 return SetStep(SemaRef
3792 .ActOnIntegerConstant(
3793 CE->getLocStart(),
3794 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3795 .get(),
3796 false);
3797 break;
3798 case OO_PlusEqual:
3799 case OO_MinusEqual:
3800 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3801 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3802 break;
3803 case OO_Equal:
3804 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3805 return CheckIncRHS(CE->getArg(1));
3806 break;
3807 default:
3808 break;
3809 }
3810 }
3811 if (Dependent() || SemaRef.CurContext->isDependentContext())
3812 return false;
3813 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3814 << S->getSourceRange() << LCDecl;
3815 return true;
3816}
3817
3818static ExprResult
3819tryBuildCapture(Sema &SemaRef, Expr *Capture,
3820 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3821 if (SemaRef.CurContext->isDependentContext())
3822 return ExprResult(Capture);
3823 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3824 return SemaRef.PerformImplicitConversion(
3825 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3826 /*AllowExplicit=*/true);
3827 auto I = Captures.find(Capture);
3828 if (I != Captures.end())
3829 return buildCapture(SemaRef, Capture, I->second);
3830 DeclRefExpr *Ref = nullptr;
3831 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3832 Captures[Capture] = Ref;
3833 return Res;
3834}
3835
3836/// \brief Build the expression to calculate the number of iterations.
3837Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3838 Scope *S, const bool LimitedType,
3839 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3840 ExprResult Diff;
3841 auto VarType = LCDecl->getType().getNonReferenceType();
3842 if (VarType->isIntegerType() || VarType->isPointerType() ||
3843 SemaRef.getLangOpts().CPlusPlus) {
3844 // Upper - Lower
3845 auto *UBExpr = TestIsLessOp ? UB : LB;
3846 auto *LBExpr = TestIsLessOp ? LB : UB;
3847 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3848 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3849 if (!Upper || !Lower)
3850 return nullptr;
3851
3852 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3853
3854 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3855 // BuildBinOp already emitted error, this one is to point user to upper
3856 // and lower bound, and to tell what is passed to 'operator-'.
3857 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3858 << Upper->getSourceRange() << Lower->getSourceRange();
3859 return nullptr;
3860 }
3861 }
3862
3863 if (!Diff.isUsable())
3864 return nullptr;
3865
3866 // Upper - Lower [- 1]
3867 if (TestIsStrictOp)
3868 Diff = SemaRef.BuildBinOp(
3869 S, DefaultLoc, BO_Sub, Diff.get(),
3870 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3871 if (!Diff.isUsable())
3872 return nullptr;
3873
3874 // Upper - Lower [- 1] + Step
3875 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3876 if (!NewStep.isUsable())
3877 return nullptr;
3878 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3879 if (!Diff.isUsable())
3880 return nullptr;
3881
3882 // Parentheses (for dumping/debugging purposes only).
3883 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3884 if (!Diff.isUsable())
3885 return nullptr;
3886
3887 // (Upper - Lower [- 1] + Step) / Step
3888 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3889 if (!Diff.isUsable())
3890 return nullptr;
3891
3892 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3893 QualType Type = Diff.get()->getType();
3894 auto &C = SemaRef.Context;
3895 bool UseVarType = VarType->hasIntegerRepresentation() &&
3896 C.getTypeSize(Type) > C.getTypeSize(VarType);
3897 if (!Type->isIntegerType() || UseVarType) {
3898 unsigned NewSize =
3899 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3900 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3901 : Type->hasSignedIntegerRepresentation();
3902 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3903 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3904 Diff = SemaRef.PerformImplicitConversion(
3905 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3906 if (!Diff.isUsable())
3907 return nullptr;
3908 }
3909 }
3910 if (LimitedType) {
3911 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3912 if (NewSize != C.getTypeSize(Type)) {
3913 if (NewSize < C.getTypeSize(Type)) {
3914 assert(NewSize == 64 && "incorrect loop var size")((NewSize == 64 && "incorrect loop var size") ? static_cast
<void> (0) : __assert_fail ("NewSize == 64 && \"incorrect loop var size\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3914, __PRETTY_FUNCTION__))
;
3915 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3916 << InitSrcRange << ConditionSrcRange;
3917 }
3918 QualType NewType = C.getIntTypeForBitwidth(
3919 NewSize, Type->hasSignedIntegerRepresentation() ||
3920 C.getTypeSize(Type) < NewSize);
3921 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3922 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3923 Sema::AA_Converting, true);
3924 if (!Diff.isUsable())
3925 return nullptr;
3926 }
3927 }
3928 }
3929
3930 return Diff.get();
3931}
3932
3933Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3934 Scope *S, Expr *Cond,
3935 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3936 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3937 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3938 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3939
3940 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3941 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3942 if (!NewLB.isUsable() || !NewUB.isUsable())
3943 return nullptr;
3944
3945 auto CondExpr = SemaRef.BuildBinOp(
3946 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3947 : (TestIsStrictOp ? BO_GT : BO_GE),
3948 NewLB.get(), NewUB.get());
3949 if (CondExpr.isUsable()) {
3950 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3951 SemaRef.Context.BoolTy))
3952 CondExpr = SemaRef.PerformImplicitConversion(
3953 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3954 /*AllowExplicit=*/true);
3955 }
3956 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3957 // Otherwise use original loop conditon and evaluate it in runtime.
3958 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3959}
3960
3961/// \brief Build reference expression to the counter be used for codegen.
3962DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3963 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3964 auto *VD = dyn_cast<VarDecl>(LCDecl);
3965 if (!VD) {
3966 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3967 auto *Ref = buildDeclRefExpr(
3968 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3969 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3970 // If the loop control decl is explicitly marked as private, do not mark it
3971 // as captured again.
3972 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3973 Captures.insert(std::make_pair(LCRef, Ref));
3974 return Ref;
3975 }
3976 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3977 DefaultLoc);
3978}
3979
3980Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3981 if (LCDecl && !LCDecl->isInvalidDecl()) {
3982 auto Type = LCDecl->getType().getNonReferenceType();
3983 auto *PrivateVar =
3984 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3985 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3986 if (PrivateVar->isInvalidDecl())
3987 return nullptr;
3988 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3989 }
3990 return nullptr;
3991}
3992
3993/// \brief Build initialization of the counter to be used for codegen.
3994Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3995
3996/// \brief Build step of the counter be used for codegen.
3997Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3998
3999/// \brief Iteration space of a single for loop.
4000struct LoopIterationSpace final {
4001 /// \brief Condition of the loop.
4002 Expr *PreCond = nullptr;
4003 /// \brief This expression calculates the number of iterations in the loop.
4004 /// It is always possible to calculate it before starting the loop.
4005 Expr *NumIterations = nullptr;
4006 /// \brief The loop counter variable.
4007 Expr *CounterVar = nullptr;
4008 /// \brief Private loop counter variable.
4009 Expr *PrivateCounterVar = nullptr;
4010 /// \brief This is initializer for the initial value of #CounterVar.
4011 Expr *CounterInit = nullptr;
4012 /// \brief This is step for the #CounterVar used to generate its update:
4013 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4014 Expr *CounterStep = nullptr;
4015 /// \brief Should step be subtracted?
4016 bool Subtract = false;
4017 /// \brief Source range of the loop init.
4018 SourceRange InitSrcRange;
4019 /// \brief Source range of the loop condition.
4020 SourceRange CondSrcRange;
4021 /// \brief Source range of the loop increment.
4022 SourceRange IncSrcRange;
4023};
4024
4025} // namespace
4026
4027void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4028 assert(getLangOpts().OpenMP && "OpenMP is not active.")((getLangOpts().OpenMP && "OpenMP is not active.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && \"OpenMP is not active.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4028, __PRETTY_FUNCTION__))
;
4029 assert(Init && "Expected loop in canonical form.")((Init && "Expected loop in canonical form.") ? static_cast
<void> (0) : __assert_fail ("Init && \"Expected loop in canonical form.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4029, __PRETTY_FUNCTION__))
;
4030 unsigned AssociatedLoops = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops();
4031 if (AssociatedLoops > 0 &&
1
Assuming 'AssociatedLoops' is > 0
3
Taking true branch
4032 isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())
) {
2
Assuming the condition is true
4033 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4034 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4
Taking true branch
4035 if (auto *D = ISC.GetLoopDecl()) {
5
Assuming 'D' is non-null
6
Taking true branch
4036 auto *VD = dyn_cast<VarDecl>(D);
4037 if (!VD) {
7
Taking true branch
4038 if (auto *Private = IsOpenMPCapturedDecl(D))
8
Taking false branch
4039 VD = Private;
4040 else {
4041 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
9
Calling 'buildCapture'
4042 /*WithInit=*/false);
4043 VD = cast<VarDecl>(Ref->getDecl());
4044 }
4045 }
4046 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addLoopControlVariable(D, VD);
4047 }
4048 }
4049 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setAssociatedLoops(AssociatedLoops - 1);
4050 }
4051}
4052
4053/// \brief Called on a for stmt to check and extract its iteration space
4054/// for further processing (such as collapsing).
4055static bool CheckOpenMPIterationSpace(
4056 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4057 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4058 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
4059 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4060 LoopIterationSpace &ResultIterSpace,
4061 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4062 // OpenMP [2.6, Canonical Loop Form]
4063 // for (init-expr; test-expr; incr-expr) structured-block
4064 auto *For = dyn_cast_or_null<ForStmt>(S);
4065 if (!For) {
4066 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
4067 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4068 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4069 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4070 if (NestedLoopCount > 1) {
4071 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4072 SemaRef.Diag(DSA.getConstructLoc(),
4073 diag::note_omp_collapse_ordered_expr)
4074 << 2 << CollapseLoopCountExpr->getSourceRange()
4075 << OrderedLoopCountExpr->getSourceRange();
4076 else if (CollapseLoopCountExpr)
4077 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4078 diag::note_omp_collapse_ordered_expr)
4079 << 0 << CollapseLoopCountExpr->getSourceRange();
4080 else
4081 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4082 diag::note_omp_collapse_ordered_expr)
4083 << 1 << OrderedLoopCountExpr->getSourceRange();
4084 }
4085 return true;
4086 }
4087 assert(For->getBody())((For->getBody()) ? static_cast<void> (0) : __assert_fail
("For->getBody()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4087, __PRETTY_FUNCTION__))
;
4088
4089 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4090
4091 // Check init.
4092 auto Init = For->getInit();
4093 if (ISC.CheckInit(Init))
4094 return true;
4095
4096 bool HasErrors = false;
4097
4098 // Check loop variable's type.
4099 if (auto *LCDecl = ISC.GetLoopDecl()) {
4100 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
4101
4102 // OpenMP [2.6, Canonical Loop Form]
4103 // Var is one of the following:
4104 // A variable of signed or unsigned integer type.
4105 // For C++, a variable of a random access iterator type.
4106 // For C, a variable of a pointer type.
4107 auto VarType = LCDecl->getType().getNonReferenceType();
4108 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4109 !VarType->isPointerType() &&
4110 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4111 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4112 << SemaRef.getLangOpts().CPlusPlus;
4113 HasErrors = true;
4114 }
4115
4116 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4117 // a Construct
4118 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4119 // parallel for construct is (are) private.
4120 // The loop iteration variable in the associated for-loop of a simd
4121 // construct with just one associated for-loop is linear with a
4122 // constant-linear-step that is the increment of the associated for-loop.
4123 // Exclude loop var from the list of variables with implicitly defined data
4124 // sharing attributes.
4125 VarsWithImplicitDSA.erase(LCDecl);
4126
4127 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4128 // in a Construct, C/C++].
4129 // The loop iteration variable in the associated for-loop of a simd
4130 // construct with just one associated for-loop may be listed in a linear
4131 // clause with a constant-linear-step that is the increment of the
4132 // associated for-loop.
4133 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4134 // parallel for construct may be listed in a private or lastprivate clause.
4135 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4136 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4137 // declared in the loop and it is predetermined as a private.
4138 auto PredeterminedCKind =
4139 isOpenMPSimdDirective(DKind)
4140 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4141 : OMPC_private;
4142 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4143 DVar.CKind != PredeterminedCKind) ||
4144 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4145 isOpenMPDistributeDirective(DKind)) &&
4146 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4147 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4148 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4149 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4150 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4151 << getOpenMPClauseName(PredeterminedCKind);
4152 if (DVar.RefExpr == nullptr)
4153 DVar.CKind = PredeterminedCKind;
4154 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4155 HasErrors = true;
4156 } else if (LoopDeclRefExpr != nullptr) {
4157 // Make the loop iteration variable private (for worksharing constructs),
4158 // linear (for simd directives with the only one associated loop) or
4159 // lastprivate (for simd directives with several collapsed or ordered
4160 // loops).
4161 if (DVar.CKind == OMPC_unknown)
4162 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4163 [](OpenMPDirectiveKind) -> bool { return true; },
4164 /*FromParent=*/false);
4165 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4166 }
4167
4168 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars")((isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(DKind) && \"DSA for non-loop vars\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4168, __PRETTY_FUNCTION__))
;
4169
4170 // Check test-expr.
4171 HasErrors |= ISC.CheckCond(For->getCond());
4172
4173 // Check incr-expr.
4174 HasErrors |= ISC.CheckInc(For->getInc());
4175 }
4176
4177 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4178 return HasErrors;
4179
4180 // Build the loop's iteration space representation.
4181 ResultIterSpace.PreCond =
4182 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4183 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
4184 DSA.getCurScope(),
4185 (isOpenMPWorksharingDirective(DKind) ||
4186 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4187 Captures);
4188 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
4189 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
4190 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4191 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4192 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4193 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4194 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4195 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4196
4197 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4198 ResultIterSpace.NumIterations == nullptr ||
4199 ResultIterSpace.CounterVar == nullptr ||
4200 ResultIterSpace.PrivateCounterVar == nullptr ||
4201 ResultIterSpace.CounterInit == nullptr ||
4202 ResultIterSpace.CounterStep == nullptr);
4203
4204 return HasErrors;
4205}
4206
4207/// \brief Build 'VarRef = Start.
4208static ExprResult
4209BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4210 ExprResult Start,
4211 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4212 // Build 'VarRef = Start.
4213 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4214 if (!NewStart.isUsable())
4215 return ExprError();
4216 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4217 VarRef.get()->getType())) {
4218 NewStart = SemaRef.PerformImplicitConversion(
4219 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4220 /*AllowExplicit=*/true);
4221 if (!NewStart.isUsable())
4222 return ExprError();
4223 }
4224
4225 auto Init =
4226 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4227 return Init;
4228}
4229
4230/// \brief Build 'VarRef = Start + Iter * Step'.
4231static ExprResult
4232BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4233 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4234 ExprResult Step, bool Subtract,
4235 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
4236 // Add parentheses (for debugging purposes only).
4237 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4238 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4239 !Step.isUsable())
4240 return ExprError();
4241
4242 ExprResult NewStep = Step;
4243 if (Captures)
4244 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4245 if (NewStep.isInvalid())
4246 return ExprError();
4247 ExprResult Update =
4248 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4249 if (!Update.isUsable())
4250 return ExprError();
4251
4252 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4253 // 'VarRef = Start (+|-) Iter * Step'.
4254 ExprResult NewStart = Start;
4255 if (Captures)
4256 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4257 if (NewStart.isInvalid())
4258 return ExprError();
4259
4260 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4261 ExprResult SavedUpdate = Update;
4262 ExprResult UpdateVal;
4263 if (VarRef.get()->getType()->isOverloadableType() ||
4264 NewStart.get()->getType()->isOverloadableType() ||
4265 Update.get()->getType()->isOverloadableType()) {
4266 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4267 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4268 Update =
4269 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4270 if (Update.isUsable()) {
4271 UpdateVal =
4272 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4273 VarRef.get(), SavedUpdate.get());
4274 if (UpdateVal.isUsable()) {
4275 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4276 UpdateVal.get());
4277 }
4278 }
4279 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4280 }
4281
4282 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4283 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4284 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4285 NewStart.get(), SavedUpdate.get());
4286 if (!Update.isUsable())
4287 return ExprError();
4288
4289 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4290 VarRef.get()->getType())) {
4291 Update = SemaRef.PerformImplicitConversion(
4292 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4293 if (!Update.isUsable())
4294 return ExprError();
4295 }
4296
4297 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4298 }
4299 return Update;
4300}
4301
4302/// \brief Convert integer expression \a E to make it have at least \a Bits
4303/// bits.
4304static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4305 if (E == nullptr)
4306 return ExprError();
4307 auto &C = SemaRef.Context;
4308 QualType OldType = E->getType();
4309 unsigned HasBits = C.getTypeSize(OldType);
4310 if (HasBits >= Bits)
4311 return ExprResult(E);
4312 // OK to convert to signed, because new type has more bits than old.
4313 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4314 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4315 true);
4316}
4317
4318/// \brief Check if the given expression \a E is a constant integer that fits
4319/// into \a Bits bits.
4320static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4321 if (E == nullptr)
4322 return false;
4323 llvm::APSInt Result;
4324 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4325 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4326 return false;
4327}
4328
4329/// Build preinits statement for the given declarations.
4330static Stmt *buildPreInits(ASTContext &Context,
4331 MutableArrayRef<Decl *> PreInits) {
4332 if (!PreInits.empty()) {
4333 return new (Context) DeclStmt(
4334 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4335 SourceLocation(), SourceLocation());
4336 }
4337 return nullptr;
4338}
4339
4340/// Build preinits statement for the given declarations.
4341static Stmt *
4342buildPreInits(ASTContext &Context,
4343 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4344 if (!Captures.empty()) {
4345 SmallVector<Decl *, 16> PreInits;
4346 for (auto &Pair : Captures)
4347 PreInits.push_back(Pair.second->getDecl());
4348 return buildPreInits(Context, PreInits);
4349 }
4350 return nullptr;
4351}
4352
4353/// Build postupdate expression for the given list of postupdates expressions.
4354static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4355 Expr *PostUpdate = nullptr;
4356 if (!PostUpdates.empty()) {
4357 for (auto *E : PostUpdates) {
4358 Expr *ConvE = S.BuildCStyleCastExpr(
4359 E->getExprLoc(),
4360 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4361 E->getExprLoc(), E)
4362 .get();
4363 PostUpdate = PostUpdate
4364 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4365 PostUpdate, ConvE)
4366 .get()
4367 : ConvE;
4368 }
4369 }
4370 return PostUpdate;
4371}
4372
4373/// \brief Called on a for stmt to check itself and nested loops (if any).
4374/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4375/// number of collapsed loops otherwise.
4376static unsigned
4377CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4378 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4379 DSAStackTy &DSA,
4380 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4381 OMPLoopDirective::HelperExprs &Built) {
4382 unsigned NestedLoopCount = 1;
4383 if (CollapseLoopCountExpr) {
4384 // Found 'collapse' clause - calculate collapse number.
4385 llvm::APSInt Result;
4386 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4387 NestedLoopCount = Result.getLimitedValue();
4388 }
4389 if (OrderedLoopCountExpr) {
4390 // Found 'ordered' clause - calculate collapse number.
4391 llvm::APSInt Result;
4392 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4393 if (Result.getLimitedValue() < NestedLoopCount) {
4394 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4395 diag::err_omp_wrong_ordered_loop_count)
4396 << OrderedLoopCountExpr->getSourceRange();
4397 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4398 diag::note_collapse_loop_count)
4399 << CollapseLoopCountExpr->getSourceRange();
4400 }
4401 NestedLoopCount = Result.getLimitedValue();
4402 }
4403 }
4404 // This is helper routine for loop directives (e.g., 'for', 'simd',
4405 // 'for simd', etc.).
4406 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
4407 SmallVector<LoopIterationSpace, 4> IterSpaces;
4408 IterSpaces.resize(NestedLoopCount);
4409 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4410 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4411 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4412 NestedLoopCount, CollapseLoopCountExpr,
4413 OrderedLoopCountExpr, VarsWithImplicitDSA,
4414 IterSpaces[Cnt], Captures))
4415 return 0;
4416 // Move on to the next nested for loop, or to the loop body.
4417 // OpenMP [2.8.1, simd construct, Restrictions]
4418 // All loops associated with the construct must be perfectly nested; that
4419 // is, there must be no intervening code nor any OpenMP directive between
4420 // any two loops.
4421 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4422 }
4423
4424 Built.clear(/* size */ NestedLoopCount);
4425
4426 if (SemaRef.CurContext->isDependentContext())
4427 return NestedLoopCount;
4428
4429 // An example of what is generated for the following code:
4430 //
4431 // #pragma omp simd collapse(2) ordered(2)
4432 // for (i = 0; i < NI; ++i)
4433 // for (k = 0; k < NK; ++k)
4434 // for (j = J0; j < NJ; j+=2) {
4435 // <loop body>
4436 // }
4437 //
4438 // We generate the code below.
4439 // Note: the loop body may be outlined in CodeGen.
4440 // Note: some counters may be C++ classes, operator- is used to find number of
4441 // iterations and operator+= to calculate counter value.
4442 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4443 // or i64 is currently supported).
4444 //
4445 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4446 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4447 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4448 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4449 // // similar updates for vars in clauses (e.g. 'linear')
4450 // <loop body (using local i and j)>
4451 // }
4452 // i = NI; // assign final values of counters
4453 // j = NJ;
4454 //
4455
4456 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4457 // the iteration counts of the collapsed for loops.
4458 // Precondition tests if there is at least one iteration (all conditions are
4459 // true).
4460 auto PreCond = ExprResult(IterSpaces[0].PreCond);
4461 auto N0 = IterSpaces[0].NumIterations;
4462 ExprResult LastIteration32 = WidenIterationCount(
4463 32 /* Bits */, SemaRef
4464 .PerformImplicitConversion(
4465 N0->IgnoreImpCasts(), N0->getType(),
4466 Sema::AA_Converting, /*AllowExplicit=*/true)
4467 .get(),
4468 SemaRef);
4469 ExprResult LastIteration64 = WidenIterationCount(
4470 64 /* Bits */, SemaRef
4471 .PerformImplicitConversion(
4472 N0->IgnoreImpCasts(), N0->getType(),
4473 Sema::AA_Converting, /*AllowExplicit=*/true)
4474 .get(),
4475 SemaRef);
4476
4477 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4478 return NestedLoopCount;
4479
4480 auto &C = SemaRef.Context;
4481 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4482
4483 Scope *CurScope = DSA.getCurScope();
4484 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4485 if (PreCond.isUsable()) {
4486 PreCond =
4487 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4488 PreCond.get(), IterSpaces[Cnt].PreCond);
4489 }
4490 auto N = IterSpaces[Cnt].NumIterations;
4491 SourceLocation Loc = N->getExprLoc();
4492 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4493 if (LastIteration32.isUsable())
4494 LastIteration32 = SemaRef.BuildBinOp(
4495 CurScope, Loc, BO_Mul, LastIteration32.get(),
4496 SemaRef
4497 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4498 Sema::AA_Converting,
4499 /*AllowExplicit=*/true)
4500 .get());
4501 if (LastIteration64.isUsable())
4502 LastIteration64 = SemaRef.BuildBinOp(
4503 CurScope, Loc, BO_Mul, LastIteration64.get(),
4504 SemaRef
4505 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4506 Sema::AA_Converting,
4507 /*AllowExplicit=*/true)
4508 .get());
4509 }
4510
4511 // Choose either the 32-bit or 64-bit version.
4512 ExprResult LastIteration = LastIteration64;
4513 if (LastIteration32.isUsable() &&
4514 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4515 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4516 FitsInto(
4517 32 /* Bits */,
4518 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4519 LastIteration64.get(), SemaRef)))
4520 LastIteration = LastIteration32;
4521 QualType VType = LastIteration.get()->getType();
4522 QualType RealVType = VType;
4523 QualType StrideVType = VType;
4524 if (isOpenMPTaskLoopDirective(DKind)) {
4525 VType =
4526 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4527 StrideVType =
4528 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4529 }
4530
4531 if (!LastIteration.isUsable())
4532 return 0;
4533
4534 // Save the number of iterations.
4535 ExprResult NumIterations = LastIteration;
4536 {
4537 LastIteration = SemaRef.BuildBinOp(
4538 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4539 LastIteration.get(),
4540 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4541 if (!LastIteration.isUsable())
4542 return 0;
4543 }
4544
4545 // Calculate the last iteration number beforehand instead of doing this on
4546 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4547 llvm::APSInt Result;
4548 bool IsConstant =
4549 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4550 ExprResult CalcLastIteration;
4551 if (!IsConstant) {
4552 ExprResult SaveRef =
4553 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4554 LastIteration = SaveRef;
4555
4556 // Prepare SaveRef + 1.
4557 NumIterations = SemaRef.BuildBinOp(
4558 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4559 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4560 if (!NumIterations.isUsable())
4561 return 0;
4562 }
4563
4564 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4565
4566 // Build variables passed into runtime, necessary for worksharing directives.
4567 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
4568 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4569 isOpenMPDistributeDirective(DKind)) {
4570 // Lower bound variable, initialized with zero.
4571 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4572 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4573 SemaRef.AddInitializerToDecl(LBDecl,
4574 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4575 /*DirectInit*/ false);
4576
4577 // Upper bound variable, initialized with last iteration number.
4578 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4579 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4580 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4581 /*DirectInit*/ false);
4582
4583 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4584 // This will be used to implement clause 'lastprivate'.
4585 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4586 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4587 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4588 SemaRef.AddInitializerToDecl(ILDecl,
4589 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4590 /*DirectInit*/ false);
4591
4592 // Stride variable returned by runtime (we initialize it to 1 by default).
4593 VarDecl *STDecl =
4594 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4595 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4596 SemaRef.AddInitializerToDecl(STDecl,
4597 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4598 /*DirectInit*/ false);
4599
4600 // Build expression: UB = min(UB, LastIteration)
4601 // It is necessary for CodeGen of directives with static scheduling.
4602 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4603 UB.get(), LastIteration.get());
4604 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4605 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4606 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4607 CondOp.get());
4608 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4609
4610 // If we have a combined directive that combines 'distribute', 'for' or
4611 // 'simd' we need to be able to access the bounds of the schedule of the
4612 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4613 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4614 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4615
4616 // Lower bound variable, initialized with zero.
4617 VarDecl *CombLBDecl =
4618 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4619 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4620 SemaRef.AddInitializerToDecl(
4621 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4622 /*DirectInit*/ false);
4623
4624 // Upper bound variable, initialized with last iteration number.
4625 VarDecl *CombUBDecl =
4626 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4627 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4628 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4629 /*DirectInit*/ false);
4630
4631 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4632 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4633 ExprResult CombCondOp =
4634 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4635 LastIteration.get(), CombUB.get());
4636 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4637 CombCondOp.get());
4638 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4639
4640 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4641 // We expect to have at least 2 more parameters than the 'parallel'
4642 // directive does - the lower and upper bounds of the previous schedule.
4643 assert(CD->getNumParams() >= 4 &&((CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"
) ? static_cast<void> (0) : __assert_fail ("CD->getNumParams() >= 4 && \"Unexpected number of parameters in loop combined directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4644, __PRETTY_FUNCTION__))
4644 "Unexpected number of parameters in loop combined directive")((CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"
) ? static_cast<void> (0) : __assert_fail ("CD->getNumParams() >= 4 && \"Unexpected number of parameters in loop combined directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4644, __PRETTY_FUNCTION__))
;
4645
4646 // Set the proper type for the bounds given what we learned from the
4647 // enclosed loops.
4648 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4649 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4650
4651 // Previous lower and upper bounds are obtained from the region
4652 // parameters.
4653 PrevLB =
4654 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4655 PrevUB =
4656 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4657 }
4658 }
4659
4660 // Build the iteration variable and its initialization before loop.
4661 ExprResult IV;
4662 ExprResult Init, CombInit;
4663 {
4664 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4665 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4666 Expr *RHS =
4667 (isOpenMPWorksharingDirective(DKind) ||
4668 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4669 ? LB.get()
4670 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4671 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4672 Init = SemaRef.ActOnFinishFullExpr(Init.get());
4673
4674 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4675 Expr *CombRHS =
4676 (isOpenMPWorksharingDirective(DKind) ||
4677 isOpenMPTaskLoopDirective(DKind) ||
4678 isOpenMPDistributeDirective(DKind))
4679 ? CombLB.get()
4680 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4681 CombInit =
4682 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4683 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4684 }
4685 }
4686
4687 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4688 SourceLocation CondLoc;
4689 ExprResult Cond =
4690 (isOpenMPWorksharingDirective(DKind) ||
4691 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4692 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4693 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4694 NumIterations.get());
4695 ExprResult CombCond;
4696 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4697 CombCond =
4698 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4699 }
4700 // Loop increment (IV = IV + 1)
4701 SourceLocation IncLoc;
4702 ExprResult Inc =
4703 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4704 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4705 if (!Inc.isUsable())
4706 return 0;
4707 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4708 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4709 if (!Inc.isUsable())
4710 return 0;
4711
4712 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4713 // Used for directives with static scheduling.
4714 // In combined construct, add combined version that use CombLB and CombUB
4715 // base variables for the update
4716 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
4717 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4718 isOpenMPDistributeDirective(DKind)) {
4719 // LB + ST
4720 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4721 if (!NextLB.isUsable())
4722 return 0;
4723 // LB = LB + ST
4724 NextLB =
4725 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4726 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4727 if (!NextLB.isUsable())
4728 return 0;
4729 // UB + ST
4730 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4731 if (!NextUB.isUsable())
4732 return 0;
4733 // UB = UB + ST
4734 NextUB =
4735 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4736 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4737 if (!NextUB.isUsable())
4738 return 0;
4739 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4740 CombNextLB =
4741 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4742 if (!NextLB.isUsable())
4743 return 0;
4744 // LB = LB + ST
4745 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4746 CombNextLB.get());
4747 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4748 if (!CombNextLB.isUsable())
4749 return 0;
4750 // UB + ST
4751 CombNextUB =
4752 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4753 if (!CombNextUB.isUsable())
4754 return 0;
4755 // UB = UB + ST
4756 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4757 CombNextUB.get());
4758 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4759 if (!CombNextUB.isUsable())
4760 return 0;
4761 }
4762 }
4763
4764 // Create increment expression for distribute loop when combined in a same
4765 // directive with for as IV = IV + ST; ensure upper bound expression based
4766 // on PrevUB instead of NumIterations - used to implement 'for' when found
4767 // in combination with 'distribute', like in 'distribute parallel for'
4768 SourceLocation DistIncLoc;
4769 ExprResult DistCond, DistInc, PrevEUB;
4770 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4771 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4772 assert(DistCond.isUsable() && "distribute cond expr was not built")((DistCond.isUsable() && "distribute cond expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistCond.isUsable() && \"distribute cond expr was not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4772, __PRETTY_FUNCTION__))
;
4773
4774 DistInc =
4775 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4776 assert(DistInc.isUsable() && "distribute inc expr was not built")((DistInc.isUsable() && "distribute inc expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistInc.isUsable() && \"distribute inc expr was not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4776, __PRETTY_FUNCTION__))
;
4777 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4778 DistInc.get());
4779 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4780 assert(DistInc.isUsable() && "distribute inc expr was not built")((DistInc.isUsable() && "distribute inc expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistInc.isUsable() && \"distribute inc expr was not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4780, __PRETTY_FUNCTION__))
;
4781
4782 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4783 // construct
4784 SourceLocation DistEUBLoc;
4785 ExprResult IsUBGreater =
4786 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4787 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4788 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4789 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4790 CondOp.get());
4791 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4792 }
4793
4794 // Build updates and final values of the loop counters.
4795 bool HasErrors = false;
4796 Built.Counters.resize(NestedLoopCount);
4797 Built.Inits.resize(NestedLoopCount);
4798 Built.Updates.resize(NestedLoopCount);
4799 Built.Finals.resize(NestedLoopCount);
4800 SmallVector<Expr *, 4> LoopMultipliers;
4801 {
4802 ExprResult Div;
4803 // Go from inner nested loop to outer.
4804 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4805 LoopIterationSpace &IS = IterSpaces[Cnt];
4806 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4807 // Build: Iter = (IV / Div) % IS.NumIters
4808 // where Div is product of previous iterations' IS.NumIters.
4809 ExprResult Iter;
4810 if (Div.isUsable()) {
4811 Iter =
4812 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4813 } else {
4814 Iter = IV;
4815 assert((Cnt == (int)NestedLoopCount - 1) &&(((Cnt == (int)NestedLoopCount - 1) && "unusable div expected on first iteration only"
) ? static_cast<void> (0) : __assert_fail ("(Cnt == (int)NestedLoopCount - 1) && \"unusable div expected on first iteration only\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4816, __PRETTY_FUNCTION__))
4816 "unusable div expected on first iteration only")(((Cnt == (int)NestedLoopCount - 1) && "unusable div expected on first iteration only"
) ? static_cast<void> (0) : __assert_fail ("(Cnt == (int)NestedLoopCount - 1) && \"unusable div expected on first iteration only\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4816, __PRETTY_FUNCTION__))
;
4817 }
4818
4819 if (Cnt != 0 && Iter.isUsable())
4820 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4821 IS.NumIterations);
4822 if (!Iter.isUsable()) {
4823 HasErrors = true;
4824 break;
4825 }
4826
4827 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4828 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4829 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4830 IS.CounterVar->getExprLoc(),
4831 /*RefersToCapture=*/true);
4832 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4833 IS.CounterInit, Captures);
4834 if (!Init.isUsable()) {
4835 HasErrors = true;
4836 break;
4837 }
4838 ExprResult Update = BuildCounterUpdate(
4839 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4840 IS.CounterStep, IS.Subtract, &Captures);
4841 if (!Update.isUsable()) {
4842 HasErrors = true;
4843 break;
4844 }
4845
4846 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4847 ExprResult Final = BuildCounterUpdate(
4848 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4849 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4850 if (!Final.isUsable()) {
4851 HasErrors = true;
4852 break;
4853 }
4854
4855 // Build Div for the next iteration: Div <- Div * IS.NumIters
4856 if (Cnt != 0) {
4857 if (Div.isUnset())
4858 Div = IS.NumIterations;
4859 else
4860 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4861 IS.NumIterations);
4862
4863 // Add parentheses (for debugging purposes only).
4864 if (Div.isUsable())
4865 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4866 if (!Div.isUsable()) {
4867 HasErrors = true;
4868 break;
4869 }
4870 LoopMultipliers.push_back(Div.get());
4871 }
4872 if (!Update.isUsable() || !Final.isUsable()) {
4873 HasErrors = true;
4874 break;
4875 }
4876 // Save results
4877 Built.Counters[Cnt] = IS.CounterVar;
4878 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4879 Built.Inits[Cnt] = Init.get();
4880 Built.Updates[Cnt] = Update.get();
4881 Built.Finals[Cnt] = Final.get();
4882 }
4883 }
4884
4885 if (HasErrors)
4886 return 0;
4887
4888 // Save results
4889 Built.IterationVarRef = IV.get();
4890 Built.LastIteration = LastIteration.get();
4891 Built.NumIterations = NumIterations.get();
4892 Built.CalcLastIteration =
4893 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4894 Built.PreCond = PreCond.get();
4895 Built.PreInits = buildPreInits(C, Captures);
4896 Built.Cond = Cond.get();
4897 Built.Init = Init.get();
4898 Built.Inc = Inc.get();
4899 Built.LB = LB.get();
4900 Built.UB = UB.get();
4901 Built.IL = IL.get();
4902 Built.ST = ST.get();
4903 Built.EUB = EUB.get();
4904 Built.NLB = NextLB.get();
4905 Built.NUB = NextUB.get();
4906 Built.PrevLB = PrevLB.get();
4907 Built.PrevUB = PrevUB.get();
4908 Built.DistInc = DistInc.get();
4909 Built.PrevEUB = PrevEUB.get();
4910 Built.DistCombinedFields.LB = CombLB.get();
4911 Built.DistCombinedFields.UB = CombUB.get();
4912 Built.DistCombinedFields.EUB = CombEUB.get();
4913 Built.DistCombinedFields.Init = CombInit.get();
4914 Built.DistCombinedFields.Cond = CombCond.get();
4915 Built.DistCombinedFields.NLB = CombNextLB.get();
4916 Built.DistCombinedFields.NUB = CombNextUB.get();
4917
4918 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4919 // Fill data for doacross depend clauses.
4920 for (auto Pair : DSA.getDoacrossDependClauses()) {
4921 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4922 Pair.first->setCounterValue(CounterVal);
4923 else {
4924 if (NestedLoopCount != Pair.second.size() ||
4925 NestedLoopCount != LoopMultipliers.size() + 1) {
4926 // Erroneous case - clause has some problems.
4927 Pair.first->setCounterValue(CounterVal);
4928 continue;
4929 }
4930 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink)((Pair.first->getDependencyKind() == OMPC_DEPEND_sink) ? static_cast
<void> (0) : __assert_fail ("Pair.first->getDependencyKind() == OMPC_DEPEND_sink"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4930, __PRETTY_FUNCTION__))
;
4931 auto I = Pair.second.rbegin();
4932 auto IS = IterSpaces.rbegin();
4933 auto ILM = LoopMultipliers.rbegin();
4934 Expr *UpCounterVal = CounterVal;
4935 Expr *Multiplier = nullptr;
4936 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4937 if (I->first) {
4938 assert(IS->CounterStep)((IS->CounterStep) ? static_cast<void> (0) : __assert_fail
("IS->CounterStep", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4938, __PRETTY_FUNCTION__))
;
4939 Expr *NormalizedOffset =
4940 SemaRef
4941 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4942 I->first, IS->CounterStep)
4943 .get();
4944 if (Multiplier) {
4945 NormalizedOffset =
4946 SemaRef
4947 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4948 NormalizedOffset, Multiplier)
4949 .get();
4950 }
4951 assert(I->second == OO_Plus || I->second == OO_Minus)((I->second == OO_Plus || I->second == OO_Minus) ? static_cast
<void> (0) : __assert_fail ("I->second == OO_Plus || I->second == OO_Minus"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4951, __PRETTY_FUNCTION__))
;
4952 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4953 UpCounterVal = SemaRef
4954 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4955 UpCounterVal, NormalizedOffset)
4956 .get();
4957 }
4958 Multiplier = *ILM;
4959 ++I;
4960 ++IS;
4961 ++ILM;
4962 }
4963 Pair.first->setCounterValue(UpCounterVal);
4964 }
4965 }
4966
4967 return NestedLoopCount;
4968}
4969
4970static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4971 auto CollapseClauses =
4972 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4973 if (CollapseClauses.begin() != CollapseClauses.end())
4974 return (*CollapseClauses.begin())->getNumForLoops();
4975 return nullptr;
4976}
4977
4978static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4979 auto OrderedClauses =
4980 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4981 if (OrderedClauses.begin() != OrderedClauses.end())
4982 return (*OrderedClauses.begin())->getNumForLoops();
4983 return nullptr;
4984}
4985
4986static bool checkSimdlenSafelenSpecified(Sema &S,
4987 const ArrayRef<OMPClause *> Clauses) {
4988 OMPSafelenClause *Safelen = nullptr;
4989 OMPSimdlenClause *Simdlen = nullptr;
4990
4991 for (auto *Clause : Clauses) {
4992 if (Clause->getClauseKind() == OMPC_safelen)
4993 Safelen = cast<OMPSafelenClause>(Clause);
4994 else if (Clause->getClauseKind() == OMPC_simdlen)
4995 Simdlen = cast<OMPSimdlenClause>(Clause);
4996 if (Safelen && Simdlen)
4997 break;
4998 }
4999
5000 if (Simdlen && Safelen) {
5001 llvm::APSInt SimdlenRes, SafelenRes;
5002 auto SimdlenLength = Simdlen->getSimdlen();
5003 auto SafelenLength = Safelen->getSafelen();
5004 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5005 SimdlenLength->isInstantiationDependent() ||
5006 SimdlenLength->containsUnexpandedParameterPack())
5007 return false;
5008 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5009 SafelenLength->isInstantiationDependent() ||
5010 SafelenLength->containsUnexpandedParameterPack())
5011 return false;
5012 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5013 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5014 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5015 // If both simdlen and safelen clauses are specified, the value of the
5016 // simdlen parameter must be less than or equal to the value of the safelen
5017 // parameter.
5018 if (SimdlenRes > SafelenRes) {
5019 S.Diag(SimdlenLength->getExprLoc(),
5020 diag::err_omp_wrong_simdlen_safelen_values)
5021 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5022 return true;
5023 }
5024 }
5025 return false;
5026}
5027
5028StmtResult Sema::ActOnOpenMPSimdDirective(
5029 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5030 SourceLocation EndLoc,
5031 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5032 if (!AStmt)
5033 return StmtError();
5034
5035 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5035, __PRETTY_FUNCTION__))
;
5036 OMPLoopDirective::HelperExprs B;
5037 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5038 // define the nested loops number.
5039 unsigned NestedLoopCount = CheckOpenMPLoop(
5040 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5041 AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
5042 if (NestedLoopCount == 0)
5043 return StmtError();
5044
5045 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp simd loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5046, __PRETTY_FUNCTION__))
5046 "omp simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp simd loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5046, __PRETTY_FUNCTION__))
;
5047
5048 if (!CurContext->isDependentContext()) {
5049 // Finalize the clauses that need pre-built expressions for CodeGen.
5050 for (auto C : Clauses) {
5051 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5052 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5053 B.NumIterations, *this, CurScope,
5054 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
5055 return StmtError();
5056 }
5057 }
5058
5059 if (checkSimdlenSafelenSpecified(*this, Clauses))
5060 return StmtError();
5061
5062 getCurFunction()->setHasBranchProtectedScope();
5063 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5064 Clauses, AStmt, B);
5065}
5066
5067StmtResult Sema::ActOnOpenMPForDirective(
5068 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5069 SourceLocation EndLoc,
5070 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5071 if (!AStmt)
5072 return StmtError();
5073
5074 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5074, __PRETTY_FUNCTION__))
;
5075 OMPLoopDirective::HelperExprs B;
5076 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5077 // define the nested loops number.
5078 unsigned NestedLoopCount = CheckOpenMPLoop(
5079 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5080 AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
5081 if (NestedLoopCount == 0)
5082 return StmtError();
5083
5084 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5085, __PRETTY_FUNCTION__))
5085 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5085, __PRETTY_FUNCTION__))
;
5086
5087 if (!CurContext->isDependentContext()) {
5088 // Finalize the clauses that need pre-built expressions for CodeGen.
5089 for (auto C : Clauses) {
5090 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5091 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5092 B.NumIterations, *this, CurScope,
5093 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
5094 return StmtError();
5095 }
5096 }
5097
5098 getCurFunction()->setHasBranchProtectedScope();
5099 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5100 Clauses, AStmt, B, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5101}
5102
5103StmtResult Sema::ActOnOpenMPForSimdDirective(
5104 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5105 SourceLocation EndLoc,
5106 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5107 if (!AStmt)
5108 return StmtError();
5109
5110 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5110, __PRETTY_FUNCTION__))
;
5111 OMPLoopDirective::HelperExprs B;
5112 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5113 // define the nested loops number.
5114 unsigned NestedLoopCount =
5115 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5116 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
5117 VarsWithImplicitDSA, B);
5118 if (NestedLoopCount == 0)
5119 return StmtError();
5120
5121 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for simd loop exprs were not built") ? static_cast<void
> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5122, __PRETTY_FUNCTION__))
5122 "omp for simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for simd loop exprs were not built") ? static_cast<void
> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5122, __PRETTY_FUNCTION__))
;
5123
5124 if (!CurContext->isDependentContext()) {
5125 // Finalize the clauses that need pre-built expressions for CodeGen.
5126 for (auto C : Clauses) {
5127 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5128 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5129 B.NumIterations, *this, CurScope,
5130 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
5131 return StmtError();
5132 }
5133 }
5134
5135 if (checkSimdlenSafelenSpecified(*this, Clauses))
5136 return StmtError();
5137
5138 getCurFunction()->setHasBranchProtectedScope();
5139 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5140 Clauses, AStmt, B);
5141}
5142
5143StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5144 Stmt *AStmt,
5145 SourceLocation StartLoc,
5146 SourceLocation EndLoc) {
5147 if (!AStmt)
5148 return StmtError();
5149
5150 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5150, __PRETTY_FUNCTION__))
;
5151 auto BaseStmt = AStmt;
5152 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5153 BaseStmt = CS->getCapturedStmt();
5154 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5155 auto S = C->children();
5156 if (S.begin() == S.end())
5157 return StmtError();
5158 // All associated statements must be '#pragma omp section' except for
5159 // the first one.
5160 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5161 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5162 if (SectionStmt)
5163 Diag(SectionStmt->getLocStart(),
5164 diag::err_omp_sections_substmt_not_section);
5165 return StmtError();
5166 }
5167 cast<OMPSectionDirective>(SectionStmt)
5168 ->setHasCancel(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5169 }
5170 } else {
5171 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5172 return StmtError();
5173 }
5174
5175 getCurFunction()->setHasBranchProtectedScope();
5176
5177 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5178 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5179}
5180
5181StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5182 SourceLocation StartLoc,
5183 SourceLocation EndLoc) {
5184 if (!AStmt)
5185 return StmtError();
5186
5187 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5187, __PRETTY_FUNCTION__))
;
5188
5189 getCurFunction()->setHasBranchProtectedScope();
5190 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentCancelRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5191
5192 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5193 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5194}
5195
5196StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5197 Stmt *AStmt,
5198 SourceLocation StartLoc,
5199 SourceLocation EndLoc) {
5200 if (!AStmt)
5201 return StmtError();
5202
5203 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5203, __PRETTY_FUNCTION__))
;
5204
5205 getCurFunction()->setHasBranchProtectedScope();
5206
5207 // OpenMP [2.7.3, single Construct, Restrictions]
5208 // The copyprivate clause must not be used with the nowait clause.
5209 OMPClause *Nowait = nullptr;
5210 OMPClause *Copyprivate = nullptr;
5211 for (auto *Clause : Clauses) {
5212 if (Clause->getClauseKind() == OMPC_nowait)
5213 Nowait = Clause;
5214 else if (Clause->getClauseKind() == OMPC_copyprivate)
5215 Copyprivate = Clause;
5216 if (Copyprivate && Nowait) {
5217 Diag(Copyprivate->getLocStart(),
5218 diag::err_omp_single_copyprivate_with_nowait);
5219 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5220 return StmtError();
5221 }
5222 }
5223
5224 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5225}
5226
5227StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5228 SourceLocation StartLoc,
5229 SourceLocation EndLoc) {
5230 if (!AStmt)
5231 return StmtError();
5232
5233 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5233, __PRETTY_FUNCTION__))
;
5234
5235 getCurFunction()->setHasBranchProtectedScope();
5236
5237 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5238}
5239
5240StmtResult Sema::ActOnOpenMPCriticalDirective(
5241 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5242 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5243 if (!AStmt)
5244 return StmtError();
5245
5246 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5246, __PRETTY_FUNCTION__))
;
5247
5248 bool ErrorFound = false;
5249 llvm::APSInt Hint;
5250 SourceLocation HintLoc;
5251 bool DependentHint = false;
5252 for (auto *C : Clauses) {
5253 if (C->getClauseKind() == OMPC_hint) {
5254 if (!DirName.getName()) {
5255 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5256 ErrorFound = true;
5257 }
5258 Expr *E = cast<OMPHintClause>(C)->getHint();
5259 if (E->isTypeDependent() || E->isValueDependent() ||
5260 E->isInstantiationDependent())
5261 DependentHint = true;
5262 else {
5263 Hint = E->EvaluateKnownConstInt(Context);
5264 HintLoc = C->getLocStart();
5265 }
5266 }
5267 }
5268 if (ErrorFound)
5269 return StmtError();
5270 auto Pair = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCriticalWithHint(DirName);
5271 if (Pair.first && DirName.getName() && !DependentHint) {
5272 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5273 Diag(StartLoc, diag::err_omp_critical_with_hint);
5274 if (HintLoc.isValid()) {
5275 Diag(HintLoc, diag::note_omp_critical_hint_here)
5276 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5277 } else
5278 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5279 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5280 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5281 << 1
5282 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5283 /*Radix=*/10, /*Signed=*/false);
5284 } else
5285 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5286 }
5287 }
5288
5289 getCurFunction()->setHasBranchProtectedScope();
5290
5291 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5292 Clauses, AStmt);
5293 if (!Pair.first && DirName.getName() && !DependentHint)
5294 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addCriticalWithHint(Dir, Hint);
5295 return Dir;
5296}
5297
5298StmtResult Sema::ActOnOpenMPParallelForDirective(
5299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5300 SourceLocation EndLoc,
5301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5302 if (!AStmt)
5303 return StmtError();
5304
5305 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5306 // 1.2.2 OpenMP Language Terminology
5307 // Structured block - An executable statement with a single entry at the
5308 // top and a single exit at the bottom.
5309 // The point of exit cannot be a branch out of the structured block.
5310 // longjmp() and throw() must not violate the entry/exit criteria.
5311 CS->getCapturedDecl()->setNothrow();
5312
5313 OMPLoopDirective::HelperExprs B;
5314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5315 // define the nested loops number.
5316 unsigned NestedLoopCount =
5317 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5318 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
5319 VarsWithImplicitDSA, B);
5320 if (NestedLoopCount == 0)
5321 return StmtError();
5322
5323 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp parallel for loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5324, __PRETTY_FUNCTION__))
5324 "omp parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp parallel for loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5324, __PRETTY_FUNCTION__))
;
5325
5326 if (!CurContext->isDependentContext()) {
5327 // Finalize the clauses that need pre-built expressions for CodeGen.
5328 for (auto C : Clauses) {
5329 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5331 B.NumIterations, *this, CurScope,
5332 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
5333 return StmtError();
5334 }
5335 }
5336
5337 getCurFunction()->setHasBranchProtectedScope();
5338 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5339 NestedLoopCount, Clauses, AStmt, B,
5340 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5341}
5342
5343StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5344 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5345 SourceLocation EndLoc,
5346 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5347 if (!AStmt)
5348 return StmtError();
5349
5350 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5351 // 1.2.2 OpenMP Language Terminology
5352 // Structured block - An executable statement with a single entry at the
5353 // top and a single exit at the bottom.
5354 // The point of exit cannot be a branch out of the structured block.
5355 // longjmp() and throw() must not violate the entry/exit criteria.
5356 CS->getCapturedDecl()->setNothrow();
5357
5358 OMPLoopDirective::HelperExprs B;
5359 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5360 // define the nested loops number.
5361 unsigned NestedLoopCount =
5362 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5363 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
5364 VarsWithImplicitDSA, B);
5365 if (NestedLoopCount == 0)
5366 return StmtError();
5367
5368 if (!CurContext->isDependentContext()) {
5369 // Finalize the clauses that need pre-built expressions for CodeGen.
5370 for (auto C : Clauses) {
5371 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5372 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5373 B.NumIterations, *this, CurScope,
5374 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
5375 return StmtError();
5376 }
5377 }
5378
5379 if (checkSimdlenSafelenSpecified(*this, Clauses))
5380 return StmtError();
5381
5382 getCurFunction()->setHasBranchProtectedScope();
5383 return OMPParallelForSimdDirective::Create(
5384 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5385}
5386
5387StmtResult
5388Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5389 Stmt *AStmt, SourceLocation StartLoc,
5390 SourceLocation EndLoc) {
5391 if (!AStmt)
5392 return StmtError();
5393
5394 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5394, __PRETTY_FUNCTION__))
;
5395 auto BaseStmt = AStmt;
5396 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5397 BaseStmt = CS->getCapturedStmt();
5398 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5399 auto S = C->children();
5400 if (S.begin() == S.end())
5401 return StmtError();
5402 // All associated statements must be '#pragma omp section' except for
5403 // the first one.
5404 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5405 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5406 if (SectionStmt)
5407 Diag(SectionStmt->getLocStart(),
5408 diag::err_omp_parallel_sections_substmt_not_section);
5409 return StmtError();
5410 }
5411 cast<OMPSectionDirective>(SectionStmt)
5412 ->setHasCancel(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5413 }
5414 } else {
5415 Diag(AStmt->getLocStart(),
5416 diag::err_omp_parallel_sections_not_compound_stmt);
5417 return StmtError();
5418 }
5419
5420 getCurFunction()->setHasBranchProtectedScope();
5421
5422 return OMPParallelSectionsDirective::Create(
5423 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5424}
5425
5426StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5427 Stmt *AStmt, SourceLocation StartLoc,
5428 SourceLocation EndLoc) {
5429 if (!AStmt)
5430 return StmtError();
5431
5432 auto *CS = cast<CapturedStmt>(AStmt);
5433 // 1.2.2 OpenMP Language Terminology
5434 // Structured block - An executable statement with a single entry at the
5435 // top and a single exit at the bottom.
5436 // The point of exit cannot be a branch out of the structured block.
5437 // longjmp() and throw() must not violate the entry/exit criteria.
5438 CS->getCapturedDecl()->setNothrow();
5439
5440 getCurFunction()->setHasBranchProtectedScope();
5441
5442 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5443 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5444}
5445
5446StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5447 SourceLocation EndLoc) {
5448 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5449}
5450
5451StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5452 SourceLocation EndLoc) {
5453 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5454}
5455
5456StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5457 SourceLocation EndLoc) {
5458 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5459}
5460
5461StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5462 Stmt *AStmt,
5463 SourceLocation StartLoc,
5464 SourceLocation EndLoc) {
5465 if (!AStmt)
5466 return StmtError();
5467
5468 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5468, __PRETTY_FUNCTION__))
;
5469
5470 getCurFunction()->setHasBranchProtectedScope();
5471
5472 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5473 AStmt,
5474 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTaskgroupReductionRef());
5475}
5476
5477StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5478 SourceLocation StartLoc,
5479 SourceLocation EndLoc) {
5480 assert(Clauses.size() <= 1 && "Extra clauses in flush directive")((Clauses.size() <= 1 && "Extra clauses in flush directive"
) ? static_cast<void> (0) : __assert_fail ("Clauses.size() <= 1 && \"Extra clauses in flush directive\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5480, __PRETTY_FUNCTION__))
;
5481 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5482}
5483
5484StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5485 Stmt *AStmt,
5486 SourceLocation StartLoc,
5487 SourceLocation EndLoc) {
5488 OMPClause *DependFound = nullptr;
5489 OMPClause *DependSourceClause = nullptr;
5490 OMPClause *DependSinkClause = nullptr;
5491 bool ErrorFound = false;
5492 OMPThreadsClause *TC = nullptr;
5493 OMPSIMDClause *SC = nullptr;
5494 for (auto *C : Clauses) {
5495 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5496 DependFound = C;
5497 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5498 if (DependSourceClause) {
5499 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5500 << getOpenMPDirectiveName(OMPD_ordered)
5501 << getOpenMPClauseName(OMPC_depend) << 2;
5502 ErrorFound = true;
5503 } else
5504 DependSourceClause = C;
5505 if (DependSinkClause) {
5506 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5507 << 0;
5508 ErrorFound = true;
5509 }
5510 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5511 if (DependSourceClause) {
5512 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5513 << 1;
5514 ErrorFound = true;
5515 }
5516 DependSinkClause = C;
5517 }
5518 } else if (C->getClauseKind() == OMPC_threads)
5519 TC = cast<OMPThreadsClause>(C);
5520 else if (C->getClauseKind() == OMPC_simd)
5521 SC = cast<OMPSIMDClause>(C);
5522 }
5523 if (!ErrorFound && !SC &&
5524 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective())) {
5525 // OpenMP [2.8.1,simd Construct, Restrictions]
5526 // An ordered construct with the simd clause is the only OpenMP construct
5527 // that can appear in the simd region.
5528 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5529 ErrorFound = true;
5530 } else if (DependFound && (TC || SC)) {
5531 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5532 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5533 ErrorFound = true;
5534 } else if (DependFound && !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam()) {
5535 Diag(DependFound->getLocStart(),
5536 diag::err_omp_ordered_directive_without_param);
5537 ErrorFound = true;
5538 } else if (TC || Clauses.empty()) {
5539 if (auto *Param = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam()) {
5540 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5541 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5542 << (TC != nullptr);
5543 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5544 ErrorFound = true;
5545 }
5546 }
5547 if ((!AStmt && !DependFound) || ErrorFound)
5548 return StmtError();
5549
5550 if (AStmt) {
5551 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5551, __PRETTY_FUNCTION__))
;
5552
5553 getCurFunction()->setHasBranchProtectedScope();
5554 }
5555
5556 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5557}
5558
5559namespace {
5560/// \brief Helper class for checking expression in 'omp atomic [update]'
5561/// construct.
5562class OpenMPAtomicUpdateChecker {
5563 /// \brief Error results for atomic update expressions.
5564 enum ExprAnalysisErrorCode {
5565 /// \brief A statement is not an expression statement.
5566 NotAnExpression,
5567 /// \brief Expression is not builtin binary or unary operation.
5568 NotABinaryOrUnaryExpression,
5569 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5570 NotAnUnaryIncDecExpression,
5571 /// \brief An expression is not of scalar type.
5572 NotAScalarType,
5573 /// \brief A binary operation is not an assignment operation.
5574 NotAnAssignmentOp,
5575 /// \brief RHS part of the binary operation is not a binary expression.
5576 NotABinaryExpression,
5577 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5578 /// expression.
5579 NotABinaryOperator,
5580 /// \brief RHS binary operation does not have reference to the updated LHS
5581 /// part.
5582 NotAnUpdateExpression,
5583 /// \brief No errors is found.
5584 NoError
5585 };
5586 /// \brief Reference to Sema.
5587 Sema &SemaRef;
5588 /// \brief A location for note diagnostics (when error is found).
5589 SourceLocation NoteLoc;
5590 /// \brief 'x' lvalue part of the source atomic expression.
5591 Expr *X;
5592 /// \brief 'expr' rvalue part of the source atomic expression.
5593 Expr *E;
5594 /// \brief Helper expression of the form
5595 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5596 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5597 Expr *UpdateExpr;
5598 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5599 /// important for non-associative operations.
5600 bool IsXLHSInRHSPart;
5601 BinaryOperatorKind Op;
5602 SourceLocation OpLoc;
5603 /// \brief true if the source expression is a postfix unary operation, false
5604 /// if it is a prefix unary operation.
5605 bool IsPostfixUpdate;
5606
5607public:
5608 OpenMPAtomicUpdateChecker(Sema &SemaRef)
5609 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5610 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5611 /// \brief Check specified statement that it is suitable for 'atomic update'
5612 /// constructs and extract 'x', 'expr' and Operation from the original
5613 /// expression. If DiagId and NoteId == 0, then only check is performed
5614 /// without error notification.
5615 /// \param DiagId Diagnostic which should be emitted if error is found.
5616 /// \param NoteId Diagnostic note for the main error message.
5617 /// \return true if statement is not an update expression, false otherwise.
5618 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5619 /// \brief Return the 'x' lvalue part of the source atomic expression.
5620 Expr *getX() const { return X; }
5621 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5622 Expr *getExpr() const { return E; }
5623 /// \brief Return the update expression used in calculation of the updated
5624 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5625 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5626 Expr *getUpdateExpr() const { return UpdateExpr; }
5627 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5628 /// false otherwise.
5629 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5630
5631 /// \brief true if the source expression is a postfix unary operation, false
5632 /// if it is a prefix unary operation.
5633 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5634
5635private:
5636 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5637 unsigned NoteId = 0);
5638};
5639} // namespace
5640
5641bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5642 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5643 ExprAnalysisErrorCode ErrorFound = NoError;
5644 SourceLocation ErrorLoc, NoteLoc;
5645 SourceRange ErrorRange, NoteRange;
5646 // Allowed constructs are:
5647 // x = x binop expr;
5648 // x = expr binop x;
5649 if (AtomicBinOp->getOpcode() == BO_Assign) {
5650 X = AtomicBinOp->getLHS();
5651 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5652 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5653 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5654 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5655 AtomicInnerBinOp->isBitwiseOp()) {
5656 Op = AtomicInnerBinOp->getOpcode();
5657 OpLoc = AtomicInnerBinOp->getOperatorLoc();
5658 auto *LHS = AtomicInnerBinOp->getLHS();
5659 auto *RHS = AtomicInnerBinOp->getRHS();
5660 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5661 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5662 /*Canonical=*/true);
5663 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5664 /*Canonical=*/true);
5665 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5666 /*Canonical=*/true);
5667 if (XId == LHSId) {
5668 E = RHS;
5669 IsXLHSInRHSPart = true;
5670 } else if (XId == RHSId) {
5671 E = LHS;
5672 IsXLHSInRHSPart = false;
5673 } else {
5674 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5675 ErrorRange = AtomicInnerBinOp->getSourceRange();
5676 NoteLoc = X->getExprLoc();
5677 NoteRange = X->getSourceRange();
5678 ErrorFound = NotAnUpdateExpression;
5679 }
5680 } else {
5681 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5682 ErrorRange = AtomicInnerBinOp->getSourceRange();
5683 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5684 NoteRange = SourceRange(NoteLoc, NoteLoc);
5685 ErrorFound = NotABinaryOperator;
5686 }
5687 } else {
5688 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5689 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5690 ErrorFound = NotABinaryExpression;
5691 }
5692 } else {
5693 ErrorLoc = AtomicBinOp->getExprLoc();
5694 ErrorRange = AtomicBinOp->getSourceRange();
5695 NoteLoc = AtomicBinOp->getOperatorLoc();
5696 NoteRange = SourceRange(NoteLoc, NoteLoc);
5697 ErrorFound = NotAnAssignmentOp;
5698 }
5699 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5700 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5701 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5702 return true;
5703 } else if (SemaRef.CurContext->isDependentContext())
5704 E = X = UpdateExpr = nullptr;
5705 return ErrorFound != NoError;
5706}
5707
5708bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5709 unsigned NoteId) {
5710 ExprAnalysisErrorCode ErrorFound = NoError;
5711 SourceLocation ErrorLoc, NoteLoc;
5712 SourceRange ErrorRange, NoteRange;
5713 // Allowed constructs are:
5714 // x++;
5715 // x--;
5716 // ++x;
5717 // --x;
5718 // x binop= expr;
5719 // x = x binop expr;
5720 // x = expr binop x;
5721 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5722 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5723 if (AtomicBody->getType()->isScalarType() ||
5724 AtomicBody->isInstantiationDependent()) {
5725 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5726 AtomicBody->IgnoreParenImpCasts())) {
5727 // Check for Compound Assignment Operation
5728 Op = BinaryOperator::getOpForCompoundAssignment(
5729 AtomicCompAssignOp->getOpcode());
5730 OpLoc = AtomicCompAssignOp->getOperatorLoc();
5731 E = AtomicCompAssignOp->getRHS();
5732 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5733 IsXLHSInRHSPart = true;
5734 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5735 AtomicBody->IgnoreParenImpCasts())) {
5736 // Check for Binary Operation
5737 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5738 return true;
5739 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5740 AtomicBody->IgnoreParenImpCasts())) {
5741 // Check for Unary Operation
5742 if (AtomicUnaryOp->isIncrementDecrementOp()) {
5743 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5744 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5745 OpLoc = AtomicUnaryOp->getOperatorLoc();
5746 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5747 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5748 IsXLHSInRHSPart = true;
5749 } else {
5750 ErrorFound = NotAnUnaryIncDecExpression;
5751 ErrorLoc = AtomicUnaryOp->getExprLoc();
5752 ErrorRange = AtomicUnaryOp->getSourceRange();
5753 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5754 NoteRange = SourceRange(NoteLoc, NoteLoc);
5755 }
5756 } else if (!AtomicBody->isInstantiationDependent()) {
5757 ErrorFound = NotABinaryOrUnaryExpression;
5758 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5759 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5760 }
5761 } else {
5762 ErrorFound = NotAScalarType;
5763 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5764 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5765 }
5766 } else {
5767 ErrorFound = NotAnExpression;
5768 NoteLoc = ErrorLoc = S->getLocStart();
5769 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5770 }
5771 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5772 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5773 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5774 return true;
5775 } else if (SemaRef.CurContext->isDependentContext())
5776 E = X = UpdateExpr = nullptr;
5777 if (ErrorFound == NoError && E && X) {
5778 // Build an update expression of form 'OpaqueValueExpr(x) binop
5779 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5780 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5781 auto *OVEX = new (SemaRef.getASTContext())
5782 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5783 auto *OVEExpr = new (SemaRef.getASTContext())
5784 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5785 auto Update =
5786 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5787 IsXLHSInRHSPart ? OVEExpr : OVEX);
5788 if (Update.isInvalid())
5789 return true;
5790 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5791 Sema::AA_Casting);
5792 if (Update.isInvalid())
5793 return true;
5794 UpdateExpr = Update.get();
5795 }
5796 return ErrorFound != NoError;
5797}
5798
5799StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5800 Stmt *AStmt,
5801 SourceLocation StartLoc,
5802 SourceLocation EndLoc) {
5803 if (!AStmt)
5804 return StmtError();
5805
5806 auto *CS = cast<CapturedStmt>(AStmt);
5807 // 1.2.2 OpenMP Language Terminology
5808 // Structured block - An executable statement with a single entry at the
5809 // top and a single exit at the bottom.
5810 // The point of exit cannot be a branch out of the structured block.
5811 // longjmp() and throw() must not violate the entry/exit criteria.
5812 OpenMPClauseKind AtomicKind = OMPC_unknown;
5813 SourceLocation AtomicKindLoc;
5814 for (auto *C : Clauses) {
5815 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5816 C->getClauseKind() == OMPC_update ||
5817 C->getClauseKind() == OMPC_capture) {
5818 if (AtomicKind != OMPC_unknown) {
5819 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5820 << SourceRange(C->getLocStart(), C->getLocEnd());
5821 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5822 << getOpenMPClauseName(AtomicKind);
5823 } else {
5824 AtomicKind = C->getClauseKind();
5825 AtomicKindLoc = C->getLocStart();
5826 }
5827 }
5828 }
5829
5830 auto Body = CS->getCapturedStmt();
5831 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5832 Body = EWC->getSubExpr();
5833
5834 Expr *X = nullptr;
5835 Expr *V = nullptr;
5836 Expr *E = nullptr;
5837 Expr *UE = nullptr;
5838 bool IsXLHSInRHSPart = false;
5839 bool IsPostfixUpdate = false;
5840 // OpenMP [2.12.6, atomic Construct]
5841 // In the next expressions:
5842 // * x and v (as applicable) are both l-value expressions with scalar type.
5843 // * During the execution of an atomic region, multiple syntactic
5844 // occurrences of x must designate the same storage location.
5845 // * Neither of v and expr (as applicable) may access the storage location
5846 // designated by x.
5847 // * Neither of x and expr (as applicable) may access the storage location
5848 // designated by v.
5849 // * expr is an expression with scalar type.
5850 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5851 // * binop, binop=, ++, and -- are not overloaded operators.
5852 // * The expression x binop expr must be numerically equivalent to x binop
5853 // (expr). This requirement is satisfied if the operators in expr have
5854 // precedence greater than binop, or by using parentheses around expr or
5855 // subexpressions of expr.
5856 // * The expression expr binop x must be numerically equivalent to (expr)
5857 // binop x. This requirement is satisfied if the operators in expr have
5858 // precedence equal to or greater than binop, or by using parentheses around
5859 // expr or subexpressions of expr.
5860 // * For forms that allow multiple occurrences of x, the number of times
5861 // that x is evaluated is unspecified.
5862 if (AtomicKind == OMPC_read) {
5863 enum {
5864 NotAnExpression,
5865 NotAnAssignmentOp,
5866 NotAScalarType,
5867 NotAnLValue,
5868 NoError
5869 } ErrorFound = NoError;
5870 SourceLocation ErrorLoc, NoteLoc;
5871 SourceRange ErrorRange, NoteRange;
5872 // If clause is read:
5873 // v = x;
5874 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5875 auto *AtomicBinOp =
5876 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5877 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5878 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5879 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5880 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5881 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5882 if (!X->isLValue() || !V->isLValue()) {
5883 auto NotLValueExpr = X->isLValue() ? V : X;
5884 ErrorFound = NotAnLValue;
5885 ErrorLoc = AtomicBinOp->getExprLoc();
5886 ErrorRange = AtomicBinOp->getSourceRange();
5887 NoteLoc = NotLValueExpr->getExprLoc();
5888 NoteRange = NotLValueExpr->getSourceRange();
5889 }
5890 } else if (!X->isInstantiationDependent() ||
5891 !V->isInstantiationDependent()) {
5892 auto NotScalarExpr =
5893 (X->isInstantiationDependent() || X->getType()->isScalarType())
5894 ? V
5895 : X;
5896 ErrorFound = NotAScalarType;
5897 ErrorLoc = AtomicBinOp->getExprLoc();
5898 ErrorRange = AtomicBinOp->getSourceRange();
5899 NoteLoc = NotScalarExpr->getExprLoc();
5900 NoteRange = NotScalarExpr->getSourceRange();
5901 }
5902 } else if (!AtomicBody->isInstantiationDependent()) {
5903 ErrorFound = NotAnAssignmentOp;
5904 ErrorLoc = AtomicBody->getExprLoc();
5905 ErrorRange = AtomicBody->getSourceRange();
5906 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5907 : AtomicBody->getExprLoc();
5908 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5909 : AtomicBody->getSourceRange();
5910 }
5911 } else {
5912 ErrorFound = NotAnExpression;
5913 NoteLoc = ErrorLoc = Body->getLocStart();
5914 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5915 }
5916 if (ErrorFound != NoError) {
5917 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5918 << ErrorRange;
5919 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5920 << NoteRange;
5921 return StmtError();
5922 } else if (CurContext->isDependentContext())
5923 V = X = nullptr;
5924 } else if (AtomicKind == OMPC_write) {
5925 enum {
5926 NotAnExpression,
5927 NotAnAssignmentOp,
5928 NotAScalarType,
5929 NotAnLValue,
5930 NoError
5931 } ErrorFound = NoError;
5932 SourceLocation ErrorLoc, NoteLoc;
5933 SourceRange ErrorRange, NoteRange;
5934 // If clause is write:
5935 // x = expr;
5936 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5937 auto *AtomicBinOp =
5938 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5939 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5940 X = AtomicBinOp->getLHS();
5941 E = AtomicBinOp->getRHS();
5942 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5943 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5944 if (!X->isLValue()) {
5945 ErrorFound = NotAnLValue;
5946 ErrorLoc = AtomicBinOp->getExprLoc();
5947 ErrorRange = AtomicBinOp->getSourceRange();
5948 NoteLoc = X->getExprLoc();
5949 NoteRange = X->getSourceRange();
5950 }
5951 } else if (!X->isInstantiationDependent() ||
5952 !E->isInstantiationDependent()) {
5953 auto NotScalarExpr =
5954 (X->isInstantiationDependent() || X->getType()->isScalarType())
5955 ? E
5956 : X;
5957 ErrorFound = NotAScalarType;
5958 ErrorLoc = AtomicBinOp->getExprLoc();
5959 ErrorRange = AtomicBinOp->getSourceRange();
5960 NoteLoc = NotScalarExpr->getExprLoc();
5961 NoteRange = NotScalarExpr->getSourceRange();
5962 }
5963 } else if (!AtomicBody->isInstantiationDependent()) {
5964 ErrorFound = NotAnAssignmentOp;
5965 ErrorLoc = AtomicBody->getExprLoc();
5966 ErrorRange = AtomicBody->getSourceRange();
5967 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5968 : AtomicBody->getExprLoc();
5969 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5970 : AtomicBody->getSourceRange();
5971 }
5972 } else {
5973 ErrorFound = NotAnExpression;
5974 NoteLoc = ErrorLoc = Body->getLocStart();
5975 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5976 }
5977 if (ErrorFound != NoError) {
5978 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5979 << ErrorRange;
5980 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5981 << NoteRange;
5982 return StmtError();
5983 } else if (CurContext->isDependentContext())
5984 E = X = nullptr;
5985 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5986 // If clause is update:
5987 // x++;
5988 // x--;
5989 // ++x;
5990 // --x;
5991 // x binop= expr;
5992 // x = x binop expr;
5993 // x = expr binop x;
5994 OpenMPAtomicUpdateChecker Checker(*this);
5995 if (Checker.checkStatement(
5996 Body, (AtomicKind == OMPC_update)
5997 ? diag::err_omp_atomic_update_not_expression_statement
5998 : diag::err_omp_atomic_not_expression_statement,
5999 diag::note_omp_atomic_update))
6000 return StmtError();
6001 if (!CurContext->isDependentContext()) {
6002 E = Checker.getExpr();
6003 X = Checker.getX();
6004 UE = Checker.getUpdateExpr();
6005 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6006 }
6007 } else if (AtomicKind == OMPC_capture) {
6008 enum {
6009 NotAnAssignmentOp,
6010 NotACompoundStatement,
6011 NotTwoSubstatements,
6012 NotASpecificExpression,
6013 NoError
6014 } ErrorFound = NoError;
6015 SourceLocation ErrorLoc, NoteLoc;
6016 SourceRange ErrorRange, NoteRange;
6017 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6018 // If clause is a capture:
6019 // v = x++;
6020 // v = x--;
6021 // v = ++x;
6022 // v = --x;
6023 // v = x binop= expr;
6024 // v = x = x binop expr;
6025 // v = x = expr binop x;
6026 auto *AtomicBinOp =
6027 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6028 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6029 V = AtomicBinOp->getLHS();
6030 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6031 OpenMPAtomicUpdateChecker Checker(*this);
6032 if (Checker.checkStatement(
6033 Body, diag::err_omp_atomic_capture_not_expression_statement,
6034 diag::note_omp_atomic_update))
6035 return StmtError();
6036 E = Checker.getExpr();
6037 X = Checker.getX();
6038 UE = Checker.getUpdateExpr();
6039 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6040 IsPostfixUpdate = Checker.isPostfixUpdate();
6041 } else if (!AtomicBody->isInstantiationDependent()) {
6042 ErrorLoc = AtomicBody->getExprLoc();
6043 ErrorRange = AtomicBody->getSourceRange();
6044 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6045 : AtomicBody->getExprLoc();
6046 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6047 : AtomicBody->getSourceRange();
6048 ErrorFound = NotAnAssignmentOp;
6049 }
6050 if (ErrorFound != NoError) {
6051 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6052 << ErrorRange;
6053 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6054 return StmtError();
6055 } else if (CurContext->isDependentContext()) {
6056 UE = V = E = X = nullptr;
6057 }
6058 } else {
6059 // If clause is a capture:
6060 // { v = x; x = expr; }
6061 // { v = x; x++; }
6062 // { v = x; x--; }
6063 // { v = x; ++x; }
6064 // { v = x; --x; }
6065 // { v = x; x binop= expr; }
6066 // { v = x; x = x binop expr; }
6067 // { v = x; x = expr binop x; }
6068 // { x++; v = x; }
6069 // { x--; v = x; }
6070 // { ++x; v = x; }
6071 // { --x; v = x; }
6072 // { x binop= expr; v = x; }
6073 // { x = x binop expr; v = x; }
6074 // { x = expr binop x; v = x; }
6075 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6076 // Check that this is { expr1; expr2; }
6077 if (CS->size() == 2) {
6078 auto *First = CS->body_front();
6079 auto *Second = CS->body_back();
6080 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6081 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6082 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6083 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6084 // Need to find what subexpression is 'v' and what is 'x'.
6085 OpenMPAtomicUpdateChecker Checker(*this);
6086 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6087 BinaryOperator *BinOp = nullptr;
6088 if (IsUpdateExprFound) {
6089 BinOp = dyn_cast<BinaryOperator>(First);
6090 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6091 }
6092 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6093 // { v = x; x++; }
6094 // { v = x; x--; }
6095 // { v = x; ++x; }
6096 // { v = x; --x; }
6097 // { v = x; x binop= expr; }
6098 // { v = x; x = x binop expr; }
6099 // { v = x; x = expr binop x; }
6100 // Check that the first expression has form v = x.
6101 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6102 llvm::FoldingSetNodeID XId, PossibleXId;
6103 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6104 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6105 IsUpdateExprFound = XId == PossibleXId;
6106 if (IsUpdateExprFound) {
6107 V = BinOp->getLHS();
6108 X = Checker.getX();
6109 E = Checker.getExpr();
6110 UE = Checker.getUpdateExpr();
6111 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6112 IsPostfixUpdate = true;
6113 }
6114 }
6115 if (!IsUpdateExprFound) {
6116 IsUpdateExprFound = !Checker.checkStatement(First);
6117 BinOp = nullptr;
6118 if (IsUpdateExprFound) {
6119 BinOp = dyn_cast<BinaryOperator>(Second);
6120 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6121 }
6122 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6123 // { x++; v = x; }
6124 // { x--; v = x; }
6125 // { ++x; v = x; }
6126 // { --x; v = x; }
6127 // { x binop= expr; v = x; }
6128 // { x = x binop expr; v = x; }
6129 // { x = expr binop x; v = x; }
6130 // Check that the second expression has form v = x.
6131 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6132 llvm::FoldingSetNodeID XId, PossibleXId;
6133 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6134 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6135 IsUpdateExprFound = XId == PossibleXId;
6136 if (IsUpdateExprFound) {
6137 V = BinOp->getLHS();
6138 X = Checker.getX();
6139 E = Checker.getExpr();
6140 UE = Checker.getUpdateExpr();
6141 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6142 IsPostfixUpdate = false;
6143 }
6144 }
6145 }
6146 if (!IsUpdateExprFound) {
6147 // { v = x; x = expr; }
6148 auto *FirstExpr = dyn_cast<Expr>(First);
6149 auto *SecondExpr = dyn_cast<Expr>(Second);
6150 if (!FirstExpr || !SecondExpr ||
6151 !(FirstExpr->isInstantiationDependent() ||
6152 SecondExpr->isInstantiationDependent())) {
6153 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6154 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6155 ErrorFound = NotAnAssignmentOp;
6156 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6157 : First->getLocStart();
6158 NoteRange = ErrorRange = FirstBinOp
6159 ? FirstBinOp->getSourceRange()
6160 : SourceRange(ErrorLoc, ErrorLoc);
6161 } else {
6162 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6163 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6164 ErrorFound = NotAnAssignmentOp;
6165 NoteLoc = ErrorLoc = SecondBinOp
6166 ? SecondBinOp->getOperatorLoc()
6167 : Second->getLocStart();
6168 NoteRange = ErrorRange =
6169 SecondBinOp ? SecondBinOp->getSourceRange()
6170 : SourceRange(ErrorLoc, ErrorLoc);
6171 } else {
6172 auto *PossibleXRHSInFirst =
6173 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6174 auto *PossibleXLHSInSecond =
6175 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6176 llvm::FoldingSetNodeID X1Id, X2Id;
6177 PossibleXRHSInFirst->Profile(X1Id, Context,
6178 /*Canonical=*/true);
6179 PossibleXLHSInSecond->Profile(X2Id, Context,
6180 /*Canonical=*/true);
6181 IsUpdateExprFound = X1Id == X2Id;
6182 if (IsUpdateExprFound) {
6183 V = FirstBinOp->getLHS();
6184 X = SecondBinOp->getLHS();
6185 E = SecondBinOp->getRHS();
6186 UE = nullptr;
6187 IsXLHSInRHSPart = false;
6188 IsPostfixUpdate = true;
6189 } else {
6190 ErrorFound = NotASpecificExpression;
6191 ErrorLoc = FirstBinOp->getExprLoc();
6192 ErrorRange = FirstBinOp->getSourceRange();
6193 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6194 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6195 }
6196 }
6197 }
6198 }
6199 }
6200 } else {
6201 NoteLoc = ErrorLoc = Body->getLocStart();
6202 NoteRange = ErrorRange =
6203 SourceRange(Body->getLocStart(), Body->getLocStart());
6204 ErrorFound = NotTwoSubstatements;
6205 }
6206 } else {
6207 NoteLoc = ErrorLoc = Body->getLocStart();
6208 NoteRange = ErrorRange =
6209 SourceRange(Body->getLocStart(), Body->getLocStart());
6210 ErrorFound = NotACompoundStatement;
6211 }
6212 if (ErrorFound != NoError) {
6213 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6214 << ErrorRange;
6215 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6216 return StmtError();
6217 } else if (CurContext->isDependentContext()) {
6218 UE = V = E = X = nullptr;
6219 }
6220 }
6221 }
6222
6223 getCurFunction()->setHasBranchProtectedScope();
6224
6225 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6226 X, V, E, UE, IsXLHSInRHSPart,
6227 IsPostfixUpdate);
6228}
6229
6230StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6231 Stmt *AStmt,
6232 SourceLocation StartLoc,
6233 SourceLocation EndLoc) {
6234 if (!AStmt)
6235 return StmtError();
6236
6237 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6238 // 1.2.2 OpenMP Language Terminology
6239 // Structured block - An executable statement with a single entry at the
6240 // top and a single exit at the bottom.
6241 // The point of exit cannot be a branch out of the structured block.
6242 // longjmp() and throw() must not violate the entry/exit criteria.
6243 CS->getCapturedDecl()->setNothrow();
6244
6245 // OpenMP [2.16, Nesting of Regions]
6246 // If specified, a teams construct must be contained within a target
6247 // construct. That target construct must contain no statements or directives
6248 // outside of the teams construct.
6249 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasInnerTeamsRegion()) {
6250 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6251 bool OMPTeamsFound = true;
6252 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6253 auto I = CS->body_begin();
6254 while (I != CS->body_end()) {
6255 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6256 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6257 OMPTeamsFound = false;
6258 break;
6259 }
6260 ++I;
6261 }
6262 assert(I != CS->body_end() && "Not found statement")((I != CS->body_end() && "Not found statement") ? static_cast
<void> (0) : __assert_fail ("I != CS->body_end() && \"Not found statement\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6262, __PRETTY_FUNCTION__))
;
6263 S = *I;
6264 } else {
6265 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6266 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6267 }
6268 if (!OMPTeamsFound) {
6269 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6270 Diag(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getInnerTeamsRegionLoc(),
6271 diag::note_omp_nested_teams_construct_here);
6272 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6273 << isa<OMPExecutableDirective>(S);
6274 return StmtError();
6275 }
6276 }
6277
6278 getCurFunction()->setHasBranchProtectedScope();
6279
6280 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6281}
6282
6283StmtResult
6284Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6285 Stmt *AStmt, SourceLocation StartLoc,
6286 SourceLocation EndLoc) {
6287 if (!AStmt)
6288 return StmtError();
6289
6290 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6291 // 1.2.2 OpenMP Language Terminology
6292 // Structured block - An executable statement with a single entry at the
6293 // top and a single exit at the bottom.
6294 // The point of exit cannot be a branch out of the structured block.
6295 // longjmp() and throw() must not violate the entry/exit criteria.
6296 CS->getCapturedDecl()->setNothrow();
6297
6298 getCurFunction()->setHasBranchProtectedScope();
6299
6300 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6301 AStmt);
6302}
6303
6304StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6305 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6306 SourceLocation EndLoc,
6307 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6308 if (!AStmt)
6309 return StmtError();
6310
6311 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6312 // 1.2.2 OpenMP Language Terminology
6313 // Structured block - An executable statement with a single entry at the
6314 // top and a single exit at the bottom.
6315 // The point of exit cannot be a branch out of the structured block.
6316 // longjmp() and throw() must not violate the entry/exit criteria.
6317 CS->getCapturedDecl()->setNothrow();
6318 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6319 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6320 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6321 // 1.2.2 OpenMP Language Terminology
6322 // Structured block - An executable statement with a single entry at the
6323 // top and a single exit at the bottom.
6324 // The point of exit cannot be a branch out of the structured block.
6325 // longjmp() and throw() must not violate the entry/exit criteria.
6326 CS->getCapturedDecl()->setNothrow();
6327 }
6328
6329 OMPLoopDirective::HelperExprs B;
6330 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6331 // define the nested loops number.
6332 unsigned NestedLoopCount =
6333 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6334 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6335 VarsWithImplicitDSA, B);
6336 if (NestedLoopCount == 0)
6337 return StmtError();
6338
6339 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6340, __PRETTY_FUNCTION__))
6340 "omp target parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6340, __PRETTY_FUNCTION__))
;
6341
6342 if (!CurContext->isDependentContext()) {
6343 // Finalize the clauses that need pre-built expressions for CodeGen.
6344 for (auto C : Clauses) {
6345 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6346 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6347 B.NumIterations, *this, CurScope,
6348 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6349 return StmtError();
6350 }
6351 }
6352
6353 getCurFunction()->setHasBranchProtectedScope();
6354 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6355 NestedLoopCount, Clauses, AStmt,
6356 B, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6357}
6358
6359/// Check for existence of a map clause in the list of clauses.
6360static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6361 const OpenMPClauseKind K) {
6362 return llvm::any_of(
6363 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6364}
6365
6366template <typename... Params>
6367static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6368 const Params... ClauseTypes) {
6369 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
6370}
6371
6372StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6373 Stmt *AStmt,
6374 SourceLocation StartLoc,
6375 SourceLocation EndLoc) {
6376 if (!AStmt)
6377 return StmtError();
6378
6379 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6379, __PRETTY_FUNCTION__))
;
6380
6381 // OpenMP [2.10.1, Restrictions, p. 97]
6382 // At least one map clause must appear on the directive.
6383 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6384 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6385 << "'map' or 'use_device_ptr'"
6386 << getOpenMPDirectiveName(OMPD_target_data);
6387 return StmtError();
6388 }
6389
6390 getCurFunction()->setHasBranchProtectedScope();
6391
6392 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6393 AStmt);
6394}
6395
6396StmtResult
6397Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6398 SourceLocation StartLoc,
6399 SourceLocation EndLoc) {
6400 // OpenMP [2.10.2, Restrictions, p. 99]
6401 // At least one map clause must appear on the directive.
6402 if (!hasClauses(Clauses, OMPC_map)) {
6403 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6404 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
6405 return StmtError();
6406 }
6407
6408 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6409 Clauses);
6410}
6411
6412StmtResult
6413Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6414 SourceLocation StartLoc,
6415 SourceLocation EndLoc) {
6416 // OpenMP [2.10.3, Restrictions, p. 102]
6417 // At least one map clause must appear on the directive.
6418 if (!hasClauses(Clauses, OMPC_map)) {
6419 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6420 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
6421 return StmtError();
6422 }
6423
6424 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6425}
6426
6427StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6428 SourceLocation StartLoc,
6429 SourceLocation EndLoc) {
6430 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
6431 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6432 return StmtError();
6433 }
6434 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6435}
6436
6437StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6438 Stmt *AStmt, SourceLocation StartLoc,
6439 SourceLocation EndLoc) {
6440 if (!AStmt)
6441 return StmtError();
6442
6443 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6444 // 1.2.2 OpenMP Language Terminology
6445 // Structured block - An executable statement with a single entry at the
6446 // top and a single exit at the bottom.
6447 // The point of exit cannot be a branch out of the structured block.
6448 // longjmp() and throw() must not violate the entry/exit criteria.
6449 CS->getCapturedDecl()->setNothrow();
6450
6451 getCurFunction()->setHasBranchProtectedScope();
6452
6453 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6454}
6455
6456StmtResult
6457Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6458 SourceLocation EndLoc,
6459 OpenMPDirectiveKind CancelRegion) {
6460 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentNowaitRegion()) {
6461 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6462 return StmtError();
6463 }
6464 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion()) {
6465 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6466 return StmtError();
6467 }
6468 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6469 CancelRegion);
6470}
6471
6472StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6473 SourceLocation StartLoc,
6474 SourceLocation EndLoc,
6475 OpenMPDirectiveKind CancelRegion) {
6476 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentNowaitRegion()) {
6477 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6478 return StmtError();
6479 }
6480 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion()) {
6481 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6482 return StmtError();
6483 }
6484 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentCancelRegion(/*Cancel=*/true);
6485 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6486 CancelRegion);
6487}
6488
6489static bool checkGrainsizeNumTasksClauses(Sema &S,
6490 ArrayRef<OMPClause *> Clauses) {
6491 OMPClause *PrevClause = nullptr;
6492 bool ErrorFound = false;
6493 for (auto *C : Clauses) {
6494 if (C->getClauseKind() == OMPC_grainsize ||
6495 C->getClauseKind() == OMPC_num_tasks) {
6496 if (!PrevClause)
6497 PrevClause = C;
6498 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6499 S.Diag(C->getLocStart(),
6500 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6501 << getOpenMPClauseName(C->getClauseKind())
6502 << getOpenMPClauseName(PrevClause->getClauseKind());
6503 S.Diag(PrevClause->getLocStart(),
6504 diag::note_omp_previous_grainsize_num_tasks)
6505 << getOpenMPClauseName(PrevClause->getClauseKind());
6506 ErrorFound = true;
6507 }
6508 }
6509 }
6510 return ErrorFound;
6511}
6512
6513static bool checkReductionClauseWithNogroup(Sema &S,
6514 ArrayRef<OMPClause *> Clauses) {
6515 OMPClause *ReductionClause = nullptr;
6516 OMPClause *NogroupClause = nullptr;
6517 for (auto *C : Clauses) {
6518 if (C->getClauseKind() == OMPC_reduction) {
6519 ReductionClause = C;
6520 if (NogroupClause)
6521 break;
6522 continue;
6523 }
6524 if (C->getClauseKind() == OMPC_nogroup) {
6525 NogroupClause = C;
6526 if (ReductionClause)
6527 break;
6528 continue;
6529 }
6530 }
6531 if (ReductionClause && NogroupClause) {
6532 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6533 << SourceRange(NogroupClause->getLocStart(),
6534 NogroupClause->getLocEnd());
6535 return true;
6536 }
6537 return false;
6538}
6539
6540StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6541 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6542 SourceLocation EndLoc,
6543 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6544 if (!AStmt)
6545 return StmtError();
6546
6547 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6547, __PRETTY_FUNCTION__))
;
6548 OMPLoopDirective::HelperExprs B;
6549 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6550 // define the nested loops number.
6551 unsigned NestedLoopCount =
6552 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6553 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6554 VarsWithImplicitDSA, B);
6555 if (NestedLoopCount == 0)
6556 return StmtError();
6557
6558 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6559, __PRETTY_FUNCTION__))
6559 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6559, __PRETTY_FUNCTION__))
;
6560
6561 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6562 // The grainsize clause and num_tasks clause are mutually exclusive and may
6563 // not appear on the same taskloop directive.
6564 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6565 return StmtError();
6566 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6567 // If a reduction clause is present on the taskloop directive, the nogroup
6568 // clause must not be specified.
6569 if (checkReductionClauseWithNogroup(*this, Clauses))
6570 return StmtError();
6571
6572 getCurFunction()->setHasBranchProtectedScope();
6573 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6574 NestedLoopCount, Clauses, AStmt, B);
6575}
6576
6577StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6578 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6579 SourceLocation EndLoc,
6580 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6581 if (!AStmt)
6582 return StmtError();
6583
6584 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6584, __PRETTY_FUNCTION__))
;
6585 OMPLoopDirective::HelperExprs B;
6586 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6587 // define the nested loops number.
6588 unsigned NestedLoopCount =
6589 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6590 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6591 VarsWithImplicitDSA, B);
6592 if (NestedLoopCount == 0)
6593 return StmtError();
6594
6595 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6596, __PRETTY_FUNCTION__))
6596 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6596, __PRETTY_FUNCTION__))
;
6597
6598 if (!CurContext->isDependentContext()) {
6599 // Finalize the clauses that need pre-built expressions for CodeGen.
6600 for (auto C : Clauses) {
6601 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6602 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6603 B.NumIterations, *this, CurScope,
6604 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6605 return StmtError();
6606 }
6607 }
6608
6609 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6610 // The grainsize clause and num_tasks clause are mutually exclusive and may
6611 // not appear on the same taskloop directive.
6612 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6613 return StmtError();
6614 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6615 // If a reduction clause is present on the taskloop directive, the nogroup
6616 // clause must not be specified.
6617 if (checkReductionClauseWithNogroup(*this, Clauses))
6618 return StmtError();
6619
6620 getCurFunction()->setHasBranchProtectedScope();
6621 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6622 NestedLoopCount, Clauses, AStmt, B);
6623}
6624
6625StmtResult Sema::ActOnOpenMPDistributeDirective(
6626 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6627 SourceLocation EndLoc,
6628 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6629 if (!AStmt)
6630 return StmtError();
6631
6632 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6632, __PRETTY_FUNCTION__))
;
6633 OMPLoopDirective::HelperExprs B;
6634 // In presence of clause 'collapse' with number of loops, it will
6635 // define the nested loops number.
6636 unsigned NestedLoopCount =
6637 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6638 nullptr /*ordered not a clause on distribute*/, AStmt,
6639 *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
6640 if (NestedLoopCount == 0)
6641 return StmtError();
6642
6643 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6644, __PRETTY_FUNCTION__))
6644 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6644, __PRETTY_FUNCTION__))
;
6645
6646 getCurFunction()->setHasBranchProtectedScope();
6647 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6648 NestedLoopCount, Clauses, AStmt, B);
6649}
6650
6651StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6652 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6653 SourceLocation EndLoc,
6654 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6655 if (!AStmt)
6656 return StmtError();
6657
6658 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6659 // 1.2.2 OpenMP Language Terminology
6660 // Structured block - An executable statement with a single entry at the
6661 // top and a single exit at the bottom.
6662 // The point of exit cannot be a branch out of the structured block.
6663 // longjmp() and throw() must not violate the entry/exit criteria.
6664 CS->getCapturedDecl()->setNothrow();
6665
6666 OMPLoopDirective::HelperExprs B;
6667 // In presence of clause 'collapse' with number of loops, it will
6668 // define the nested loops number.
6669 unsigned NestedLoopCount = CheckOpenMPLoop(
6670 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6671 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6672 VarsWithImplicitDSA, B);
6673 if (NestedLoopCount == 0)
6674 return StmtError();
6675
6676 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6677, __PRETTY_FUNCTION__))
6677 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6677, __PRETTY_FUNCTION__))
;
6678
6679 getCurFunction()->setHasBranchProtectedScope();
6680 return OMPDistributeParallelForDirective::Create(
6681 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6682}
6683
6684StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6685 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6686 SourceLocation EndLoc,
6687 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6688 if (!AStmt)
6689 return StmtError();
6690
6691 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6692 // 1.2.2 OpenMP Language Terminology
6693 // Structured block - An executable statement with a single entry at the
6694 // top and a single exit at the bottom.
6695 // The point of exit cannot be a branch out of the structured block.
6696 // longjmp() and throw() must not violate the entry/exit criteria.
6697 CS->getCapturedDecl()->setNothrow();
6698
6699 OMPLoopDirective::HelperExprs B;
6700 // In presence of clause 'collapse' with number of loops, it will
6701 // define the nested loops number.
6702 unsigned NestedLoopCount = CheckOpenMPLoop(
6703 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6704 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6705 VarsWithImplicitDSA, B);
6706 if (NestedLoopCount == 0)
6707 return StmtError();
6708
6709 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6710, __PRETTY_FUNCTION__))
6710 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6710, __PRETTY_FUNCTION__))
;
6711
6712 if (checkSimdlenSafelenSpecified(*this, Clauses))
6713 return StmtError();
6714
6715 getCurFunction()->setHasBranchProtectedScope();
6716 return OMPDistributeParallelForSimdDirective::Create(
6717 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6718}
6719
6720StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6721 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6722 SourceLocation EndLoc,
6723 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6724 if (!AStmt)
6725 return StmtError();
6726
6727 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6728 // 1.2.2 OpenMP Language Terminology
6729 // Structured block - An executable statement with a single entry at the
6730 // top and a single exit at the bottom.
6731 // The point of exit cannot be a branch out of the structured block.
6732 // longjmp() and throw() must not violate the entry/exit criteria.
6733 CS->getCapturedDecl()->setNothrow();
6734
6735 OMPLoopDirective::HelperExprs B;
6736 // In presence of clause 'collapse' with number of loops, it will
6737 // define the nested loops number.
6738 unsigned NestedLoopCount =
6739 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6740 nullptr /*ordered not a clause on distribute*/, AStmt,
6741 *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
6742 if (NestedLoopCount == 0)
6743 return StmtError();
6744
6745 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6746, __PRETTY_FUNCTION__))
6746 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6746, __PRETTY_FUNCTION__))
;
6747
6748 if (checkSimdlenSafelenSpecified(*this, Clauses))
6749 return StmtError();
6750
6751 getCurFunction()->setHasBranchProtectedScope();
6752 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6753 NestedLoopCount, Clauses, AStmt, B);
6754}
6755
6756StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6758 SourceLocation EndLoc,
6759 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6760 if (!AStmt)
6761 return StmtError();
6762
6763 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6764 // 1.2.2 OpenMP Language Terminology
6765 // Structured block - An executable statement with a single entry at the
6766 // top and a single exit at the bottom.
6767 // The point of exit cannot be a branch out of the structured block.
6768 // longjmp() and throw() must not violate the entry/exit criteria.
6769 CS->getCapturedDecl()->setNothrow();
6770 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6771 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6772 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6773 // 1.2.2 OpenMP Language Terminology
6774 // Structured block - An executable statement with a single entry at the
6775 // top and a single exit at the bottom.
6776 // The point of exit cannot be a branch out of the structured block.
6777 // longjmp() and throw() must not violate the entry/exit criteria.
6778 CS->getCapturedDecl()->setNothrow();
6779 }
6780
6781 OMPLoopDirective::HelperExprs B;
6782 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6783 // define the nested loops number.
6784 unsigned NestedLoopCount = CheckOpenMPLoop(
6785 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6786 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6787 VarsWithImplicitDSA, B);
6788 if (NestedLoopCount == 0)
6789 return StmtError();
6790
6791 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6792, __PRETTY_FUNCTION__))
6792 "omp target parallel for simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6792, __PRETTY_FUNCTION__))
;
6793
6794 if (!CurContext->isDependentContext()) {
6795 // Finalize the clauses that need pre-built expressions for CodeGen.
6796 for (auto C : Clauses) {
6797 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6798 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6799 B.NumIterations, *this, CurScope,
6800 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6801 return StmtError();
6802 }
6803 }
6804 if (checkSimdlenSafelenSpecified(*this, Clauses))
6805 return StmtError();
6806
6807 getCurFunction()->setHasBranchProtectedScope();
6808 return OMPTargetParallelForSimdDirective::Create(
6809 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6810}
6811
6812StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6814 SourceLocation EndLoc,
6815 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6816 if (!AStmt)
6817 return StmtError();
6818
6819 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6820 // 1.2.2 OpenMP Language Terminology
6821 // Structured block - An executable statement with a single entry at the
6822 // top and a single exit at the bottom.
6823 // The point of exit cannot be a branch out of the structured block.
6824 // longjmp() and throw() must not violate the entry/exit criteria.
6825 CS->getCapturedDecl()->setNothrow();
6826
6827 OMPLoopDirective::HelperExprs B;
6828 // In presence of clause 'collapse' with number of loops, it will define the
6829 // nested loops number.
6830 unsigned NestedLoopCount =
6831 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6832 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6833 VarsWithImplicitDSA, B);
6834 if (NestedLoopCount == 0)
6835 return StmtError();
6836
6837 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target simd loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6838, __PRETTY_FUNCTION__))
6838 "omp target simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target simd loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6838, __PRETTY_FUNCTION__))
;
6839
6840 if (!CurContext->isDependentContext()) {
6841 // Finalize the clauses that need pre-built expressions for CodeGen.
6842 for (auto C : Clauses) {
6843 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6844 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6845 B.NumIterations, *this, CurScope,
6846 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6847 return StmtError();
6848 }
6849 }
6850
6851 if (checkSimdlenSafelenSpecified(*this, Clauses))
6852 return StmtError();
6853
6854 getCurFunction()->setHasBranchProtectedScope();
6855 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6856 NestedLoopCount, Clauses, AStmt, B);
6857}
6858
6859StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6860 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6861 SourceLocation EndLoc,
6862 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6863 if (!AStmt)
6864 return StmtError();
6865
6866 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6867 // 1.2.2 OpenMP Language Terminology
6868 // Structured block - An executable statement with a single entry at the
6869 // top and a single exit at the bottom.
6870 // The point of exit cannot be a branch out of the structured block.
6871 // longjmp() and throw() must not violate the entry/exit criteria.
6872 CS->getCapturedDecl()->setNothrow();
6873
6874 OMPLoopDirective::HelperExprs B;
6875 // In presence of clause 'collapse' with number of loops, it will
6876 // define the nested loops number.
6877 unsigned NestedLoopCount =
6878 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6879 nullptr /*ordered not a clause on distribute*/, AStmt,
6880 *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
6881 if (NestedLoopCount == 0)
6882 return StmtError();
6883
6884 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6885, __PRETTY_FUNCTION__))
6885 "omp teams distribute loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6885, __PRETTY_FUNCTION__))
;
6886
6887 getCurFunction()->setHasBranchProtectedScope();
6888 return OMPTeamsDistributeDirective::Create(
6889 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6890}
6891
6892StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6893 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6894 SourceLocation EndLoc,
6895 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6896 if (!AStmt)
6897 return StmtError();
6898
6899 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6900 // 1.2.2 OpenMP Language Terminology
6901 // Structured block - An executable statement with a single entry at the
6902 // top and a single exit at the bottom.
6903 // The point of exit cannot be a branch out of the structured block.
6904 // longjmp() and throw() must not violate the entry/exit criteria.
6905 CS->getCapturedDecl()->setNothrow();
6906
6907 OMPLoopDirective::HelperExprs B;
6908 // In presence of clause 'collapse' with number of loops, it will
6909 // define the nested loops number.
6910 unsigned NestedLoopCount = CheckOpenMPLoop(
6911 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6912 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6913 VarsWithImplicitDSA, B);
6914
6915 if (NestedLoopCount == 0)
6916 return StmtError();
6917
6918 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6919, __PRETTY_FUNCTION__))
6919 "omp teams distribute simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6919, __PRETTY_FUNCTION__))
;
6920
6921 if (!CurContext->isDependentContext()) {
6922 // Finalize the clauses that need pre-built expressions for CodeGen.
6923 for (auto C : Clauses) {
6924 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6925 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6926 B.NumIterations, *this, CurScope,
6927 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6928 return StmtError();
6929 }
6930 }
6931
6932 if (checkSimdlenSafelenSpecified(*this, Clauses))
6933 return StmtError();
6934
6935 getCurFunction()->setHasBranchProtectedScope();
6936 return OMPTeamsDistributeSimdDirective::Create(
6937 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6938}
6939
6940StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6941 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6942 SourceLocation EndLoc,
6943 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6944 if (!AStmt)
6945 return StmtError();
6946
6947 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6948 // 1.2.2 OpenMP Language Terminology
6949 // Structured block - An executable statement with a single entry at the
6950 // top and a single exit at the bottom.
6951 // The point of exit cannot be a branch out of the structured block.
6952 // longjmp() and throw() must not violate the entry/exit criteria.
6953 CS->getCapturedDecl()->setNothrow();
6954
6955 OMPLoopDirective::HelperExprs B;
6956 // In presence of clause 'collapse' with number of loops, it will
6957 // define the nested loops number.
6958 auto NestedLoopCount = CheckOpenMPLoop(
6959 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6960 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6961 VarsWithImplicitDSA, B);
6962
6963 if (NestedLoopCount == 0)
6964 return StmtError();
6965
6966 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6967, __PRETTY_FUNCTION__))
6967 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6967, __PRETTY_FUNCTION__))
;
6968
6969 if (!CurContext->isDependentContext()) {
6970 // Finalize the clauses that need pre-built expressions for CodeGen.
6971 for (auto C : Clauses) {
6972 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6973 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6974 B.NumIterations, *this, CurScope,
6975 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6976 return StmtError();
6977 }
6978 }
6979
6980 if (checkSimdlenSafelenSpecified(*this, Clauses))
6981 return StmtError();
6982
6983 getCurFunction()->setHasBranchProtectedScope();
6984 return OMPTeamsDistributeParallelForSimdDirective::Create(
6985 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6986}
6987
6988StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6989 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6990 SourceLocation EndLoc,
6991 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6992 if (!AStmt)
6993 return StmtError();
6994
6995 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6996 // 1.2.2 OpenMP Language Terminology
6997 // Structured block - An executable statement with a single entry at the
6998 // top and a single exit at the bottom.
6999 // The point of exit cannot be a branch out of the structured block.
7000 // longjmp() and throw() must not violate the entry/exit criteria.
7001 CS->getCapturedDecl()->setNothrow();
7002
7003 OMPLoopDirective::HelperExprs B;
7004 // In presence of clause 'collapse' with number of loops, it will
7005 // define the nested loops number.
7006 unsigned NestedLoopCount = CheckOpenMPLoop(
7007 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7008 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7009 VarsWithImplicitDSA, B);
7010
7011 if (NestedLoopCount == 0)
7012 return StmtError();
7013
7014 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7015, __PRETTY_FUNCTION__))
7015 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7015, __PRETTY_FUNCTION__))
;
7016
7017 if (!CurContext->isDependentContext()) {
7018 // Finalize the clauses that need pre-built expressions for CodeGen.
7019 for (auto C : Clauses) {
7020 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7021 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7022 B.NumIterations, *this, CurScope,
7023 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7024 return StmtError();
7025 }
7026 }
7027
7028 getCurFunction()->setHasBranchProtectedScope();
7029 return OMPTeamsDistributeParallelForDirective::Create(
7030 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7031}
7032
7033StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7034 Stmt *AStmt,
7035 SourceLocation StartLoc,
7036 SourceLocation EndLoc) {
7037 if (!AStmt)
7038 return StmtError();
7039
7040 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7041 // 1.2.2 OpenMP Language Terminology
7042 // Structured block - An executable statement with a single entry at the
7043 // top and a single exit at the bottom.
7044 // The point of exit cannot be a branch out of the structured block.
7045 // longjmp() and throw() must not violate the entry/exit criteria.
7046 CS->getCapturedDecl()->setNothrow();
7047
7048 getCurFunction()->setHasBranchProtectedScope();
7049
7050 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7051 AStmt);
7052}
7053
7054StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7055 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7056 SourceLocation EndLoc,
7057 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7058 if (!AStmt)
7059 return StmtError();
7060
7061 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7062 // 1.2.2 OpenMP Language Terminology
7063 // Structured block - An executable statement with a single entry at the
7064 // top and a single exit at the bottom.
7065 // The point of exit cannot be a branch out of the structured block.
7066 // longjmp() and throw() must not violate the entry/exit criteria.
7067 CS->getCapturedDecl()->setNothrow();
7068
7069 OMPLoopDirective::HelperExprs B;
7070 // In presence of clause 'collapse' with number of loops, it will
7071 // define the nested loops number.
7072 auto NestedLoopCount = CheckOpenMPLoop(
7073 OMPD_target_teams_distribute,
7074 getCollapseNumberExpr(Clauses),
7075 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7076 VarsWithImplicitDSA, B);
7077 if (NestedLoopCount == 0)
7078 return StmtError();
7079
7080 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7081, __PRETTY_FUNCTION__))
7081 "omp target teams distribute loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7081, __PRETTY_FUNCTION__))
;
7082
7083 getCurFunction()->setHasBranchProtectedScope();
7084 return OMPTargetTeamsDistributeDirective::Create(
7085 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7086}
7087
7088StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7089 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7090 SourceLocation EndLoc,
7091 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7092 if (!AStmt)
7093 return StmtError();
7094
7095 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7096 // 1.2.2 OpenMP Language Terminology
7097 // Structured block - An executable statement with a single entry at the
7098 // top and a single exit at the bottom.
7099 // The point of exit cannot be a branch out of the structured block.
7100 // longjmp() and throw() must not violate the entry/exit criteria.
7101 CS->getCapturedDecl()->setNothrow();
7102
7103 OMPLoopDirective::HelperExprs B;
7104 // In presence of clause 'collapse' with number of loops, it will
7105 // define the nested loops number.
7106 auto NestedLoopCount = CheckOpenMPLoop(
7107 OMPD_target_teams_distribute_parallel_for,
7108 getCollapseNumberExpr(Clauses),
7109 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7110 VarsWithImplicitDSA, B);
7111 if (NestedLoopCount == 0)
7112 return StmtError();
7113
7114 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7115, __PRETTY_FUNCTION__))
7115 "omp target teams distribute parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7115, __PRETTY_FUNCTION__))
;
7116
7117 if (!CurContext->isDependentContext()) {
7118 // Finalize the clauses that need pre-built expressions for CodeGen.
7119 for (auto C : Clauses) {
7120 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7121 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7122 B.NumIterations, *this, CurScope,
7123 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7124 return StmtError();
7125 }
7126 }
7127
7128 getCurFunction()->setHasBranchProtectedScope();
7129 return OMPTargetTeamsDistributeParallelForDirective::Create(
7130 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7131}
7132
7133StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7134 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7135 SourceLocation EndLoc,
7136 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7137 if (!AStmt)
7138 return StmtError();
7139
7140 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7141 // 1.2.2 OpenMP Language Terminology
7142 // Structured block - An executable statement with a single entry at the
7143 // top and a single exit at the bottom.
7144 // The point of exit cannot be a branch out of the structured block.
7145 // longjmp() and throw() must not violate the entry/exit criteria.
7146 CS->getCapturedDecl()->setNothrow();
7147
7148 OMPLoopDirective::HelperExprs B;
7149 // In presence of clause 'collapse' with number of loops, it will
7150 // define the nested loops number.
7151 auto NestedLoopCount = CheckOpenMPLoop(
7152 OMPD_target_teams_distribute_parallel_for_simd,
7153 getCollapseNumberExpr(Clauses),
7154 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7155 VarsWithImplicitDSA, B);
7156 if (NestedLoopCount == 0)
7157 return StmtError();
7158
7159 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7161, __PRETTY_FUNCTION__))
7160 "omp target teams distribute parallel for simd loop exprs were not "(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7161, __PRETTY_FUNCTION__))
7161 "built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7161, __PRETTY_FUNCTION__))
;
7162
7163 if (!CurContext->isDependentContext()) {
7164 // Finalize the clauses that need pre-built expressions for CodeGen.
7165 for (auto C : Clauses) {
7166 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7167 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7168 B.NumIterations, *this, CurScope,
7169 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7170 return StmtError();
7171 }
7172 }
7173
7174 getCurFunction()->setHasBranchProtectedScope();
7175 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7176 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7177}
7178
7179StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7180 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7181 SourceLocation EndLoc,
7182 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7183 if (!AStmt)
7184 return StmtError();
7185
7186 auto *CS = cast<CapturedStmt>(AStmt);
7187 // 1.2.2 OpenMP Language Terminology
7188 // Structured block - An executable statement with a single entry at the
7189 // top and a single exit at the bottom.
7190 // The point of exit cannot be a branch out of the structured block.
7191 // longjmp() and throw() must not violate the entry/exit criteria.
7192 CS->getCapturedDecl()->setNothrow();
7193
7194 OMPLoopDirective::HelperExprs B;
7195 // In presence of clause 'collapse' with number of loops, it will
7196 // define the nested loops number.
7197 auto NestedLoopCount = CheckOpenMPLoop(
7198 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7199 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7200 VarsWithImplicitDSA, B);
7201 if (NestedLoopCount == 0)
7202 return StmtError();
7203
7204 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute simd loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7205, __PRETTY_FUNCTION__))
7205 "omp target teams distribute simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute simd loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7205, __PRETTY_FUNCTION__))
;
7206
7207 getCurFunction()->setHasBranchProtectedScope();
7208 return OMPTargetTeamsDistributeSimdDirective::Create(
7209 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7210}
7211
7212OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
7213 SourceLocation StartLoc,
7214 SourceLocation LParenLoc,
7215 SourceLocation EndLoc) {
7216 OMPClause *Res = nullptr;
7217 switch (Kind) {
7218 case OMPC_final:
7219 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7220 break;
7221 case OMPC_num_threads:
7222 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7223 break;
7224 case OMPC_safelen:
7225 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7226 break;
7227 case OMPC_simdlen:
7228 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7229 break;
7230 case OMPC_collapse:
7231 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7232 break;
7233 case OMPC_ordered:
7234 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7235 break;
7236 case OMPC_device:
7237 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7238 break;
7239 case OMPC_num_teams:
7240 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7241 break;
7242 case OMPC_thread_limit:
7243 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7244 break;
7245 case OMPC_priority:
7246 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7247 break;
7248 case OMPC_grainsize:
7249 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7250 break;
7251 case OMPC_num_tasks:
7252 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7253 break;
7254 case OMPC_hint:
7255 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7256 break;
7257 case OMPC_if:
7258 case OMPC_default:
7259 case OMPC_proc_bind:
7260 case OMPC_schedule:
7261 case OMPC_private:
7262 case OMPC_firstprivate:
7263 case OMPC_lastprivate:
7264 case OMPC_shared:
7265 case OMPC_reduction:
7266 case OMPC_task_reduction:
7267 case OMPC_in_reduction:
7268 case OMPC_linear:
7269 case OMPC_aligned:
7270 case OMPC_copyin:
7271 case OMPC_copyprivate:
7272 case OMPC_nowait:
7273 case OMPC_untied:
7274 case OMPC_mergeable:
7275 case OMPC_threadprivate:
7276 case OMPC_flush:
7277 case OMPC_read:
7278 case OMPC_write:
7279 case OMPC_update:
7280 case OMPC_capture:
7281 case OMPC_seq_cst:
7282 case OMPC_depend:
7283 case OMPC_threads:
7284 case OMPC_simd:
7285 case OMPC_map:
7286 case OMPC_nogroup:
7287 case OMPC_dist_schedule:
7288 case OMPC_defaultmap:
7289 case OMPC_unknown:
7290 case OMPC_uniform:
7291 case OMPC_to:
7292 case OMPC_from:
7293 case OMPC_use_device_ptr:
7294 case OMPC_is_device_ptr:
7295 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7295)
;
7296 }
7297 return Res;
7298}
7299
7300// An OpenMP directive such as 'target parallel' has two captured regions:
7301// for the 'target' and 'parallel' respectively. This function returns
7302// the region in which to capture expressions associated with a clause.
7303// A return value of OMPD_unknown signifies that the expression should not
7304// be captured.
7305static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7306 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7307 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
7308 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7309
7310 switch (CKind) {
7311 case OMPC_if:
7312 switch (DKind) {
7313 case OMPD_target_parallel:
7314 case OMPD_target_parallel_for:
7315 case OMPD_target_parallel_for_simd:
7316 // If this clause applies to the nested 'parallel' region, capture within
7317 // the 'target' region, otherwise do not capture.
7318 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7319 CaptureRegion = OMPD_target;
7320 break;
7321 case OMPD_cancel:
7322 case OMPD_parallel:
7323 case OMPD_parallel_sections:
7324 case OMPD_parallel_for:
7325 case OMPD_parallel_for_simd:
7326 case OMPD_target:
7327 case OMPD_target_simd:
7328 case OMPD_target_teams:
7329 case OMPD_target_teams_distribute:
7330 case OMPD_target_teams_distribute_simd:
7331 case OMPD_target_teams_distribute_parallel_for:
7332 case OMPD_target_teams_distribute_parallel_for_simd:
7333 case OMPD_teams_distribute_parallel_for:
7334 case OMPD_teams_distribute_parallel_for_simd:
7335 case OMPD_distribute_parallel_for:
7336 case OMPD_distribute_parallel_for_simd:
7337 case OMPD_task:
7338 case OMPD_taskloop:
7339 case OMPD_taskloop_simd:
7340 case OMPD_target_data:
7341 case OMPD_target_enter_data:
7342 case OMPD_target_exit_data:
7343 case OMPD_target_update:
7344 // Do not capture if-clause expressions.
7345 break;
7346 case OMPD_threadprivate:
7347 case OMPD_taskyield:
7348 case OMPD_barrier:
7349 case OMPD_taskwait:
7350 case OMPD_cancellation_point:
7351 case OMPD_flush:
7352 case OMPD_declare_reduction:
7353 case OMPD_declare_simd:
7354 case OMPD_declare_target:
7355 case OMPD_end_declare_target:
7356 case OMPD_teams:
7357 case OMPD_simd:
7358 case OMPD_for:
7359 case OMPD_for_simd:
7360 case OMPD_sections:
7361 case OMPD_section:
7362 case OMPD_single:
7363 case OMPD_master:
7364 case OMPD_critical:
7365 case OMPD_taskgroup:
7366 case OMPD_distribute:
7367 case OMPD_ordered:
7368 case OMPD_atomic:
7369 case OMPD_distribute_simd:
7370 case OMPD_teams_distribute:
7371 case OMPD_teams_distribute_simd:
7372 llvm_unreachable("Unexpected OpenMP directive with if-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with if-clause"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7372)
;
7373 case OMPD_unknown:
7374 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7374)
;
7375 }
7376 break;
7377 case OMPC_num_threads:
7378 switch (DKind) {
7379 case OMPD_target_parallel:
7380 case OMPD_target_parallel_for:
7381 case OMPD_target_parallel_for_simd:
7382 CaptureRegion = OMPD_target;
7383 break;
7384 case OMPD_cancel:
7385