Bug Summary

File:tools/clang/lib/Sema/SemaOpenMP.cpp
Warning:line 1860, column 5
Value stored to 'ErrorFound' is never read

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