clang 20.0.0git
CGStmtOpenMP.cpp
Go to the documentation of this file.
1//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit OpenMP nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCleanup.h"
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "TargetInfo.h"
19#include "clang/AST/Attr.h"
22#include "clang/AST/Stmt.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/BinaryFormat/Dwarf.h"
30#include "llvm/Frontend/OpenMP/OMPConstants.h"
31#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DebugInfoMetadata.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/Support/AtomicOrdering.h"
38#include "llvm/Support/Debug.h"
39#include <optional>
40using namespace clang;
41using namespace CodeGen;
42using namespace llvm::omp;
43
44#define TTL_CODEGEN_TYPE "target-teams-loop-codegen"
45
46static const VarDecl *getBaseDecl(const Expr *Ref);
49
50namespace {
51/// Lexical scope for OpenMP executable constructs, that handles correct codegen
52/// for captured expressions.
53class OMPLexicalScope : public CodeGenFunction::LexicalScope {
54 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
55 for (const auto *C : S.clauses()) {
56 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
57 if (const auto *PreInit =
58 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
59 for (const auto *I : PreInit->decls()) {
60 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
61 CGF.EmitVarDecl(cast<VarDecl>(*I));
62 } else {
63 CodeGenFunction::AutoVarEmission Emission =
64 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
65 CGF.EmitAutoVarCleanups(Emission);
66 }
67 }
68 }
69 }
70 }
71 }
72 CodeGenFunction::OMPPrivateScope InlinedShareds;
73
74 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
75 return CGF.LambdaCaptureFields.lookup(VD) ||
76 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
77 (isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl) &&
78 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
79 }
80
81public:
82 OMPLexicalScope(
84 const std::optional<OpenMPDirectiveKind> CapturedRegion = std::nullopt,
85 const bool EmitPreInitStmt = true)
86 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
87 InlinedShareds(CGF) {
88 if (EmitPreInitStmt)
89 emitPreInitStmt(CGF, S);
90 if (!CapturedRegion)
91 return;
92 assert(S.hasAssociatedStmt() &&
93 "Expected associated statement for inlined directive.");
94 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
95 for (const auto &C : CS->captures()) {
96 if (C.capturesVariable() || C.capturesVariableByCopy()) {
97 auto *VD = C.getCapturedVar();
98 assert(VD == VD->getCanonicalDecl() &&
99 "Canonical decl must be captured.");
100 DeclRefExpr DRE(
101 CGF.getContext(), const_cast<VarDecl *>(VD),
102 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
103 InlinedShareds.isGlobalVarCaptured(VD)),
104 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
105 InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress());
106 }
107 }
108 (void)InlinedShareds.Privatize();
109 }
110};
111
112/// Lexical scope for OpenMP parallel construct, that handles correct codegen
113/// for captured expressions.
114class OMPParallelScope final : public OMPLexicalScope {
115 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
117 return !(isOpenMPTargetExecutionDirective(EKind) ||
120 }
121
122public:
123 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
124 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/std::nullopt,
125 EmitPreInitStmt(S)) {}
126};
127
128/// Lexical scope for OpenMP teams construct, that handles correct codegen
129/// for captured expressions.
130class OMPTeamsScope final : public OMPLexicalScope {
131 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
133 return !isOpenMPTargetExecutionDirective(EKind) &&
135 }
136
137public:
138 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
139 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/std::nullopt,
140 EmitPreInitStmt(S)) {}
141};
142
143/// Private scope for OpenMP loop-based directives, that supports capturing
144/// of used expression from loop statement.
145class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
146 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) {
147 const Stmt *PreInits;
148 CodeGenFunction::OMPMapVars PreCondVars;
149 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
150 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
151 for (const auto *E : LD->counters()) {
152 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
153 EmittedAsPrivate.insert(VD->getCanonicalDecl());
154 (void)PreCondVars.setVarAddr(
155 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
156 }
157 // Mark private vars as undefs.
158 for (const auto *C : LD->getClausesOfKind<OMPPrivateClause>()) {
159 for (const Expr *IRef : C->varlist()) {
160 const auto *OrigVD =
161 cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
162 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
163 QualType OrigVDTy = OrigVD->getType().getNonReferenceType();
164 (void)PreCondVars.setVarAddr(
165 CGF, OrigVD,
166 Address(llvm::UndefValue::get(CGF.ConvertTypeForMem(
167 CGF.getContext().getPointerType(OrigVDTy))),
168 CGF.ConvertTypeForMem(OrigVDTy),
169 CGF.getContext().getDeclAlign(OrigVD)));
170 }
171 }
172 }
173 (void)PreCondVars.apply(CGF);
174 // Emit init, __range and __end variables for C++ range loops.
176 LD->getInnermostCapturedStmt()->getCapturedStmt(),
177 /*TryImperfectlyNestedLoops=*/true, LD->getLoopsNumber(),
178 [&CGF](unsigned Cnt, const Stmt *CurStmt) {
179 if (const auto *CXXFor = dyn_cast<CXXForRangeStmt>(CurStmt)) {
180 if (const Stmt *Init = CXXFor->getInit())
181 CGF.EmitStmt(Init);
182 CGF.EmitStmt(CXXFor->getRangeStmt());
183 CGF.EmitStmt(CXXFor->getEndStmt());
184 }
185 return false;
186 });
187 PreInits = LD->getPreInits();
188 } else if (const auto *Tile = dyn_cast<OMPTileDirective>(&S)) {
189 PreInits = Tile->getPreInits();
190 } else if (const auto *Unroll = dyn_cast<OMPUnrollDirective>(&S)) {
191 PreInits = Unroll->getPreInits();
192 } else if (const auto *Reverse = dyn_cast<OMPReverseDirective>(&S)) {
193 PreInits = Reverse->getPreInits();
194 } else if (const auto *Interchange =
195 dyn_cast<OMPInterchangeDirective>(&S)) {
196 PreInits = Interchange->getPreInits();
197 } else {
198 llvm_unreachable("Unknown loop-based directive kind.");
199 }
200 if (PreInits) {
201 // CompoundStmts and DeclStmts are used as lists of PreInit statements and
202 // declarations. Since declarations must be visible in the the following
203 // that they initialize, unpack the CompoundStmt they are nested in.
204 SmallVector<const Stmt *> PreInitStmts;
205 if (auto *PreInitCompound = dyn_cast<CompoundStmt>(PreInits))
206 llvm::append_range(PreInitStmts, PreInitCompound->body());
207 else
208 PreInitStmts.push_back(PreInits);
209
210 for (const Stmt *S : PreInitStmts) {
211 // EmitStmt skips any OMPCapturedExprDecls, but needs to be emitted
212 // here.
213 if (auto *PreInitDecl = dyn_cast<DeclStmt>(S)) {
214 for (Decl *I : PreInitDecl->decls())
215 CGF.EmitVarDecl(cast<VarDecl>(*I));
216 continue;
217 }
218 CGF.EmitStmt(S);
219 }
220 }
221 PreCondVars.restore(CGF);
222 }
223
224public:
225 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopBasedDirective &S)
226 : CodeGenFunction::RunCleanupsScope(CGF) {
227 emitPreInitStmt(CGF, S);
228 }
229};
230
231class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
232 CodeGenFunction::OMPPrivateScope InlinedShareds;
233
234 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
235 return CGF.LambdaCaptureFields.lookup(VD) ||
236 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
237 (isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl) &&
238 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
239 }
240
241public:
242 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
243 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
244 InlinedShareds(CGF) {
245 for (const auto *C : S.clauses()) {
246 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
247 if (const auto *PreInit =
248 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
249 for (const auto *I : PreInit->decls()) {
250 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
251 CGF.EmitVarDecl(cast<VarDecl>(*I));
252 } else {
253 CodeGenFunction::AutoVarEmission Emission =
254 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
255 CGF.EmitAutoVarCleanups(Emission);
256 }
257 }
258 }
259 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
260 for (const Expr *E : UDP->varlist()) {
261 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
262 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
263 CGF.EmitVarDecl(*OED);
264 }
265 } else if (const auto *UDP = dyn_cast<OMPUseDeviceAddrClause>(C)) {
266 for (const Expr *E : UDP->varlist()) {
267 const Decl *D = getBaseDecl(E);
268 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
269 CGF.EmitVarDecl(*OED);
270 }
271 }
272 }
274 CGF.EmitOMPPrivateClause(S, InlinedShareds);
275 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
276 if (const Expr *E = TG->getReductionRef())
277 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
278 }
279 // Temp copy arrays for inscan reductions should not be emitted as they are
280 // not used in simd only mode.
281 llvm::DenseSet<CanonicalDeclPtr<const Decl>> CopyArrayTemps;
282 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
283 if (C->getModifier() != OMPC_REDUCTION_inscan)
284 continue;
285 for (const Expr *E : C->copy_array_temps())
286 CopyArrayTemps.insert(cast<DeclRefExpr>(E)->getDecl());
287 }
288 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
289 while (CS) {
290 for (auto &C : CS->captures()) {
291 if (C.capturesVariable() || C.capturesVariableByCopy()) {
292 auto *VD = C.getCapturedVar();
293 if (CopyArrayTemps.contains(VD))
294 continue;
295 assert(VD == VD->getCanonicalDecl() &&
296 "Canonical decl must be captured.");
297 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
298 isCapturedVar(CGF, VD) ||
299 (CGF.CapturedStmtInfo &&
300 InlinedShareds.isGlobalVarCaptured(VD)),
302 C.getLocation());
303 InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress());
304 }
305 }
306 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
307 }
308 (void)InlinedShareds.Privatize();
309 }
310};
311
312} // namespace
313
314// The loop directive with a bind clause will be mapped to a different
315// directive with corresponding semantics.
318 OpenMPDirectiveKind Kind = S.getDirectiveKind();
319 if (Kind != OMPD_loop)
320 return Kind;
321
323 if (const auto *C = S.getSingleClause<OMPBindClause>())
324 BindKind = C->getBindKind();
325
326 switch (BindKind) {
327 case OMPC_BIND_parallel:
328 return OMPD_for;
329 case OMPC_BIND_teams:
330 return OMPD_distribute;
331 case OMPC_BIND_thread:
332 return OMPD_simd;
333 default:
334 return OMPD_loop;
335 }
336}
337
339 const OMPExecutableDirective &S,
340 const RegionCodeGenTy &CodeGen);
341
342LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
343 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
344 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
345 OrigVD = OrigVD->getCanonicalDecl();
346 bool IsCaptured =
347 LambdaCaptureFields.lookup(OrigVD) ||
349 (isa_and_nonnull<BlockDecl>(CurCodeDecl));
350 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
351 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
352 return EmitLValue(&DRE);
353 }
354 }
355 return EmitLValue(E);
356}
357
358llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
360 llvm::Value *Size = nullptr;
361 auto SizeInChars = C.getTypeSizeInChars(Ty);
362 if (SizeInChars.isZero()) {
363 // getTypeSizeInChars() returns 0 for a VLA.
364 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
365 VlaSizePair VlaSize = getVLASize(VAT);
366 Ty = VlaSize.Type;
367 Size =
368 Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) : VlaSize.NumElts;
369 }
370 SizeInChars = C.getTypeSizeInChars(Ty);
371 if (SizeInChars.isZero())
372 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
373 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
374 }
375 return CGM.getSize(SizeInChars);
376}
377
379 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
380 const RecordDecl *RD = S.getCapturedRecordDecl();
381 auto CurField = RD->field_begin();
382 auto CurCap = S.captures().begin();
383 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
384 E = S.capture_init_end();
385 I != E; ++I, ++CurField, ++CurCap) {
386 if (CurField->hasCapturedVLAType()) {
387 const VariableArrayType *VAT = CurField->getCapturedVLAType();
388 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
389 CapturedVars.push_back(Val);
390 } else if (CurCap->capturesThis()) {
391 CapturedVars.push_back(CXXThisValue);
392 } else if (CurCap->capturesVariableByCopy()) {
393 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
394
395 // If the field is not a pointer, we need to save the actual value
396 // and load it as a void pointer.
397 if (!CurField->getType()->isAnyPointerType()) {
398 ASTContext &Ctx = getContext();
399 Address DstAddr = CreateMemTemp(
400 Ctx.getUIntPtrType(),
401 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
402 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
403
404 llvm::Value *SrcAddrVal = EmitScalarConversion(
405 DstAddr.emitRawPointer(*this),
407 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
408 LValue SrcLV =
409 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
410
411 // Store the value using the source type pointer.
413
414 // Load the value using the destination type pointer.
415 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
416 }
417 CapturedVars.push_back(CV);
418 } else {
419 assert(CurCap->capturesVariable() && "Expected capture by reference.");
420 CapturedVars.push_back(EmitLValue(*I).getAddress().emitRawPointer(*this));
421 }
422 }
423}
424
426 QualType DstType, StringRef Name,
427 LValue AddrLV) {
428 ASTContext &Ctx = CGF.getContext();
429
430 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
431 AddrLV.getAddress().emitRawPointer(CGF), Ctx.getUIntPtrType(),
432 Ctx.getPointerType(DstType), Loc);
433 // FIXME: should the pointee type (DstType) be passed?
434 Address TmpAddr =
435 CGF.MakeNaturalAlignAddrLValue(CastedPtr, DstType).getAddress();
436 return TmpAddr;
437}
438
441 return C.getLValueReferenceType(
442 getCanonicalParamType(C, T.getNonReferenceType()),
443 /*SpelledAsLValue=*/false);
444 if (T->isPointerType())
445 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
446 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
447 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
448 return getCanonicalParamType(C, VLA->getElementType());
449 if (!A->isVariablyModifiedType())
450 return C.getCanonicalType(T);
451 }
452 return C.getCanonicalParamType(T);
453}
454
455namespace {
456/// Contains required data for proper outlined function codegen.
457struct FunctionOptions {
458 /// Captured statement for which the function is generated.
459 const CapturedStmt *S = nullptr;
460 /// true if cast to/from UIntPtr is required for variables captured by
461 /// value.
462 const bool UIntPtrCastRequired = true;
463 /// true if only casted arguments must be registered as local args or VLA
464 /// sizes.
465 const bool RegisterCastedArgsOnly = false;
466 /// Name of the generated function.
467 const StringRef FunctionName;
468 /// Location of the non-debug version of the outlined function.
470 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
471 bool RegisterCastedArgsOnly, StringRef FunctionName,
473 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
474 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
475 FunctionName(FunctionName), Loc(Loc) {}
476};
477} // namespace
478
479static llvm::Function *emitOutlinedFunctionPrologue(
481 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
482 &LocalAddrs,
483 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
484 &VLASizes,
485 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
486 const CapturedDecl *CD = FO.S->getCapturedDecl();
487 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
488 assert(CD->hasBody() && "missing CapturedDecl body");
489
490 CXXThisValue = nullptr;
491 // Build the argument list.
492 CodeGenModule &CGM = CGF.CGM;
493 ASTContext &Ctx = CGM.getContext();
494 FunctionArgList TargetArgs;
495 Args.append(CD->param_begin(),
496 std::next(CD->param_begin(), CD->getContextParamPosition()));
497 TargetArgs.append(
498 CD->param_begin(),
499 std::next(CD->param_begin(), CD->getContextParamPosition()));
500 auto I = FO.S->captures().begin();
501 FunctionDecl *DebugFunctionDecl = nullptr;
502 if (!FO.UIntPtrCastRequired) {
504 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, std::nullopt, EPI);
505 DebugFunctionDecl = FunctionDecl::Create(
506 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
507 SourceLocation(), DeclarationName(), FunctionTy,
508 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
509 /*UsesFPIntrin=*/false, /*isInlineSpecified=*/false,
510 /*hasWrittenPrototype=*/false);
511 }
512 for (const FieldDecl *FD : RD->fields()) {
513 QualType ArgType = FD->getType();
514 IdentifierInfo *II = nullptr;
515 VarDecl *CapVar = nullptr;
516
517 // If this is a capture by copy and the type is not a pointer, the outlined
518 // function argument type should be uintptr and the value properly casted to
519 // uintptr. This is necessary given that the runtime library is only able to
520 // deal with pointers. We can pass in the same way the VLA type sizes to the
521 // outlined function.
522 if (FO.UIntPtrCastRequired &&
523 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
524 I->capturesVariableArrayType()))
525 ArgType = Ctx.getUIntPtrType();
526
527 if (I->capturesVariable() || I->capturesVariableByCopy()) {
528 CapVar = I->getCapturedVar();
529 II = CapVar->getIdentifier();
530 } else if (I->capturesThis()) {
531 II = &Ctx.Idents.get("this");
532 } else {
533 assert(I->capturesVariableArrayType());
534 II = &Ctx.Idents.get("vla");
535 }
536 if (ArgType->isVariablyModifiedType())
537 ArgType = getCanonicalParamType(Ctx, ArgType);
538 VarDecl *Arg;
539 if (CapVar && (CapVar->getTLSKind() != clang::VarDecl::TLS_None)) {
540 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
541 II, ArgType,
543 } else if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
545 Ctx, DebugFunctionDecl,
546 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
547 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
548 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
549 } else {
550 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
551 II, ArgType, ImplicitParamKind::Other);
552 }
553 Args.emplace_back(Arg);
554 // Do not cast arguments if we emit function with non-original types.
555 TargetArgs.emplace_back(
556 FO.UIntPtrCastRequired
557 ? Arg
558 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
559 ++I;
560 }
561 Args.append(std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
562 CD->param_end());
563 TargetArgs.append(
564 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
565 CD->param_end());
566
567 // Create the function declaration.
568 const CGFunctionInfo &FuncInfo =
570 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
571
572 auto *F =
573 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
574 FO.FunctionName, &CGM.getModule());
575 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
576 if (CD->isNothrow())
577 F->setDoesNotThrow();
578 F->setDoesNotRecurse();
579
580 // Always inline the outlined function if optimizations are enabled.
581 if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
582 F->removeFnAttr(llvm::Attribute::NoInline);
583 F->addFnAttr(llvm::Attribute::AlwaysInline);
584 }
585
586 // Generate the function.
587 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
588 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(),
589 FO.UIntPtrCastRequired ? FO.Loc
590 : CD->getBody()->getBeginLoc());
591 unsigned Cnt = CD->getContextParamPosition();
592 I = FO.S->captures().begin();
593 for (const FieldDecl *FD : RD->fields()) {
594 // Do not map arguments if we emit function with non-original types.
595 Address LocalAddr(Address::invalid());
596 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
597 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
598 TargetArgs[Cnt]);
599 } else {
600 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
601 }
602 // If we are capturing a pointer by copy we don't need to do anything, just
603 // use the value that we get from the arguments.
604 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
605 const VarDecl *CurVD = I->getCapturedVar();
606 if (!FO.RegisterCastedArgsOnly)
607 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
608 ++Cnt;
609 ++I;
610 continue;
611 }
612
613 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
615 if (FD->hasCapturedVLAType()) {
616 if (FO.UIntPtrCastRequired) {
617 ArgLVal = CGF.MakeAddrLValue(
618 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
619 Args[Cnt]->getName(), ArgLVal),
621 }
622 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
623 const VariableArrayType *VAT = FD->getCapturedVLAType();
624 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
625 } else if (I->capturesVariable()) {
626 const VarDecl *Var = I->getCapturedVar();
627 QualType VarTy = Var->getType();
628 Address ArgAddr = ArgLVal.getAddress();
629 if (ArgLVal.getType()->isLValueReferenceType()) {
630 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
631 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
632 assert(ArgLVal.getType()->isPointerType());
633 ArgAddr = CGF.EmitLoadOfPointer(
634 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
635 }
636 if (!FO.RegisterCastedArgsOnly) {
637 LocalAddrs.insert(
638 {Args[Cnt], {Var, ArgAddr.withAlignment(Ctx.getDeclAlign(Var))}});
639 }
640 } else if (I->capturesVariableByCopy()) {
641 assert(!FD->getType()->isAnyPointerType() &&
642 "Not expecting a captured pointer.");
643 const VarDecl *Var = I->getCapturedVar();
644 LocalAddrs.insert({Args[Cnt],
645 {Var, FO.UIntPtrCastRequired
647 CGF, I->getLocation(), FD->getType(),
648 Args[Cnt]->getName(), ArgLVal)
649 : ArgLVal.getAddress()}});
650 } else {
651 // If 'this' is captured, load it into CXXThisValue.
652 assert(I->capturesThis());
653 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
654 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
655 }
656 ++Cnt;
657 ++I;
658 }
659
660 return F;
661}
662
663llvm::Function *
666 assert(
668 "CapturedStmtInfo should be set when generating the captured function");
669 const CapturedDecl *CD = S.getCapturedDecl();
670 // Build the argument list.
671 bool NeedWrapperFunction =
673 FunctionArgList Args, WrapperArgs;
674 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs,
675 WrapperLocalAddrs;
676 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes,
677 WrapperVLASizes;
678 SmallString<256> Buffer;
679 llvm::raw_svector_ostream Out(Buffer);
681
682 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
683 llvm::Function *WrapperF = nullptr;
684 if (NeedWrapperFunction) {
685 // Emit the final kernel early to allow attributes to be added by the
686 // OpenMPI-IR-Builder.
687 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
688 /*RegisterCastedArgsOnly=*/true,
690 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
691 WrapperF =
692 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
693 WrapperCGF.CXXThisValue, WrapperFO);
694 Out << "_debug__";
695 }
696 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
697 Out.str(), Loc);
698 llvm::Function *F = emitOutlinedFunctionPrologue(
699 *this, WrapperArgs, WrapperLocalAddrs, WrapperVLASizes, CXXThisValue, FO);
700 CodeGenFunction::OMPPrivateScope LocalScope(*this);
701 for (const auto &LocalAddrPair : WrapperLocalAddrs) {
702 if (LocalAddrPair.second.first) {
703 LocalScope.addPrivate(LocalAddrPair.second.first,
704 LocalAddrPair.second.second);
705 }
706 }
707 (void)LocalScope.Privatize();
708 for (const auto &VLASizePair : WrapperVLASizes)
709 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
711 CapturedStmtInfo->EmitBody(*this, CD->getBody());
712 (void)LocalScope.ForceCleanup();
714 if (!NeedWrapperFunction)
715 return F;
716
717 // Reverse the order.
718 WrapperF->removeFromParent();
719 F->getParent()->getFunctionList().insertAfter(F->getIterator(), WrapperF);
720
722 auto *PI = F->arg_begin();
723 for (const auto *Arg : Args) {
724 llvm::Value *CallArg;
725 auto I = LocalAddrs.find(Arg);
726 if (I != LocalAddrs.end()) {
727 LValue LV = WrapperCGF.MakeAddrLValue(
728 I->second.second,
729 I->second.first ? I->second.first->getType() : Arg->getType(),
731 if (LV.getType()->isAnyComplexType())
732 LV.setAddress(LV.getAddress().withElementType(PI->getType()));
733 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
734 } else {
735 auto EI = VLASizes.find(Arg);
736 if (EI != VLASizes.end()) {
737 CallArg = EI->second.second;
738 } else {
739 LValue LV =
740 WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
741 Arg->getType(), AlignmentSource::Decl);
742 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
743 }
744 }
745 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
746 ++PI;
747 }
748 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
749 WrapperCGF.FinishFunction();
750 return WrapperF;
751}
752
753//===----------------------------------------------------------------------===//
754// OpenMP Directive Emission
755//===----------------------------------------------------------------------===//
757 Address DestAddr, Address SrcAddr, QualType OriginalType,
758 const llvm::function_ref<void(Address, Address)> CopyGen) {
759 // Perform element-by-element initialization.
760 QualType ElementTy;
761
762 // Drill down to the base element type on both arrays.
763 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
764 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
765 SrcAddr = SrcAddr.withElementType(DestAddr.getElementType());
766
767 llvm::Value *SrcBegin = SrcAddr.emitRawPointer(*this);
768 llvm::Value *DestBegin = DestAddr.emitRawPointer(*this);
769 // Cast from pointer to array type to pointer to single element.
770 llvm::Value *DestEnd = Builder.CreateInBoundsGEP(DestAddr.getElementType(),
771 DestBegin, NumElements);
772
773 // The basic structure here is a while-do loop.
774 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
775 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
776 llvm::Value *IsEmpty =
777 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
778 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
779
780 // Enter the loop body, making that address the current address.
781 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
782 EmitBlock(BodyBB);
783
784 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
785
786 llvm::PHINode *SrcElementPHI =
787 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
788 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
789 Address SrcElementCurrent =
790 Address(SrcElementPHI, SrcAddr.getElementType(),
791 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
792
793 llvm::PHINode *DestElementPHI = Builder.CreatePHI(
794 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
795 DestElementPHI->addIncoming(DestBegin, EntryBB);
796 Address DestElementCurrent =
797 Address(DestElementPHI, DestAddr.getElementType(),
798 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
799
800 // Emit copy.
801 CopyGen(DestElementCurrent, SrcElementCurrent);
802
803 // Shift the address forward by one element.
804 llvm::Value *DestElementNext =
805 Builder.CreateConstGEP1_32(DestAddr.getElementType(), DestElementPHI,
806 /*Idx0=*/1, "omp.arraycpy.dest.element");
807 llvm::Value *SrcElementNext =
808 Builder.CreateConstGEP1_32(SrcAddr.getElementType(), SrcElementPHI,
809 /*Idx0=*/1, "omp.arraycpy.src.element");
810 // Check whether we've reached the end.
811 llvm::Value *Done =
812 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
813 Builder.CreateCondBr(Done, DoneBB, BodyBB);
814 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
815 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
816
817 // Done.
818 EmitBlock(DoneBB, /*IsFinished=*/true);
819}
820
821void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
822 Address SrcAddr, const VarDecl *DestVD,
823 const VarDecl *SrcVD, const Expr *Copy) {
824 if (OriginalType->isArrayType()) {
825 const auto *BO = dyn_cast<BinaryOperator>(Copy);
826 if (BO && BO->getOpcode() == BO_Assign) {
827 // Perform simple memcpy for simple copying.
828 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
829 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
830 EmitAggregateAssign(Dest, Src, OriginalType);
831 } else {
832 // For arrays with complex element types perform element by element
833 // copying.
835 DestAddr, SrcAddr, OriginalType,
836 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
837 // Working with the single array element, so have to remap
838 // destination and source variables to corresponding array
839 // elements.
840 CodeGenFunction::OMPPrivateScope Remap(*this);
841 Remap.addPrivate(DestVD, DestElement);
842 Remap.addPrivate(SrcVD, SrcElement);
843 (void)Remap.Privatize();
845 });
846 }
847 } else {
848 // Remap pseudo source variable to private copy.
849 CodeGenFunction::OMPPrivateScope Remap(*this);
850 Remap.addPrivate(SrcVD, SrcAddr);
851 Remap.addPrivate(DestVD, DestAddr);
852 (void)Remap.Privatize();
853 // Emit copying of the whole variable.
855 }
856}
857
859 OMPPrivateScope &PrivateScope) {
860 if (!HaveInsertPoint())
861 return false;
863 bool DeviceConstTarget = getLangOpts().OpenMPIsTargetDevice &&
865 bool FirstprivateIsLastprivate = false;
866 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
867 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
868 for (const auto *D : C->varlist())
869 Lastprivates.try_emplace(
870 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(),
871 C->getKind());
872 }
873 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
875 getOpenMPCaptureRegions(CaptureRegions, EKind);
876 // Force emission of the firstprivate copy if the directive does not emit
877 // outlined function, like omp for, omp simd, omp distribute etc.
878 bool MustEmitFirstprivateCopy =
879 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
880 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
881 const auto *IRef = C->varlist_begin();
882 const auto *InitsRef = C->inits().begin();
883 for (const Expr *IInit : C->private_copies()) {
884 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
885 bool ThisFirstprivateIsLastprivate =
886 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
887 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
888 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
889 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
890 !FD->getType()->isReferenceType() &&
891 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
892 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
893 ++IRef;
894 ++InitsRef;
895 continue;
896 }
897 // Do not emit copy for firstprivate constant variables in target regions,
898 // captured by reference.
899 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
900 FD && FD->getType()->isReferenceType() &&
901 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
902 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
903 ++IRef;
904 ++InitsRef;
905 continue;
906 }
907 FirstprivateIsLastprivate =
908 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
909 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
910 const auto *VDInit =
911 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
912 bool IsRegistered;
913 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
914 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
915 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
916 LValue OriginalLVal;
917 if (!FD) {
918 // Check if the firstprivate variable is just a constant value.
919 ConstantEmission CE = tryEmitAsConstant(&DRE);
920 if (CE && !CE.isReference()) {
921 // Constant value, no need to create a copy.
922 ++IRef;
923 ++InitsRef;
924 continue;
925 }
926 if (CE && CE.isReference()) {
927 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
928 } else {
929 assert(!CE && "Expected non-constant firstprivate.");
930 OriginalLVal = EmitLValue(&DRE);
931 }
932 } else {
933 OriginalLVal = EmitLValue(&DRE);
934 }
935 QualType Type = VD->getType();
936 if (Type->isArrayType()) {
937 // Emit VarDecl with copy init for arrays.
938 // Get the address of the original variable captured in current
939 // captured region.
940 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
941 const Expr *Init = VD->getInit();
942 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
943 // Perform simple memcpy.
944 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(), Type);
945 EmitAggregateAssign(Dest, OriginalLVal, Type);
946 } else {
948 Emission.getAllocatedAddress(), OriginalLVal.getAddress(), Type,
949 [this, VDInit, Init](Address DestElement, Address SrcElement) {
950 // Clean up any temporaries needed by the
951 // initialization.
952 RunCleanupsScope InitScope(*this);
953 // Emit initialization for single element.
954 setAddrOfLocalVar(VDInit, SrcElement);
955 EmitAnyExprToMem(Init, DestElement,
956 Init->getType().getQualifiers(),
957 /*IsInitializer*/ false);
958 LocalDeclMap.erase(VDInit);
959 });
960 }
961 EmitAutoVarCleanups(Emission);
962 IsRegistered =
963 PrivateScope.addPrivate(OrigVD, Emission.getAllocatedAddress());
964 } else {
965 Address OriginalAddr = OriginalLVal.getAddress();
966 // Emit private VarDecl with copy init.
967 // Remap temp VDInit variable to the address of the original
968 // variable (for proper handling of captured global variables).
969 setAddrOfLocalVar(VDInit, OriginalAddr);
970 EmitDecl(*VD);
971 LocalDeclMap.erase(VDInit);
972 Address VDAddr = GetAddrOfLocalVar(VD);
973 if (ThisFirstprivateIsLastprivate &&
974 Lastprivates[OrigVD->getCanonicalDecl()] ==
975 OMPC_LASTPRIVATE_conditional) {
976 // Create/init special variable for lastprivate conditionals.
977 llvm::Value *V =
978 EmitLoadOfScalar(MakeAddrLValue(VDAddr, (*IRef)->getType(),
980 (*IRef)->getExprLoc());
982 *this, OrigVD);
983 EmitStoreOfScalar(V, MakeAddrLValue(VDAddr, (*IRef)->getType(),
985 LocalDeclMap.erase(VD);
986 setAddrOfLocalVar(VD, VDAddr);
987 }
988 IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr);
989 }
990 assert(IsRegistered &&
991 "firstprivate var already registered as private");
992 // Silence the warning about unused variable.
993 (void)IsRegistered;
994 }
995 ++IRef;
996 ++InitsRef;
997 }
998 }
999 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
1000}
1001
1004 CodeGenFunction::OMPPrivateScope &PrivateScope) {
1005 if (!HaveInsertPoint())
1006 return;
1007 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1008 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
1009 auto IRef = C->varlist_begin();
1010 for (const Expr *IInit : C->private_copies()) {
1011 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1012 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1013 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1014 EmitDecl(*VD);
1015 // Emit private VarDecl with copy init.
1016 bool IsRegistered =
1017 PrivateScope.addPrivate(OrigVD, GetAddrOfLocalVar(VD));
1018 assert(IsRegistered && "private var already registered as private");
1019 // Silence the warning about unused variable.
1020 (void)IsRegistered;
1021 }
1022 ++IRef;
1023 }
1024 }
1025}
1026
1028 if (!HaveInsertPoint())
1029 return false;
1030 // threadprivate_var1 = master_threadprivate_var1;
1031 // operator=(threadprivate_var2, master_threadprivate_var2);
1032 // ...
1033 // __kmpc_barrier(&loc, global_tid);
1034 llvm::DenseSet<const VarDecl *> CopiedVars;
1035 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
1036 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
1037 auto IRef = C->varlist_begin();
1038 auto ISrcRef = C->source_exprs().begin();
1039 auto IDestRef = C->destination_exprs().begin();
1040 for (const Expr *AssignOp : C->assignment_ops()) {
1041 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1042 QualType Type = VD->getType();
1043 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
1044 // Get the address of the master variable. If we are emitting code with
1045 // TLS support, the address is passed from the master as field in the
1046 // captured declaration.
1047 Address MasterAddr = Address::invalid();
1048 if (getLangOpts().OpenMPUseTLS &&
1049 getContext().getTargetInfo().isTLSSupported()) {
1050 assert(CapturedStmtInfo->lookup(VD) &&
1051 "Copyin threadprivates should have been captured!");
1052 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
1053 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1054 MasterAddr = EmitLValue(&DRE).getAddress();
1055 LocalDeclMap.erase(VD);
1056 } else {
1057 MasterAddr =
1059 : CGM.GetAddrOfGlobal(VD),
1061 getContext().getDeclAlign(VD));
1062 }
1063 // Get the address of the threadprivate variable.
1064 Address PrivateAddr = EmitLValue(*IRef).getAddress();
1065 if (CopiedVars.size() == 1) {
1066 // At first check if current thread is a master thread. If it is, no
1067 // need to copy data.
1068 CopyBegin = createBasicBlock("copyin.not.master");
1069 CopyEnd = createBasicBlock("copyin.not.master.end");
1070 // TODO: Avoid ptrtoint conversion.
1071 auto *MasterAddrInt = Builder.CreatePtrToInt(
1072 MasterAddr.emitRawPointer(*this), CGM.IntPtrTy);
1073 auto *PrivateAddrInt = Builder.CreatePtrToInt(
1074 PrivateAddr.emitRawPointer(*this), CGM.IntPtrTy);
1075 Builder.CreateCondBr(
1076 Builder.CreateICmpNE(MasterAddrInt, PrivateAddrInt), CopyBegin,
1077 CopyEnd);
1078 EmitBlock(CopyBegin);
1079 }
1080 const auto *SrcVD =
1081 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1082 const auto *DestVD =
1083 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1084 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
1085 }
1086 ++IRef;
1087 ++ISrcRef;
1088 ++IDestRef;
1089 }
1090 }
1091 if (CopyEnd) {
1092 // Exit out of copying procedure for non-master thread.
1093 EmitBlock(CopyEnd, /*IsFinished=*/true);
1094 return true;
1095 }
1096 return false;
1097}
1098
1100 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
1101 if (!HaveInsertPoint())
1102 return false;
1103 bool HasAtLeastOneLastprivate = false;
1105 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1106 if (isOpenMPSimdDirective(EKind)) {
1107 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1108 for (const Expr *C : LoopDirective->counters()) {
1109 SIMDLCVs.insert(
1110 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1111 }
1112 }
1113 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1114 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1115 HasAtLeastOneLastprivate = true;
1116 if (isOpenMPTaskLoopDirective(EKind) && !getLangOpts().OpenMPSimd)
1117 break;
1118 const auto *IRef = C->varlist_begin();
1119 const auto *IDestRef = C->destination_exprs().begin();
1120 for (const Expr *IInit : C->private_copies()) {
1121 // Keep the address of the original variable for future update at the end
1122 // of the loop.
1123 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1124 // Taskloops do not require additional initialization, it is done in
1125 // runtime support library.
1126 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
1127 const auto *DestVD =
1128 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1129 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1130 /*RefersToEnclosingVariableOrCapture=*/
1131 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1132 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1133 PrivateScope.addPrivate(DestVD, EmitLValue(&DRE).getAddress());
1134 // Check if the variable is also a firstprivate: in this case IInit is
1135 // not generated. Initialization of this variable will happen in codegen
1136 // for 'firstprivate' clause.
1137 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
1138 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1139 Address VDAddr = Address::invalid();
1140 if (C->getKind() == OMPC_LASTPRIVATE_conditional) {
1142 *this, OrigVD);
1143 setAddrOfLocalVar(VD, VDAddr);
1144 } else {
1145 // Emit private VarDecl with copy init.
1146 EmitDecl(*VD);
1147 VDAddr = GetAddrOfLocalVar(VD);
1148 }
1149 bool IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr);
1150 assert(IsRegistered &&
1151 "lastprivate var already registered as private");
1152 (void)IsRegistered;
1153 }
1154 }
1155 ++IRef;
1156 ++IDestRef;
1157 }
1158 }
1159 return HasAtLeastOneLastprivate;
1160}
1161
1163 const OMPExecutableDirective &D, bool NoFinals,
1164 llvm::Value *IsLastIterCond) {
1165 if (!HaveInsertPoint())
1166 return;
1167 // Emit following code:
1168 // if (<IsLastIterCond>) {
1169 // orig_var1 = private_orig_var1;
1170 // ...
1171 // orig_varn = private_orig_varn;
1172 // }
1173 llvm::BasicBlock *ThenBB = nullptr;
1174 llvm::BasicBlock *DoneBB = nullptr;
1175 if (IsLastIterCond) {
1176 // Emit implicit barrier if at least one lastprivate conditional is found
1177 // and this is not a simd mode.
1178 if (!getLangOpts().OpenMPSimd &&
1179 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
1180 [](const OMPLastprivateClause *C) {
1181 return C->getKind() == OMPC_LASTPRIVATE_conditional;
1182 })) {
1184 OMPD_unknown,
1185 /*EmitChecks=*/false,
1186 /*ForceSimpleCall=*/true);
1187 }
1188 ThenBB = createBasicBlock(".omp.lastprivate.then");
1189 DoneBB = createBasicBlock(".omp.lastprivate.done");
1190 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1191 EmitBlock(ThenBB);
1192 }
1193 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1194 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
1195 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
1196 auto IC = LoopDirective->counters().begin();
1197 for (const Expr *F : LoopDirective->finals()) {
1198 const auto *D =
1199 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1200 if (NoFinals)
1201 AlreadyEmittedVars.insert(D);
1202 else
1203 LoopCountersAndUpdates[D] = F;
1204 ++IC;
1205 }
1206 }
1207 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1208 auto IRef = C->varlist_begin();
1209 auto ISrcRef = C->source_exprs().begin();
1210 auto IDestRef = C->destination_exprs().begin();
1211 for (const Expr *AssignOp : C->assignment_ops()) {
1212 const auto *PrivateVD =
1213 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1214 QualType Type = PrivateVD->getType();
1215 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1216 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1217 // If lastprivate variable is a loop control variable for loop-based
1218 // directive, update its value before copyin back to original
1219 // variable.
1220 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1221 EmitIgnoredExpr(FinalExpr);
1222 const auto *SrcVD =
1223 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1224 const auto *DestVD =
1225 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1226 // Get the address of the private variable.
1227 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1228 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1229 PrivateAddr = Address(
1230 Builder.CreateLoad(PrivateAddr),
1231 CGM.getTypes().ConvertTypeForMem(RefTy->getPointeeType()),
1232 CGM.getNaturalTypeAlignment(RefTy->getPointeeType()));
1233 // Store the last value to the private copy in the last iteration.
1234 if (C->getKind() == OMPC_LASTPRIVATE_conditional)
1236 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
1237 (*IRef)->getExprLoc());
1238 // Get the address of the original variable.
1239 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1240 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
1241 }
1242 ++IRef;
1243 ++ISrcRef;
1244 ++IDestRef;
1245 }
1246 if (const Expr *PostUpdate = C->getPostUpdateExpr())
1247 EmitIgnoredExpr(PostUpdate);
1248 }
1249 if (IsLastIterCond)
1250 EmitBlock(DoneBB, /*IsFinished=*/true);
1251}
1252
1255 CodeGenFunction::OMPPrivateScope &PrivateScope, bool ForInscan) {
1256 if (!HaveInsertPoint())
1257 return;
1260 SmallVector<const Expr *, 4> ReductionOps;
1266 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1267 if (ForInscan != (C->getModifier() == OMPC_REDUCTION_inscan))
1268 continue;
1269 Shareds.append(C->varlist_begin(), C->varlist_end());
1270 Privates.append(C->privates().begin(), C->privates().end());
1271 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1272 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1273 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1274 if (C->getModifier() == OMPC_REDUCTION_task) {
1275 Data.ReductionVars.append(C->privates().begin(), C->privates().end());
1276 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
1277 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
1278 Data.ReductionOps.append(C->reduction_ops().begin(),
1279 C->reduction_ops().end());
1280 TaskLHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1281 TaskRHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1282 }
1283 }
1284 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
1285 unsigned Count = 0;
1286 auto *ILHS = LHSs.begin();
1287 auto *IRHS = RHSs.begin();
1288 auto *IPriv = Privates.begin();
1289 for (const Expr *IRef : Shareds) {
1290 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1291 // Emit private VarDecl with reduction init.
1292 RedCG.emitSharedOrigLValue(*this, Count);
1293 RedCG.emitAggregateType(*this, Count);
1294 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1295 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1296 RedCG.getSharedLValue(Count).getAddress(),
1297 [&Emission](CodeGenFunction &CGF) {
1298 CGF.EmitAutoVarInit(Emission);
1299 return true;
1300 });
1301 EmitAutoVarCleanups(Emission);
1302 Address BaseAddr = RedCG.adjustPrivateAddress(
1303 *this, Count, Emission.getAllocatedAddress());
1304 bool IsRegistered =
1305 PrivateScope.addPrivate(RedCG.getBaseDecl(Count), BaseAddr);
1306 assert(IsRegistered && "private var already registered as private");
1307 // Silence the warning about unused variable.
1308 (void)IsRegistered;
1309
1310 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1311 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1312 QualType Type = PrivateVD->getType();
1313 bool isaOMPArraySectionExpr = isa<ArraySectionExpr>(IRef);
1314 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1315 // Store the address of the original variable associated with the LHS
1316 // implicit variable.
1317 PrivateScope.addPrivate(LHSVD, RedCG.getSharedLValue(Count).getAddress());
1318 PrivateScope.addPrivate(RHSVD, GetAddrOfLocalVar(PrivateVD));
1319 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1320 isa<ArraySubscriptExpr>(IRef)) {
1321 // Store the address of the original variable associated with the LHS
1322 // implicit variable.
1323 PrivateScope.addPrivate(LHSVD, RedCG.getSharedLValue(Count).getAddress());
1324 PrivateScope.addPrivate(RHSVD,
1325 GetAddrOfLocalVar(PrivateVD).withElementType(
1326 ConvertTypeForMem(RHSVD->getType())));
1327 } else {
1328 QualType Type = PrivateVD->getType();
1329 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1330 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1331 // Store the address of the original variable associated with the LHS
1332 // implicit variable.
1333 if (IsArray) {
1334 OriginalAddr =
1335 OriginalAddr.withElementType(ConvertTypeForMem(LHSVD->getType()));
1336 }
1337 PrivateScope.addPrivate(LHSVD, OriginalAddr);
1338 PrivateScope.addPrivate(
1339 RHSVD, IsArray ? GetAddrOfLocalVar(PrivateVD).withElementType(
1340 ConvertTypeForMem(RHSVD->getType()))
1341 : GetAddrOfLocalVar(PrivateVD));
1342 }
1343 ++ILHS;
1344 ++IRHS;
1345 ++IPriv;
1346 ++Count;
1347 }
1348 if (!Data.ReductionVars.empty()) {
1350 Data.IsReductionWithTaskMod = true;
1351 Data.IsWorksharingReduction = isOpenMPWorksharingDirective(EKind);
1352 llvm::Value *ReductionDesc = CGM.getOpenMPRuntime().emitTaskReductionInit(
1353 *this, D.getBeginLoc(), TaskLHSs, TaskRHSs, Data);
1354 const Expr *TaskRedRef = nullptr;
1355 switch (EKind) {
1356 case OMPD_parallel:
1357 TaskRedRef = cast<OMPParallelDirective>(D).getTaskReductionRefExpr();
1358 break;
1359 case OMPD_for:
1360 TaskRedRef = cast<OMPForDirective>(D).getTaskReductionRefExpr();
1361 break;
1362 case OMPD_sections:
1363 TaskRedRef = cast<OMPSectionsDirective>(D).getTaskReductionRefExpr();
1364 break;
1365 case OMPD_parallel_for:
1366 TaskRedRef = cast<OMPParallelForDirective>(D).getTaskReductionRefExpr();
1367 break;
1368 case OMPD_parallel_master:
1369 TaskRedRef =
1370 cast<OMPParallelMasterDirective>(D).getTaskReductionRefExpr();
1371 break;
1372 case OMPD_parallel_sections:
1373 TaskRedRef =
1374 cast<OMPParallelSectionsDirective>(D).getTaskReductionRefExpr();
1375 break;
1376 case OMPD_target_parallel:
1377 TaskRedRef =
1378 cast<OMPTargetParallelDirective>(D).getTaskReductionRefExpr();
1379 break;
1380 case OMPD_target_parallel_for:
1381 TaskRedRef =
1382 cast<OMPTargetParallelForDirective>(D).getTaskReductionRefExpr();
1383 break;
1384 case OMPD_distribute_parallel_for:
1385 TaskRedRef =
1386 cast<OMPDistributeParallelForDirective>(D).getTaskReductionRefExpr();
1387 break;
1388 case OMPD_teams_distribute_parallel_for:
1389 TaskRedRef = cast<OMPTeamsDistributeParallelForDirective>(D)
1390 .getTaskReductionRefExpr();
1391 break;
1392 case OMPD_target_teams_distribute_parallel_for:
1393 TaskRedRef = cast<OMPTargetTeamsDistributeParallelForDirective>(D)
1394 .getTaskReductionRefExpr();
1395 break;
1396 case OMPD_simd:
1397 case OMPD_for_simd:
1398 case OMPD_section:
1399 case OMPD_single:
1400 case OMPD_master:
1401 case OMPD_critical:
1402 case OMPD_parallel_for_simd:
1403 case OMPD_task:
1404 case OMPD_taskyield:
1405 case OMPD_error:
1406 case OMPD_barrier:
1407 case OMPD_taskwait:
1408 case OMPD_taskgroup:
1409 case OMPD_flush:
1410 case OMPD_depobj:
1411 case OMPD_scan:
1412 case OMPD_ordered:
1413 case OMPD_atomic:
1414 case OMPD_teams:
1415 case OMPD_target:
1416 case OMPD_cancellation_point:
1417 case OMPD_cancel:
1418 case OMPD_target_data:
1419 case OMPD_target_enter_data:
1420 case OMPD_target_exit_data:
1421 case OMPD_taskloop:
1422 case OMPD_taskloop_simd:
1423 case OMPD_master_taskloop:
1424 case OMPD_master_taskloop_simd:
1425 case OMPD_parallel_master_taskloop:
1426 case OMPD_parallel_master_taskloop_simd:
1427 case OMPD_distribute:
1428 case OMPD_target_update:
1429 case OMPD_distribute_parallel_for_simd:
1430 case OMPD_distribute_simd:
1431 case OMPD_target_parallel_for_simd:
1432 case OMPD_target_simd:
1433 case OMPD_teams_distribute:
1434 case OMPD_teams_distribute_simd:
1435 case OMPD_teams_distribute_parallel_for_simd:
1436 case OMPD_target_teams:
1437 case OMPD_target_teams_distribute:
1438 case OMPD_target_teams_distribute_parallel_for_simd:
1439 case OMPD_target_teams_distribute_simd:
1440 case OMPD_declare_target:
1441 case OMPD_end_declare_target:
1442 case OMPD_threadprivate:
1443 case OMPD_allocate:
1444 case OMPD_declare_reduction:
1445 case OMPD_declare_mapper:
1446 case OMPD_declare_simd:
1447 case OMPD_requires:
1448 case OMPD_declare_variant:
1449 case OMPD_begin_declare_variant:
1450 case OMPD_end_declare_variant:
1451 case OMPD_unknown:
1452 default:
1453 llvm_unreachable("Unexpected directive with task reductions.");
1454 }
1455
1456 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(TaskRedRef)->getDecl());
1457 EmitVarDecl(*VD);
1458 EmitStoreOfScalar(ReductionDesc, GetAddrOfLocalVar(VD),
1459 /*Volatile=*/false, TaskRedRef->getType());
1460 }
1461}
1462
1464 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1465 if (!HaveInsertPoint())
1466 return;
1471 bool HasAtLeastOneReduction = false;
1472 bool IsReductionWithTaskMod = false;
1473 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1474 // Do not emit for inscan reductions.
1475 if (C->getModifier() == OMPC_REDUCTION_inscan)
1476 continue;
1477 HasAtLeastOneReduction = true;
1478 Privates.append(C->privates().begin(), C->privates().end());
1479 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1480 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1481 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1482 IsReductionWithTaskMod =
1483 IsReductionWithTaskMod || C->getModifier() == OMPC_REDUCTION_task;
1484 }
1485 if (HasAtLeastOneReduction) {
1487 if (IsReductionWithTaskMod) {
1489 *this, D.getBeginLoc(), isOpenMPWorksharingDirective(EKind));
1490 }
1491 bool TeamsLoopCanBeParallel = false;
1492 if (auto *TTLD = dyn_cast<OMPTargetTeamsGenericLoopDirective>(&D))
1493 TeamsLoopCanBeParallel = TTLD->canBeParallelFor();
1494 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1496 TeamsLoopCanBeParallel || ReductionKind == OMPD_simd;
1497 bool SimpleReduction = ReductionKind == OMPD_simd;
1498 // Emit nowait reduction if nowait clause is present or directive is a
1499 // parallel directive (it always has implicit barrier).
1501 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
1502 {WithNowait, SimpleReduction, ReductionKind});
1503 }
1504}
1505
1508 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1509 if (!CGF.HaveInsertPoint())
1510 return;
1511 llvm::BasicBlock *DoneBB = nullptr;
1512 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1513 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
1514 if (!DoneBB) {
1515 if (llvm::Value *Cond = CondGen(CGF)) {
1516 // If the first post-update expression is found, emit conditional
1517 // block if it was requested.
1518 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1519 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1520 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1521 CGF.EmitBlock(ThenBB);
1522 }
1523 }
1524 CGF.EmitIgnoredExpr(PostUpdate);
1525 }
1526 }
1527 if (DoneBB)
1528 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1529}
1530
1531namespace {
1532/// Codegen lambda for appending distribute lower and upper bounds to outlined
1533/// parallel function. This is necessary for combined constructs such as
1534/// 'distribute parallel for'
1535typedef llvm::function_ref<void(CodeGenFunction &,
1536 const OMPExecutableDirective &,
1538 CodeGenBoundParametersTy;
1539} // anonymous namespace
1540
1541static void
1543 const OMPExecutableDirective &S) {
1544 if (CGF.getLangOpts().OpenMP < 50)
1545 return;
1546 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls;
1547 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
1548 for (const Expr *Ref : C->varlist()) {
1549 if (!Ref->getType()->isScalarType())
1550 continue;
1551 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1552 if (!DRE)
1553 continue;
1554 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1556 }
1557 }
1558 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
1559 for (const Expr *Ref : C->varlist()) {
1560 if (!Ref->getType()->isScalarType())
1561 continue;
1562 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1563 if (!DRE)
1564 continue;
1565 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1567 }
1568 }
1569 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
1570 for (const Expr *Ref : C->varlist()) {
1571 if (!Ref->getType()->isScalarType())
1572 continue;
1573 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1574 if (!DRE)
1575 continue;
1576 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1578 }
1579 }
1580 // Privates should ne analyzed since they are not captured at all.
1581 // Task reductions may be skipped - tasks are ignored.
1582 // Firstprivates do not return value but may be passed by reference - no need
1583 // to check for updated lastprivate conditional.
1584 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
1585 for (const Expr *Ref : C->varlist()) {
1586 if (!Ref->getType()->isScalarType())
1587 continue;
1588 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1589 if (!DRE)
1590 continue;
1591 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1592 }
1593 }
1595 CGF, S, PrivateDecls);
1596}
1597
1600 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1601 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1602 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1603 llvm::Value *NumThreads = nullptr;
1604 llvm::Function *OutlinedFn =
1606 CGF, S, *CS->getCapturedDecl()->param_begin(), InnermostKind,
1607 CodeGen);
1608 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1609 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1610 NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1611 /*IgnoreResultAssign=*/true);
1613 CGF, NumThreads, NumThreadsClause->getBeginLoc());
1614 }
1615 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1616 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1618 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
1619 }
1620 const Expr *IfCond = nullptr;
1621 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1622 if (C->getNameModifier() == OMPD_unknown ||
1623 C->getNameModifier() == OMPD_parallel) {
1624 IfCond = C->getCondition();
1625 break;
1626 }
1627 }
1628
1629 OMPParallelScope Scope(CGF, S);
1631 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1632 // lower and upper bounds with the pragma 'for' chunking mechanism.
1633 // The following lambda takes care of appending the lower and upper bound
1634 // parameters when necessary
1635 CodeGenBoundParameters(CGF, S, CapturedVars);
1636 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1637 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
1638 CapturedVars, IfCond, NumThreads);
1639}
1640
1641static bool isAllocatableDecl(const VarDecl *VD) {
1642 const VarDecl *CVD = VD->getCanonicalDecl();
1643 if (!CVD->hasAttr<OMPAllocateDeclAttr>())
1644 return false;
1645 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
1646 // Use the default allocation.
1647 return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc ||
1648 AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc) &&
1649 !AA->getAllocator());
1650}
1651
1653 const OMPExecutableDirective &,
1655
1657 const OMPExecutableDirective &S) {
1658 bool Copyins = CGF.EmitOMPCopyinClause(S);
1659 if (Copyins) {
1660 // Emit implicit barrier to synchronize threads and avoid data races on
1661 // propagation master's thread values of threadprivate variables to local
1662 // instances of that variables of all other implicit threads.
1664 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
1665 /*ForceSimpleCall=*/true);
1666 }
1667}
1668
1670 CodeGenFunction &CGF, const VarDecl *VD) {
1671 CodeGenModule &CGM = CGF.CGM;
1672 auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1673
1674 if (!VD)
1675 return Address::invalid();
1676 const VarDecl *CVD = VD->getCanonicalDecl();
1677 if (!isAllocatableDecl(CVD))
1678 return Address::invalid();
1679 llvm::Value *Size;
1680 CharUnits Align = CGM.getContext().getDeclAlign(CVD);
1681 if (CVD->getType()->isVariablyModifiedType()) {
1682 Size = CGF.getTypeSize(CVD->getType());
1683 // Align the size: ((size + align - 1) / align) * align
1684 Size = CGF.Builder.CreateNUWAdd(
1685 Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
1686 Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
1687 Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
1688 } else {
1690 Size = CGM.getSize(Sz.alignTo(Align));
1691 }
1692
1693 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
1694 assert(AA->getAllocator() &&
1695 "Expected allocator expression for non-default allocator.");
1696 llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator());
1697 // According to the standard, the original allocator type is a enum (integer).
1698 // Convert to pointer type, if required.
1699 if (Allocator->getType()->isIntegerTy())
1700 Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy);
1701 else if (Allocator->getType()->isPointerTy())
1702 Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator,
1703 CGM.VoidPtrTy);
1704
1705 llvm::Value *Addr = OMPBuilder.createOMPAlloc(
1706 CGF.Builder, Size, Allocator,
1707 getNameWithSeparators({CVD->getName(), ".void.addr"}, ".", "."));
1708 llvm::CallInst *FreeCI =
1709 OMPBuilder.createOMPFree(CGF.Builder, Addr, Allocator);
1710
1711 CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FreeCI);
1713 Addr,
1715 getNameWithSeparators({CVD->getName(), ".addr"}, ".", "."));
1716 return Address(Addr, CGF.ConvertTypeForMem(CVD->getType()), Align);
1717}
1718
1720 CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr,
1722 CodeGenModule &CGM = CGF.CGM;
1723 if (CGM.getLangOpts().OpenMPUseTLS &&
1725 return VDAddr;
1726
1727 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1728
1729 llvm::Type *VarTy = VDAddr.getElementType();
1730 llvm::Value *Data =
1731 CGF.Builder.CreatePointerCast(VDAddr.emitRawPointer(CGF), CGM.Int8PtrTy);
1732 llvm::ConstantInt *Size = CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy));
1733 std::string Suffix = getNameWithSeparators({"cache", ""});
1734 llvm::Twine CacheName = Twine(CGM.getMangledName(VD)).concat(Suffix);
1735
1736 llvm::CallInst *ThreadPrivateCacheCall =
1737 OMPBuilder.createCachedThreadPrivate(CGF.Builder, Data, Size, CacheName);
1738
1739 return Address(ThreadPrivateCacheCall, CGM.Int8Ty, VDAddr.getAlignment());
1740}
1741
1743 ArrayRef<StringRef> Parts, StringRef FirstSeparator, StringRef Separator) {
1744 SmallString<128> Buffer;
1745 llvm::raw_svector_ostream OS(Buffer);
1746 StringRef Sep = FirstSeparator;
1747 for (StringRef Part : Parts) {
1748 OS << Sep << Part;
1749 Sep = Separator;
1750 }
1751 return OS.str().str();
1752}
1753
1755 CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP,
1756 InsertPointTy CodeGenIP, Twine RegionName) {
1758 Builder.restoreIP(CodeGenIP);
1759 llvm::BasicBlock *FiniBB = splitBBWithSuffix(Builder, /*CreateBranch=*/false,
1760 "." + RegionName + ".after");
1761
1762 {
1763 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(CGF, AllocaIP, *FiniBB);
1764 CGF.EmitStmt(RegionBodyStmt);
1765 }
1766
1767 if (Builder.saveIP().isSet())
1768 Builder.CreateBr(FiniBB);
1769}
1770
1772 CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP,
1773 InsertPointTy CodeGenIP, Twine RegionName) {
1775 Builder.restoreIP(CodeGenIP);
1776 llvm::BasicBlock *FiniBB = splitBBWithSuffix(Builder, /*CreateBranch=*/false,
1777 "." + RegionName + ".after");
1778
1779 {
1780 OMPBuilderCBHelpers::OutlinedRegionBodyRAII IRB(CGF, AllocaIP, *FiniBB);
1781 CGF.EmitStmt(RegionBodyStmt);
1782 }
1783
1784 if (Builder.saveIP().isSet())
1785 Builder.CreateBr(FiniBB);
1786}
1787
1789 if (CGM.getLangOpts().OpenMPIRBuilder) {
1790 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1791 // Check if we have any if clause associated with the directive.
1792 llvm::Value *IfCond = nullptr;
1793 if (const auto *C = S.getSingleClause<OMPIfClause>())
1794 IfCond = EmitScalarExpr(C->getCondition(),
1795 /*IgnoreResultAssign=*/true);
1796
1797 llvm::Value *NumThreads = nullptr;
1798 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
1799 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(),
1800 /*IgnoreResultAssign=*/true);
1801
1802 ProcBindKind ProcBind = OMP_PROC_BIND_default;
1803 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
1804 ProcBind = ProcBindClause->getProcBindKind();
1805
1806 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1807
1808 // The cleanup callback that finalizes all variables at the given location,
1809 // thus calls destructors etc.
1810 auto FiniCB = [this](InsertPointTy IP) {
1812 };
1813
1814 // Privatization callback that performs appropriate action for
1815 // shared/private/firstprivate/lastprivate/copyin/... variables.
1816 //
1817 // TODO: This defaults to shared right now.
1818 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1819 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
1820 // The next line is appropriate only for variables (Val) with the
1821 // data-sharing attribute "shared".
1822 ReplVal = &Val;
1823
1824 return CodeGenIP;
1825 };
1826
1827 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1828 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
1829
1830 auto BodyGenCB = [&, this](InsertPointTy AllocaIP,
1831 InsertPointTy CodeGenIP) {
1833 *this, ParallelRegionBodyStmt, AllocaIP, CodeGenIP, "parallel");
1834 };
1835
1836 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
1837 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
1838 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
1839 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
1840 Builder.restoreIP(
1841 OMPBuilder.createParallel(Builder, AllocaIP, BodyGenCB, PrivCB, FiniCB,
1842 IfCond, NumThreads, ProcBind, S.hasCancel()));
1843 return;
1844 }
1845
1846 // Emit parallel region as a standalone region.
1847 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1848 Action.Enter(CGF);
1849 OMPPrivateScope PrivateScope(CGF);
1850 emitOMPCopyinClause(CGF, S);
1851 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1852 CGF.EmitOMPPrivateClause(S, PrivateScope);
1853 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1854 (void)PrivateScope.Privatize();
1855 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
1856 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
1857 };
1858 {
1859 auto LPCRegion =
1861 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1864 [](CodeGenFunction &) { return nullptr; });
1865 }
1866 // Check for outer lastprivate conditional update.
1868}
1869
1871 EmitStmt(S.getIfStmt());
1872}
1873
1874namespace {
1875/// RAII to handle scopes for loop transformation directives.
1876class OMPTransformDirectiveScopeRAII {
1877 OMPLoopScope *Scope = nullptr;
1878 CodeGenFunction::CGCapturedStmtInfo *CGSI = nullptr;
1879 CodeGenFunction::CGCapturedStmtRAII *CapInfoRAII = nullptr;
1880
1881 OMPTransformDirectiveScopeRAII(const OMPTransformDirectiveScopeRAII &) =
1882 delete;
1883 OMPTransformDirectiveScopeRAII &
1884 operator=(const OMPTransformDirectiveScopeRAII &) = delete;
1885
1886public:
1887 OMPTransformDirectiveScopeRAII(CodeGenFunction &CGF, const Stmt *S) {
1888 if (const auto *Dir = dyn_cast<OMPLoopBasedDirective>(S)) {
1889 Scope = new OMPLoopScope(CGF, *Dir);
1890 CGSI = new CodeGenFunction::CGCapturedStmtInfo(CR_OpenMP);
1891 CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI);
1892 }
1893 }
1894 ~OMPTransformDirectiveScopeRAII() {
1895 if (!Scope)
1896 return;
1897 delete CapInfoRAII;
1898 delete CGSI;
1899 delete Scope;
1900 }
1901};
1902} // namespace
1903
1904static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1905 int MaxLevel, int Level = 0) {
1906 assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1907 const Stmt *SimplifiedS = S->IgnoreContainers();
1908 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1909 PrettyStackTraceLoc CrashInfo(
1910 CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1911 "LLVM IR generation of compound statement ('{}')");
1912
1913 // Keep track of the current cleanup stack depth, including debug scopes.
1914 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1915 for (const Stmt *CurStmt : CS->body())
1916 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1917 return;
1918 }
1919 if (SimplifiedS == NextLoop) {
1920 if (auto *Dir = dyn_cast<OMPLoopTransformationDirective>(SimplifiedS))
1921 SimplifiedS = Dir->getTransformedStmt();
1922 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(SimplifiedS))
1923 SimplifiedS = CanonLoop->getLoopStmt();
1924 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1925 S = For->getBody();
1926 } else {
1927 assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1928 "Expected canonical for loop or range-based for loop.");
1929 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1930 CGF.EmitStmt(CXXFor->getLoopVarStmt());
1931 S = CXXFor->getBody();
1932 }
1933 if (Level + 1 < MaxLevel) {
1935 S, /*TryImperfectlyNestedLoops=*/true);
1936 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1937 return;
1938 }
1939 }
1940 CGF.EmitStmt(S);
1941}
1942
1944 JumpDest LoopExit) {
1945 RunCleanupsScope BodyScope(*this);
1946 // Update counters values on current iteration.
1947 for (const Expr *UE : D.updates())
1948 EmitIgnoredExpr(UE);
1949 // Update the linear variables.
1950 // In distribute directives only loop counters may be marked as linear, no
1951 // need to generate the code for them.
1953 if (!isOpenMPDistributeDirective(EKind)) {
1954 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1955 for (const Expr *UE : C->updates())
1956 EmitIgnoredExpr(UE);
1957 }
1958 }
1959
1960 // On a continue in the body, jump to the end.
1961 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
1962 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1963 for (const Expr *E : D.finals_conditions()) {
1964 if (!E)
1965 continue;
1966 // Check that loop counter in non-rectangular nest fits into the iteration
1967 // space.
1968 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1969 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1971 EmitBlock(NextBB);
1972 }
1973
1974 OMPPrivateScope InscanScope(*this);
1975 EmitOMPReductionClauseInit(D, InscanScope, /*ForInscan=*/true);
1976 bool IsInscanRegion = InscanScope.Privatize();
1977 if (IsInscanRegion) {
1978 // Need to remember the block before and after scan directive
1979 // to dispatch them correctly depending on the clause used in
1980 // this directive, inclusive or exclusive. For inclusive scan the natural
1981 // order of the blocks is used, for exclusive clause the blocks must be
1982 // executed in reverse order.
1983 OMPBeforeScanBlock = createBasicBlock("omp.before.scan.bb");
1984 OMPAfterScanBlock = createBasicBlock("omp.after.scan.bb");
1985 // No need to allocate inscan exit block, in simd mode it is selected in the
1986 // codegen for the scan directive.
1987 if (EKind != OMPD_simd && !getLangOpts().OpenMPSimd)
1988 OMPScanExitBlock = createBasicBlock("omp.exit.inscan.bb");
1989 OMPScanDispatch = createBasicBlock("omp.inscan.dispatch");
1992 }
1993
1994 // Emit loop variables for C++ range loops.
1995 const Stmt *Body =
1996 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
1997 // Emit loop body.
1998 emitBody(*this, Body,
2000 Body, /*TryImperfectlyNestedLoops=*/true),
2001 D.getLoopsNumber());
2002
2003 // Jump to the dispatcher at the end of the loop body.
2004 if (IsInscanRegion)
2006
2007 // The end (updates/cleanups).
2008 EmitBlock(Continue.getBlock());
2009 BreakContinueStack.pop_back();
2010}
2011
2012using EmittedClosureTy = std::pair<llvm::Function *, llvm::Value *>;
2013
2014/// Emit a captured statement and return the function as well as its captured
2015/// closure context.
2017 const CapturedStmt *S) {
2018 LValue CapStruct = ParentCGF.InitCapturedStruct(*S);
2019 CodeGenFunction CGF(ParentCGF.CGM, /*suppressNewContext=*/true);
2020 std::unique_ptr<CodeGenFunction::CGCapturedStmtInfo> CSI =
2021 std::make_unique<CodeGenFunction::CGCapturedStmtInfo>(*S);
2022 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, CSI.get());
2023 llvm::Function *F = CGF.GenerateCapturedStmtFunction(*S);
2024
2025 return {F, CapStruct.getPointer(ParentCGF)};
2026}
2027
2028/// Emit a call to a previously captured closure.
2029static llvm::CallInst *
2032 // Append the closure context to the argument.
2033 SmallVector<llvm::Value *> EffectiveArgs;
2034 EffectiveArgs.reserve(Args.size() + 1);
2035 llvm::append_range(EffectiveArgs, Args);
2036 EffectiveArgs.push_back(Cap.second);
2037
2038 return ParentCGF.Builder.CreateCall(Cap.first, EffectiveArgs);
2039}
2040
2041llvm::CanonicalLoopInfo *
2043 assert(Depth == 1 && "Nested loops with OpenMPIRBuilder not yet implemented");
2044
2045 // The caller is processing the loop-associated directive processing the \p
2046 // Depth loops nested in \p S. Put the previous pending loop-associated
2047 // directive to the stack. If the current loop-associated directive is a loop
2048 // transformation directive, it will push its generated loops onto the stack
2049 // such that together with the loops left here they form the combined loop
2050 // nest for the parent loop-associated directive.
2051 int ParentExpectedOMPLoopDepth = ExpectedOMPLoopDepth;
2052 ExpectedOMPLoopDepth = Depth;
2053
2054 EmitStmt(S);
2055 assert(OMPLoopNestStack.size() >= (size_t)Depth && "Found too few loops");
2056
2057 // The last added loop is the outermost one.
2058 llvm::CanonicalLoopInfo *Result = OMPLoopNestStack.back();
2059
2060 // Pop the \p Depth loops requested by the call from that stack and restore
2061 // the previous context.
2062 OMPLoopNestStack.pop_back_n(Depth);
2063 ExpectedOMPLoopDepth = ParentExpectedOMPLoopDepth;
2064
2065 return Result;
2066}
2067
2069 const Stmt *SyntacticalLoop = S->getLoopStmt();
2070 if (!getLangOpts().OpenMPIRBuilder) {
2071 // Ignore if OpenMPIRBuilder is not enabled.
2072 EmitStmt(SyntacticalLoop);
2073 return;
2074 }
2075
2076 LexicalScope ForScope(*this, S->getSourceRange());
2077
2078 // Emit init statements. The Distance/LoopVar funcs may reference variable
2079 // declarations they contain.
2080 const Stmt *BodyStmt;
2081 if (const auto *For = dyn_cast<ForStmt>(SyntacticalLoop)) {
2082 if (const Stmt *InitStmt = For->getInit())
2083 EmitStmt(InitStmt);
2084 BodyStmt = For->getBody();
2085 } else if (const auto *RangeFor =
2086 dyn_cast<CXXForRangeStmt>(SyntacticalLoop)) {
2087 if (const DeclStmt *RangeStmt = RangeFor->getRangeStmt())
2088 EmitStmt(RangeStmt);
2089 if (const DeclStmt *BeginStmt = RangeFor->getBeginStmt())
2090 EmitStmt(BeginStmt);
2091 if (const DeclStmt *EndStmt = RangeFor->getEndStmt())
2092 EmitStmt(EndStmt);
2093 if (const DeclStmt *LoopVarStmt = RangeFor->getLoopVarStmt())
2094 EmitStmt(LoopVarStmt);
2095 BodyStmt = RangeFor->getBody();
2096 } else
2097 llvm_unreachable("Expected for-stmt or range-based for-stmt");
2098
2099 // Emit closure for later use. By-value captures will be captured here.
2100 const CapturedStmt *DistanceFunc = S->getDistanceFunc();
2101 EmittedClosureTy DistanceClosure = emitCapturedStmtFunc(*this, DistanceFunc);
2102 const CapturedStmt *LoopVarFunc = S->getLoopVarFunc();
2103 EmittedClosureTy LoopVarClosure = emitCapturedStmtFunc(*this, LoopVarFunc);
2104
2105 // Call the distance function to get the number of iterations of the loop to
2106 // come.
2107 QualType LogicalTy = DistanceFunc->getCapturedDecl()
2108 ->getParam(0)
2109 ->getType()
2111 RawAddress CountAddr = CreateMemTemp(LogicalTy, ".count.addr");
2112 emitCapturedStmtCall(*this, DistanceClosure, {CountAddr.getPointer()});
2113 llvm::Value *DistVal = Builder.CreateLoad(CountAddr, ".count");
2114
2115 // Emit the loop structure.
2116 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
2117 auto BodyGen = [&, this](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP,
2118 llvm::Value *IndVar) {
2119 Builder.restoreIP(CodeGenIP);
2120
2121 // Emit the loop body: Convert the logical iteration number to the loop
2122 // variable and emit the body.
2123 const DeclRefExpr *LoopVarRef = S->getLoopVarRef();
2124 LValue LCVal = EmitLValue(LoopVarRef);
2125 Address LoopVarAddress = LCVal.getAddress();
2126 emitCapturedStmtCall(*this, LoopVarClosure,
2127 {LoopVarAddress.emitRawPointer(*this), IndVar});
2128
2129 RunCleanupsScope BodyScope(*this);
2130 EmitStmt(BodyStmt);
2131 };
2132 llvm::CanonicalLoopInfo *CL =
2133 OMPBuilder.createCanonicalLoop(Builder, BodyGen, DistVal);
2134
2135 // Finish up the loop.
2136 Builder.restoreIP(CL->getAfterIP());
2137 ForScope.ForceCleanup();
2138
2139 // Remember the CanonicalLoopInfo for parent AST nodes consuming it.
2140 OMPLoopNestStack.push_back(CL);
2141}
2142
2144 const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond,
2145 const Expr *IncExpr,
2146 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
2147 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
2148 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
2149
2150 // Start the loop with a block that tests the condition.
2151 auto CondBlock = createBasicBlock("omp.inner.for.cond");
2152 EmitBlock(CondBlock);
2153 const SourceRange R = S.getSourceRange();
2154
2155 // If attributes are attached, push to the basic block with them.
2156 const auto &OMPED = cast<OMPExecutableDirective>(S);
2157 const CapturedStmt *ICS = OMPED.getInnermostCapturedStmt();
2158 const Stmt *SS = ICS->getCapturedStmt();
2159 const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(SS);
2160 OMPLoopNestStack.clear();
2161 if (AS)
2165 else
2168
2169 // If there are any cleanups between here and the loop-exit scope,
2170 // create a block to stage a loop exit along.
2171 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
2172 if (RequiresCleanup)
2173 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
2174
2175 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
2176
2177 // Emit condition.
2178 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
2179 if (ExitBlock != LoopExit.getBlock()) {
2180 EmitBlock(ExitBlock);
2182 }
2183
2184 EmitBlock(LoopBody);
2186
2187 // Create a block for the increment.
2188 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
2189 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2190
2191 BodyGen(*this);
2192
2193 // Emit "IV = IV + 1" and a back-edge to the condition block.
2194 EmitBlock(Continue.getBlock());
2195 EmitIgnoredExpr(IncExpr);
2196 PostIncGen(*this);
2197 BreakContinueStack.pop_back();
2198 EmitBranch(CondBlock);
2199 LoopStack.pop();
2200 // Emit the fall-through block.
2201 EmitBlock(LoopExit.getBlock());
2202}
2203
2205 if (!HaveInsertPoint())
2206 return false;
2207 // Emit inits for the linear variables.
2208 bool HasLinears = false;
2209 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2210 for (const Expr *Init : C->inits()) {
2211 HasLinears = true;
2212 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
2213 if (const auto *Ref =
2214 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
2215 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
2216 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
2217 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
2218 CapturedStmtInfo->lookup(OrigVD) != nullptr,
2219 VD->getInit()->getType(), VK_LValue,
2220 VD->getInit()->getExprLoc());
2222 &DRE, VD,
2223 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
2224 /*capturedByInit=*/false);
2225 EmitAutoVarCleanups(Emission);
2226 } else {
2227 EmitVarDecl(*VD);
2228 }
2229 }
2230 // Emit the linear steps for the linear clauses.
2231 // If a step is not constant, it is pre-calculated before the loop.
2232 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
2233 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
2234 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
2235 // Emit calculation of the linear step.
2236 EmitIgnoredExpr(CS);
2237 }
2238 }
2239 return HasLinears;
2240}
2241
2243 const OMPLoopDirective &D,
2244 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
2245 if (!HaveInsertPoint())
2246 return;
2247 llvm::BasicBlock *DoneBB = nullptr;
2248 // Emit the final values of the linear variables.
2249 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2250 auto IC = C->varlist_begin();
2251 for (const Expr *F : C->finals()) {
2252 if (!DoneBB) {
2253 if (llvm::Value *Cond = CondGen(*this)) {
2254 // If the first post-update expression is found, emit conditional
2255 // block if it was requested.
2256 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
2257 DoneBB = createBasicBlock(".omp.linear.pu.done");
2258 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
2259 EmitBlock(ThenBB);
2260 }
2261 }
2262 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
2263 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
2264 CapturedStmtInfo->lookup(OrigVD) != nullptr,
2265 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
2266 Address OrigAddr = EmitLValue(&DRE).getAddress();
2267 CodeGenFunction::OMPPrivateScope VarScope(*this);
2268 VarScope.addPrivate(OrigVD, OrigAddr);
2269 (void)VarScope.Privatize();
2270 EmitIgnoredExpr(F);
2271 ++IC;
2272 }
2273 if (const Expr *PostUpdate = C->getPostUpdateExpr())
2274 EmitIgnoredExpr(PostUpdate);
2275 }
2276 if (DoneBB)
2277 EmitBlock(DoneBB, /*IsFinished=*/true);
2278}
2279
2281 const OMPExecutableDirective &D) {
2282 if (!CGF.HaveInsertPoint())
2283 return;
2284 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
2285 llvm::APInt ClauseAlignment(64, 0);
2286 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
2287 auto *AlignmentCI =
2288 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
2289 ClauseAlignment = AlignmentCI->getValue();
2290 }
2291 for (const Expr *E : Clause->varlist()) {
2292 llvm::APInt Alignment(ClauseAlignment);
2293 if (Alignment == 0) {
2294 // OpenMP [2.8.1, Description]
2295 // If no optional parameter is specified, implementation-defined default
2296 // alignments for SIMD instructions on the target platforms are assumed.
2297 Alignment =
2298 CGF.getContext()
2300 E->getType()->getPointeeType()))
2301 .getQuantity();
2302 }
2303 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
2304 "alignment is not power of 2");
2305 if (Alignment != 0) {
2306 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
2308 PtrValue, E, /*No second loc needed*/ SourceLocation(),
2309 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
2310 }
2311 }
2312 }
2313}
2314
2316 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
2317 if (!HaveInsertPoint())
2318 return;
2319 auto I = S.private_counters().begin();
2320 for (const Expr *E : S.counters()) {
2321 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2322 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2323 // Emit var without initialization.
2324 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
2325 EmitAutoVarCleanups(VarEmission);
2326 LocalDeclMap.erase(PrivateVD);
2327 (void)LoopScope.addPrivate(VD, VarEmission.getAllocatedAddress());
2328 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
2329 VD->hasGlobalStorage()) {
2330 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
2331 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
2332 E->getType(), VK_LValue, E->getExprLoc());
2333 (void)LoopScope.addPrivate(PrivateVD, EmitLValue(&DRE).getAddress());
2334 } else {
2335 (void)LoopScope.addPrivate(PrivateVD, VarEmission.getAllocatedAddress());
2336 }
2337 ++I;
2338 }
2339 // Privatize extra loop counters used in loops for ordered(n) clauses.
2340 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
2341 if (!C->getNumForLoops())
2342 continue;
2343 for (unsigned I = S.getLoopsNumber(), E = C->getLoopNumIterations().size();
2344 I < E; ++I) {
2345 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
2346 const auto *VD = cast<VarDecl>(DRE->getDecl());
2347 // Override only those variables that can be captured to avoid re-emission
2348 // of the variables declared within the loops.
2349 if (DRE->refersToEnclosingVariableOrCapture()) {
2350 (void)LoopScope.addPrivate(
2351 VD, CreateMemTemp(DRE->getType(), VD->getName()));
2352 }
2353 }
2354 }
2355}
2356
2358 const Expr *Cond, llvm::BasicBlock *TrueBlock,
2359 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
2360 if (!CGF.HaveInsertPoint())
2361 return;
2362 {
2363 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
2364 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
2365 (void)PreCondScope.Privatize();
2366 // Get initial values of real counters.
2367 for (const Expr *I : S.inits()) {
2368 CGF.EmitIgnoredExpr(I);
2369 }
2370 }
2371 // Create temp loop control variables with their init values to support
2372 // non-rectangular loops.
2373 CodeGenFunction::OMPMapVars PreCondVars;
2374 for (const Expr *E : S.dependent_counters()) {
2375 if (!E)
2376 continue;
2377 assert(!E->getType().getNonReferenceType()->isRecordType() &&
2378 "dependent counter must not be an iterator.");
2379 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2380 Address CounterAddr =
2382 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
2383 }
2384 (void)PreCondVars.apply(CGF);
2385 for (const Expr *E : S.dependent_inits()) {
2386 if (!E)
2387 continue;
2388 CGF.EmitIgnoredExpr(E);
2389 }
2390 // Check that loop is executed at least one time.
2391 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
2392 PreCondVars.restore(CGF);
2393}
2394
2396 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
2397 if (!HaveInsertPoint())
2398 return;
2399 llvm::DenseSet<const VarDecl *> SIMDLCVs;
2401 if (isOpenMPSimdDirective(EKind)) {
2402 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
2403 for (const Expr *C : LoopDirective->counters()) {
2404 SIMDLCVs.insert(
2405 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
2406 }
2407 }
2408 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2409 auto CurPrivate = C->privates().begin();
2410 for (const Expr *E : C->varlist()) {
2411 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2412 const auto *PrivateVD =
2413 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
2414 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
2415 // Emit private VarDecl with copy init.
2416 EmitVarDecl(*PrivateVD);
2417 bool IsRegistered =
2418 PrivateScope.addPrivate(VD, GetAddrOfLocalVar(PrivateVD));
2419 assert(IsRegistered && "linear var already registered as private");
2420 // Silence the warning about unused variable.
2421 (void)IsRegistered;
2422 } else {
2423 EmitVarDecl(*PrivateVD);
2424 }
2425 ++CurPrivate;
2426 }
2427 }
2428}
2429
2431 const OMPExecutableDirective &D) {
2432 if (!CGF.HaveInsertPoint())
2433 return;
2434 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
2435 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
2436 /*ignoreResult=*/true);
2437 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2438 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
2439 // In presence of finite 'safelen', it may be unsafe to mark all
2440 // the memory instructions parallel, because loop-carried
2441 // dependences of 'safelen' iterations are possible.
2442 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
2443 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
2444 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
2445 /*ignoreResult=*/true);
2446 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2447 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
2448 // In presence of finite 'safelen', it may be unsafe to mark all
2449 // the memory instructions parallel, because loop-carried
2450 // dependences of 'safelen' iterations are possible.
2451 CGF.LoopStack.setParallel(/*Enable=*/false);
2452 }
2453}
2454
2456 // Walk clauses and process safelen/lastprivate.
2457 LoopStack.setParallel(/*Enable=*/true);
2460 if (const auto *C = D.getSingleClause<OMPOrderClause>())
2461 if (C->getKind() == OMPC_ORDER_concurrent)
2462 LoopStack.setParallel(/*Enable=*/true);
2464 if ((EKind == OMPD_simd ||
2465 (getLangOpts().OpenMPSimd && isOpenMPSimdDirective(EKind))) &&
2466 llvm::any_of(D.getClausesOfKind<OMPReductionClause>(),
2467 [](const OMPReductionClause *C) {
2468 return C->getModifier() == OMPC_REDUCTION_inscan;
2469 }))
2470 // Disable parallel access in case of prefix sum.
2471 LoopStack.setParallel(/*Enable=*/false);
2472}
2473
2475 const OMPLoopDirective &D,
2476 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
2477 if (!HaveInsertPoint())
2478 return;
2479 llvm::BasicBlock *DoneBB = nullptr;
2480 auto IC = D.counters().begin();
2481 auto IPC = D.private_counters().begin();
2482 for (const Expr *F : D.finals()) {
2483 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
2484 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
2485 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
2486 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
2487 OrigVD->hasGlobalStorage() || CED) {
2488 if (!DoneBB) {
2489 if (llvm::Value *Cond = CondGen(*this)) {
2490 // If the first post-update expression is found, emit conditional
2491 // block if it was requested.
2492 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
2493 DoneBB = createBasicBlock(".omp.final.done");
2494 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
2495 EmitBlock(ThenBB);
2496 }
2497 }
2498 Address OrigAddr = Address::invalid();
2499 if (CED) {
2500 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
2501 } else {
2502 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
2503 /*RefersToEnclosingVariableOrCapture=*/false,
2504 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
2505 OrigAddr = EmitLValue(&DRE).getAddress();
2506 }
2507 OMPPrivateScope VarScope(*this);
2508 VarScope.addPrivate(OrigVD, OrigAddr);
2509 (void)VarScope.Privatize();
2510 EmitIgnoredExpr(F);
2511 }
2512 ++IC;
2513 ++IPC;
2514 }
2515 if (DoneBB)
2516 EmitBlock(DoneBB, /*IsFinished=*/true);
2517}
2518
2520 const OMPLoopDirective &S,
2521 CodeGenFunction::JumpDest LoopExit) {
2522 CGF.EmitOMPLoopBody(S, LoopExit);
2523 CGF.EmitStopPoint(&S);
2524}
2525
2526/// Emit a helper variable and return corresponding lvalue.
2528 const DeclRefExpr *Helper) {
2529 auto VDecl = cast<VarDecl>(Helper->getDecl());
2530 CGF.EmitVarDecl(*VDecl);
2531 return CGF.EmitLValue(Helper);
2532}
2533
2535 const RegionCodeGenTy &SimdInitGen,
2536 const RegionCodeGenTy &BodyCodeGen) {
2537 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
2538 PrePostActionTy &) {
2539 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
2540 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2541 SimdInitGen(CGF);
2542
2543 BodyCodeGen(CGF);
2544 };
2545 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
2546 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2547 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
2548
2549 BodyCodeGen(CGF);
2550 };
2551 const Expr *IfCond = nullptr;
2553 if (isOpenMPSimdDirective(EKind)) {
2554 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2555 if (CGF.getLangOpts().OpenMP >= 50 &&
2556 (C->getNameModifier() == OMPD_unknown ||
2557 C->getNameModifier() == OMPD_simd)) {
2558 IfCond = C->getCondition();
2559 break;
2560 }
2561 }
2562 }
2563 if (IfCond) {
2564 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2565 } else {
2566 RegionCodeGenTy ThenRCG(ThenGen);
2567 ThenRCG(CGF);
2568 }
2569}
2570
2572 PrePostActionTy &Action) {
2573 Action.Enter(CGF);
2574 OMPLoopScope PreInitScope(CGF, S);
2575 // if (PreCond) {
2576 // for (IV in 0..LastIteration) BODY;
2577 // <Final counter/linear vars updates>;
2578 // }
2579
2580 // The presence of lower/upper bound variable depends on the actual directive
2581 // kind in the AST node. The variables must be emitted because some of the
2582 // expressions associated with the loop will use them.
2583 OpenMPDirectiveKind DKind = S.getDirectiveKind();
2584 if (isOpenMPDistributeDirective(DKind) ||
2587 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2588 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2589 }
2590
2592 // Emit: if (PreCond) - begin.
2593 // If the condition constant folds and can be elided, avoid emitting the
2594 // whole loop.
2595 bool CondConstant;
2596 llvm::BasicBlock *ContBlock = nullptr;
2597 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2598 if (!CondConstant)
2599 return;
2600 } else {
2601 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
2602 ContBlock = CGF.createBasicBlock("simd.if.end");
2603 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
2604 CGF.getProfileCount(&S));
2605 CGF.EmitBlock(ThenBlock);
2607 }
2608
2609 // Emit the loop iteration variable.
2610 const Expr *IVExpr = S.getIterationVariable();
2611 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
2612 CGF.EmitVarDecl(*IVDecl);
2613 CGF.EmitIgnoredExpr(S.getInit());
2614
2615 // Emit the iterations count variable.
2616 // If it is not a variable, Sema decided to calculate iterations count on
2617 // each iteration (e.g., it is foldable into a constant).
2618 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2619 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2620 // Emit calculation of the iterations count.
2621 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
2622 }
2623
2624 emitAlignedClause(CGF, S);
2625 (void)CGF.EmitOMPLinearClauseInit(S);
2626 {
2627 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2628 CGF.EmitOMPPrivateClause(S, LoopScope);
2629 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
2630 CGF.EmitOMPLinearClause(S, LoopScope);
2631 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2633 CGF, S, CGF.EmitLValue(S.getIterationVariable()));
2634 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2635 (void)LoopScope.Privatize();
2638
2640 CGF, S,
2641 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2642 CGF.EmitOMPSimdInit(S);
2643 },
2644 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2645 CGF.EmitOMPInnerLoop(
2646 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
2647 [&S](CodeGenFunction &CGF) {
2648 emitOMPLoopBodyWithStopPoint(CGF, S,
2649 CodeGenFunction::JumpDest());
2650 },
2651 [](CodeGenFunction &) {});
2652 });
2653 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
2654 // Emit final copy of the lastprivate variables at the end of loops.
2655 if (HasLastprivateClause)
2656 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
2657 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
2659 [](CodeGenFunction &) { return nullptr; });
2660 LoopScope.restoreMap();
2661 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
2662 }
2663 // Emit: if (PreCond) - end.
2664 if (ContBlock) {
2665 CGF.EmitBranch(ContBlock);
2666 CGF.EmitBlock(ContBlock, true);
2667 }
2668}
2669
2670// Pass OMPLoopDirective (instead of OMPSimdDirective) to make this function
2671// available for "loop bind(thread)", which maps to "simd".
2673 // Check for unsupported clauses
2674 for (OMPClause *C : S.clauses()) {
2675 // Currently only order, simdlen and safelen clauses are supported
2676 if (!(isa<OMPSimdlenClause>(C) || isa<OMPSafelenClause>(C) ||
2677 isa<OMPOrderClause>(C) || isa<OMPAlignedClause>(C)))
2678 return false;
2679 }
2680
2681 // Check if we have a statement with the ordered directive.
2682 // Visit the statement hierarchy to find a compound statement
2683 // with a ordered directive in it.
2684 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(S.getRawStmt())) {
2685 if (const Stmt *SyntacticalLoop = CanonLoop->getLoopStmt()) {
2686 for (const Stmt *SubStmt : SyntacticalLoop->children()) {
2687 if (!SubStmt)
2688 continue;
2689 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(SubStmt)) {
2690 for (const Stmt *CSSubStmt : CS->children()) {
2691 if (!CSSubStmt)
2692 continue;
2693 if (isa<OMPOrderedDirective>(CSSubStmt)) {
2694 return false;
2695 }
2696 }
2697 }
2698 }
2699 }
2700 }
2701 return true;
2702}
2703
2704static llvm::MapVector<llvm::Value *, llvm::Value *>
2706 llvm::MapVector<llvm::Value *, llvm::Value *> AlignedVars;
2707 for (const auto *Clause : S.getClausesOfKind<OMPAlignedClause>()) {
2708 llvm::APInt ClauseAlignment(64, 0);
2709 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
2710 auto *AlignmentCI =
2711 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
2712 ClauseAlignment = AlignmentCI->getValue();
2713 }
2714 for (const Expr *E : Clause->varlist()) {
2715 llvm::APInt Alignment(ClauseAlignment);
2716 if (Alignment == 0) {
2717 // OpenMP [2.8.1, Description]
2718 // If no optional parameter is specified, implementation-defined default
2719 // alignments for SIMD instructions on the target platforms are assumed.
2720 Alignment =
2721 CGF.getContext()
2723 E->getType()->getPointeeType()))
2724 .getQuantity();
2725 }
2726 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
2727 "alignment is not power of 2");
2728 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
2729 AlignedVars[PtrValue] = CGF.Builder.getInt64(Alignment.getSExtValue());
2730 }
2731 }
2732 return AlignedVars;
2733}
2734
2735// Pass OMPLoopDirective (instead of OMPSimdDirective) to make this function
2736// available for "loop bind(thread)", which maps to "simd".
2738 CodeGenModule &CGM) {
2739 bool UseOMPIRBuilder =
2740 CGM.getLangOpts().OpenMPIRBuilder && isSimdSupportedByOpenMPIRBuilder(S);
2741 if (UseOMPIRBuilder) {
2742 auto &&CodeGenIRBuilder = [&S, &CGM, UseOMPIRBuilder](CodeGenFunction &CGF,
2743 PrePostActionTy &) {
2744 // Use the OpenMPIRBuilder if enabled.
2745 if (UseOMPIRBuilder) {
2746 llvm::MapVector<llvm::Value *, llvm::Value *> AlignedVars =
2747 GetAlignedMapping(S, CGF);
2748 // Emit the associated statement and get its loop representation.
2749 const Stmt *Inner = S.getRawStmt();
2750 llvm::CanonicalLoopInfo *CLI =
2751 CGF.EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
2752
2753 llvm::OpenMPIRBuilder &OMPBuilder =
2755 // Add SIMD specific metadata
2756 llvm::ConstantInt *Simdlen = nullptr;
2757 if (const auto *C = S.getSingleClause<OMPSimdlenClause>()) {
2758 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
2759 /*ignoreResult=*/true);
2760 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2761 Simdlen = Val;
2762 }
2763 llvm::ConstantInt *Safelen = nullptr;
2764 if (const auto *C = S.getSingleClause<OMPSafelenClause>()) {
2765 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
2766 /*ignoreResult=*/true);
2767 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2768 Safelen = Val;
2769 }
2770 llvm::omp::OrderKind Order = llvm::omp::OrderKind::OMP_ORDER_unknown;
2771 if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
2772 if (C->getKind() == OpenMPOrderClauseKind::OMPC_ORDER_concurrent) {
2773 Order = llvm::omp::OrderKind::OMP_ORDER_concurrent;
2774 }
2775 }
2776 // Add simd metadata to the collapsed loop. Do not generate
2777 // another loop for if clause. Support for if clause is done earlier.
2778 OMPBuilder.applySimd(CLI, AlignedVars,
2779 /*IfCond*/ nullptr, Order, Simdlen, Safelen);
2780 return;
2781 }
2782 };
2783 {
2784 auto LPCRegion =
2786 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
2787 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
2788 CodeGenIRBuilder);
2789 }
2790 return;
2791 }
2792
2793 CodeGenFunction::ParentLoopDirectiveForScanRegion ScanRegion(CGF, S);
2794 CGF.OMPFirstScanLoop = true;
2795 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2796 emitOMPSimdRegion(CGF, S, Action);
2797 };
2798 {
2799 auto LPCRegion =
2801 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
2802 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd, CodeGen);
2803 }
2804 // Check for outer lastprivate conditional update.
2806}
2807
2809 emitOMPSimdDirective(S, *this, CGM);
2810}
2811
2813 // Emit the de-sugared statement.
2814 OMPTransformDirectiveScopeRAII TileScope(*this, &S);
2815 EmitStmt(S.getTransformedStmt());
2816}
2817
2819 // Emit the de-sugared statement.
2820 OMPTransformDirectiveScopeRAII ReverseScope(*this, &S);
2821 EmitStmt(S.getTransformedStmt());
2822}
2823
2825 const OMPInterchangeDirective &S) {
2826 // Emit the de-sugared statement.
2827 OMPTransformDirectiveScopeRAII InterchangeScope(*this, &S);
2828 EmitStmt(S.getTransformedStmt());
2829}
2830
2832 bool UseOMPIRBuilder = CGM.getLangOpts().OpenMPIRBuilder;
2833
2834 if (UseOMPIRBuilder) {
2835 auto DL = SourceLocToDebugLoc(S.getBeginLoc());
2836 const Stmt *Inner = S.getRawStmt();
2837
2838 // Consume nested loop. Clear the entire remaining loop stack because a
2839 // fully unrolled loop is non-transformable. For partial unrolling the
2840 // generated outer loop is pushed back to the stack.
2841 llvm::CanonicalLoopInfo *CLI = EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
2842 OMPLoopNestStack.clear();
2843
2844 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
2845
2846 bool NeedsUnrolledCLI = ExpectedOMPLoopDepth >= 1;
2847 llvm::CanonicalLoopInfo *UnrolledCLI = nullptr;
2848
2849 if (S.hasClausesOfKind<OMPFullClause>()) {
2850 assert(ExpectedOMPLoopDepth == 0);
2851 OMPBuilder.unrollLoopFull(DL, CLI);
2852 } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
2853 uint64_t Factor = 0;
2854 if (Expr *FactorExpr = PartialClause->getFactor()) {
2855 Factor = FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
2856 assert(Factor >= 1 && "Only positive factors are valid");
2857 }
2858 OMPBuilder.unrollLoopPartial(DL, CLI, Factor,
2859 NeedsUnrolledCLI ? &UnrolledCLI : nullptr);
2860 } else {
2861 OMPBuilder.unrollLoopHeuristic(DL, CLI);
2862 }
2863
2864 assert((!NeedsUnrolledCLI || UnrolledCLI) &&
2865 "NeedsUnrolledCLI implies UnrolledCLI to be set");
2866 if (UnrolledCLI)
2867 OMPLoopNestStack.push_back(UnrolledCLI);
2868
2869 return;
2870 }
2871
2872 // This function is only called if the unrolled loop is not consumed by any
2873 // other loop-associated construct. Such a loop-associated construct will have
2874 // used the transformed AST.
2875
2876 // Set the unroll metadata for the next emitted loop.
2878
2879 if (S.hasClausesOfKind<OMPFullClause>()) {
2881 } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
2882 if (Expr *FactorExpr = PartialClause->getFactor()) {
2883 uint64_t Factor =
2884 FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
2885 assert(Factor >= 1 && "Only positive factors are valid");
2886 LoopStack.setUnrollCount(Factor);
2887 }
2888 }
2889
2890 EmitStmt(S.getAssociatedStmt());
2891}
2892
2893void CodeGenFunction::EmitOMPOuterLoop(
2894 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
2895 CodeGenFunction::OMPPrivateScope &LoopScope,
2896 const CodeGenFunction::OMPLoopArguments &LoopArgs,
2897 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
2898 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
2900
2901 const Expr *IVExpr = S.getIterationVariable();
2902 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2903 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2904
2905 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
2906
2907 // Start the loop with a block that tests the condition.
2908 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
2909 EmitBlock(CondBlock);
2910 const SourceRange R = S.getSourceRange();
2911 OMPLoopNestStack.clear();
2914
2915 llvm::Value *BoolCondVal = nullptr;
2916 if (!DynamicOrOrdered) {
2917 // UB = min(UB, GlobalUB) or
2918 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
2919 // 'distribute parallel for')
2920 EmitIgnoredExpr(LoopArgs.EUB);
2921 // IV = LB
2922 EmitIgnoredExpr(LoopArgs.Init);
2923 // IV < UB
2924 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
2925 } else {
2926 BoolCondVal =
2927 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
2928 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
2929 }
2930
2931 // If there are any cleanups between here and the loop-exit scope,
2932 // create a block to stage a loop exit along.
2933 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
2934 if (LoopScope.requiresCleanups())
2935 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
2936
2937 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
2938 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
2939 if (ExitBlock != LoopExit.getBlock()) {
2940 EmitBlock(ExitBlock);
2942 }
2943 EmitBlock(LoopBody);
2944
2945 // Emit "IV = LB" (in case of static schedule, we have already calculated new
2946 // LB for loop condition and emitted it above).
2947 if (DynamicOrOrdered)
2948 EmitIgnoredExpr(LoopArgs.Init);
2949
2950 // Create a block for the increment.
2951 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
2952 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2953
2956 *this, S,
2957 [&S, IsMonotonic, EKind](CodeGenFunction &CGF, PrePostActionTy &) {
2958 // Generate !llvm.loop.parallel metadata for loads and stores for loops
2959 // with dynamic/guided scheduling and without ordered clause.
2960 if (!isOpenMPSimdDirective(EKind)) {
2961 CGF.LoopStack.setParallel(!IsMonotonic);
2962 if (const auto *C = S.getSingleClause<OMPOrderClause>())
2963 if (C->getKind() == OMPC_ORDER_concurrent)
2964 CGF.LoopStack.setParallel(/*Enable=*/true);
2965 } else {
2966 CGF.EmitOMPSimdInit(S);
2967 }
2968 },
2969 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2970 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2971 SourceLocation Loc = S.getBeginLoc();
2972 // when 'distribute' is not combined with a 'for':
2973 // while (idx <= UB) { BODY; ++idx; }
2974 // when 'distribute' is combined with a 'for'
2975 // (e.g. 'distribute parallel for')
2976 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2977 CGF.EmitOMPInnerLoop(
2978 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2979 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2980 CodeGenLoop(CGF, S, LoopExit);
2981 },
2982 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2983 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2984 });
2985 });
2986
2987 EmitBlock(Continue.getBlock());
2988 BreakContinueStack.pop_back();
2989 if (!DynamicOrOrdered) {
2990 // Emit "LB = LB + Stride", "UB = UB + Stride".
2991 EmitIgnoredExpr(LoopArgs.NextLB);
2992 EmitIgnoredExpr(LoopArgs.NextUB);
2993 }
2994
2995 EmitBranch(CondBlock);
2996 OMPLoopNestStack.clear();
2997 LoopStack.pop();
2998 // Emit the fall-through block.
2999 EmitBlock(LoopExit.getBlock());
3000
3001 // Tell the runtime we are done.
3002 auto &&CodeGen = [DynamicOrOrdered, &S, &LoopArgs](CodeGenFunction &CGF) {
3003 if (!DynamicOrOrdered)
3004 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3005 LoopArgs.DKind);
3006 };
3007 OMPCancelStack.emitExit(*this, EKind, CodeGen);
3008}
3009
3010void CodeGenFunction::EmitOMPForOuterLoop(
3011 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
3012 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
3013 const OMPLoopArguments &LoopArgs,
3014 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
3016
3017 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
3018 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind.Schedule);
3019
3020 assert((Ordered || !RT.isStaticNonchunked(ScheduleKind.Schedule,
3021 LoopArgs.Chunk != nullptr)) &&
3022 "static non-chunked schedule does not need outer loop");
3023
3024 // Emit outer loop.
3025 //
3026 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
3027 // When schedule(dynamic,chunk_size) is specified, the iterations are
3028 // distributed to threads in the team in chunks as the threads request them.
3029 // Each thread executes a chunk of iterations, then requests another chunk,
3030 // until no chunks remain to be distributed. Each chunk contains chunk_size
3031 // iterations, except for the last chunk to be distributed, which may have
3032 // fewer iterations. When no chunk_size is specified, it defaults to 1.
3033 //
3034 // When schedule(guided,chunk_size) is specified, the iterations are assigned
3035 // to threads in the team in chunks as the executing threads request them.
3036 // Each thread executes a chunk of iterations, then requests another chunk,
3037 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
3038 // each chunk is proportional to the number of unassigned iterations divided
3039 // by the number of threads in the team, decreasing to 1. For a chunk_size
3040 // with value k (greater than 1), the size of each chunk is determined in the
3041 // same way, with the restriction that the chunks do not contain fewer than k
3042 // iterations (except for the last chunk to be assigned, which may have fewer
3043 // than k iterations).
3044 //
3045 // When schedule(auto) is specified, the decision regarding scheduling is
3046 // delegated to the compiler and/or runtime system. The programmer gives the
3047 // implementation the freedom to choose any possible mapping of iterations to
3048 // threads in the team.
3049 //
3050 // When schedule(runtime) is specified, the decision regarding scheduling is
3051 // deferred until run time, and the schedule and chunk size are taken from the
3052 // run-sched-var ICV. If the ICV is set to auto, the schedule is
3053 // implementation defined
3054 //
3055 // __kmpc_dispatch_init();
3056 // while(__kmpc_dispatch_next(&LB, &UB)) {
3057 // idx = LB;
3058 // while (idx <= UB) { BODY; ++idx;
3059 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
3060 // } // inner loop
3061 // }
3062 // __kmpc_dispatch_deinit();
3063 //
3064 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
3065 // When schedule(static, chunk_size) is specified, iterations are divided into
3066 // chunks of size chunk_size, and the chunks are assigned to the threads in
3067 // the team in a round-robin fashion in the order of the thread number.
3068 //
3069 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
3070 // while (idx <= UB) { BODY; ++idx; } // inner loop
3071 // LB = LB + ST;
3072 // UB = UB + ST;
3073 // }
3074 //
3075
3076 const Expr *IVExpr = S.getIterationVariable();
3077 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3078 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3079
3080 if (DynamicOrOrdered) {
3081 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
3082 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
3083 llvm::Value *LBVal = DispatchBounds.first;
3084 llvm::Value *UBVal = DispatchBounds.second;
3085 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
3086 LoopArgs.Chunk};
3087 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
3088 IVSigned, Ordered, DipatchRTInputValues);
3089 } else {
3091 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
3092 LoopArgs.ST, LoopArgs.Chunk);
3094 RT.emitForStaticInit(*this, S.getBeginLoc(), EKind, ScheduleKind,
3095 StaticInit);
3096 }
3097
3098 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
3099 const unsigned IVSize,
3100 const bool IVSigned) {
3101 if (Ordered) {
3103 IVSigned);
3104 }
3105 };
3106
3107 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
3108 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
3109 OuterLoopArgs.IncExpr = S.getInc();
3110 OuterLoopArgs.Init = S.getInit();
3111 OuterLoopArgs.Cond = S.getCond();
3112 OuterLoopArgs.NextLB = S.getNextLowerBound();
3113 OuterLoopArgs.NextUB = S.getNextUpperBound();
3114 OuterLoopArgs.DKind = LoopArgs.DKind;
3115 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
3116 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
3117 if (DynamicOrOrdered) {
3118 RT.emitForDispatchDeinit(*this, S.getBeginLoc());
3119 }
3120}
3121
3123 const unsigned IVSize, const bool IVSigned) {}
3124
3125void CodeGenFunction::EmitOMPDistributeOuterLoop(
3126 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
3127 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
3128 const CodeGenLoopTy &CodeGenLoopContent) {
3129
3131
3132 // Emit outer loop.
3133 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
3134 // dynamic
3135 //
3136
3137 const Expr *IVExpr = S.getIterationVariable();
3138 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3139 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3141
3143 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
3144 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
3145 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
3146
3147 // for combined 'distribute' and 'for' the increment expression of distribute
3148 // is stored in DistInc. For 'distribute' alone, it is in Inc.
3149 Expr *IncExpr;
3151 IncExpr = S.getDistInc();
3152 else
3153 IncExpr = S.getInc();
3154
3155 // this routine is shared by 'omp distribute parallel for' and
3156 // 'omp distribute': select the right EUB expression depending on the
3157 // directive
3158 OMPLoopArguments OuterLoopArgs;
3159 OuterLoopArgs.LB = LoopArgs.LB;
3160 OuterLoopArgs.UB = LoopArgs.UB;
3161 OuterLoopArgs.ST = LoopArgs.ST;
3162 OuterLoopArgs.IL = LoopArgs.IL;
3163 OuterLoopArgs.Chunk = LoopArgs.Chunk;
3164 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(EKind)
3165 ? S.getCombinedEnsureUpperBound()
3166 : S.getEnsureUpperBound();
3167 OuterLoopArgs.IncExpr = IncExpr;
3168 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(EKind)
3169 ? S.getCombinedInit()
3170 : S.getInit();
3171 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(EKind)
3172 ? S.getCombinedCond()
3173 : S.getCond();
3174 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(EKind)
3175 ? S.getCombinedNextLowerBound()
3176 : S.getNextLowerBound();
3177 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(EKind)
3178 ? S.getCombinedNextUpperBound()
3179 : S.getNextUpperBound();
3180 OuterLoopArgs.DKind = OMPD_distribute;
3181
3182 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
3183 LoopScope, OuterLoopArgs, CodeGenLoopContent,
3185}
3186
3187static std::pair<LValue, LValue>
3189 const OMPExecutableDirective &S) {
3190 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
3191 LValue LB =
3192 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
3193 LValue UB =
3194 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
3195
3196 // When composing 'distribute' with 'for' (e.g. as in 'distribute
3197 // parallel for') we need to use the 'distribute'
3198 // chunk lower and upper bounds rather than the whole loop iteration
3199 // space. These are parameters to the outlined function for 'parallel'
3200 // and we copy the bounds of the previous schedule into the
3201 // the current ones.
3202 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
3203 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
3204 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
3205 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
3206 PrevLBVal = CGF.EmitScalarConversion(
3207 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
3210 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
3211 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
3212 PrevUBVal = CGF.EmitScalarConversion(
3213 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
3216
3217 CGF.EmitStoreOfScalar(PrevLBVal, LB);
3218 CGF.EmitStoreOfScalar(PrevUBVal, UB);
3219
3220 return {LB, UB};
3221}
3222
3223/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
3224/// we need to use the LB and UB expressions generated by the worksharing
3225/// code generation support, whereas in non combined situations we would
3226/// just emit 0 and the LastIteration expression
3227/// This function is necessary due to the difference of the LB and UB
3228/// types for the RT emission routines for 'for_static_init' and
3229/// 'for_dispatch_init'
3230static std::pair<llvm::Value *, llvm::Value *>
3232 const OMPExecutableDirective &S,
3233 Address LB, Address UB) {
3234 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
3235 const Expr *IVExpr = LS.getIterationVariable();
3236 // when implementing a dynamic schedule for a 'for' combined with a
3237 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
3238 // is not normalized as each team only executes its own assigned
3239 // distribute chunk
3240 QualType IteratorTy = IVExpr->getType();
3241 llvm::Value *LBVal =
3242 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
3243 llvm::Value *UBVal =
3244 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
3245 return {LBVal, UBVal};
3246}
3247
3251 const auto &Dir = cast<OMPLoopDirective>(S);
3252 LValue LB =
3253 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
3254 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
3255 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
3256 CapturedVars.push_back(LBCast);
3257 LValue UB =
3258 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
3259
3260 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
3261 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
3262 CapturedVars.push_back(UBCast);
3263}
3264
3265static void
3267 const OMPLoopDirective &S,
3268 CodeGenFunction::JumpDest LoopExit) {
3270 auto &&CGInlinedWorksharingLoop = [&S, EKind](CodeGenFunction &CGF,
3271 PrePostActionTy &Action) {
3272 Action.Enter(CGF);
3273 bool HasCancel = false;
3274 if (!isOpenMPSimdDirective(EKind)) {
3275 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
3276 HasCancel = D->hasCancel();
3277 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
3278 HasCancel = D->hasCancel();
3279 else if (const auto *D =
3280 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
3281 HasCancel = D->hasCancel();
3282 }
3283 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
3284 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
3287 };
3288
3290 CGF, S, isOpenMPSimdDirective(EKind) ? OMPD_for_simd : OMPD_for,
3291 CGInlinedWorksharingLoop,
3293}
3294
3297 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3299 S.getDistInc());
3300 };
3301 OMPLexicalScope Scope(*this, S, OMPD_parallel);
3302 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3303}
3304
3307 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3309 S.getDistInc());
3310 };
3311 OMPLexicalScope Scope(*this, S, OMPD_parallel);
3312 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3313}
3314
3316 const OMPDistributeSimdDirective &S) {
3317 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3319 };
3320 OMPLexicalScope Scope(*this, S, OMPD_unknown);
3321 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
3322}
3323
3325 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
3326 // Emit SPMD target parallel for region as a standalone region.
3327 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3328 emitOMPSimdRegion(CGF, S, Action);
3329 };
3330 llvm::Function *Fn;
3331 llvm::Constant *Addr;
3332 // Emit target region as a standalone region.
3334 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3335 assert(Fn && Addr && "Target device function emission failed.");
3336}
3337
3339 const OMPTargetSimdDirective &S) {
3340 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3341 emitOMPSimdRegion(CGF, S, Action);
3342 };
3343 emitCommonOMPTargetDirective(*this, S, CodeGen);
3344}
3345
3346namespace {
3347struct ScheduleKindModifiersTy {
3351 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
3354 : Kind(Kind), M1(M1), M2(M2) {}
3355};
3356} // namespace
3357
3359 const OMPLoopDirective &S, Expr *EUB,
3360 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3361 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
3362 // Emit the loop iteration variable.
3363 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3364 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
3365 EmitVarDecl(*IVDecl);
3366
3367 // Emit the iterations count variable.
3368 // If it is not a variable, Sema decided to calculate iterations count on each
3369 // iteration (e.g., it is foldable into a constant).
3370 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3371 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3372 // Emit calculation of the iterations count.
3373 EmitIgnoredExpr(S.getCalcLastIteration());
3374 }
3375
3377
3378 bool HasLastprivateClause;
3379 // Check pre-condition.
3380 {
3381 OMPLoopScope PreInitScope(*this, S);
3382 // Skip the entire loop if we don't meet the precondition.
3383 // If the condition constant folds and can be elided, avoid emitting the
3384 // whole loop.
3385 bool CondConstant;
3386 llvm::BasicBlock *ContBlock = nullptr;
3387 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3388 if (!CondConstant)
3389 return false;
3390 } else {
3391 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
3392 ContBlock = createBasicBlock("omp.precond.end");
3393 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3394 getProfileCount(&S));
3395 EmitBlock(ThenBlock);
3397 }
3398
3399 RunCleanupsScope DoacrossCleanupScope(*this);
3400 bool Ordered = false;
3401 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
3402 if (OrderedClause->getNumForLoops())
3403 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
3404 else
3405 Ordered = true;
3406 }
3407
3408 llvm::DenseSet<const Expr *> EmittedFinals;
3409 emitAlignedClause(*this, S);
3410 bool HasLinears = EmitOMPLinearClauseInit(S);
3411 // Emit helper vars inits.
3412
3413 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
3414 LValue LB = Bounds.first;
3415 LValue UB = Bounds.second;
3416 LValue ST =
3417 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3418 LValue IL =
3419 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3420
3421 // Emit 'then' code.
3422 {
3424 OMPPrivateScope LoopScope(*this);
3425 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
3426 // Emit implicit barrier to synchronize threads and avoid data races on
3427 // initialization of firstprivate variables and post-update of
3428 // lastprivate variables.
3430 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3431 /*ForceSimpleCall=*/true);
3432 }
3433 EmitOMPPrivateClause(S, LoopScope);
3435 *this, S, EmitLValue(S.getIterationVariable()));
3436 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3437 EmitOMPReductionClauseInit(S, LoopScope);
3438 EmitOMPPrivateLoopCounters(S, LoopScope);
3439 EmitOMPLinearClause(S, LoopScope);
3440 (void)LoopScope.Privatize();
3443
3444 // Detect the loop schedule kind and chunk.
3445 const Expr *ChunkExpr = nullptr;
3446 OpenMPScheduleTy ScheduleKind;
3447 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
3448 ScheduleKind.Schedule = C->getScheduleKind();
3449 ScheduleKind.M1 = C->getFirstScheduleModifier();
3450 ScheduleKind.M2 = C->getSecondScheduleModifier();
3451 ChunkExpr = C->getChunkSize();
3452 } else {
3453 // Default behaviour for schedule clause.
3455 *this, S, ScheduleKind.Schedule, ChunkExpr);
3456 }
3457 bool HasChunkSizeOne = false;
3458 llvm::Value *Chunk = nullptr;
3459 if (ChunkExpr) {
3460 Chunk = EmitScalarExpr(ChunkExpr);
3461 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
3462 S.getIterationVariable()->getType(),
3463 S.getBeginLoc());
3465 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
3466 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
3467 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
3468 }
3469 }
3470 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3471 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3472 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
3473 // If the static schedule kind is specified or if the ordered clause is
3474 // specified, and if no monotonic modifier is specified, the effect will
3475 // be as if the monotonic modifier was specified.
3476 bool StaticChunkedOne =
3477 RT.isStaticChunked(ScheduleKind.Schedule,
3478 /* Chunked */ Chunk != nullptr) &&
3479 HasChunkSizeOne && isOpenMPLoopBoundSharingDirective(EKind);
3480 bool IsMonotonic =
3481 Ordered ||
3482 (ScheduleKind.Schedule == OMPC_SCHEDULE_static &&
3483 !(ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3484 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)) ||
3485 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
3486 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
3487 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
3488 /* Chunked */ Chunk != nullptr) ||
3489 StaticChunkedOne) &&
3490 !Ordered) {
3491 JumpDest LoopExit =
3494 *this, S,
3495 [&S, EKind](CodeGenFunction &CGF, PrePostActionTy &) {
3496 if (isOpenMPSimdDirective(EKind)) {
3497 CGF.EmitOMPSimdInit(S);
3498 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
3499 if (C->getKind() == OMPC_ORDER_concurrent)
3500 CGF.LoopStack.setParallel(/*Enable=*/true);
3501 }
3502 },
3503 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
3504 &S, ScheduleKind, LoopExit, EKind,
3505 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
3506 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
3507 // When no chunk_size is specified, the iteration space is divided
3508 // into chunks that are approximately equal in size, and at most
3509 // one chunk is distributed to each thread. Note that the size of
3510 // the chunks is unspecified in this case.
3512 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
3513 UB.getAddress(), ST.getAddress(),
3514 StaticChunkedOne ? Chunk : nullptr);
3515 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
3516 CGF, S.getBeginLoc(), EKind, ScheduleKind, StaticInit);
3517 // UB = min(UB, GlobalUB);
3518 if (!StaticChunkedOne)
3519 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
3520 // IV = LB;
3521 CGF.EmitIgnoredExpr(S.getInit());
3522 // For unchunked static schedule generate:
3523 //
3524 // while (idx <= UB) {
3525 // BODY;
3526 // ++idx;
3527 // }
3528 //
3529 // For static schedule with chunk one:
3530 //
3531 // while (IV <= PrevUB) {
3532 // BODY;
3533 // IV += ST;
3534 // }
3535 CGF.EmitOMPInnerLoop(
3536 S, LoopScope.requiresCleanups(),
3537 StaticChunkedOne ? S.getCombinedParForInDistCond()
3538 : S.getCond(),
3539 StaticChunkedOne ? S.getDistInc() : S.getInc(),
3540 [&S, LoopExit](CodeGenFunction &CGF) {
3541 emitOMPLoopBodyWithStopPoint(CGF, S, LoopExit);
3542 },
3543 [](CodeGenFunction &) {});
3544 });
3545 EmitBlock(LoopExit.getBlock());
3546 // Tell the runtime we are done.
3547 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3548 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3549 OMPD_for);
3550 };
3551 OMPCancelStack.emitExit(*this, EKind, CodeGen);
3552 } else {
3553 // Emit the outer loop, which requests its work chunk [LB..UB] from
3554 // runtime and runs the inner loop to process it.
3555 OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
3556 ST.getAddress(), IL.getAddress(), Chunk,
3557 EUB);
3558 LoopArguments.DKind = OMPD_for;
3559 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
3560 LoopArguments, CGDispatchBounds);
3561 }
3562 if (isOpenMPSimdDirective(EKind)) {
3563 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
3564 return CGF.Builder.CreateIsNotNull(
3565 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3566 });
3567 }
3569 S, /*ReductionKind=*/isOpenMPSimdDirective(EKind)
3570 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
3571 : /*Parallel only*/ OMPD_parallel);
3572 // Emit post-update of the reduction variables if IsLastIter != 0.
3574 *this, S, [IL, &S](CodeGenFunction &CGF) {
3575 return CGF.Builder.CreateIsNotNull(
3576 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3577 });
3578 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3579 if (HasLastprivateClause)
3581 S, isOpenMPSimdDirective(EKind),
3582 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
3583 LoopScope.restoreMap();
3584 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
3585 return CGF.Builder.CreateIsNotNull(
3586 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3587 });
3588 }
3589 DoacrossCleanupScope.ForceCleanup();
3590 // We're now done with the loop, so jump to the continuation block.
3591 if (ContBlock) {
3592 EmitBranch(ContBlock);
3593 EmitBlock(ContBlock, /*IsFinished=*/true);
3594 }
3595 }
3596 return HasLastprivateClause;
3597}
3598
3599/// The following two functions generate expressions for the loop lower
3600/// and upper bounds in case of static and dynamic (dispatch) schedule
3601/// of the associated 'for' or 'distribute' loop.
3602static std::pair<LValue, LValue>
3604 const auto &LS = cast<OMPLoopDirective>(S);
3605 LValue LB =
3606 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
3607 LValue UB =
3608 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
3609 return {LB, UB};
3610}
3611
3612/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
3613/// consider the lower and upper bound expressions generated by the
3614/// worksharing loop support, but we use 0 and the iteration space size as
3615/// constants
3616static std::pair<llvm::Value *, llvm::Value *>
3618 Address LB, Address UB) {
3619 const auto &LS = cast<OMPLoopDirective>(S);
3620 const Expr *IVExpr = LS.getIterationVariable();
3621 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
3622 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
3623 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
3624 return {LBVal, UBVal};
3625}
3626
3627/// Emits internal temp array declarations for the directive with inscan
3628/// reductions.
3629/// The code is the following:
3630/// \code
3631/// size num_iters = <num_iters>;
3632/// <type> buffer[num_iters];
3633/// \endcode
3635 CodeGenFunction &CGF, const OMPLoopDirective &S,
3636 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) {
3637 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
3638 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
3641 SmallVector<const Expr *, 4> ReductionOps;
3642 SmallVector<const Expr *, 4> CopyArrayTemps;
3643 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3644 assert(C->getModifier() == OMPC_REDUCTION_inscan &&
3645 "Only inscan reductions are expected.");
3646 Shareds.append(C->varlist_begin(), C->varlist_end());
3647 Privates.append(C->privates().begin(), C->privates().end());
3648 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
3649 CopyArrayTemps.append(C->copy_array_temps().begin(),
3650 C->copy_array_temps().end());
3651 }
3652 {
3653 // Emit buffers for each reduction variables.
3654 // ReductionCodeGen is required to emit correctly the code for array
3655 // reductions.
3656 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
3657 unsigned Count = 0;
3658 auto *ITA = CopyArrayTemps.begin();
3659 for (const Expr *IRef : Privates) {
3660 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
3661 // Emit variably modified arrays, used for arrays/array sections
3662 // reductions.
3663 if (PrivateVD->getType()->isVariablyModifiedType()) {
3664 RedCG.emitSharedOrigLValue(CGF, Count);
3665 RedCG.emitAggregateType(CGF, Count);
3666 }
3667 CodeGenFunction::OpaqueValueMapping DimMapping(
3668 CGF,
3669 cast<OpaqueValueExpr>(
3670 cast<VariableArrayType>((*ITA)->getType()->getAsArrayTypeUnsafe())
3671 ->getSizeExpr()),
3672 RValue::get(OMPScanNumIterations));
3673 // Emit temp buffer.
3674 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl()));
3675 ++ITA;
3676 ++Count;
3677 }
3678 }
3679}
3680
3681/// Copies final inscan reductions values to the original variables.
3682/// The code is the following:
3683/// \code
3684/// <orig_var> = buffer[num_iters-1];
3685/// \endcode
3687 CodeGenFunction &CGF, const OMPLoopDirective &S,
3688 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) {
3689 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
3690 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
3696 SmallVector<const Expr *, 4> CopyArrayElems;
3697 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3698 assert(C->getModifier() == OMPC_REDUCTION_inscan &&
3699 "Only inscan reductions are expected.");
3700 Shareds.append(C->varlist_begin(), C->varlist_end());
3701 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
3702 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
3703 Privates.append(C->privates().begin(), C->privates().end());
3704 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
3705 CopyArrayElems.append(C->copy_array_elems().begin(),
3706 C->copy_array_elems().end());
3707 }
3708 // Create temp var and copy LHS value to this temp value.
3709 // LHS = TMP[LastIter];
3710 llvm::Value *OMPLast = CGF.Builder.CreateNSWSub(
3711 OMPScanNumIterations,
3712 llvm::ConstantInt::get(CGF.SizeTy, 1, /*isSigned=*/false));
3713 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
3714 const Expr *PrivateExpr = Privates[I];
3715 const Expr *OrigExpr = Shareds[I];
3716 const Expr *CopyArrayElem = CopyArrayElems[I];
3717 CodeGenFunction::OpaqueValueMapping IdxMapping(
3718 CGF,
3719 cast<OpaqueValueExpr>(
3720 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
3721 RValue::get(OMPLast));
3722 LValue DestLVal = CGF.EmitLValue(OrigExpr);
3723 LValue SrcLVal = CGF.EmitLValue(CopyArrayElem);
3724 CGF.EmitOMPCopy(
3725 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
3726 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
3727 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
3728 }
3729}
3730
3731/// Emits the code for the directive with inscan reductions.
3732/// The code is the following:
3733/// \code
3734/// #pragma omp ...
3735/// for (i: 0..<num_iters>) {
3736/// <input phase>;
3737/// buffer[i] = red;
3738/// }
3739/// #pragma omp master // in parallel region
3740/// for (int k = 0; k != ceil(log2(num_iters)); ++k)
3741/// for (size cnt = last_iter; cnt >= pow(2, k); --k)
3742/// buffer[i] op= buffer[i-pow(2,k)];
3743/// #pragma omp barrier // in parallel region
3744/// #pragma omp ...
3745/// for (0..<num_iters>) {
3746/// red = InclusiveScan ? buffer[i] : buffer[i-1];
3747/// <scan phase>;
3748/// }
3749/// \endcode
3751 CodeGenFunction &CGF, const OMPLoopDirective &S,
3752 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen,
3753 llvm::function_ref<void(CodeGenFunction &)> FirstGen,
3754 llvm::function_ref<void(CodeGenFunction &)> SecondGen) {
3755 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
3756 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
3758 SmallVector<const Expr *, 4> ReductionOps;
3761 SmallVector<const Expr *, 4> CopyArrayElems;
3762 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3763 assert(C->getModifier() == OMPC_REDUCTION_inscan &&
3764 "Only inscan reductions are expected.");
3765 Privates.append(C->privates().begin(), C->privates().end());
3766 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
3767 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
3768 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
3769 CopyArrayElems.append(C->copy_array_elems().begin(),
3770 C->copy_array_elems().end());
3771 }
3772 CodeGenFunction::ParentLoopDirectiveForScanRegion ScanRegion(CGF, S);
3773 {
3774 // Emit loop with input phase:
3775 // #pragma omp ...
3776 // for (i: 0..<num_iters>) {
3777 // <input phase>;
3778 // buffer[i] = red;
3779 // }
3780 CGF.OMPFirstScanLoop = true;
3781 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
3782 FirstGen(CGF);
3783 }
3784 // #pragma omp barrier // in parallel region
3785 auto &&CodeGen = [&S, OMPScanNumIterations, &LHSs, &RHSs, &CopyArrayElems,
3786 &ReductionOps,
3787 &Privates](CodeGenFunction &CGF, PrePostActionTy &Action) {
3788 Action.Enter(CGF);
3789 // Emit prefix reduction:
3790 // #pragma omp master // in parallel region
3791 // for (int k = 0; k <= ceil(log2(n)); ++k)
3792 llvm::BasicBlock *InputBB = CGF.Builder.GetInsertBlock();
3793 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.outer.log.scan.body");
3794 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.outer.log.scan.exit");
3795 llvm::Function *F =
3796 CGF.CGM.getIntrinsic(llvm::Intrinsic::log2, CGF.DoubleTy);
3797 llvm::Value *Arg =
3798 CGF.Builder.CreateUIToFP(OMPScanNumIterations, CGF.DoubleTy);
3799 llvm::Value *LogVal = CGF.EmitNounwindRuntimeCall(F, Arg);
3800 F = CGF.CGM.getIntrinsic(llvm::Intrinsic::ceil, CGF.DoubleTy);
3801 LogVal = CGF.EmitNounwindRuntimeCall(F, LogVal);
3802 LogVal = CGF.Builder.CreateFPToUI(LogVal, CGF.IntTy);
3803 llvm::Value *NMin1 = CGF.Builder.CreateNUWSub(
3804 OMPScanNumIterations, llvm::ConstantInt::get(CGF.SizeTy, 1));
3805 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getBeginLoc());
3806 CGF.EmitBlock(LoopBB);
3807 auto *Counter = CGF.Builder.CreatePHI(CGF.IntTy, 2);
3808 // size pow2k = 1;
3809 auto *Pow2K = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
3810 Counter->addIncoming(llvm::ConstantInt::get(CGF.IntTy, 0), InputBB);
3811 Pow2K->addIncoming(llvm::ConstantInt::get(CGF.SizeTy, 1), InputBB);
3812 // for (size i = n - 1; i >= 2 ^ k; --i)
3813 // tmp[i] op= tmp[i-pow2k];
3814 llvm::BasicBlock *InnerLoopBB =
3815 CGF.createBasicBlock("omp.inner.log.scan.body");
3816 llvm::BasicBlock *InnerExitBB =
3817 CGF.createBasicBlock("omp.inner.log.scan.exit");
3818 llvm::Value *CmpI = CGF.Builder.CreateICmpUGE(NMin1, Pow2K);
3819 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
3820 CGF.EmitBlock(InnerLoopBB);
3821 auto *IVal = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
3822 IVal->addIncoming(NMin1, LoopBB);
3823 {
3824 CodeGenFunction::OMPPrivateScope PrivScope(CGF);
3825 auto *ILHS = LHSs.begin();
3826 auto *IRHS = RHSs.begin();
3827 for (const Expr *CopyArrayElem : CopyArrayElems) {
3828 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3829 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3830 Address LHSAddr = Address::invalid();
3831 {
3832 CodeGenFunction::OpaqueValueMapping IdxMapping(
3833 CGF,
3834 cast<OpaqueValueExpr>(
3835 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
3836 RValue::get(IVal));
3837 LHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress();
3838 }
3839 PrivScope.addPrivate(LHSVD, LHSAddr);
3840 Address RHSAddr = Address::invalid();
3841 {
3842 llvm::Value *OffsetIVal = CGF.Builder.CreateNUWSub(IVal, Pow2K);
3843 CodeGenFunction::OpaqueValueMapping IdxMapping(
3844 CGF,
3845 cast<OpaqueValueExpr>(
3846 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
3847 RValue::get(OffsetIVal));
3848 RHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress();
3849 }
3850 PrivScope.addPrivate(RHSVD, RHSAddr);
3851 ++ILHS;
3852 ++IRHS;
3853 }
3854 PrivScope.Privatize();
3855 CGF.CGM.getOpenMPRuntime().emitReduction(
3856 CGF, S.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
3857 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_unknown});
3858 }
3859 llvm::Value *NextIVal =
3860 CGF.Builder.CreateNUWSub(IVal, llvm::ConstantInt::get(CGF.SizeTy, 1));
3861 IVal->addIncoming(NextIVal, CGF.Builder.GetInsertBlock());
3862 CmpI = CGF.Builder.CreateICmpUGE(NextIVal, Pow2K);
3863 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
3864 CGF.EmitBlock(InnerExitBB);
3865 llvm::Value *Next =
3866 CGF.Builder.CreateNUWAdd(Counter, llvm::ConstantInt::get(CGF.IntTy, 1));
3867 Counter->addIncoming(Next, CGF.Builder.GetInsertBlock());
3868 // pow2k <<= 1;
3869 llvm::Value *NextPow2K =
3870 CGF.Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true);
3871 Pow2K->addIncoming(NextPow2K, CGF.Builder.GetInsertBlock());
3872 llvm::Value *Cmp = CGF.Builder.CreateICmpNE(Next, LogVal);
3873 CGF.Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
3874 auto DL1 = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getEndLoc());
3875 CGF.EmitBlock(ExitBB);
3876 };
3878 if (isOpenMPParallelDirective(EKind)) {
3879 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
3880 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3881 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3882 /*ForceSimpleCall=*/true);
3883 } else {
3884 RegionCodeGenTy RCG(CodeGen);
3885 RCG(CGF);
3886 }
3887
3888 CGF.OMPFirstScanLoop = false;
3889 SecondGen(CGF);
3890}
3891
3893 const OMPLoopDirective &S,
3894 bool HasCancel) {
3895 bool HasLastprivates;
3897 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
3898 [](const OMPReductionClause *C) {
3899 return C->getModifier() == OMPC_REDUCTION_inscan;
3900 })) {
3901 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
3902 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
3903 OMPLoopScope LoopScope(CGF, S);
3904 return CGF.EmitScalarExpr(S.getNumIterations());
3905 };
3906 const auto &&FirstGen = [&S, HasCancel, EKind](CodeGenFunction &CGF) {
3907 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
3908 (void)CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
3911 // Emit an implicit barrier at the end.
3912 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(),
3913 OMPD_for);
3914 };
3915 const auto &&SecondGen = [&S, HasCancel, EKind,
3916 &HasLastprivates](CodeGenFunction &CGF) {
3917 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
3918 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
3921 };
3922 if (!isOpenMPParallelDirective(EKind))
3923 emitScanBasedDirectiveDecls(CGF, S, NumIteratorsGen);
3924 emitScanBasedDirective(CGF, S, NumIteratorsGen, FirstGen, SecondGen);
3925 if (!isOpenMPParallelDirective(EKind))
3926 emitScanBasedDirectiveFinals(CGF, S, NumIteratorsGen);
3927 } else {
3928 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, EKind, HasCancel);
3929 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
3932 }
3933 return HasLastprivates;
3934}
3935
3936// Pass OMPLoopDirective (instead of OMPForDirective) to make this check
3937// available for "loop bind(parallel)", which maps to "for".
3939 bool HasCancel) {
3940 if (HasCancel)
3941 return false;
3942 for (OMPClause *C : S.clauses()) {
3943 if (isa<OMPNowaitClause, OMPBindClause>(C))
3944 continue;
3945
3946 if (auto *SC = dyn_cast<OMPScheduleClause>(C)) {
3947 if (SC->getFirstScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown)
3948 return false;
3949 if (SC->getSecondScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown)
3950 return false;
3951 switch (SC->getScheduleKind()) {
3952 case OMPC_SCHEDULE_auto:
3953 case OMPC_SCHEDULE_dynamic:
3954 case OMPC_SCHEDULE_runtime:
3955 case OMPC_SCHEDULE_guided:
3956 case OMPC_SCHEDULE_static:
3957 continue;
3959 return false;
3960 }
3961 }
3962
3963 return false;
3964 }
3965
3966 return true;
3967}
3968
3969static llvm::omp::ScheduleKind
3971 switch (ScheduleClauseKind) {
3973 return llvm::omp::OMP_SCHEDULE_Default;
3974 case OMPC_SCHEDULE_auto:
3975 return llvm::omp::OMP_SCHEDULE_Auto;
3976 case OMPC_SCHEDULE_dynamic:
3977 return llvm::omp::OMP_SCHEDULE_Dynamic;
3978 case OMPC_SCHEDULE_guided:
3979 return llvm::omp::OMP_SCHEDULE_Guided;
3980 case OMPC_SCHEDULE_runtime:
3981 return llvm::omp::OMP_SCHEDULE_Runtime;
3982 case OMPC_SCHEDULE_static:
3983 return llvm::omp::OMP_SCHEDULE_Static;
3984 }
3985 llvm_unreachable("Unhandled schedule kind");
3986}
3987
3988// Pass OMPLoopDirective (instead of OMPForDirective) to make this function
3989// available for "loop bind(parallel)", which maps to "for".
3991 CodeGenModule &CGM, bool HasCancel) {
3992 bool HasLastprivates = false;
3993 bool UseOMPIRBuilder = CGM.getLangOpts().OpenMPIRBuilder &&
3994 isForSupportedByOpenMPIRBuilder(S, HasCancel);
3995 auto &&CodeGen = [&S, &CGM, HasCancel, &HasLastprivates,
3996 UseOMPIRBuilder](CodeGenFunction &CGF, PrePostActionTy &) {
3997 // Use the OpenMPIRBuilder if enabled.
3998 if (UseOMPIRBuilder) {
3999 bool NeedsBarrier = !S.getSingleClause<OMPNowaitClause>();
4000
4001 llvm::omp::ScheduleKind SchedKind = llvm::omp::OMP_SCHEDULE_Default;
4002 llvm::Value *ChunkSize = nullptr;
4003 if (auto *SchedClause = S.getSingleClause<OMPScheduleClause>()) {
4004 SchedKind =
4005 convertClauseKindToSchedKind(SchedClause->getScheduleKind());
4006 if (const Expr *ChunkSizeExpr = SchedClause->getChunkSize())
4007 ChunkSize = CGF.EmitScalarExpr(ChunkSizeExpr);
4008 }
4009
4010 // Emit the associated statement and get its loop representation.
4011 const Stmt *Inner = S.getRawStmt();
4012 llvm::CanonicalLoopInfo *CLI =
4014
4015 llvm::OpenMPIRBuilder &OMPBuilder =
4017 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
4018 CGF.AllocaInsertPt->getParent(), CGF.AllocaInsertPt->getIterator());
4019 OMPBuilder.applyWorkshareLoop(
4020 CGF.Builder.getCurrentDebugLocation(), CLI, AllocaIP, NeedsBarrier,
4021 SchedKind, ChunkSize, /*HasSimdModifier=*/false,
4022 /*HasMonotonicModifier=*/false, /*HasNonmonotonicModifier=*/false,
4023 /*HasOrderedClause=*/false);
4024 return;
4025 }
4026
4027 HasLastprivates = emitWorksharingDirective(CGF, S, HasCancel);
4028 };
4029 {
4030 auto LPCRegion =
4032 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
4033 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_for, CodeGen,
4034 HasCancel);
4035 }
4036
4037 if (!UseOMPIRBuilder) {
4038 // Emit an implicit barrier at the end.
4039 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
4040 CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(), OMPD_for);
4041 }
4042 // Check for outer lastprivate conditional update.
4044}
4045
4047 return emitOMPForDirective(S, *this, CGM, S.hasCancel());
4048}
4049
4051 bool HasLastprivates = false;
4052 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
4053 PrePostActionTy &) {
4054 HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
4055 };
4056 {
4057 auto LPCRegion =
4059 OMPLexicalScope Scope(*this, S, OMPD_unknown);
4060 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
4061 }
4062
4063 // Emit an implicit barrier at the end.
4064 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
4065 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
4066 // Check for outer lastprivate conditional update.
4068}
4069
4071 const Twine &Name,
4072 llvm::Value *Init = nullptr) {
4073 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
4074 if (Init)
4075 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
4076 return LVal;
4077}
4078
4079void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
4080 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
4081 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
4082 bool HasLastprivates = false;
4084 auto &&CodeGen = [&S, CapturedStmt, CS, EKind,
4085 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
4086 const ASTContext &C = CGF.getContext();
4087 QualType KmpInt32Ty =
4088 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4089 // Emit helper vars inits.
4090 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
4091 CGF.Builder.getInt32(0));
4092 llvm::ConstantInt *GlobalUBVal = CS != nullptr
4093 ? CGF.Builder.getInt32(CS->size() - 1)
4094 : CGF.Builder.getInt32(0);
4095 LValue UB =
4096 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
4097 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
4098 CGF.Builder.getInt32(1));
4099 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
4100 CGF.Builder.getInt32(0));
4101 // Loop counter.
4102 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
4103 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
4104 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
4105 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
4106 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
4107 // Generate condition for loop.
4109 C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_PRValue, OK_Ordinary,
4110 S.getBeginLoc(), FPOptionsOverride());
4111 // Increment for loop counter.
4113 C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_PRValue, OK_Ordinary,
4114 S.getBeginLoc(), true, FPOptionsOverride());
4115 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
4116 // Iterate through all sections and emit a switch construct:
4117 // switch (IV) {
4118 // case 0:
4119 // <SectionStmt[0]>;
4120 // break;
4121 // ...
4122 // case <NumSection> - 1:
4123 // <SectionStmt[<NumSection> - 1]>;
4124 // break;
4125 // }
4126 // .omp.sections.exit:
4127 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
4128 llvm::SwitchInst *SwitchStmt =
4129 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
4130 ExitBB, CS == nullptr ? 1 : CS->size());
4131 if (CS) {
4132 unsigned CaseNumber = 0;
4133 for (const Stmt *SubStmt : CS->children()) {
4134 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
4135 CGF.EmitBlock(CaseBB);
4136 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
4137 CGF.EmitStmt(SubStmt);
4138 CGF.EmitBranch(ExitBB);
4139 ++CaseNumber;
4140 }
4141 } else {
4142 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
4143 CGF.EmitBlock(CaseBB);
4144 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
4145 CGF.EmitStmt(CapturedStmt);
4146 CGF.EmitBranch(ExitBB);
4147 }
4148 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
4149 };
4150
4151 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
4152 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
4153 // Emit implicit barrier to synchronize threads and avoid data races on
4154 // initialization of firstprivate variables and post-update of lastprivate
4155 // variables.
4156 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
4157 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
4158 /*ForceSimpleCall=*/true);
4159 }
4160 CGF.EmitOMPPrivateClause(S, LoopScope);
4161 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
4162 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
4163 CGF.EmitOMPReductionClauseInit(S, LoopScope);
4164 (void)LoopScope.Privatize();
4166 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4167
4168 // Emit static non-chunked loop.
4169 OpenMPScheduleTy ScheduleKind;
4170 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
4172 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
4173 LB.getAddress(), UB.getAddress(), ST.getAddress());
4174 CGF.CGM.getOpenMPRuntime().emitForStaticInit(CGF, S.getBeginLoc(), EKind,
4175 ScheduleKind, StaticInit);
4176 // UB = min(UB, GlobalUB);
4177 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
4178 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
4179 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
4180 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
4181 // IV = LB;
4182 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
4183 // while (idx <= UB) { BODY; ++idx; }
4184 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen,
4185 [](CodeGenFunction &) {});
4186 // Tell the runtime we are done.
4187 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
4188 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
4189 OMPD_sections);
4190 };
4191 CGF.OMPCancelStack.emitExit(CGF, EKind, CodeGen);
4192 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4193 // Emit post-update of the reduction variables if IsLastIter != 0.
4194 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
4195 return CGF.Builder.CreateIsNotNull(
4196 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
4197 });
4198
4199 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4200 if (HasLastprivates)
4202 S, /*NoFinals=*/false,
4203 CGF.Builder.CreateIsNotNull(
4204 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
4205 };
4206
4207 bool HasCancel = false;
4208 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
4209 HasCancel = OSD->hasCancel();
4210 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
4211 HasCancel = OPSD->hasCancel();
4212 OMPCancelStackRAII CancelRegion(*this, EKind, HasCancel);
4213 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
4214 HasCancel);
4215 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
4216 // clause. Otherwise the barrier will be generated by the codegen for the
4217 // directive.
4218 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
4219 // Emit implicit barrier to synchronize threads and avoid data races on
4220 // initialization of firstprivate variables.
4221 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
4222 OMPD_unknown);
4223 }
4224}
4225
4227 if (CGM.getLangOpts().OpenMPIRBuilder) {
4228 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4229 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4230 using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
4231
4232 auto FiniCB = [this](InsertPointTy IP) {
4234 };
4235
4236 const CapturedStmt *ICS = S.getInnermostCapturedStmt();
4237 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
4238 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
4240 if (CS) {
4241 for (const Stmt *SubStmt : CS->children()) {
4242 auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP,
4243 InsertPointTy CodeGenIP) {
4245 *this, SubStmt, AllocaIP, CodeGenIP, "section");
4246 };
4247 SectionCBVector.push_back(SectionCB);
4248 }
4249 } else {
4250 auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP,
4251 InsertPointTy CodeGenIP) {
4253 *this, CapturedStmt, AllocaIP, CodeGenIP, "section");
4254 };
4255 SectionCBVector.push_back(SectionCB);
4256 }
4257
4258 // Privatization callback that performs appropriate action for
4259 // shared/private/firstprivate/lastprivate/copyin/... variables.
4260 //
4261 // TODO: This defaults to shared right now.
4262 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
4263 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
4264 // The next line is appropriate only for variables (Val) with the
4265 // data-sharing attribute "shared".
4266 ReplVal = &Val;
4267
4268 return CodeGenIP;
4269 };
4270
4271 CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP);
4272 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
4273 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
4274 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
4275 Builder.restoreIP(OMPBuilder.createSections(
4276 Builder, AllocaIP, SectionCBVector, PrivCB, FiniCB, S.hasCancel(),
4277 S.getSingleClause<OMPNowaitClause>()));
4278 return;
4279 }
4280 {
4281 auto LPCRegion =
4283 OMPLexicalScope Scope(*this, S, OMPD_unknown);
4284 EmitSections(S);
4285 }
4286 // Emit an implicit barrier at the end.
4287 if (!S.getSingleClause<OMPNowaitClause>()) {
4288 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
4289 OMPD_sections);
4290 }
4291 // Check for outer lastprivate conditional update.
4293}
4294
4296 if (CGM.getLangOpts().OpenMPIRBuilder) {
4297 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4298 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4299
4300 const Stmt *SectionRegionBodyStmt = S.getAssociatedStmt();
4301 auto FiniCB = [this](InsertPointTy IP) {
4303 };
4304
4305 auto BodyGenCB = [SectionRegionBodyStmt, this](InsertPointTy AllocaIP,
4306 InsertPointTy CodeGenIP) {
4308 *this, SectionRegionBodyStmt, AllocaIP, CodeGenIP, "section");
4309 };
4310
4311 LexicalScope Scope(*this, S.getSourceRange());
4312 EmitStopPoint(&S);
4313 Builder.restoreIP(OMPBuilder.createSection(Builder, BodyGenCB, FiniCB));
4314
4315 return;
4316 }
4317 LexicalScope Scope(*this, S.getSourceRange());
4318 EmitStopPoint(&S);
4319 EmitStmt(S.getAssociatedStmt());
4320}
4321
4323 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
4327 // Check if there are any 'copyprivate' clauses associated with this
4328 // 'single' construct.
4329 // Build a list of copyprivate variables along with helper expressions
4330 // (<source>, <destination>, <destination>=<source> expressions)
4331 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
4332 CopyprivateVars.append(C->varlist_begin(), C->varlist_end());
4333 DestExprs.append(C->destination_exprs().begin(),
4334 C->destination_exprs().end());
4335 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
4336 AssignmentOps.append(C->assignment_ops().begin(),
4337 C->assignment_ops().end());
4338 }
4339 // Emit code for 'single' region along with 'copyprivate' clauses
4340 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4341 Action.Enter(CGF);
4342 OMPPrivateScope SingleScope(CGF);
4345 (void)SingleScope.Privatize();
4346 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4347 };
4348 {
4349 auto LPCRegion =
4351 OMPLexicalScope Scope(*this, S, OMPD_unknown);
4352 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
4353 CopyprivateVars, DestExprs,
4354 SrcExprs, AssignmentOps);
4355 }
4356 // Emit an implicit barrier at the end (to avoid data race on firstprivate
4357 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
4358 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
4360 *this, S.getBeginLoc(),
4361 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
4362 }
4363 // Check for outer lastprivate conditional update.
4365}
4366
4368 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4369 Action.Enter(CGF);
4370 CGF.EmitStmt(S.getRawStmt());
4371 };
4372 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
4373}
4374
4376 if (CGM.getLangOpts().OpenMPIRBuilder) {
4377 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4378 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4379
4380 const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt();
4381
4382 auto FiniCB = [this](InsertPointTy IP) {
4384 };
4385
4386 auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP,
4387 InsertPointTy CodeGenIP) {
4389 *this, MasterRegionBodyStmt, AllocaIP, CodeGenIP, "master");
4390 };
4391
4392 LexicalScope Scope(*this, S.getSourceRange());
4393 EmitStopPoint(&S);
4394 Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB));
4395
4396 return;
4397 }
4398 LexicalScope Scope(*this, S.getSourceRange());
4399 EmitStopPoint(&S);
4400 emitMaster(*this, S);
4401}
4402
4404 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4405 Action.Enter(CGF);
4406 CGF.EmitStmt(S.getRawStmt());
4407 };
4408 Expr *Filter = nullptr;
4409 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4410 Filter = FilterClause->getThreadID();
4411 CGF.CGM.getOpenMPRuntime().emitMaskedRegion(CGF, CodeGen, S.getBeginLoc(),
4412 Filter);
4413}
4414
4416 if (CGM.getLangOpts().OpenMPIRBuilder) {
4417 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4418 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4419
4420 const Stmt *MaskedRegionBodyStmt = S.getAssociatedStmt();
4421 const Expr *Filter = nullptr;
4422 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4423 Filter = FilterClause->getThreadID();
4424 llvm::Value *FilterVal = Filter
4425 ? EmitScalarExpr(Filter, CGM.Int32Ty)
4426 : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0);
4427
4428 auto FiniCB = [this](InsertPointTy IP) {
4430 };
4431
4432 auto BodyGenCB = [MaskedRegionBodyStmt, this](InsertPointTy AllocaIP,
4433 InsertPointTy CodeGenIP) {
4435 *this, MaskedRegionBodyStmt, AllocaIP, CodeGenIP, "masked");
4436 };
4437
4438 LexicalScope Scope(*this, S.getSourceRange());
4439 EmitStopPoint(&S);
4440 Builder.restoreIP(
4441 OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, FilterVal));
4442
4443 return;
4444 }
4445 LexicalScope Scope(*this, S.getSourceRange());
4446 EmitStopPoint(&S);
4447 emitMasked(*this, S);
4448}
4449
4451 if (CGM.getLangOpts().OpenMPIRBuilder) {
4452 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4453 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4454
4455 const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt();
4456 const Expr *Hint = nullptr;
4457 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4458 Hint = HintClause->getHint();
4459
4460 // TODO: This is slightly different from what's currently being done in
4461 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything
4462 // about typing is final.
4463 llvm::Value *HintInst = nullptr;
4464 if (Hint)
4465 HintInst =
4466 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false);
4467
4468 auto FiniCB = [this](InsertPointTy IP) {
4470 };
4471
4472 auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP,
4473 InsertPointTy CodeGenIP) {
4475 *this, CriticalRegionBodyStmt, AllocaIP, CodeGenIP, "critical");
4476 };
4477
4478 LexicalScope Scope(*this, S.getSourceRange());
4479 EmitStopPoint(&S);
4480 Builder.restoreIP(OMPBuilder.createCritical(
4481 Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(),
4482 HintInst));
4483
4484 return;
4485 }
4486
4487 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4488 Action.Enter(CGF);
4489 CGF.EmitStmt(S.getAssociatedStmt());
4490 };
4491 const Expr *Hint = nullptr;
4492 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4493 Hint = HintClause->getHint();
4494 LexicalScope Scope(*this, S.getSourceRange());
4495 EmitStopPoint(&S);
4497 S.getDirectiveName().getAsString(),
4498 CodeGen, S.getBeginLoc(), Hint);
4499}
4500
4502 const OMPParallelForDirective &S) {
4503 // Emit directive as a combined directive that consists of two implicit
4504 // directives: 'parallel' with 'for' directive.
4505 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4506 Action.Enter(CGF);
4507 emitOMPCopyinClause(CGF, S);
4508 (void)emitWorksharingDirective(CGF, S, S.hasCancel());
4509 };
4510 {
4511 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
4512 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
4513 CGCapturedStmtInfo CGSI(CR_OpenMP);
4514 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
4515 OMPLoopScope LoopScope(CGF, S);
4516 return CGF.EmitScalarExpr(S.getNumIterations());
4517 };
4518 bool IsInscan = llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
4519 [](const OMPReductionClause *C) {
4520 return C->getModifier() == OMPC_REDUCTION_inscan;
4521 });
4522 if (IsInscan)
4523 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
4524 auto LPCRegion =
4526 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
4528 if (IsInscan)
4529 emitScanBasedDirectiveFinals(*this, S, NumIteratorsGen);
4530 }
4531 // Check for outer lastprivate conditional update.
4533}
4534
4536 const OMPParallelForSimdDirective &S) {
4537 // Emit directive as a combined directive that consists of two implicit
4538 // directives: 'parallel' with 'for' directive.
4539 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4540 Action.Enter(CGF);
4541 emitOMPCopyinClause(CGF, S);
4542 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
4543 };
4544 {
4545 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
4546 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
4547 CGCapturedStmtInfo CGSI(CR_OpenMP);
4548 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
4549 OMPLoopScope LoopScope(CGF, S);
4550 return CGF.EmitScalarExpr(S.getNumIterations());
4551 };
4552 bool IsInscan = llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
4553 [](const OMPReductionClause *C) {
4554 return C->getModifier() == OMPC_REDUCTION_inscan;
4555 });
4556 if (IsInscan)
4557 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
4558 auto LPCRegion =
4560 emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen,
4562 if (IsInscan)
4563 emitScanBasedDirectiveFinals(*this, S, NumIteratorsGen);
4564 }
4565 // Check for outer lastprivate conditional update.
4567}
4568
4570 const OMPParallelMasterDirective &S) {
4571 // Emit directive as a combined directive that consists of two implicit
4572 // directives: 'parallel' with 'master' directive.
4573 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4574 Action.Enter(CGF);
4575 OMPPrivateScope PrivateScope(CGF);
4576 emitOMPCopyinClause(CGF, S);
4577 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4578 CGF.EmitOMPPrivateClause(S, PrivateScope);
4579 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4580 (void)PrivateScope.Privatize();
4581 emitMaster(CGF, S);
4582 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4583 };
4584 {
4585 auto LPCRegion =
4587 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
4590 [](CodeGenFunction &) { return nullptr; });
4591 }
4592 // Check for outer lastprivate conditional update.
4594}
4595
4597 const OMPParallelMaskedDirective &S) {
4598 // Emit directive as a combined directive that consists of two implicit
4599 // directives: 'parallel' with 'masked' directive.
4600 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4601 Action.Enter(CGF);
4602 OMPPrivateScope PrivateScope(CGF);
4603 emitOMPCopyinClause(CGF, S);
4604 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4605 CGF.EmitOMPPrivateClause(S, PrivateScope);
4606 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4607 (void)PrivateScope.Privatize();
4608 emitMasked(CGF, S);
4609 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4610 };
4611 {
4612 auto LPCRegion =
4614 emitCommonOMPParallelDirective(*this, S, OMPD_masked, CodeGen,
4617 [](CodeGenFunction &) { return nullptr; });
4618 }
4619 // Check for outer lastprivate conditional update.
4621}
4622
4625 // Emit directive as a combined directive that consists of two implicit
4626 // directives: 'parallel' with 'sections' directive.
4627 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4628 Action.Enter(CGF);
4629 emitOMPCopyinClause(CGF, S);
4630 CGF.EmitSections(S);
4631 };
4632 {
4633 auto LPCRegion =
4635 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
4637 }
4638 // Check for outer lastprivate conditional update.
4640}
4641
4642namespace {
4643/// Get the list of variables declared in the context of the untied tasks.
4644class CheckVarsEscapingUntiedTaskDeclContext final
4645 : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> {
4647
4648public:
4649 explicit CheckVarsEscapingUntiedTaskDeclContext() = default;
4650 virtual ~CheckVarsEscapingUntiedTaskDeclContext() = default;
4651 void VisitDeclStmt(const DeclStmt *S) {
4652 if (!S)
4653 return;
4654 // Need to privatize only local vars, static locals can be processed as is.
4655 for (const Decl *D : S->decls()) {
4656 if (const auto *VD = dyn_cast_or_null<VarDecl>(D))
4657 if (VD->hasLocalStorage())
4658 PrivateDecls.push_back(VD);
4659 }
4660 }
4661 void VisitOMPExecutableDirective(const OMPExecutableDirective *) {}
4662 void VisitCapturedStmt(const CapturedStmt *) {}
4663 void VisitLambdaExpr(const LambdaExpr *) {}
4664 void VisitBlockExpr(const BlockExpr *) {}
4665 void VisitStmt(const Stmt *S) {
4666 if (!S)
4667 return;
4668 for (const Stmt *Child : S->children())
4669 if (Child)
4670 Visit(Child);
4671 }
4672
4673 /// Swaps list of vars with the provided one.
4674 ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; }
4675};
4676} // anonymous namespace
4677
4680
4681 // First look for 'omp_all_memory' and add this first.
4682 bool OmpAllMemory = false;
4683 if (llvm::any_of(
4684 S.getClausesOfKind<OMPDependClause>(), [](const OMPDependClause *C) {
4685 return C->getDependencyKind() == OMPC_DEPEND_outallmemory ||
4686 C->getDependencyKind() == OMPC_DEPEND_inoutallmemory;
4687 })) {
4688 OmpAllMemory = true;
4689 // Since both OMPC_DEPEND_outallmemory and OMPC_DEPEND_inoutallmemory are
4690 // equivalent to the runtime, always use OMPC_DEPEND_outallmemory to
4691 // simplify.
4693 Data.Dependences.emplace_back(OMPC_DEPEND_outallmemory,
4694 /*IteratorExpr=*/nullptr);
4695 // Add a nullptr Expr to simplify the codegen in emitDependData.
4696 DD.DepExprs.push_back(nullptr);
4697 }
4698 // Add remaining dependences skipping any 'out' or 'inout' if they are
4699 // overridden by 'omp_all_memory'.
4700 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
4701 OpenMPDependClauseKind Kind = C->getDependencyKind();
4702 if (Kind == OMPC_DEPEND_outallmemory || Kind == OMPC_DEPEND_inoutallmemory)
4703 continue;
4704 if (OmpAllMemory && (Kind == OMPC_DEPEND_out || Kind == OMPC_DEPEND_inout))
4705 continue;
4707 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
4708 DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
4709 }
4710}
4711
4713 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
4714 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
4716 // Emit outlined function for task construct.
4717 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
4718 auto I = CS->getCapturedDecl()->param_begin();
4719 auto PartId = std::next(I);
4720 auto TaskT = std::next(I, 4);
4721 // Check if the task is final
4722 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
4723 // If the condition constant folds and can be elided, try to avoid emitting
4724 // the condition and the dead arm of the if/else.
4725 const Expr *Cond = Clause->getCondition();
4726 bool CondConstant;
4727 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
4728 Data.Final.setInt(CondConstant);
4729 else
4730 Data.Final.setPointer(EvaluateExprAsBool(Cond));
4731 } else {
4732 // By default the task is not final.
4733 Data.Final.setInt(/*IntVal=*/false);
4734 }
4735 // Check if the task has 'priority' clause.
4736 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
4737 const Expr *Prio = Clause->getPriority();
4738 Data.Priority.setInt(/*IntVal=*/true);
4739 Data.Priority.setPointer(EmitScalarConversion(
4740 EmitScalarExpr(Prio), Prio->getType(),
4741 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4742 Prio->getExprLoc()));
4743 }
4744 // The first function argument for tasks is a thread id, the second one is a
4745 // part id (0 for tied tasks, >=0 for untied task).
4746 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
4747 // Get list of private variables.
4748 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
4749 auto IRef = C->varlist_begin();
4750 for (const Expr *IInit : C->private_copies()) {
4751 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4752 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4753 Data.PrivateVars.push_back(*IRef);
4754 Data.PrivateCopies.push_back(IInit);
4755 }
4756 ++IRef;
4757 }
4758 }
4759 EmittedAsPrivate.clear();
4760 // Get list of firstprivate variables.
4761 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
4762 auto IRef = C->varlist_begin();
4763 auto IElemInitRef = C->inits().begin();
4764 for (const Expr *IInit : C->private_copies()) {
4765 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4766 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4767 Data.FirstprivateVars.push_back(*IRef);
4768 Data.FirstprivateCopies.push_back(IInit);
4769 Data.FirstprivateInits.push_back(*IElemInitRef);
4770 }
4771 ++IRef;
4772 ++IElemInitRef;
4773 }
4774 }
4775 // Get list of lastprivate variables (for taskloops).
4776 llvm::MapVector<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
4777 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
4778 auto IRef = C->varlist_begin();
4779 auto ID = C->destination_exprs().begin();
4780 for (const Expr *IInit : C->private_copies()) {
4781 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4782 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4783 Data.LastprivateVars.push_back(*IRef);
4784 Data.LastprivateCopies.push_back(IInit);
4785 }
4786 LastprivateDstsOrigs.insert(
4787 std::make_pair(cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
4788 cast<DeclRefExpr>(*IRef)));
4789 ++IRef;
4790 ++ID;
4791 }
4792 }
4795 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
4796 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
4797 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
4798 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
4799 Data.ReductionOps.append(C->reduction_ops().begin(),
4800 C->reduction_ops().end());
4801 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4802 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4803 }
4805 *this, S.getBeginLoc(), LHSs, RHSs, Data);
4806 // Build list of dependences.
4808 // Get list of local vars for untied tasks.
4809 if (!Data.Tied) {
4810 CheckVarsEscapingUntiedTaskDeclContext Checker;
4811 Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt());
4812 Data.PrivateLocals.append(Checker.getPrivateDecls().begin(),
4813 Checker.getPrivateDecls().end());
4814 }
4815 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
4816 CapturedRegion](CodeGenFunction &CGF,
4817 PrePostActionTy &Action) {
4818 llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
4819 std::pair<Address, Address>>
4820 UntiedLocalVars;
4821 // Set proper addresses for generated private copies.
4822 OMPPrivateScope Scope(CGF);
4823 // Generate debug info for variables present in shared clause.
4824 if (auto *DI = CGF.getDebugInfo()) {
4825 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields =
4826 CGF.CapturedStmtInfo->getCaptureFields();
4827 llvm::Value *ContextValue = CGF.CapturedStmtInfo->getContextValue();
4828 if (CaptureFields.size() && ContextValue) {
4829 unsigned CharWidth = CGF.getContext().getCharWidth();
4830 // The shared variables are packed together as members of structure.
4831 // So the address of each shared variable can be computed by adding
4832 // offset of it (within record) to the base address of record. For each
4833 // shared variable, debug intrinsic llvm.dbg.declare is generated with
4834 // appropriate expressions (DIExpression).
4835 // Ex:
4836 // %12 = load %struct.anon*, %struct.anon** %__context.addr.i
4837 // call void @llvm.dbg.declare(metadata %struct.anon* %12,
4838 // metadata !svar1,
4839 // metadata !DIExpression(DW_OP_deref))
4840 // call void @llvm.dbg.declare(metadata %struct.anon* %12,
4841 // metadata !svar2,
4842 // metadata !DIExpression(DW_OP_plus_uconst, 8, DW_OP_deref))
4843 for (auto It = CaptureFields.begin(); It != CaptureFields.end(); ++It) {
4844 const VarDecl *SharedVar = It->first;
4845 RecordDecl *CaptureRecord = It->second->getParent();
4846 const ASTRecordLayout &Layout =
4847 CGF.getContext().getASTRecordLayout(CaptureRecord);
4848 unsigned Offset =
4849 Layout.getFieldOffset(It->second->getFieldIndex()) / CharWidth;
4850 if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
4851 (void)DI->EmitDeclareOfAutoVariable(SharedVar, ContextValue,
4852 CGF.Builder, false);
4853 // Get the call dbg.declare instruction we just created and update
4854 // its DIExpression to add offset to base address.
4855 auto UpdateExpr = [](llvm::LLVMContext &Ctx, auto *Declare,
4856 unsigned Offset) {
4858 // Add offset to the base address if non zero.
4859 if (Offset) {
4860 Ops.push_back(llvm::dwarf::DW_OP_plus_uconst);
4861 Ops.push_back(Offset);
4862 }
4863 Ops.push_back(llvm::dwarf::DW_OP_deref);
4864 Declare->setExpression(llvm::DIExpression::get(Ctx, Ops));
4865 };
4866 llvm::Instruction &Last = CGF.Builder.GetInsertBlock()->back();
4867 if (auto DDI = dyn_cast<llvm::DbgVariableIntrinsic>(&Last))
4868 UpdateExpr(DDI->getContext(), DDI, Offset);
4869 // If we're emitting using the new debug info format into a block
4870 // without a terminator, the record will be "trailing".
4871 assert(!Last.isTerminator() && "unexpected terminator");
4872 if (auto *Marker =
4873 CGF.Builder.GetInsertBlock()->getTrailingDbgRecords()) {
4874 for (llvm::DbgVariableRecord &DVR : llvm::reverse(
4875 llvm::filterDbgVars(Marker->getDbgRecordRange()))) {
4876 UpdateExpr(Last.getContext(), &DVR, Offset);
4877 break;
4878 }
4879 }
4880 }
4881 }
4882 }
4884 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
4885 !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) {
4886 enum { PrivatesParam = 2, CopyFnParam = 3 };
4887 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
4888 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
4889 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
4890 CS->getCapturedDecl()->getParam(PrivatesParam)));
4891 // Map privates.
4895 CallArgs.push_back(PrivatesPtr);
4896 ParamTypes.push_back(PrivatesPtr->getType());
4897 for (const Expr *E : Data.PrivateVars) {
4898 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4899 RawAddress PrivatePtr = CGF.CreateMemTemp(
4900 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
4901 PrivatePtrs.emplace_back(VD, PrivatePtr);
4902 CallArgs.push_back(PrivatePtr.getPointer());
4903 ParamTypes.push_back(PrivatePtr.getType());
4904 }
4905 for (const Expr *E : Data.FirstprivateVars) {
4906 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4907 RawAddress PrivatePtr =
4908 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4909 ".firstpriv.ptr.addr");
4910 PrivatePtrs.emplace_back(VD, PrivatePtr);
4911 FirstprivatePtrs.emplace_back(VD, PrivatePtr);
4912 CallArgs.push_back(PrivatePtr.getPointer());
4913 ParamTypes.push_back(PrivatePtr.getType());
4914 }
4915 for (const Expr *E : Data.LastprivateVars) {
4916 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4917 RawAddress PrivatePtr =
4918 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4919 ".lastpriv.ptr.addr");
4920 PrivatePtrs.emplace_back(VD, PrivatePtr);
4921 CallArgs.push_back(PrivatePtr.getPointer());
4922 ParamTypes.push_back(PrivatePtr.getType());
4923 }
4924 for (const VarDecl *VD : Data.PrivateLocals) {
4926 if (VD->getType()->isLValueReferenceType())
4927 Ty = CGF.getContext().getPointerType(Ty);
4928 if (isAllocatableDecl(VD))
4929 Ty = CGF.getContext().getPointerType(Ty);
4930 RawAddress PrivatePtr = CGF.CreateMemTemp(
4931 CGF.getContext().getPointerType(Ty), ".local.ptr.addr");
4932 auto Result = UntiedLocalVars.insert(
4933 std::make_pair(VD, std::make_pair(PrivatePtr, Address::invalid())));
4934 // If key exists update in place.
4935 if (Result.second == false)
4936 *Result.first = std::make_pair(
4937 VD, std::make_pair(PrivatePtr, Address::invalid()));
4938 CallArgs.push_back(PrivatePtr.getPointer());
4939 ParamTypes.push_back(PrivatePtr.getType());
4940 }
4941 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
4942 ParamTypes, /*isVarArg=*/false);
4943 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4944 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
4945 for (const auto &Pair : LastprivateDstsOrigs) {
4946 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
4947 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
4948 /*RefersToEnclosingVariableOrCapture=*/
4949 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
4950 Pair.second->getType(), VK_LValue,
4951 Pair.second->getExprLoc());
4952 Scope.addPrivate(Pair.first, CGF.EmitLValue(&DRE).getAddress());
4953 }
4954 for (const auto &Pair : PrivatePtrs) {
4955 Address Replacement = Address(
4956 CGF.Builder.CreateLoad(Pair.second),
4957 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
4958 CGF.getContext().getDeclAlign(Pair.first));
4959 Scope.addPrivate(Pair.first, Replacement);
4960 if (auto *DI = CGF.getDebugInfo())
4961 if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
4962 (void)DI->EmitDeclareOfAutoVariable(
4963 Pair.first, Pair.second.getBasePointer(), CGF.Builder,
4964 /*UsePointerValue*/ true);
4965 }
4966 // Adjust mapping for internal locals by mapping actual memory instead of
4967 // a pointer to this memory.
4968 for (auto &Pair : UntiedLocalVars) {
4969 QualType VDType = Pair.first->getType().getNonReferenceType();
4970 if (Pair.first->getType()->isLValueReferenceType())
4971 VDType = CGF.getContext().getPointerType(VDType);
4972 if (isAllocatableDecl(Pair.first)) {
4973 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
4974 Address Replacement(
4975 Ptr,
4976 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(VDType)),
4977 CGF.getPointerAlign());
4978 Pair.second.first = Replacement;
4979 Ptr = CGF.Builder.CreateLoad(Replacement);
4980 Replacement = Address(Ptr, CGF.ConvertTypeForMem(VDType),
4981 CGF.getContext().getDeclAlign(Pair.first));
4982 Pair.second.second = Replacement;
4983 } else {
4984 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
4985 Address Replacement(Ptr, CGF.ConvertTypeForMem(VDType),
4986 CGF.getContext().getDeclAlign(Pair.first));
4987 Pair.second.first = Replacement;
4988 }
4989 }
4990 }
4991 if (Data.Reductions) {
4992 OMPPrivateScope FirstprivateScope(CGF);
4993 for (const auto &Pair : FirstprivatePtrs) {
4994 Address Replacement(
4995 CGF.Builder.CreateLoad(Pair.second),
4996 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
4997 CGF.getContext().getDeclAlign(Pair.first));
4998 FirstprivateScope.addPrivate(Pair.first, Replacement);
4999 }
5000 (void)FirstprivateScope.Privatize();
5001 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
5002 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
5003 Data.ReductionCopies, Data.ReductionOps);
5004 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
5005 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
5006 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
5007 RedCG.emitSharedOrigLValue(CGF, Cnt);
5008 RedCG.emitAggregateType(CGF, Cnt);
5009 // FIXME: This must removed once the runtime library is fixed.
5010 // Emit required threadprivate variables for
5011 // initializer/combiner/finalizer.
5012 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5013 RedCG, Cnt);
5014 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
5015 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5016 Replacement = Address(
5017 CGF.EmitScalarConversion(Replacement.emitRawPointer(CGF),
5018 CGF.getContext().VoidPtrTy,
5019 CGF.getContext().getPointerType(
5020 Data.ReductionCopies[Cnt]->getType()),
5021 Data.ReductionCopies[Cnt]->getExprLoc()),
5022 CGF.ConvertTypeForMem(Data.ReductionCopies[Cnt]->getType()),
5023 Replacement.getAlignment());
5024 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5025 Scope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5026 }
5027 }
5028 // Privatize all private variables except for in_reduction items.
5029 (void)Scope.Privatize();
5033 SmallVector<const Expr *, 4> TaskgroupDescriptors;
5034 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
5035 auto IPriv = C->privates().begin();
5036 auto IRed = C->reduction_ops().begin();
5037 auto ITD = C->taskgroup_descriptors().begin();
5038 for (const Expr *Ref : C->varlist()) {
5039 InRedVars.emplace_back(Ref);
5040 InRedPrivs.emplace_back(*IPriv);
5041 InRedOps.emplace_back(*IRed);
5042 TaskgroupDescriptors.emplace_back(*ITD);
5043 std::advance(IPriv, 1);
5044 std::advance(IRed, 1);
5045 std::advance(ITD, 1);
5046 }
5047 }
5048 // Privatize in_reduction items here, because taskgroup descriptors must be
5049 // privatized earlier.
5050 OMPPrivateScope InRedScope(CGF);
5051 if (!InRedVars.empty()) {
5052 ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
5053 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
5054 RedCG.emitSharedOrigLValue(CGF, Cnt);
5055 RedCG.emitAggregateType(CGF, Cnt);
5056 // The taskgroup descriptor variable is always implicit firstprivate and
5057 // privatized already during processing of the firstprivates.
5058 // FIXME: This must removed once the runtime library is fixed.
5059 // Emit required threadprivate variables for
5060 // initializer/combiner/finalizer.
5061 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5062 RedCG, Cnt);
5063 llvm::Value *ReductionsPtr;
5064 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
5065 ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr),
5066 TRExpr->getExprLoc());
5067 } else {
5068 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5069 }
5070 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
5071 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5072 Replacement = Address(
5073 CGF.EmitScalarConversion(
5074 Replacement.emitRawPointer(CGF), CGF.getContext().VoidPtrTy,
5075 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
5076 InRedPrivs[Cnt]->getExprLoc()),
5077 CGF.ConvertTypeForMem(InRedPrivs[Cnt]->getType()),
5078 Replacement.getAlignment());
5079 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5080 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5081 }
5082 }
5083 (void)InRedScope.Privatize();
5084
5086 UntiedLocalVars);
5087 Action.Enter(CGF);
5088 BodyGen(CGF);
5089 };
5091 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
5092 S, *I, *PartId, *TaskT, EKind, CodeGen, Data.Tied, Data.NumberOfParts);
5093 OMPLexicalScope Scope(*this, S, std::nullopt,
5094 !isOpenMPParallelDirective(EKind) &&
5095 !isOpenMPSimdDirective(EKind));
5096 TaskGen(*this, OutlinedFn, Data);
5097}
5098
5099static ImplicitParamDecl *
5101 QualType Ty, CapturedDecl *CD,
5103 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
5105 auto *OrigRef = DeclRefExpr::Create(
5107 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
5108 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
5110 auto *PrivateRef = DeclRefExpr::Create(
5111 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
5112 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
5113 QualType ElemType = C.getBaseElementType(Ty);
5114 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
5116 auto *InitRef = DeclRefExpr::Create(
5118 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
5119 PrivateVD->setInitStyle(VarDecl::CInit);
5120 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
5121 InitRef, /*BasePath=*/nullptr,
5123 Data.FirstprivateVars.emplace_back(OrigRef);
5124 Data.FirstprivateCopies.emplace_back(PrivateRef);
5125 Data.FirstprivateInits.emplace_back(InitRef);
5126 return OrigVD;
5127}
5128
5130 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
5131 OMPTargetDataInfo &InputInfo) {
5132 // Emit outlined function for task construct.
5133 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
5134 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5136 auto I = CS->getCapturedDecl()->param_begin();
5137 auto PartId = std::next(I);
5138 auto TaskT = std::next(I, 4);
5140 // The task is not final.
5141 Data.Final.setInt(/*IntVal=*/false);
5142 // Get list of firstprivate variables.
5143 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
5144 auto IRef = C->varlist_begin();
5145 auto IElemInitRef = C->inits().begin();
5146 for (auto *IInit : C->private_copies()) {
5147 Data.FirstprivateVars.push_back(*IRef);
5148 Data.FirstprivateCopies.push_back(IInit);
5149 Data.FirstprivateInits.push_back(*IElemInitRef);
5150 ++IRef;
5151 ++IElemInitRef;
5152 }
5153 }
5156 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
5157 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
5158 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
5159 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
5160 Data.ReductionOps.append(C->reduction_ops().begin(),
5161 C->reduction_ops().end());
5162 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
5163 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
5164 }
5165 OMPPrivateScope TargetScope(*this);
5166 VarDecl *BPVD = nullptr;
5167 VarDecl *PVD = nullptr;
5168 VarDecl *SVD = nullptr;
5169 VarDecl *MVD = nullptr;
5170 if (InputInfo.NumberOfTargetItems > 0) {
5171 auto *CD = CapturedDecl::Create(
5172 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
5173 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
5174 QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType(
5175 getContext().VoidPtrTy, ArrSize, nullptr, ArraySizeModifier::Normal,
5176 /*IndexTypeQuals=*/0);
5178 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
5180 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
5182 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
5183 ArrSize, nullptr, ArraySizeModifier::Normal,
5184 /*IndexTypeQuals=*/0);
5185 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
5186 S.getBeginLoc());
5187 TargetScope.addPrivate(BPVD, InputInfo.BasePointersArray);
5188 TargetScope.addPrivate(PVD, InputInfo.PointersArray);
5189 TargetScope.addPrivate(SVD, InputInfo.SizesArray);
5190 // If there is no user-defined mapper, the mapper array will be nullptr. In
5191 // this case, we don't need to privatize it.
5192 if (!isa_and_nonnull<llvm::ConstantPointerNull>(
5193 InputInfo.MappersArray.emitRawPointer(*this))) {
5195 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
5196 TargetScope.addPrivate(MVD, InputInfo.MappersArray);
5197 }
5198 }
5199 (void)TargetScope.Privatize();
5202 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD, EKind,
5203 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
5204 // Set proper addresses for generated private copies.
5205 OMPPrivateScope Scope(CGF);
5206 if (!Data.FirstprivateVars.empty()) {
5207 enum { PrivatesParam = 2, CopyFnParam = 3 };
5208 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
5209 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
5210 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
5211 CS->getCapturedDecl()->getParam(PrivatesParam)));
5212 // Map privates.
5216 CallArgs.push_back(PrivatesPtr);
5217 ParamTypes.push_back(PrivatesPtr->getType());
5218 for (const Expr *E : Data.FirstprivateVars) {
5219 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5220 RawAddress PrivatePtr =
5221 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
5222 ".firstpriv.ptr.addr");
5223 PrivatePtrs.emplace_back(VD, PrivatePtr);
5224 CallArgs.push_back(PrivatePtr.getPointer());
5225 ParamTypes.push_back(PrivatePtr.getType());
5226 }
5227 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
5228 ParamTypes, /*isVarArg=*/false);
5229 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
5230 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
5231 for (const auto &Pair : PrivatePtrs) {
5232 Address Replacement(
5233 CGF.Builder.CreateLoad(Pair.second),
5234 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
5235 CGF.getContext().getDeclAlign(Pair.first));
5236 Scope.addPrivate(Pair.first, Replacement);
5237 }
5238 }
5239 CGF.processInReduction(S, Data, CGF, CS, Scope);
5240 if (InputInfo.NumberOfTargetItems > 0) {
5241 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
5242 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
5243 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
5244 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
5245 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
5246 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
5247 // If MVD is nullptr, the mapper array is not privatized
5248 if (MVD)
5249 InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
5250 CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
5251 }
5252
5253 Action.Enter(CGF);
5254 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
5255 auto *TL = S.getSingleClause<OMPThreadLimitClause>();
5256 if (CGF.CGM.getLangOpts().OpenMP >= 51 &&
5257 needsTaskBasedThreadLimit(EKind) && TL) {
5258 // Emit __kmpc_set_thread_limit() to set the thread_limit for the task
5259 // enclosing this target region. This will indirectly set the thread_limit
5260 // for every applicable construct within target region.
5261 CGF.CGM.getOpenMPRuntime().emitThreadLimitClause(
5262 CGF, TL->getThreadLimit().front(), S.getBeginLoc());
5263 }
5264 BodyGen(CGF);
5265 };
5266 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
5267 S, *I, *PartId, *TaskT, EKind, CodeGen, /*Tied=*/true,
5268 Data.NumberOfParts);
5269 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
5270 IntegerLiteral IfCond(getContext(), TrueOrFalse,
5271 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
5272 SourceLocation());
5273 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
5274 SharedsTy, CapturedStruct, &IfCond, Data);
5275}
5276
5279 CodeGenFunction &CGF,
5280 const CapturedStmt *CS,
5281 OMPPrivateScope &Scope) {
5283 if (Data.Reductions) {
5284 OpenMPDirectiveKind CapturedRegion = EKind;
5285 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
5286 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
5287 Data.ReductionCopies, Data.ReductionOps);
5288 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
5290 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
5291 RedCG.emitSharedOrigLValue(CGF, Cnt);
5292 RedCG.emitAggregateType(CGF, Cnt);
5293 // FIXME: This must removed once the runtime library is fixed.
5294 // Emit required threadprivate variables for
5295 // initializer/combiner/finalizer.
5296 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5297 RedCG, Cnt);
5299 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5300 Replacement = Address(
5301 CGF.EmitScalarConversion(Replacement.emitRawPointer(CGF),
5302 CGF.getContext().VoidPtrTy,
5304 Data.ReductionCopies[Cnt]->getType()),
5305 Data.ReductionCopies[Cnt]->getExprLoc()),
5306 CGF.ConvertTypeForMem(Data.ReductionCopies[Cnt]->getType()),
5307 Replacement.getAlignment());
5308 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5309 Scope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5310 }
5311 }
5312 (void)Scope.Privatize();
5316 SmallVector<const Expr *, 4> TaskgroupDescriptors;
5317 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
5318 auto IPriv = C->privates().begin();
5319 auto IRed = C->reduction_ops().begin();
5320 auto ITD = C->taskgroup_descriptors().begin();
5321 for (const Expr *Ref : C->varlist()) {
5322 InRedVars.emplace_back(Ref);
5323 InRedPrivs.emplace_back(*IPriv);
5324 InRedOps.emplace_back(*IRed);
5325 TaskgroupDescriptors.emplace_back(*ITD);
5326 std::advance(IPriv, 1);
5327 std::advance(IRed, 1);
5328 std::advance(ITD, 1);
5329 }
5330 }
5331 OMPPrivateScope InRedScope(CGF);
5332 if (!InRedVars.empty()) {
5333 ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
5334 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
5335 RedCG.emitSharedOrigLValue(CGF, Cnt);
5336 RedCG.emitAggregateType(CGF, Cnt);
5337 // FIXME: This must removed once the runtime library is fixed.
5338 // Emit required threadprivate variables for
5339 // initializer/combiner/finalizer.
5340 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
5341 RedCG, Cnt);
5342 llvm::Value *ReductionsPtr;
5343 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
5344 ReductionsPtr =
5345 CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr), TRExpr->getExprLoc());
5346 } else {
5347 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5348 }
5350 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
5351 Replacement = Address(
5353 Replacement.emitRawPointer(CGF), CGF.getContext().VoidPtrTy,
5354 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
5355 InRedPrivs[Cnt]->getExprLoc()),
5356 CGF.ConvertTypeForMem(InRedPrivs[Cnt]->getType()),
5357 Replacement.getAlignment());
5358 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
5359 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
5360 }
5361 }
5362 (void)InRedScope.Privatize();
5363}
5364
5366 // Emit outlined function for task construct.
5367 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
5368 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5370 const Expr *IfCond = nullptr;
5371 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5372 if (C->getNameModifier() == OMPD_unknown ||
5373 C->getNameModifier() == OMPD_task) {
5374 IfCond = C->getCondition();
5375 break;
5376 }
5377 }
5378
5380 // Check if we should emit tied or untied task.
5381 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
5382 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
5383 CGF.EmitStmt(CS->getCapturedStmt());
5384 };
5385 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
5386 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
5387 const OMPTaskDataTy &Data) {
5388 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
5389 SharedsTy, CapturedStruct, IfCond,
5390 Data);
5391 };
5392 auto LPCRegion =
5394 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
5395}
5396
5398 const OMPTaskyieldDirective &S) {
5399 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
5400}
5401
5403 const OMPMessageClause *MC = S.getSingleClause<OMPMessageClause>();
5404 Expr *ME = MC ? MC->getMessageString() : nullptr;
5405 const OMPSeverityClause *SC = S.getSingleClause<OMPSeverityClause>();
5406 bool IsFatal = false;
5407 if (!SC || SC->getSeverityKind() == OMPC_SEVERITY_fatal)
5408 IsFatal = true;
5409 CGM.getOpenMPRuntime().emitErrorCall(*this, S.getBeginLoc(), ME, IsFatal);
5410}
5411
5413 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
5414}
5415
5418 // Build list of dependences
5420 Data.HasNowaitClause = S.hasClausesOfKind<OMPNowaitClause>();
5421 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc(), Data);
5422}
5423
5425 return T.clauses().empty();
5426}
5427
5429 const OMPTaskgroupDirective &S) {
5430 OMPLexicalScope Scope(*this, S, OMPD_unknown);
5431 if (CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S)) {
5432 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
5433 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
5434 InsertPointTy AllocaIP(AllocaInsertPt->getParent(),
5435 AllocaInsertPt->getIterator());
5436
5437 auto BodyGenCB = [&, this](InsertPointTy AllocaIP,
5438 InsertPointTy CodeGenIP) {
5439 Builder.restoreIP(CodeGenIP);
5440 EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5441 };
5442 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
5443 if (!CapturedStmtInfo)
5444 CapturedStmtInfo = &CapStmtInfo;
5445 Builder.restoreIP(OMPBuilder.createTaskgroup(Builder, AllocaIP, BodyGenCB));
5446 return;
5447 }
5448 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5449 Action.Enter(CGF);
5450 if (const Expr *E = S.getReductionRef()) {
5454 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
5455 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
5456 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
5457 Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
5458 Data.ReductionOps.append(C->reduction_ops().begin(),
5459 C->reduction_ops().end());
5460 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
5461 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
5462 }
5463 llvm::Value *ReductionDesc =
5464 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
5465 LHSs, RHSs, Data);
5466 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5467 CGF.EmitVarDecl(*VD);
5468 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
5469 /*Volatile=*/false, E->getType());
5470 }
5471 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5472 };
5473 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
5474}
5475
5477 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>()
5478 ? llvm::AtomicOrdering::NotAtomic
5479 : llvm::AtomicOrdering::AcquireRelease;
5481 *this,
5482 [&S]() -> ArrayRef<const Expr *> {
5483 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
5484 return llvm::ArrayRef(FlushClause->varlist_begin(),
5485 FlushClause->varlist_end());
5486 return std::nullopt;
5487 }(),
5488 S.getBeginLoc(), AO);
5489}
5490
5492 const auto *DO = S.getSingleClause<OMPDepobjClause>();
5493 LValue DOLVal = EmitLValue(DO->getDepobj());
5494 if (const auto *DC = S.getSingleClause<OMPDependClause>()) {
5495 OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(),
5496 DC->getModifier());
5497 Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end());
5499 *this, Dependencies, DC->getBeginLoc());
5500 EmitStoreOfScalar(DepAddr.emitRawPointer(*this), DOLVal);
5501 return;
5502 }
5503 if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) {
5504 CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc());
5505 return;
5506 }
5507 if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) {
5509 *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc());
5510 return;
5511 }
5512}
5513
5516 return;
5518 bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>();
5523 SmallVector<const Expr *, 4> ReductionOps;
5525 SmallVector<const Expr *, 4> CopyArrayTemps;
5526 SmallVector<const Expr *, 4> CopyArrayElems;
5527 for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) {
5528 if (C->getModifier() != OMPC_REDUCTION_inscan)
5529 continue;
5530 Shareds.append(C->varlist_begin(), C->varlist_end());
5531 Privates.append(C->privates().begin(), C->privates().end());
5532 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
5533 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
5534 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
5535 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
5536 CopyArrayTemps.append(C->copy_array_temps().begin(),
5537 C->copy_array_temps().end());
5538 CopyArrayElems.append(C->copy_array_elems().begin(),
5539 C->copy_array_elems().end());
5540 }
5541 if (ParentDir.getDirectiveKind() == OMPD_simd ||
5542 (getLangOpts().OpenMPSimd &&
5544 // For simd directive and simd-based directives in simd only mode, use the
5545 // following codegen:
5546 // int x = 0;
5547 // #pragma omp simd reduction(inscan, +: x)
5548 // for (..) {
5549 // <first part>
5550 // #pragma omp scan inclusive(x)
5551 // <second part>
5552 // }
5553 // is transformed to:
5554 // int x = 0;
5555 // for (..) {
5556 // int x_priv = 0;
5557 // <first part>
5558 // x = x_priv + x;
5559 // x_priv = x;
5560 // <second part>
5561 // }
5562 // and
5563 // int x = 0;
5564 // #pragma omp simd reduction(inscan, +: x)
5565 // for (..) {
5566 // <first part>
5567 // #pragma omp scan exclusive(x)
5568 // <second part>
5569 // }
5570 // to
5571 // int x = 0;
5572 // for (..) {
5573 // int x_priv = 0;
5574 // <second part>
5575 // int temp = x;
5576 // x = x_priv + x;
5577 // x_priv = temp;
5578 // <first part>
5579 // }
5580 llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce");
5581 EmitBranch(IsInclusive
5582 ? OMPScanReduce
5583 : BreakContinueStack.back().ContinueBlock.getBlock());
5585 {
5586 // New scope for correct construction/destruction of temp variables for
5587 // exclusive scan.
5588 LexicalScope Scope(*this, S.getSourceRange());
5590 EmitBlock(OMPScanReduce);
5591 if (!IsInclusive) {
5592 // Create temp var and copy LHS value to this temp value.
5593 // TMP = LHS;
5594 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5595 const Expr *PrivateExpr = Privates[I];
5596 const Expr *TempExpr = CopyArrayTemps[I];
5598 *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl()));
5599 LValue DestLVal = EmitLValue(TempExpr);
5600 LValue SrcLVal = EmitLValue(LHSs[I]);
5601 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(),
5602 SrcLVal.getAddress(),
5603 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5604 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
5605 CopyOps[I]);
5606 }
5607 }
5609 *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
5610 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_simd});
5611 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5612 const Expr *PrivateExpr = Privates[I];
5613 LValue DestLVal;
5614 LValue SrcLVal;
5615 if (IsInclusive) {
5616 DestLVal = EmitLValue(RHSs[I]);
5617 SrcLVal = EmitLValue(LHSs[I]);
5618 } else {
5619 const Expr *TempExpr = CopyArrayTemps[I];
5620 DestLVal = EmitLValue(RHSs[I]);
5621 SrcLVal = EmitLValue(TempExpr);
5622 }
5624 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
5625 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5626 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
5627 }
5628 }
5630 OMPScanExitBlock = IsInclusive
5631 ? BreakContinueStack.back().ContinueBlock.getBlock()
5632 : OMPScanReduce;
5634 return;
5635 }
5636 if (!IsInclusive) {
5637 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5639 }
5640 if (OMPFirstScanLoop) {
5641 // Emit buffer[i] = red; at the end of the input phase.
5642 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
5643 .getIterationVariable()
5645 LValue IdxLVal = EmitLValue(IVExpr);
5646 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
5647 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
5648 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5649 const Expr *PrivateExpr = Privates[I];
5650 const Expr *OrigExpr = Shareds[I];
5651 const Expr *CopyArrayElem = CopyArrayElems[I];
5652 OpaqueValueMapping IdxMapping(
5653 *this,
5654 cast<OpaqueValueExpr>(
5655 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
5656 RValue::get(IdxVal));
5657 LValue DestLVal = EmitLValue(CopyArrayElem);
5658 LValue SrcLVal = EmitLValue(OrigExpr);
5660 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
5661 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5662 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
5663 }
5664 }
5665 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5666 if (IsInclusive) {
5668 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5669 }
5671 if (!OMPFirstScanLoop) {
5672 // Emit red = buffer[i]; at the entrance to the scan phase.
5673 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
5674 .getIterationVariable()
5676 LValue IdxLVal = EmitLValue(IVExpr);
5677 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
5678 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
5679 llvm::BasicBlock *ExclusiveExitBB = nullptr;
5680 if (!IsInclusive) {
5681 llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec");
5682 ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit");
5683 llvm::Value *Cmp = Builder.CreateIsNull(IdxVal);
5684 Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB);
5685 EmitBlock(ContBB);
5686 // Use idx - 1 iteration for exclusive scan.
5687 IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1));
5688 }
5689 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5690 const Expr *PrivateExpr = Privates[I];
5691 const Expr *OrigExpr = Shareds[I];
5692 const Expr *CopyArrayElem = CopyArrayElems[I];
5693 OpaqueValueMapping IdxMapping(
5694 *this,
5695 cast<OpaqueValueExpr>(
5696 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
5697 RValue::get(IdxVal));
5698 LValue SrcLVal = EmitLValue(CopyArrayElem);
5699 LValue DestLVal = EmitLValue(OrigExpr);
5701 PrivateExpr->getType(), DestLVal.getAddress(), SrcLVal.getAddress(),
5702 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5703 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), CopyOps[I]);
5704 }
5705 if (!IsInclusive) {
5706 EmitBlock(ExclusiveExitBB);
5707 }
5708 }
5712}
5713
5715 const CodeGenLoopTy &CodeGenLoop,
5716 Expr *IncExpr) {
5717 // Emit the loop iteration variable.
5718 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
5719 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
5720 EmitVarDecl(*IVDecl);
5721
5722 // Emit the iterations count variable.
5723 // If it is not a variable, Sema decided to calculate iterations count on each
5724 // iteration (e.g., it is foldable into a constant).
5725 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
5726 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5727 // Emit calculation of the iterations count.
5728 EmitIgnoredExpr(S.getCalcLastIteration());
5729 }
5730
5732
5733 bool HasLastprivateClause = false;
5734 // Check pre-condition.
5735 {
5736 OMPLoopScope PreInitScope(*this, S);
5737 // Skip the entire loop if we don't meet the precondition.
5738 // If the condition constant folds and can be elided, avoid emitting the
5739 // whole loop.
5740 bool CondConstant;
5741 llvm::BasicBlock *ContBlock = nullptr;
5742 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5743 if (!CondConstant)
5744 return;
5745 } else {
5746 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
5747 ContBlock = createBasicBlock("omp.precond.end");
5748 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
5749 getProfileCount(&S));
5750 EmitBlock(ThenBlock);
5752 }
5753
5754 emitAlignedClause(*this, S);
5755 // Emit 'then' code.
5756 {
5757 // Emit helper vars inits.
5758
5760 *this, cast<DeclRefExpr>(
5761 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5762 ? S.getCombinedLowerBoundVariable()
5763 : S.getLowerBoundVariable())));
5765 *this, cast<DeclRefExpr>(
5766 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5767 ? S.getCombinedUpperBoundVariable()
5768 : S.getUpperBoundVariable())));
5769 LValue ST =
5770 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
5771 LValue IL =
5772 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
5773
5774 OMPPrivateScope LoopScope(*this);
5775 if (EmitOMPFirstprivateClause(S, LoopScope)) {
5776 // Emit implicit barrier to synchronize threads and avoid data races
5777 // on initialization of firstprivate variables and post-update of
5778 // lastprivate variables.
5780 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
5781 /*ForceSimpleCall=*/true);
5782 }
5783 EmitOMPPrivateClause(S, LoopScope);
5784 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
5785 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
5786 !isOpenMPTeamsDirective(S.getDirectiveKind()))
5787 EmitOMPReductionClauseInit(S, LoopScope);
5788 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
5789 EmitOMPPrivateLoopCounters(S, LoopScope);
5790 (void)LoopScope.Privatize();
5791 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
5793
5794 // Detect the distribute schedule kind and chunk.
5795 llvm::Value *Chunk = nullptr;
5797 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
5798 ScheduleKind = C->getDistScheduleKind();
5799 if (const Expr *Ch = C->getChunkSize()) {
5800 Chunk = EmitScalarExpr(Ch);
5801 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
5802 S.getIterationVariable()->getType(),
5803 S.getBeginLoc());
5804 }
5805 } else {
5806 // Default behaviour for dist_schedule clause.
5808 *this, S, ScheduleKind, Chunk);
5809 }
5810 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
5811 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
5812
5813 // OpenMP [2.10.8, distribute Construct, Description]
5814 // If dist_schedule is specified, kind must be static. If specified,
5815 // iterations are divided into chunks of size chunk_size, chunks are
5816 // assigned to the teams of the league in a round-robin fashion in the
5817 // order of the team number. When no chunk_size is specified, the
5818 // iteration space is divided into chunks that are approximately equal
5819 // in size, and at most one chunk is distributed to each team of the
5820 // league. The size of the chunks is unspecified in this case.
5821 bool StaticChunked =
5822 RT.isStaticChunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
5823 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
5824 if (RT.isStaticNonchunked(ScheduleKind,
5825 /* Chunked */ Chunk != nullptr) ||
5826 StaticChunked) {
5828 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
5829 LB.getAddress(), UB.getAddress(), ST.getAddress(),
5830 StaticChunked ? Chunk : nullptr);
5831 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
5832 StaticInit);
5833 JumpDest LoopExit =
5835 // UB = min(UB, GlobalUB);
5837 ? S.getCombinedEnsureUpperBound()
5838 : S.getEnsureUpperBound());
5839 // IV = LB;
5841 ? S.getCombinedInit()
5842 : S.getInit());
5843
5844 const Expr *Cond =
5845 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5846 ? S.getCombinedCond()
5847 : S.getCond();
5848
5849 if (StaticChunked)
5850 Cond = S.getCombinedDistCond();
5851
5852 // For static unchunked schedules generate:
5853 //
5854 // 1. For distribute alone, codegen
5855 // while (idx <= UB) {
5856 // BODY;
5857 // ++idx;
5858 // }
5859 //
5860 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
5861 // while (idx <= UB) {
5862 // <CodeGen rest of pragma>(LB, UB);
5863 // idx += ST;
5864 // }
5865 //
5866 // For static chunk one schedule generate:
5867 //
5868 // while (IV <= GlobalUB) {
5869 // <CodeGen rest of pragma>(LB, UB);
5870 // LB += ST;
5871 // UB += ST;
5872 // UB = min(UB, GlobalUB);
5873 // IV = LB;
5874 // }
5875 //
5877 *this, S,
5878 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5879 if (isOpenMPSimdDirective(S.getDirectiveKind()))
5880 CGF.EmitOMPSimdInit(S);
5881 },
5882 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
5883 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
5884 CGF.EmitOMPInnerLoop(
5885 S, LoopScope.requiresCleanups(), Cond, IncExpr,
5886 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
5887 CodeGenLoop(CGF, S, LoopExit);
5888 },
5889 [&S, StaticChunked](CodeGenFunction &CGF) {
5890 if (StaticChunked) {
5891 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
5892 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
5893 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
5894 CGF.EmitIgnoredExpr(S.getCombinedInit());
5895 }
5896 });
5897 });
5898 EmitBlock(LoopExit.getBlock());
5899 // Tell the runtime we are done.
5900 RT.emitForStaticFinish(*this, S.getEndLoc(), OMPD_distribute);
5901 } else {
5902 // Emit the outer loop, which requests its work chunk [LB..UB] from
5903 // runtime and runs the inner loop to process it.
5904 const OMPLoopArguments LoopArguments = {
5905 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
5906 Chunk};
5907 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
5908 CodeGenLoop);
5909 }
5910 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
5911 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
5912 return CGF.Builder.CreateIsNotNull(
5913 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
5914 });
5915 }
5916 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
5917 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
5918 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
5919 EmitOMPReductionClauseFinal(S, OMPD_simd);
5920 // Emit post-update of the reduction variables if IsLastIter != 0.
5922 *this, S, [IL, &S](CodeGenFunction &CGF) {
5923 return CGF.Builder.CreateIsNotNull(
5924 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
5925 });
5926 }
5927 // Emit final copy of the lastprivate variables if IsLastIter != 0.
5928 if (HasLastprivateClause) {
5930 S, /*NoFinals=*/false,
5931 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
5932 }
5933 }
5934
5935 // We're now done with the loop, so jump to the continuation block.
5936 if (ContBlock) {
5937 EmitBranch(ContBlock);
5938 EmitBlock(ContBlock, true);
5939 }
5940 }
5941}
5942
5943// Pass OMPLoopDirective (instead of OMPDistributeDirective) to make this
5944// function available for "loop bind(teams)", which maps to "distribute".
5946 CodeGenModule &CGM) {
5947 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5949 };
5950 OMPLexicalScope Scope(CGF, S, OMPD_unknown);
5951 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, CodeGen);
5952}
5953
5955 const OMPDistributeDirective &S) {
5957}
5958
5960 const CapturedStmt *S,
5962 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
5963 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
5964 CGF.CapturedStmtInfo = &CapStmtInfo;
5965 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc);
5966 Fn->setDoesNotRecurse();
5967 return Fn;
5968}
5969
5970template <typename T>
5971static void emitRestoreIP(CodeGenFunction &CGF, const T *C,
5972 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP,
5973 llvm::OpenMPIRBuilder &OMPBuilder) {
5974
5975 unsigned NumLoops = C->getNumLoops();
5977 /*DestWidth=*/64, /*Signed=*/1);
5979 for (unsigned I = 0; I < NumLoops; I++) {
5980 const Expr *CounterVal = C->getLoopData(I);
5981 assert(CounterVal);
5982 llvm::Value *StoreValue = CGF.EmitScalarConversion(
5983 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
5984 CounterVal->getExprLoc());
5985 StoreValues.emplace_back(StoreValue);
5986 }
5987 OMPDoacrossKind<T> ODK;
5988 bool IsDependSource = ODK.isSource(C);
5989 CGF.Builder.restoreIP(
5990 OMPBuilder.createOrderedDepend(CGF.Builder, AllocaIP, NumLoops,
5991 StoreValues, ".cnt.addr", IsDependSource));
5992}
5993
5995 if (CGM.getLangOpts().OpenMPIRBuilder) {
5996 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
5997 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
5998
5999 if (S.hasClausesOfKind<OMPDependClause>() ||
6000 S.hasClausesOfKind<OMPDoacrossClause>()) {
6001 // The ordered directive with depend clause.
6002 assert(!S.hasAssociatedStmt() && "No associated statement must be in "
6003 "ordered depend|doacross construct.");
6004 InsertPointTy AllocaIP(AllocaInsertPt->getParent(),
6005 AllocaInsertPt->getIterator());
6006 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
6007 emitRestoreIP(*this, DC, AllocaIP, OMPBuilder);
6008 for (const auto *DC : S.getClausesOfKind<OMPDoacrossClause>())
6009 emitRestoreIP(*this, DC, AllocaIP, OMPBuilder);
6010 } else {
6011 // The ordered directive with threads or simd clause, or without clause.
6012 // Without clause, it behaves as if the threads clause is specified.
6013 const auto *C = S.getSingleClause<OMPSIMDClause>();
6014
6015 auto FiniCB = [this](InsertPointTy IP) {
6017 };
6018
6019 auto BodyGenCB = [&S, C, this](InsertPointTy AllocaIP,
6020 InsertPointTy CodeGenIP) {
6021 Builder.restoreIP(CodeGenIP);
6022
6023 const CapturedStmt *CS = S.getInnermostCapturedStmt();
6024 if (C) {
6025 llvm::BasicBlock *FiniBB = splitBBWithSuffix(
6026 Builder, /*CreateBranch=*/false, ".ordered.after");
6028 GenerateOpenMPCapturedVars(*CS, CapturedVars);
6029 llvm::Function *OutlinedFn =
6030 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
6031 assert(S.getBeginLoc().isValid() &&
6032 "Outlined function call location must be valid.");
6033 ApplyDebugLocation::CreateDefaultArtificial(*this, S.getBeginLoc());
6034 OMPBuilderCBHelpers::EmitCaptureStmt(*this, CodeGenIP, *FiniBB,
6035 OutlinedFn, CapturedVars);
6036 } else {
6038 *this, CS->getCapturedStmt(), AllocaIP, CodeGenIP, "ordered");
6039 }
6040 };
6041
6042 OMPLexicalScope Scope(*this, S, OMPD_unknown);
6043 Builder.restoreIP(
6044 OMPBuilder.createOrderedThreadsSimd(Builder, BodyGenCB, FiniCB, !C));
6045 }
6046 return;
6047 }
6048
6049 if (S.hasClausesOfKind<OMPDependClause>()) {
6050 assert(!S.hasAssociatedStmt() &&
6051 "No associated statement must be in ordered depend construct.");
6052 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
6054 return;
6055 }
6056 if (S.hasClausesOfKind<OMPDoacrossClause>()) {
6057 assert(!S.hasAssociatedStmt() &&
6058 "No associated statement must be in ordered doacross construct.");
6059 for (const auto *DC : S.getClausesOfKind<OMPDoacrossClause>())
6061 return;
6062 }
6063 const auto *C = S.getSingleClause<OMPSIMDClause>();
6064 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
6065 PrePostActionTy &Action) {
6066 const CapturedStmt *CS = S.getInnermostCapturedStmt();
6067 if (C) {
6069 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
6070 llvm::Function *OutlinedFn =
6071 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
6072 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
6073 OutlinedFn, CapturedVars);
6074 } else {
6075 Action.Enter(CGF);
6076 CGF.EmitStmt(CS->getCapturedStmt());
6077 }
6078 };
6079 OMPLexicalScope Scope(*this, S, OMPD_unknown);
6080 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
6081}
6082
6083static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
6084 QualType SrcType, QualType DestType,
6086 assert(CGF.hasScalarEvaluationKind(DestType) &&
6087 "DestType must have scalar evaluation kind.");
6088 assert(!Val.isAggregate() && "Must be a scalar or complex.");
6089 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
6090 DestType, Loc)
6092 Val.getComplexVal(), SrcType, DestType, Loc);
6093}
6094
6097 QualType DestType, SourceLocation Loc) {
6098 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
6099 "DestType must have complex evaluation kind.");
6101 if (Val.isScalar()) {
6102 // Convert the input element to the element type of the complex.
6103 QualType DestElementType =
6104 DestType->castAs<ComplexType>()->getElementType();
6105 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
6106 Val.getScalarVal(), SrcType, DestElementType, Loc);
6107 ComplexVal = CodeGenFunction::ComplexPairTy(
6108 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
6109 } else {
6110 assert(Val.isComplex() && "Must be a scalar or complex.");
6111 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
6112 QualType DestElementType =
6113 DestType->castAs<ComplexType>()->getElementType();
6114 ComplexVal.first = CGF.EmitScalarConversion(
6115 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
6116 ComplexVal.second = CGF.EmitScalarConversion(
6117 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
6118 }
6119 return ComplexVal;
6120}
6121
6122static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
6123 LValue LVal, RValue RVal) {
6124 if (LVal.isGlobalReg())
6125 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
6126 else
6127 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false);
6128}
6129
6131 llvm::AtomicOrdering AO, LValue LVal,
6133 if (LVal.isGlobalReg())
6134 return CGF.EmitLoadOfLValue(LVal, Loc);
6135 return CGF.EmitAtomicLoad(
6136 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO),
6137 LVal.isVolatile());
6138}
6139
6141 QualType RValTy, SourceLocation Loc) {
6142 switch (getEvaluationKind(LVal.getType())) {
6143 case TEK_Scalar:
6145 *this, RVal, RValTy, LVal.getType(), Loc)),
6146 LVal);
6147 break;
6148 case TEK_Complex:
6150 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
6151 /*isInit=*/false);
6152 break;
6153 case TEK_Aggregate:
6154 llvm_unreachable("Must be a scalar or complex.");
6155 }
6156}
6157
6158static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
6159 const Expr *X, const Expr *V,
6161 // v = x;
6162 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
6163 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
6164 LValue XLValue = CGF.EmitLValue(X);
6165 LValue VLValue = CGF.EmitLValue(V);
6166 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc);
6167 // OpenMP, 2.17.7, atomic Construct
6168 // If the read or capture clause is specified and the acquire, acq_rel, or
6169 // seq_cst clause is specified then the strong flush on exit from the atomic
6170 // operation is also an acquire flush.
6171 switch (AO) {
6172 case llvm::AtomicOrdering::Acquire:
6173 case llvm::AtomicOrdering::AcquireRelease:
6174 case llvm::AtomicOrdering::SequentiallyConsistent:
6175 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
6176 llvm::AtomicOrdering::Acquire);
6177 break;
6178 case llvm::AtomicOrdering::Monotonic:
6179 case llvm::AtomicOrdering::Release:
6180 break;
6181 case llvm::AtomicOrdering::NotAtomic:
6182 case llvm::AtomicOrdering::Unordered:
6183 llvm_unreachable("Unexpected ordering.");
6184 }
6185 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
6187}
6188
6190 llvm::AtomicOrdering AO, const Expr *X,
6191 const Expr *E, SourceLocation Loc) {
6192 // x = expr;
6193 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
6194 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
6196 // OpenMP, 2.17.7, atomic Construct
6197 // If the write, update, or capture clause is specified and the release,
6198 // acq_rel, or seq_cst clause is specified then the strong flush on entry to
6199 // the atomic operation is also a release flush.
6200 switch (AO) {
6201 case llvm::AtomicOrdering::Release:
6202 case llvm::AtomicOrdering::AcquireRelease:
6203 case llvm::AtomicOrdering::SequentiallyConsistent:
6204 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
6205 llvm::AtomicOrdering::Release);
6206 break;
6207 case llvm::AtomicOrdering::Acquire:
6208 case llvm::AtomicOrdering::Monotonic:
6209 break;
6210 case llvm::AtomicOrdering::NotAtomic:
6211 case llvm::AtomicOrdering::Unordered:
6212 llvm_unreachable("Unexpected ordering.");
6213 }
6214}
6215
6216static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
6217 RValue Update,
6219 llvm::AtomicOrdering AO,
6220 bool IsXLHSInRHSPart) {
6221 ASTContext &Context = CGF.getContext();
6222 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
6223 // expression is simple and atomic is allowed for the given type for the
6224 // target platform.
6225 if (BO == BO_Comma || !Update.isScalar() || !X.isSimple() ||
6226 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
6227 (Update.getScalarVal()->getType() != X.getAddress().getElementType())) ||
6229 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
6230 return std::make_pair(false, RValue::get(nullptr));
6231
6232 auto &&CheckAtomicSupport = [&CGF](llvm::Type *T, BinaryOperatorKind BO) {
6233 if (T->isIntegerTy())
6234 return true;
6235
6236 if (T->isFloatingPointTy() && (BO == BO_Add || BO == BO_Sub))
6237 return llvm::isPowerOf2_64(CGF.CGM.getDataLayout().getTypeStoreSize(T));
6238
6239 return false;
6240 };
6241
6242 if (!CheckAtomicSupport(Update.getScalarVal()->getType(), BO) ||
6243 !CheckAtomicSupport(X.getAddress().getElementType(), BO))
6244 return std::make_pair(false, RValue::get(nullptr));
6245
6246 bool IsInteger = X.getAddress().getElementType()->isIntegerTy();
6247 llvm::AtomicRMWInst::BinOp RMWOp;
6248 switch (BO) {
6249 case BO_Add:
6250 RMWOp = IsInteger ? llvm::AtomicRMWInst::Add : llvm::AtomicRMWInst::FAdd;
6251 break;
6252 case BO_Sub:
6253 if (!IsXLHSInRHSPart)
6254 return std::make_pair(false, RValue::get(nullptr));
6255 RMWOp = IsInteger ? llvm::AtomicRMWInst::Sub : llvm::AtomicRMWInst::FSub;
6256 break;
6257 case BO_And:
6258 RMWOp = llvm::AtomicRMWInst::And;
6259 break;
6260 case BO_Or:
6261 RMWOp = llvm::AtomicRMWInst::Or;
6262 break;
6263 case BO_Xor:
6264 RMWOp = llvm::AtomicRMWInst::Xor;
6265 break;
6266 case BO_LT:
6267 if (IsInteger)
6268 RMWOp = X.getType()->hasSignedIntegerRepresentation()
6269 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
6270 : llvm::AtomicRMWInst::Max)
6271 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
6272 : llvm::AtomicRMWInst::UMax);
6273 else
6274 RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMin
6275 : llvm::AtomicRMWInst::FMax;
6276 break;
6277 case BO_GT:
6278 if (IsInteger)
6279 RMWOp = X.getType()->hasSignedIntegerRepresentation()
6280 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
6281 : llvm::AtomicRMWInst::Min)
6282 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
6283 : llvm::AtomicRMWInst::UMin);
6284 else
6285 RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMax
6286 : llvm::AtomicRMWInst::FMin;
6287 break;
6288 case BO_Assign:
6289 RMWOp = llvm::AtomicRMWInst::Xchg;
6290 break;
6291 case BO_Mul:
6292 case BO_Div:
6293 case BO_Rem:
6294 case BO_Shl:
6295 case BO_Shr:
6296 case BO_LAnd:
6297 case BO_LOr:
6298 return std::make_pair(false, RValue::get(nullptr));
6299 case BO_PtrMemD:
6300 case BO_PtrMemI:
6301 case BO_LE:
6302 case BO_GE:
6303 case BO_EQ:
6304 case BO_NE:
6305 case BO_Cmp:
6306 case BO_AddAssign:
6307 case BO_SubAssign:
6308 case BO_AndAssign:
6309 case BO_OrAssign:
6310 case BO_XorAssign:
6311 case BO_MulAssign:
6312 case BO_DivAssign:
6313 case BO_RemAssign:
6314 case BO_ShlAssign:
6315 case BO_ShrAssign:
6316 case BO_Comma:
6317 llvm_unreachable("Unsupported atomic update operation");
6318 }
6319 llvm::Value *UpdateVal = Update.getScalarVal();
6320 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
6321 if (IsInteger)
6322 UpdateVal = CGF.Builder.CreateIntCast(
6323 IC, X.getAddress().getElementType(),
6324 X.getType()->hasSignedIntegerRepresentation());
6325 else
6326 UpdateVal = CGF.Builder.CreateCast(llvm::Instruction::CastOps::UIToFP, IC,
6327 X.getAddress().getElementType());
6328 }
6329 llvm::AtomicRMWInst *Res =
6330 CGF.emitAtomicRMWInst(RMWOp, X.getAddress(), UpdateVal, AO);
6331 return std::make_pair(true, RValue::get(Res));
6332}
6333
6335 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
6336 llvm::AtomicOrdering AO, SourceLocation Loc,
6337 const llvm::function_ref<RValue(RValue)> CommonGen) {
6338 // Update expressions are allowed to have the following forms:
6339 // x binop= expr; -> xrval + expr;
6340 // x++, ++x -> xrval + 1;
6341 // x--, --x -> xrval - 1;
6342 // x = x binop expr; -> xrval binop expr
6343 // x = expr Op x; - > expr binop xrval;
6344 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
6345 if (!Res.first) {
6346 if (X.isGlobalReg()) {
6347 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
6348 // 'xrval'.
6350 } else {
6351 // Perform compare-and-swap procedure.
6352 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
6353 }
6354 }
6355 return Res;
6356}
6357
6359 llvm::AtomicOrdering AO, const Expr *X,
6360 const Expr *E, const Expr *UE,
6361 bool IsXLHSInRHSPart, SourceLocation Loc) {
6362 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
6363 "Update expr in 'atomic update' must be a binary operator.");
6364 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
6365 // Update expressions are allowed to have the following forms:
6366 // x binop= expr; -> xrval + expr;
6367 // x++, ++x -> xrval + 1;
6368 // x--, --x -> xrval - 1;
6369 // x = x binop expr; -> xrval binop expr
6370 // x = expr Op x; - > expr binop xrval;
6371 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
6372 LValue XLValue = CGF.EmitLValue(X);
6373 RValue ExprRValue = CGF.EmitAnyExpr(E);
6374 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
6375 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
6376 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
6377 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
6378 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
6379 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
6380 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
6381 return CGF.EmitAnyExpr(UE);
6382 };
6384 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
6386 // OpenMP, 2.17.7, atomic Construct
6387 // If the write, update, or capture clause is specified and the release,
6388 // acq_rel, or seq_cst clause is specified then the strong flush on entry to
6389 // the atomic operation is also a release flush.
6390 switch (AO) {
6391 case llvm::AtomicOrdering::Release:
6392 case llvm::AtomicOrdering::AcquireRelease:
6393 case llvm::AtomicOrdering::SequentiallyConsistent:
6394 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
6395 llvm::AtomicOrdering::Release);
6396 break;
6397 case llvm::AtomicOrdering::Acquire:
6398 case llvm::AtomicOrdering::Monotonic:
6399 break;
6400 case llvm::AtomicOrdering::NotAtomic:
6401 case llvm::AtomicOrdering::Unordered:
6402 llvm_unreachable("Unexpected ordering.");
6403 }
6404}
6405
6407 QualType SourceType, QualType ResType,
6409 switch (CGF.getEvaluationKind(ResType)) {
6410 case TEK_Scalar:
6411 return RValue::get(
6412 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
6413 case TEK_Complex: {
6414 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
6415 return RValue::getComplex(Res.first, Res.second);
6416 }
6417 case TEK_Aggregate:
6418 break;
6419 }
6420 llvm_unreachable("Must be a scalar or complex.");
6421}
6422
6424 llvm::AtomicOrdering AO,
6425 bool IsPostfixUpdate, const Expr *V,
6426 const Expr *X, const Expr *E,
6427 const Expr *UE, bool IsXLHSInRHSPart,
6429 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
6430 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
6431 RValue NewVVal;
6432 LValue VLValue = CGF.EmitLValue(V);
6433 LValue XLValue = CGF.EmitLValue(X);
6434 RValue ExprRValue = CGF.EmitAnyExpr(E);
6435 QualType NewVValType;
6436 if (UE) {
6437 // 'x' is updated with some additional value.
6438 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
6439 "Update expr in 'atomic capture' must be a binary operator.");
6440 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
6441 // Update expressions are allowed to have the following forms:
6442 // x binop= expr; -> xrval + expr;
6443 // x++, ++x -> xrval + 1;
6444 // x--, --x -> xrval - 1;
6445 // x = x binop expr; -> xrval binop expr
6446 // x = expr Op x; - > expr binop xrval;
6447 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
6448 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
6449 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
6450 NewVValType = XRValExpr->getType();
6451 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
6452 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
6453 IsPostfixUpdate](RValue XRValue) {
6454 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
6455 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
6456 RValue Res = CGF.EmitAnyExpr(UE);
6457 NewVVal = IsPostfixUpdate ? XRValue : Res;
6458 return Res;
6459 };
6460 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
6461 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
6463 if (Res.first) {
6464 // 'atomicrmw' instruction was generated.
6465 if (IsPostfixUpdate) {
6466 // Use old value from 'atomicrmw'.
6467 NewVVal = Res.second;
6468 } else {
6469 // 'atomicrmw' does not provide new value, so evaluate it using old
6470 // value of 'x'.
6471 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
6472 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
6473 NewVVal = CGF.EmitAnyExpr(UE);
6474 }
6475 }
6476 } else {
6477 // 'x' is simply rewritten with some 'expr'.
6478 NewVValType = X->getType().getNonReferenceType();
6479 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
6480 X->getType().getNonReferenceType(), Loc);
6481 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
6482 NewVVal = XRValue;
6483 return ExprRValue;
6484 };
6485 // Try to perform atomicrmw xchg, otherwise simple exchange.
6486 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
6487 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
6488 Loc, Gen);
6490 if (Res.first) {
6491 // 'atomicrmw' instruction was generated.
6492 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
6493 }
6494 }
6495 // Emit post-update store to 'v' of old/new 'x' value.
6496 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
6498 // OpenMP 5.1 removes the required flush for capture clause.
6499 if (CGF.CGM.getLangOpts().OpenMP < 51) {
6500 // OpenMP, 2.17.7, atomic Construct
6501 // If the write, update, or capture clause is specified and the release,
6502 // acq_rel, or seq_cst clause is specified then the strong flush on entry to
6503 // the atomic operation is also a release flush.
6504 // If the read or capture clause is specified and the acquire, acq_rel, or
6505 // seq_cst clause is specified then the strong flush on exit from the atomic
6506 // operation is also an acquire flush.
6507 switch (AO) {
6508 case llvm::AtomicOrdering::Release:
6509 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
6510 llvm::AtomicOrdering::Release);
6511 break;
6512 case llvm::AtomicOrdering::Acquire:
6513 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
6514 llvm::AtomicOrdering::Acquire);
6515 break;
6516 case llvm::AtomicOrdering::AcquireRelease:
6517 case llvm::AtomicOrdering::SequentiallyConsistent:
6519 CGF, std::nullopt, Loc, llvm::AtomicOrdering::AcquireRelease);
6520 break;
6521 case llvm::AtomicOrdering::Monotonic:
6522 break;
6523 case llvm::AtomicOrdering::NotAtomic:
6524 case llvm::AtomicOrdering::Unordered:
6525 llvm_unreachable("Unexpected ordering.");
6526 }
6527 }
6528}
6529
6531 CodeGenFunction &CGF, llvm::AtomicOrdering AO, llvm::AtomicOrdering FailAO,
6532 const Expr *X, const Expr *V, const Expr *R, const Expr *E, const Expr *D,
6533 const Expr *CE, bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly,
6535 llvm::OpenMPIRBuilder &OMPBuilder =
6537
6538 OMPAtomicCompareOp Op;
6539 assert(isa<BinaryOperator>(CE) && "CE is not a BinaryOperator");
6540 switch (cast<BinaryOperator>(CE)->getOpcode()) {
6541 case BO_EQ:
6542 Op = OMPAtomicCompareOp::EQ;
6543 break;
6544 case BO_LT:
6545 Op = OMPAtomicCompareOp::MIN;
6546 break;
6547 case BO_GT:
6548 Op = OMPAtomicCompareOp::MAX;
6549 break;
6550 default:
6551 llvm_unreachable("unsupported atomic compare binary operator");
6552 }
6553
6554 LValue XLVal = CGF.EmitLValue(X);
6555 Address XAddr = XLVal.getAddress();
6556
6557 auto EmitRValueWithCastIfNeeded = [&CGF, Loc](const Expr *X, const Expr *E) {
6558 if (X->getType() == E->getType())
6559 return CGF.EmitScalarExpr(E);
6560 const Expr *NewE = E->IgnoreImplicitAsWritten();
6561 llvm::Value *V = CGF.EmitScalarExpr(NewE);
6562 if (NewE->getType() == X->getType())
6563 return V;
6564 return CGF.EmitScalarConversion(V, NewE->getType(), X->getType(), Loc);
6565 };
6566
6567 llvm::Value *EVal = EmitRValueWithCastIfNeeded(X, E);
6568 llvm::Value *DVal = D ? EmitRValueWithCastIfNeeded(X, D) : nullptr;
6569 if (auto *CI = dyn_cast<llvm::ConstantInt>(EVal))
6570 EVal = CGF.Builder.CreateIntCast(
6571 CI, XLVal.getAddress().getElementType(),
6573 if (DVal)
6574 if (auto *CI = dyn_cast<llvm::ConstantInt>(DVal))
6575 DVal = CGF.Builder.CreateIntCast(
6576 CI, XLVal.getAddress().getElementType(),
6577 D->getType()->hasSignedIntegerRepresentation());
6578
6579 llvm::OpenMPIRBuilder::AtomicOpValue XOpVal{
6580 XAddr.emitRawPointer(CGF), XAddr.getElementType(),
6581 X->getType()->hasSignedIntegerRepresentation(),
6582 X->getType().isVolatileQualified()};
6583 llvm::OpenMPIRBuilder::AtomicOpValue VOpVal, ROpVal;
6584 if (V) {
6585 LValue LV = CGF.EmitLValue(V);
6586 Address Addr = LV.getAddress();
6587 VOpVal = {Addr.emitRawPointer(CGF), Addr.getElementType(),
6588 V->getType()->hasSignedIntegerRepresentation(),
6589 V->getType().isVolatileQualified()};
6590 }
6591 if (R) {
6592 LValue LV = CGF.EmitLValue(R);
6593 Address Addr = LV.getAddress();
6594 ROpVal = {Addr.emitRawPointer(CGF), Addr.getElementType(),
6597 }
6598
6599 if (FailAO == llvm::AtomicOrdering::NotAtomic) {
6600 // fail clause was not mentioned on the
6601 // "#pragma omp atomic compare" construct.
6602 CGF.Builder.restoreIP(OMPBuilder.createAtomicCompare(
6603 CGF.Builder, XOpVal, VOpVal, ROpVal, EVal, DVal, AO, Op, IsXBinopExpr,
6604 IsPostfixUpdate, IsFailOnly));
6605 } else
6606 CGF.Builder.restoreIP(OMPBuilder.createAtomicCompare(
6607 CGF.Builder, XOpVal, VOpVal, ROpVal, EVal, DVal, AO, Op, IsXBinopExpr,
6608 IsPostfixUpdate, IsFailOnly, FailAO));
6609}
6610
6612 llvm::AtomicOrdering AO,
6613 llvm::AtomicOrdering FailAO, bool IsPostfixUpdate,
6614 const Expr *X, const Expr *V, const Expr *R,
6615 const Expr *E, const Expr *UE, const Expr *D,
6616 const Expr *CE, bool IsXLHSInRHSPart,
6617 bool IsFailOnly, SourceLocation Loc) {
6618 switch (Kind) {
6619 case OMPC_read:
6620 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc);
6621 break;
6622 case OMPC_write:
6623 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc);
6624 break;
6625 case OMPC_unknown:
6626 case OMPC_update:
6627 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc);
6628 break;
6629 case OMPC_capture:
6630 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE,
6631 IsXLHSInRHSPart, Loc);
6632 break;
6633 case OMPC_compare: {
6634 emitOMPAtomicCompareExpr(CGF, AO, FailAO, X, V, R, E, D, CE,
6635 IsXLHSInRHSPart, IsPostfixUpdate, IsFailOnly, Loc);
6636 break;
6637 }
6638 default:
6639 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
6640 }
6641}
6642
6644 llvm::AtomicOrdering AO = CGM.getOpenMPRuntime().getDefaultMemoryOrdering();
6645 // Fail Memory Clause Ordering.
6646 llvm::AtomicOrdering FailAO = llvm::AtomicOrdering::NotAtomic;
6647 bool MemOrderingSpecified = false;
6648 if (S.getSingleClause<OMPSeqCstClause>()) {
6649 AO = llvm::AtomicOrdering::SequentiallyConsistent;
6650 MemOrderingSpecified = true;
6651 } else if (S.getSingleClause<OMPAcqRelClause>()) {
6652 AO = llvm::AtomicOrdering::AcquireRelease;
6653 MemOrderingSpecified = true;
6654 } else if (S.getSingleClause<OMPAcquireClause>()) {
6655 AO = llvm::AtomicOrdering::Acquire;
6656 MemOrderingSpecified = true;
6657 } else if (S.getSingleClause<OMPReleaseClause>()) {
6658 AO = llvm::AtomicOrdering::Release;
6659 MemOrderingSpecified = true;
6660 } else if (S.getSingleClause<OMPRelaxedClause>()) {
6661 AO = llvm::AtomicOrdering::Monotonic;
6662 MemOrderingSpecified = true;
6663 }
6664 llvm::SmallSet<OpenMPClauseKind, 2> KindsEncountered;
6665 OpenMPClauseKind Kind = OMPC_unknown;
6666 for (const OMPClause *C : S.clauses()) {
6667 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause,
6668 // if it is first).
6669 OpenMPClauseKind K = C->getClauseKind();
6670 // TBD
6671 if (K == OMPC_weak)
6672 return;
6673 if (K == OMPC_seq_cst || K == OMPC_acq_rel || K == OMPC_acquire ||
6674 K == OMPC_release || K == OMPC_relaxed || K == OMPC_hint)
6675 continue;
6676 Kind = K;
6677 KindsEncountered.insert(K);
6678 }
6679 // We just need to correct Kind here. No need to set a bool saying it is
6680 // actually compare capture because we can tell from whether V and R are
6681 // nullptr.
6682 if (KindsEncountered.contains(OMPC_compare) &&
6683 KindsEncountered.contains(OMPC_capture))
6684 Kind = OMPC_compare;
6685 if (!MemOrderingSpecified) {
6686 llvm::AtomicOrdering DefaultOrder =
6688 if (DefaultOrder == llvm::AtomicOrdering::Monotonic ||
6689 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent ||
6690 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease &&
6691 Kind == OMPC_capture)) {
6692 AO = DefaultOrder;
6693 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) {
6694 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) {
6695 AO = llvm::AtomicOrdering::Release;
6696 } else if (Kind == OMPC_read) {
6697 assert(Kind == OMPC_read && "Unexpected atomic kind.");
6698 AO = llvm::AtomicOrdering::Acquire;
6699 }
6700 }
6701 }
6702
6703 if (KindsEncountered.contains(OMPC_compare) &&
6704 KindsEncountered.contains(OMPC_fail)) {
6705 Kind = OMPC_compare;
6706 const auto *FailClause = S.getSingleClause<OMPFailClause>();
6707 if (FailClause) {
6708 OpenMPClauseKind FailParameter = FailClause->getFailParameter();
6709 if (FailParameter == llvm::omp::OMPC_relaxed)
6710 FailAO = llvm::AtomicOrdering::Monotonic;
6711 else if (FailParameter == llvm::omp::OMPC_acquire)
6712 FailAO = llvm::AtomicOrdering::Acquire;
6713 else if (FailParameter == llvm::omp::OMPC_seq_cst)
6714 FailAO = llvm::AtomicOrdering::SequentiallyConsistent;
6715 }
6716 }
6717
6718 LexicalScope Scope(*this, S.getSourceRange());
6719 EmitStopPoint(S.getAssociatedStmt());
6720 emitOMPAtomicExpr(*this, Kind, AO, FailAO, S.isPostfixUpdate(), S.getX(),
6721 S.getV(), S.getR(), S.getExpr(), S.getUpdateExpr(),
6722 S.getD(), S.getCondExpr(), S.isXLHSInRHSPart(),
6723 S.isFailOnly(), S.getBeginLoc());
6724}
6725
6727 const OMPExecutableDirective &S,
6728 const RegionCodeGenTy &CodeGen) {
6729 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
6730 CodeGenModule &CGM = CGF.CGM;
6731
6732 // On device emit this construct as inlined code.
6733 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
6734 OMPLexicalScope Scope(CGF, S, OMPD_target);
6736 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6737 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
6738 });
6739 return;
6740 }
6741
6743 llvm::Function *Fn = nullptr;
6744 llvm::Constant *FnID = nullptr;
6745
6746 const Expr *IfCond = nullptr;
6747 // Check for the at most one if clause associated with the target region.
6748 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
6749 if (C->getNameModifier() == OMPD_unknown ||
6750 C->getNameModifier() == OMPD_target) {
6751 IfCond = C->getCondition();
6752 break;
6753 }
6754 }
6755
6756 // Check if we have any device clause associated with the directive.
6757 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device(
6758 nullptr, OMPC_DEVICE_unknown);
6759 if (auto *C = S.getSingleClause<OMPDeviceClause>())
6760 Device.setPointerAndInt(C->getDevice(), C->getModifier());
6761
6762 // Check if we have an if clause whose conditional always evaluates to false
6763 // or if we do not have any targets specified. If so the target region is not
6764 // an offload entry point.
6765 bool IsOffloadEntry = true;
6766 if (IfCond) {
6767 bool Val;
6768 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
6769 IsOffloadEntry = false;
6770 }
6771 if (CGM.getLangOpts().OMPTargetTriples.empty())
6772 IsOffloadEntry = false;
6773
6774 if (CGM.getLangOpts().OpenMPOffloadMandatory && !IsOffloadEntry) {
6775 unsigned DiagID = CGM.getDiags().getCustomDiagID(
6777 "No offloading entry generated while offloading is mandatory.");
6778 CGM.getDiags().Report(DiagID);
6779 }
6780
6781 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
6782 StringRef ParentName;
6783 // In case we have Ctors/Dtors we use the complete type variant to produce
6784 // the mangling of the device outlined kernel.
6785 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
6787 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
6789 else
6790 ParentName =
6791 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
6792
6793 // Emit target region as a standalone region.
6794 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
6795 IsOffloadEntry, CodeGen);
6796 OMPLexicalScope Scope(CGF, S, OMPD_task);
6797 auto &&SizeEmitter =
6798 [IsOffloadEntry](CodeGenFunction &CGF,
6799 const OMPLoopDirective &D) -> llvm::Value * {
6800 if (IsOffloadEntry) {
6801 OMPLoopScope(CGF, D);
6802 // Emit calculation of the iterations count.
6803 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
6804 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
6805 /*isSigned=*/false);
6806 return NumIterations;
6807 }
6808 return nullptr;
6809 };
6810 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
6811 SizeEmitter);
6812}
6813
6815 PrePostActionTy &Action) {
6816 Action.Enter(CGF);
6817 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6818 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6819 CGF.EmitOMPPrivateClause(S, PrivateScope);
6820 (void)PrivateScope.Privatize();
6821 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6823
6824 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
6825 CGF.EnsureInsertPoint();
6826}
6827
6829 StringRef ParentName,
6830 const OMPTargetDirective &S) {
6831 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6832 emitTargetRegion(CGF, S, Action);
6833 };
6834 llvm::Function *Fn;
6835 llvm::Constant *Addr;
6836 // Emit target region as a standalone region.
6838 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6839 assert(Fn && Addr && "Target device function emission failed.");
6840}
6841
6843 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6844 emitTargetRegion(CGF, S, Action);
6845 };
6846 emitCommonOMPTargetDirective(*this, S, CodeGen);
6847}
6848
6850 const OMPExecutableDirective &S,
6851 OpenMPDirectiveKind InnermostKind,
6852 const RegionCodeGenTy &CodeGen) {
6853 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
6854 llvm::Function *OutlinedFn =
6856 CGF, S, *CS->getCapturedDecl()->param_begin(), InnermostKind,
6857 CodeGen);
6858
6859 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
6860 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
6861 if (NT || TL) {
6862 const Expr *NumTeams = NT ? NT->getNumTeams().front() : nullptr;
6863 const Expr *ThreadLimit = TL ? TL->getThreadLimit().front() : nullptr;
6864
6865 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
6866 S.getBeginLoc());
6867 }
6868
6869 OMPTeamsScope Scope(CGF, S);
6871 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
6872 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
6873 CapturedVars);
6874}
6875
6877 // Emit teams region as a standalone region.
6878 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6879 Action.Enter(CGF);
6880 OMPPrivateScope PrivateScope(CGF);
6881 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6882 CGF.EmitOMPPrivateClause(S, PrivateScope);
6883 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6884 (void)PrivateScope.Privatize();
6885 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
6886 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6887 };
6888 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
6890 [](CodeGenFunction &) { return nullptr; });
6891}
6892
6894 const OMPTargetTeamsDirective &S) {
6895 auto *CS = S.getCapturedStmt(OMPD_teams);
6896 Action.Enter(CGF);
6897 // Emit teams region as a standalone region.
6898 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
6899 Action.Enter(CGF);
6900 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6901 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6902 CGF.EmitOMPPrivateClause(S, PrivateScope);
6903 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6904 (void)PrivateScope.Privatize();
6905 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6907 CGF.EmitStmt(CS->getCapturedStmt());
6908 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6909 };
6910 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
6912 [](CodeGenFunction &) { return nullptr; });
6913}
6914
6916 CodeGenModule &CGM, StringRef ParentName,
6917 const OMPTargetTeamsDirective &S) {
6918 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6919 emitTargetTeamsRegion(CGF, Action, S);
6920 };
6921 llvm::Function *Fn;
6922 llvm::Constant *Addr;
6923 // Emit target region as a standalone region.
6925 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6926 assert(Fn && Addr && "Target device function emission failed.");
6927}
6928
6930 const OMPTargetTeamsDirective &S) {
6931 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6932 emitTargetTeamsRegion(CGF, Action, S);
6933 };
6934 emitCommonOMPTargetDirective(*this, S, CodeGen);
6935}
6936
6937static void
6940 Action.Enter(CGF);
6941 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6943 };
6944
6945 // Emit teams region as a standalone region.
6946 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6947 PrePostActionTy &Action) {
6948 Action.Enter(CGF);
6949 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6950 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6951 (void)PrivateScope.Privatize();
6952 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6953 CodeGenDistribute);
6954 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6955 };
6956 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
6958 [](CodeGenFunction &) { return nullptr; });
6959}
6960
6962 CodeGenModule &CGM, StringRef ParentName,
6964 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6965 emitTargetTeamsDistributeRegion(CGF, Action, S);
6966 };
6967 llvm::Function *Fn;
6968 llvm::Constant *Addr;
6969 // Emit target region as a standalone region.
6971 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6972 assert(Fn && Addr && "Target device function emission failed.");
6973}
6974
6977 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6978 emitTargetTeamsDistributeRegion(CGF, Action, S);
6979 };
6980 emitCommonOMPTargetDirective(*this, S, CodeGen);
6981}
6982
6984 CodeGenFunction &CGF, PrePostActionTy &Action,
6986 Action.Enter(CGF);
6987 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6989 };
6990
6991 // Emit teams region as a standalone region.
6992 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6993 PrePostActionTy &Action) {
6994 Action.Enter(CGF);
6995 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6996 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6997 (void)PrivateScope.Privatize();
6998 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6999 CodeGenDistribute);
7000 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7001 };
7002 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
7004 [](CodeGenFunction &) { return nullptr; });
7005}
7006
7008 CodeGenModule &CGM, StringRef ParentName,
7010 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7012 };
7013 llvm::Function *Fn;
7014 llvm::Constant *Addr;
7015 // Emit target region as a standalone region.
7017 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7018 assert(Fn && Addr && "Target device function emission failed.");
7019}
7020
7023 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7025 };
7026 emitCommonOMPTargetDirective(*this, S, CodeGen);
7027}
7028
7030 const OMPTeamsDistributeDirective &S) {
7031
7032 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7034 };
7035
7036 // Emit teams region as a standalone region.
7037 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7038 PrePostActionTy &Action) {
7039 Action.Enter(CGF);
7040 OMPPrivateScope PrivateScope(CGF);
7041 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7042 (void)PrivateScope.Privatize();
7043 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
7044 CodeGenDistribute);
7045 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7046 };
7047 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
7049 [](CodeGenFunction &) { return nullptr; });
7050}
7051
7054 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7056 };
7057
7058 // Emit teams region as a standalone region.
7059 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7060 PrePostActionTy &Action) {
7061 Action.Enter(CGF);
7062 OMPPrivateScope PrivateScope(CGF);
7063 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7064 (void)PrivateScope.Privatize();
7065 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
7066 CodeGenDistribute);
7067 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7068 };
7069 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
7071 [](CodeGenFunction &) { return nullptr; });
7072}
7073
7076 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7078 S.getDistInc());
7079 };
7080
7081 // Emit teams region as a standalone region.
7082 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7083 PrePostActionTy &Action) {
7084 Action.Enter(CGF);
7085 OMPPrivateScope PrivateScope(CGF);
7086 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7087 (void)PrivateScope.Privatize();
7088 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
7089 CodeGenDistribute);
7090 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7091 };
7092 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
7094 [](CodeGenFunction &) { return nullptr; });
7095}
7096
7099 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7101 S.getDistInc());
7102 };
7103
7104 // Emit teams region as a standalone region.
7105 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7106 PrePostActionTy &Action) {
7107 Action.Enter(CGF);
7108 OMPPrivateScope PrivateScope(CGF);
7109 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7110 (void)PrivateScope.Privatize();
7111 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
7112 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
7113 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7114 };
7115 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
7116 CodeGen);
7118 [](CodeGenFunction &) { return nullptr; });
7119}
7120
7122 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
7123 llvm::Value *Device = nullptr;
7124 llvm::Value *NumDependences = nullptr;
7125 llvm::Value *DependenceList = nullptr;
7126
7127 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7128 Device = EmitScalarExpr(C->getDevice());
7129
7130 // Build list and emit dependences
7133 if (!Data.Dependences.empty()) {
7134 Address DependenciesArray = Address::invalid();
7135 std::tie(NumDependences, DependenciesArray) =
7136 CGM.getOpenMPRuntime().emitDependClause(*this, Data.Dependences,
7137 S.getBeginLoc());
7138 DependenceList = DependenciesArray.emitRawPointer(*this);
7139 }
7140 Data.HasNowaitClause = S.hasClausesOfKind<OMPNowaitClause>();
7141
7142 assert(!(Data.HasNowaitClause && !(S.getSingleClause<OMPInitClause>() ||
7143 S.getSingleClause<OMPDestroyClause>() ||
7144 S.getSingleClause<OMPUseClause>())) &&
7145 "OMPNowaitClause clause is used separately in OMPInteropDirective.");
7146
7147 auto ItOMPInitClause = S.getClausesOfKind<OMPInitClause>();
7148 if (!ItOMPInitClause.empty()) {
7149 // Look at the multiple init clauses
7150 for (const OMPInitClause *C : ItOMPInitClause) {
7151 llvm::Value *InteropvarPtr =
7152 EmitLValue(C->getInteropVar()).getPointer(*this);
7153 llvm::omp::OMPInteropType InteropType =
7154 llvm::omp::OMPInteropType::Unknown;
7155 if (C->getIsTarget()) {
7156 InteropType = llvm::omp::OMPInteropType::Target;
7157 } else {
7158 assert(C->getIsTargetSync() &&
7159 "Expected interop-type target/targetsync");
7160 InteropType = llvm::omp::OMPInteropType::TargetSync;
7161 }
7162 OMPBuilder.createOMPInteropInit(Builder, InteropvarPtr, InteropType,
7163 Device, NumDependences, DependenceList,
7164 Data.HasNowaitClause);
7165 }
7166 }
7167 auto ItOMPDestroyClause = S.getClausesOfKind<OMPDestroyClause>();
7168 if (!ItOMPDestroyClause.empty()) {
7169 // Look at the multiple destroy clauses
7170 for (const OMPDestroyClause *C : ItOMPDestroyClause) {
7171 llvm::Value *InteropvarPtr =
7172 EmitLValue(C->getInteropVar()).getPointer(*this);
7173 OMPBuilder.createOMPInteropDestroy(Builder, InteropvarPtr, Device,
7174 NumDependences, DependenceList,
7175 Data.HasNowaitClause);
7176 }
7177 }
7178 auto ItOMPUseClause = S.getClausesOfKind<OMPUseClause>();
7179 if (!ItOMPUseClause.empty()) {
7180 // Look at the multiple use clauses
7181 for (const OMPUseClause *C : ItOMPUseClause) {
7182 llvm::Value *InteropvarPtr =
7183 EmitLValue(C->getInteropVar()).getPointer(*this);
7184 OMPBuilder.createOMPInteropUse(Builder, InteropvarPtr, Device,
7185 NumDependences, DependenceList,
7186 Data.HasNowaitClause);
7187 }
7188 }
7189}
7190
7193 PrePostActionTy &Action) {
7194 Action.Enter(CGF);
7195 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7197 S.getDistInc());
7198 };
7199
7200 // Emit teams region as a standalone region.
7201 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7202 PrePostActionTy &Action) {
7203 Action.Enter(CGF);
7204 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7205 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7206 (void)PrivateScope.Privatize();
7208 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
7209 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7210 };
7211
7212 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
7213 CodeGenTeams);
7215 [](CodeGenFunction &) { return nullptr; });
7216}
7217
7219 CodeGenModule &CGM, StringRef ParentName,
7221 // Emit SPMD target teams distribute parallel for region as a standalone
7222 // region.
7223 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7225 };
7226 llvm::Function *Fn;
7227 llvm::Constant *Addr;
7228 // Emit target region as a standalone region.
7230 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7231 assert(Fn && Addr && "Target device function emission failed.");
7232}
7233
7236 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7238 };
7239 emitCommonOMPTargetDirective(*this, S, CodeGen);
7240}
7241
7243 CodeGenFunction &CGF,
7245 PrePostActionTy &Action) {
7246 Action.Enter(CGF);
7247 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7249 S.getDistInc());
7250 };
7251
7252 // Emit teams region as a standalone region.
7253 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
7254 PrePostActionTy &Action) {
7255 Action.Enter(CGF);
7256 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7257 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7258 (void)PrivateScope.Privatize();
7260 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
7261 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
7262 };
7263
7264 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
7265 CodeGenTeams);
7267 [](CodeGenFunction &) { return nullptr; });
7268}
7269
7271 CodeGenModule &CGM, StringRef ParentName,
7273 // Emit SPMD target teams distribute parallel for simd region as a standalone
7274 // region.
7275 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7277 };
7278 llvm::Function *Fn;
7279 llvm::Constant *Addr;
7280 // Emit target region as a standalone region.
7282 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7283 assert(Fn && Addr && "Target device function emission failed.");
7284}
7285
7288 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7290 };
7291 emitCommonOMPTargetDirective(*this, S, CodeGen);
7292}
7293
7296 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
7297 S.getCancelRegion());
7298}
7299
7301 const Expr *IfCond = nullptr;
7302 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
7303 if (C->getNameModifier() == OMPD_unknown ||
7304 C->getNameModifier() == OMPD_cancel) {
7305 IfCond = C->getCondition();
7306 break;
7307 }
7308 }
7309 if (CGM.getLangOpts().OpenMPIRBuilder) {
7310 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
7311 // TODO: This check is necessary as we only generate `omp parallel` through
7312 // the OpenMPIRBuilder for now.
7313 if (S.getCancelRegion() == OMPD_parallel ||
7314 S.getCancelRegion() == OMPD_sections ||
7315 S.getCancelRegion() == OMPD_section) {
7316 llvm::Value *IfCondition = nullptr;
7317 if (IfCond)
7318 IfCondition = EmitScalarExpr(IfCond,
7319 /*IgnoreResultAssign=*/true);
7320 return Builder.restoreIP(
7321 OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion()));
7322 }
7323 }
7324
7325 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
7326 S.getCancelRegion());
7327}
7328
7329CodeGenFunction::JumpDest
7331 if (Kind == OMPD_parallel || Kind == OMPD_task ||
7332 Kind == OMPD_target_parallel || Kind == OMPD_taskloop ||
7333 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop)
7334 return ReturnBlock;
7335 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
7336 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
7337 Kind == OMPD_distribute_parallel_for ||
7338 Kind == OMPD_target_parallel_for ||
7339 Kind == OMPD_teams_distribute_parallel_for ||
7340 Kind == OMPD_target_teams_distribute_parallel_for);
7341 return OMPCancelStack.getExitBlock();
7342}
7343
7345 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
7346 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
7347 CaptureDeviceAddrMap) {
7348 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
7349 for (const Expr *OrigVarIt : C.varlist()) {
7350 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(OrigVarIt)->getDecl());
7351 if (!Processed.insert(OrigVD).second)
7352 continue;
7353
7354 // In order to identify the right initializer we need to match the
7355 // declaration used by the mapping logic. In some cases we may get
7356 // OMPCapturedExprDecl that refers to the original declaration.
7357 const ValueDecl *MatchingVD = OrigVD;
7358 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
7359 // OMPCapturedExprDecl are used to privative fields of the current
7360 // structure.
7361 const auto *ME = cast<MemberExpr>(OED->getInit());
7362 assert(isa<CXXThisExpr>(ME->getBase()->IgnoreImpCasts()) &&
7363 "Base should be the current struct!");
7364 MatchingVD = ME->getMemberDecl();
7365 }
7366
7367 // If we don't have information about the current list item, move on to
7368 // the next one.
7369 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
7370 if (InitAddrIt == CaptureDeviceAddrMap.end())
7371 continue;
7372
7373 llvm::Type *Ty = ConvertTypeForMem(OrigVD->getType().getNonReferenceType());
7374
7375 // Return the address of the private variable.
7376 bool IsRegistered = PrivateScope.addPrivate(
7377 OrigVD,
7378 Address(InitAddrIt->second, Ty,
7379 getContext().getTypeAlignInChars(getContext().VoidPtrTy)));
7380 assert(IsRegistered && "firstprivate var already registered as private");
7381 // Silence the warning about unused variable.
7382 (void)IsRegistered;
7383 }
7384}
7385
7386static const VarDecl *getBaseDecl(const Expr *Ref) {
7387 const Expr *Base = Ref->IgnoreParenImpCasts();
7388 while (const auto *OASE = dyn_cast<ArraySectionExpr>(Base))
7389 Base = OASE->getBase()->IgnoreParenImpCasts();
7390 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base))
7391 Base = ASE->getBase()->IgnoreParenImpCasts();
7392 return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl());
7393}
7394
7396 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
7397 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
7398 CaptureDeviceAddrMap) {
7399 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
7400 for (const Expr *Ref : C.varlist()) {
7401 const VarDecl *OrigVD = getBaseDecl(Ref);
7402 if (!Processed.insert(OrigVD).second)
7403 continue;
7404 // In order to identify the right initializer we need to match the
7405 // declaration used by the mapping logic. In some cases we may get
7406 // OMPCapturedExprDecl that refers to the original declaration.
7407 const ValueDecl *MatchingVD = OrigVD;
7408 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
7409 // OMPCapturedExprDecl are used to privative fields of the current
7410 // structure.
7411 const auto *ME = cast<MemberExpr>(OED->getInit());
7412 assert(isa<CXXThisExpr>(ME->getBase()) &&
7413 "Base should be the current struct!");
7414 MatchingVD = ME->getMemberDecl();
7415 }
7416
7417 // If we don't have information about the current list item, move on to
7418 // the next one.
7419 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
7420 if (InitAddrIt == CaptureDeviceAddrMap.end())
7421 continue;
7422
7423 llvm::Type *Ty = ConvertTypeForMem(OrigVD->getType().getNonReferenceType());
7424
7425 Address PrivAddr =
7426 Address(InitAddrIt->second, Ty,
7427 getContext().getTypeAlignInChars(getContext().VoidPtrTy));
7428 // For declrefs and variable length array need to load the pointer for
7429 // correct mapping, since the pointer to the data was passed to the runtime.
7430 if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) ||
7431 MatchingVD->getType()->isArrayType()) {
7433 OrigVD->getType().getNonReferenceType());
7434 PrivAddr =
7436 PtrTy->castAs<PointerType>());
7437 }
7438
7439 (void)PrivateScope.addPrivate(OrigVD, PrivAddr);
7440 }
7441}
7442
7443// Generate the instructions for '#pragma omp target data' directive.
7445 const OMPTargetDataDirective &S) {
7446 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true,
7447 /*SeparateBeginEndCalls=*/true);
7448
7449 // Create a pre/post action to signal the privatization of the device pointer.
7450 // This action can be replaced by the OpenMP runtime code generation to
7451 // deactivate privatization.
7452 bool PrivatizeDevicePointers = false;
7453 class DevicePointerPrivActionTy : public PrePostActionTy {
7454 bool &PrivatizeDevicePointers;
7455
7456 public:
7457 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
7458 : PrivatizeDevicePointers(PrivatizeDevicePointers) {}
7459 void Enter(CodeGenFunction &CGF) override {
7460 PrivatizeDevicePointers = true;
7461 }
7462 };
7463 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
7464
7465 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &Action) {
7466 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7467 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
7468 };
7469
7470 // Codegen that selects whether to generate the privatization code or not.
7471 auto &&PrivCodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &Action) {
7472 RegionCodeGenTy RCG(InnermostCodeGen);
7473 PrivatizeDevicePointers = false;
7474
7475 // Call the pre-action to change the status of PrivatizeDevicePointers if
7476 // needed.
7477 Action.Enter(CGF);
7478
7479 if (PrivatizeDevicePointers) {
7480 OMPPrivateScope PrivateScope(CGF);
7481 // Emit all instances of the use_device_ptr clause.
7482 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
7483 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
7484 Info.CaptureDeviceAddrMap);
7485 for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>())
7486 CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope,
7487 Info.CaptureDeviceAddrMap);
7488 (void)PrivateScope.Privatize();
7489 RCG(CGF);
7490 } else {
7491 // If we don't have target devices, don't bother emitting the data
7492 // mapping code.
7493 std::optional<OpenMPDirectiveKind> CaptureRegion;
7494 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
7495 // Emit helper decls of the use_device_ptr/use_device_addr clauses.
7496 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
7497 for (const Expr *E : C->varlist()) {
7498 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
7499 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
7500 CGF.EmitVarDecl(*OED);
7501 }
7502 for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>())
7503 for (const Expr *E : C->varlist()) {
7504 const Decl *D = getBaseDecl(E);
7505 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
7506 CGF.EmitVarDecl(*OED);
7507 }
7508 } else {
7509 CaptureRegion = OMPD_unknown;
7510 }
7511
7512 OMPLexicalScope Scope(CGF, S, CaptureRegion);
7513 RCG(CGF);
7514 }
7515 };
7516
7517 // Forward the provided action to the privatization codegen.
7518 RegionCodeGenTy PrivRCG(PrivCodeGen);
7519 PrivRCG.setAction(Action);
7520
7521 // Notwithstanding the body of the region is emitted as inlined directive,
7522 // we don't use an inline scope as changes in the references inside the
7523 // region are expected to be visible outside, so we do not privative them.
7524 OMPLexicalScope Scope(CGF, S);
7525 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
7526 PrivRCG);
7527 };
7528
7529 RegionCodeGenTy RCG(CodeGen);
7530
7531 // If we don't have target devices, don't bother emitting the data mapping
7532 // code.
7533 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
7534 RCG(*this);
7535 return;
7536 }
7537
7538 // Check if we have any if clause associated with the directive.
7539 const Expr *IfCond = nullptr;
7540 if (const auto *C = S.getSingleClause<OMPIfClause>())
7541 IfCond = C->getCondition();
7542
7543 // Check if we have any device clause associated with the directive.
7544 const Expr *Device = nullptr;
7545 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7546 Device = C->getDevice();
7547
7548 // Set the action to signal privatization of device pointers.
7549 RCG.setAction(PrivAction);
7550
7551 // Emit region code.
7552 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
7553 Info);
7554}
7555
7557 const OMPTargetEnterDataDirective &S) {
7558 // If we don't have target devices, don't bother emitting the data mapping
7559 // code.
7560 if (CGM.getLangOpts().OMPTargetTriples.empty())
7561 return;
7562
7563 // Check if we have any if clause associated with the directive.
7564 const Expr *IfCond = nullptr;
7565 if (const auto *C = S.getSingleClause<OMPIfClause>())
7566 IfCond = C->getCondition();
7567
7568 // Check if we have any device clause associated with the directive.
7569 const Expr *Device = nullptr;
7570 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7571 Device = C->getDevice();
7572
7573 OMPLexicalScope Scope(*this, S, OMPD_task);
7575}
7576
7578 const OMPTargetExitDataDirective &S) {
7579 // If we don't have target devices, don't bother emitting the data mapping
7580 // code.
7581 if (CGM.getLangOpts().OMPTargetTriples.empty())
7582 return;
7583
7584 // Check if we have any if clause associated with the directive.
7585 const Expr *IfCond = nullptr;
7586 if (const auto *C = S.getSingleClause<OMPIfClause>())
7587 IfCond = C->getCondition();
7588
7589 // Check if we have any device clause associated with the directive.
7590 const Expr *Device = nullptr;
7591 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7592 Device = C->getDevice();
7593
7594 OMPLexicalScope Scope(*this, S, OMPD_task);
7596}
7597
7600 PrePostActionTy &Action) {
7601 // Get the captured statement associated with the 'parallel' region.
7602 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
7603 Action.Enter(CGF);
7604 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
7605 Action.Enter(CGF);
7606 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7607 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
7608 CGF.EmitOMPPrivateClause(S, PrivateScope);
7609 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7610 (void)PrivateScope.Privatize();
7611 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
7613 // TODO: Add support for clauses.
7614 CGF.EmitStmt(CS->getCapturedStmt());
7615 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
7616 };
7617 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
7620 [](CodeGenFunction &) { return nullptr; });
7621}
7622
7624 CodeGenModule &CGM, StringRef ParentName,
7625 const OMPTargetParallelDirective &S) {
7626 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7627 emitTargetParallelRegion(CGF, S, Action);
7628 };
7629 llvm::Function *Fn;
7630 llvm::Constant *Addr;
7631 // Emit target region as a standalone region.
7633 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7634 assert(Fn && Addr && "Target device function emission failed.");
7635}
7636
7638 const OMPTargetParallelDirective &S) {
7639 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7640 emitTargetParallelRegion(CGF, S, Action);
7641 };
7642 emitCommonOMPTargetDirective(*this, S, CodeGen);
7643}
7644
7647 PrePostActionTy &Action) {
7648 Action.Enter(CGF);
7649 // Emit directive as a combined directive that consists of two implicit
7650 // directives: 'parallel' with 'for' directive.
7651 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7652 Action.Enter(CGF);
7653 CodeGenFunction::OMPCancelStackRAII CancelRegion(
7654 CGF, OMPD_target_parallel_for, S.hasCancel());
7655 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
7657 };
7658 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
7660}
7661
7663 CodeGenModule &CGM, StringRef ParentName,
7665 // Emit SPMD target parallel for region as a standalone region.
7666 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7667 emitTargetParallelForRegion(CGF, S, Action);
7668 };
7669 llvm::Function *Fn;
7670 llvm::Constant *Addr;
7671 // Emit target region as a standalone region.
7673 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7674 assert(Fn && Addr && "Target device function emission failed.");
7675}
7676
7679 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7680 emitTargetParallelForRegion(CGF, S, Action);
7681 };
7682 emitCommonOMPTargetDirective(*this, S, CodeGen);
7683}
7684
7685static void
7688 PrePostActionTy &Action) {
7689 Action.Enter(CGF);
7690 // Emit directive as a combined directive that consists of two implicit
7691 // directives: 'parallel' with 'for' directive.
7692 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7693 Action.Enter(CGF);
7694 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
7696 };
7697 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
7699}
7700
7702 CodeGenModule &CGM, StringRef ParentName,
7704 // Emit SPMD target parallel for region as a standalone region.
7705 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7706 emitTargetParallelForSimdRegion(CGF, S, Action);
7707 };
7708 llvm::Function *Fn;
7709 llvm::Constant *Addr;
7710 // Emit target region as a standalone region.
7712 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7713 assert(Fn && Addr && "Target device function emission failed.");
7714}
7715
7718 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7719 emitTargetParallelForSimdRegion(CGF, S, Action);
7720 };
7721 emitCommonOMPTargetDirective(*this, S, CodeGen);
7722}
7723
7724/// Emit a helper variable and return corresponding lvalue.
7725static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
7726 const ImplicitParamDecl *PVD,
7727 CodeGenFunction::OMPPrivateScope &Privates) {
7728 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
7729 Privates.addPrivate(VDecl, CGF.GetAddrOfLocalVar(PVD));
7730}
7731
7733 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
7734 // Emit outlined function for task construct.
7735 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
7736 Address CapturedStruct = Address::invalid();
7737 {
7738 OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
7739 CapturedStruct = GenerateCapturedStmtArgument(*CS);
7740 }
7742 const Expr *IfCond = nullptr;
7743 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
7744 if (C->getNameModifier() == OMPD_unknown ||
7745 C->getNameModifier() == OMPD_taskloop) {
7746 IfCond = C->getCondition();
7747 break;
7748 }
7749 }
7750
7752 // Check if taskloop must be emitted without taskgroup.
7753 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
7754 // TODO: Check if we should emit tied or untied task.
7755 Data.Tied = true;
7756 // Set scheduling for taskloop
7757 if (const auto *Clause = S.getSingleClause<OMPGrainsizeClause>()) {
7758 // grainsize clause
7759 Data.Schedule.setInt(/*IntVal=*/false);
7760 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
7761 } else if (const auto *Clause = S.getSingleClause<OMPNumTasksClause>()) {
7762 // num_tasks clause
7763 Data.Schedule.setInt(/*IntVal=*/true);
7764 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
7765 }
7766
7767 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
7768 // if (PreCond) {
7769 // for (IV in 0..LastIteration) BODY;
7770 // <Final counter/linear vars updates>;
7771 // }
7772 //
7773
7774 // Emit: if (PreCond) - begin.
7775 // If the condition constant folds and can be elided, avoid emitting the
7776 // whole loop.
7777 bool CondConstant;
7778 llvm::BasicBlock *ContBlock = nullptr;
7779 OMPLoopScope PreInitScope(CGF, S);
7780 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
7781 if (!CondConstant)
7782 return;
7783 } else {
7784 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
7785 ContBlock = CGF.createBasicBlock("taskloop.if.end");
7786 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
7787 CGF.getProfileCount(&S));
7788 CGF.EmitBlock(ThenBlock);
7789 CGF.incrementProfileCounter(&S);
7790 }
7791
7792 (void)CGF.EmitOMPLinearClauseInit(S);
7793
7794 OMPPrivateScope LoopScope(CGF);
7795 // Emit helper vars inits.
7796 enum { LowerBound = 5, UpperBound, Stride, LastIter };
7797 auto *I = CS->getCapturedDecl()->param_begin();
7798 auto *LBP = std::next(I, LowerBound);
7799 auto *UBP = std::next(I, UpperBound);
7800 auto *STP = std::next(I, Stride);
7801 auto *LIP = std::next(I, LastIter);
7802 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
7803 LoopScope);
7804 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
7805 LoopScope);
7806 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
7807 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
7808 LoopScope);
7809 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
7810 CGF.EmitOMPLinearClause(S, LoopScope);
7811 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
7812 (void)LoopScope.Privatize();
7813 // Emit the loop iteration variable.
7814 const Expr *IVExpr = S.getIterationVariable();
7815 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
7816 CGF.EmitVarDecl(*IVDecl);
7817 CGF.EmitIgnoredExpr(S.getInit());
7818
7819 // Emit the iterations count variable.
7820 // If it is not a variable, Sema decided to calculate iterations count on
7821 // each iteration (e.g., it is foldable into a constant).
7822 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
7823 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
7824 // Emit calculation of the iterations count.
7825 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
7826 }
7827
7828 {
7829 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
7831 CGF, S,
7832 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7833 if (isOpenMPSimdDirective(S.getDirectiveKind()))
7834 CGF.EmitOMPSimdInit(S);
7835 },
7836 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
7837 CGF.EmitOMPInnerLoop(
7838 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
7839 [&S](CodeGenFunction &CGF) {
7840 emitOMPLoopBodyWithStopPoint(CGF, S,
7841 CodeGenFunction::JumpDest());
7842 },
7843 [](CodeGenFunction &) {});
7844 });
7845 }
7846 // Emit: if (PreCond) - end.
7847 if (ContBlock) {
7848 CGF.EmitBranch(ContBlock);
7849 CGF.EmitBlock(ContBlock, true);
7850 }
7851 // Emit final copy of the lastprivate variables if IsLastIter != 0.
7852 if (HasLastprivateClause) {
7853 CGF.EmitOMPLastprivateClauseFinal(
7854 S, isOpenMPSimdDirective(S.getDirectiveKind()),
7855 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
7856 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
7857 (*LIP)->getType(), S.getBeginLoc())));
7858 }
7859 LoopScope.restoreMap();
7860 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
7861 return CGF.Builder.CreateIsNotNull(
7862 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
7863 (*LIP)->getType(), S.getBeginLoc()));
7864 });
7865 };
7866 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
7867 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
7868 const OMPTaskDataTy &Data) {
7869 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
7871 OMPLoopScope PreInitScope(CGF, S);
7872 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
7873 OutlinedFn, SharedsTy,
7874 CapturedStruct, IfCond, Data);
7875 };
7876 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
7877 CodeGen);
7878 };
7879 if (Data.Nogroup) {
7880 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
7881 } else {
7883 *this,
7884 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
7885 PrePostActionTy &Action) {
7886 Action.Enter(CGF);
7887 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
7888 Data);
7889 },
7890 S.getBeginLoc());
7891 }
7892}
7893
7895 auto LPCRegion =
7898}
7899
7901 const OMPTaskLoopSimdDirective &S) {
7902 auto LPCRegion =
7904 OMPLexicalScope Scope(*this, S);
7906}
7907
7909 const OMPMasterTaskLoopDirective &S) {
7910 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7911 Action.Enter(CGF);
7913 };
7914 auto LPCRegion =
7916 OMPLexicalScope Scope(*this, S, std::nullopt, /*EmitPreInitStmt=*/false);
7917 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
7918}
7919
7922 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7923 Action.Enter(CGF);
7925 };
7926 auto LPCRegion =
7928 OMPLexicalScope Scope(*this, S);
7929 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
7930}
7931
7934 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7935 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
7936 PrePostActionTy &Action) {
7937 Action.Enter(CGF);
7939 };
7940 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
7941 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
7942 S.getBeginLoc());
7943 };
7944 auto LPCRegion =
7946 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
7948}
7949
7952 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7953 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
7954 PrePostActionTy &Action) {
7955 Action.Enter(CGF);
7957 };
7958 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
7959 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
7960 S.getBeginLoc());
7961 };
7962 auto LPCRegion =
7964 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
7966}
7967
7968// Generate the instructions for '#pragma omp target update' directive.
7970 const OMPTargetUpdateDirective &S) {
7971 // If we don't have target devices, don't bother emitting the data mapping
7972 // code.
7973 if (CGM.getLangOpts().OMPTargetTriples.empty())
7974 return;
7975
7976 // Check if we have any if clause associated with the directive.
7977 const Expr *IfCond = nullptr;
7978 if (const auto *C = S.getSingleClause<OMPIfClause>())
7979 IfCond = C->getCondition();
7980
7981 // Check if we have any device clause associated with the directive.
7982 const Expr *Device = nullptr;
7983 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7984 Device = C->getDevice();
7985
7986 OMPLexicalScope Scope(*this, S, OMPD_task);
7988}
7989
7991 const OMPGenericLoopDirective &S) {
7992 // Always expect a bind clause on the loop directive. It it wasn't
7993 // in the source, it should have been added in sema.
7994
7996 if (const auto *C = S.getSingleClause<OMPBindClause>())
7997 BindKind = C->getBindKind();
7998
7999 switch (BindKind) {
8000 case OMPC_BIND_parallel: // for
8001 return emitOMPForDirective(S, *this, CGM, /*HasCancel=*/false);
8002 case OMPC_BIND_teams: // distribute
8003 return emitOMPDistributeDirective(S, *this, CGM);
8004 case OMPC_BIND_thread: // simd
8005 return emitOMPSimdDirective(S, *this, CGM);
8006 case OMPC_BIND_unknown:
8007 break;
8008 }
8009
8010 // Unimplemented, just inline the underlying statement for now.
8011 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8012 // Emit the loop iteration variable.
8013 const Stmt *CS =
8014 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
8015 const auto *ForS = dyn_cast<ForStmt>(CS);
8016 if (ForS && !isa<DeclStmt>(ForS->getInit())) {
8017 OMPPrivateScope LoopScope(CGF);
8018 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
8019 (void)LoopScope.Privatize();
8020 CGF.EmitStmt(CS);
8021 LoopScope.restoreMap();
8022 } else {
8023 CGF.EmitStmt(CS);
8024 }
8025 };
8026 OMPLexicalScope Scope(*this, S, OMPD_unknown);
8027 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_loop, CodeGen);
8028}
8029
8031 const OMPLoopDirective &S) {
8032 // Emit combined directive as if its constituent constructs are 'parallel'
8033 // and 'for'.
8034 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8035 Action.Enter(CGF);
8036 emitOMPCopyinClause(CGF, S);
8037 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
8038 };
8039 {
8040 auto LPCRegion =
8042 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
8044 }
8045 // Check for outer lastprivate conditional update.
8047}
8048
8051 // To be consistent with current behavior of 'target teams loop', emit
8052 // 'teams loop' as if its constituent constructs are 'teams' and 'distribute'.
8053 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8055 };
8056
8057 // Emit teams region as a standalone region.
8058 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
8059 PrePostActionTy &Action) {
8060 Action.Enter(CGF);
8061 OMPPrivateScope PrivateScope(CGF);
8062 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
8063 (void)PrivateScope.Privatize();
8064 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
8065 CodeGenDistribute);
8066 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
8067 };
8068 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
8070 [](CodeGenFunction &) { return nullptr; });
8071}
8072
8073#ifndef NDEBUG
8075 std::string StatusMsg,
8076 const OMPExecutableDirective &D) {
8077 bool IsDevice = CGF.CGM.getLangOpts().OpenMPIsTargetDevice;
8078 if (IsDevice)
8079 StatusMsg += ": DEVICE";
8080 else
8081 StatusMsg += ": HOST";
8083 auto &SM = CGF.getContext().getSourceManager();
8084 PresumedLoc PLoc = SM.getPresumedLoc(L);
8085 const char *FileName = PLoc.isValid() ? PLoc.getFilename() : nullptr;
8086 unsigned LineNo =
8087 PLoc.isValid() ? PLoc.getLine() : SM.getExpansionLineNumber(L);
8088 llvm::dbgs() << StatusMsg << ": " << FileName << ": " << LineNo << "\n";
8089}
8090#endif
8091
8093 CodeGenFunction &CGF, PrePostActionTy &Action,
8095 Action.Enter(CGF);
8096 // Emit 'teams loop' as if its constituent constructs are 'distribute,
8097 // 'parallel, and 'for'.
8098 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8100 S.getDistInc());
8101 };
8102
8103 // Emit teams region as a standalone region.
8104 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
8105 PrePostActionTy &Action) {
8106 Action.Enter(CGF);
8107 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
8108 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
8109 (void)PrivateScope.Privatize();
8111 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
8112 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
8113 };
8114 DEBUG_WITH_TYPE(TTL_CODEGEN_TYPE,
8116 CGF, TTL_CODEGEN_TYPE " as parallel for", S));
8117 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
8118 CodeGenTeams);
8120 [](CodeGenFunction &) { return nullptr; });
8121}
8122
8124 CodeGenFunction &CGF, PrePostActionTy &Action,
8126 Action.Enter(CGF);
8127 // Emit 'teams loop' as if its constituent construct is 'distribute'.
8128 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
8130 };
8131
8132 // Emit teams region as a standalone region.
8133 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
8134 PrePostActionTy &Action) {
8135 Action.Enter(CGF);
8136 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
8137 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
8138 (void)PrivateScope.Privatize();
8140 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
8141 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
8142 };
8143 DEBUG_WITH_TYPE(TTL_CODEGEN_TYPE,
8145 CGF, TTL_CODEGEN_TYPE " as distribute", S));
8146 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
8148 [](CodeGenFunction &) { return nullptr; });
8149}
8150
8153 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8154 if (S.canBeParallelFor())
8156 else
8158 };
8159 emitCommonOMPTargetDirective(*this, S, CodeGen);
8160}
8161
8163 CodeGenModule &CGM, StringRef ParentName,
8165 // Emit SPMD target parallel loop region as a standalone region.
8166 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8167 if (S.canBeParallelFor())
8169 else
8171 };
8172 llvm::Function *Fn;
8173 llvm::Constant *Addr;
8174 // Emit target region as a standalone region.
8176 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
8177 assert(Fn && Addr &&
8178 "Target device function emission failed for 'target teams loop'.");
8179}
8180
8183 PrePostActionTy &Action) {
8184 Action.Enter(CGF);
8185 // Emit as 'parallel for'.
8186 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8187 Action.Enter(CGF);
8188 CodeGenFunction::OMPCancelStackRAII CancelRegion(
8189 CGF, OMPD_target_parallel_loop, /*hasCancel=*/false);
8190 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
8192 };
8193 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
8195}
8196
8198 CodeGenModule &CGM, StringRef ParentName,
8200 // Emit target parallel loop region as a standalone region.
8201 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8203 };
8204 llvm::Function *Fn;
8205 llvm::Constant *Addr;
8206 // Emit target region as a standalone region.
8208 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
8209 assert(Fn && Addr && "Target device function emission failed.");
8210}
8211
8212/// Emit combined directive 'target parallel loop' as if its constituent
8213/// constructs are 'target', 'parallel', and 'for'.
8216 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
8218 };
8219 emitCommonOMPTargetDirective(*this, S, CodeGen);
8220}
8221
8223 const OMPExecutableDirective &D) {
8224 if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) {
8226 return;
8227 }
8228 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
8229 return;
8230 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
8231 OMPPrivateScope GlobalsScope(CGF);
8232 if (isOpenMPTaskingDirective(D.getDirectiveKind())) {
8233 // Capture global firstprivates to avoid crash.
8234 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
8235 for (const Expr *Ref : C->varlist()) {
8236 const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
8237 if (!DRE)
8238 continue;
8239 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
8240 if (!VD || VD->hasLocalStorage())
8241 continue;
8242 if (!CGF.LocalDeclMap.count(VD)) {
8243 LValue GlobLVal = CGF.EmitLValue(Ref);
8244 GlobalsScope.addPrivate(VD, GlobLVal.getAddress());
8245 }
8246 }
8247 }
8248 }
8249 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
8250 (void)GlobalsScope.Privatize();
8251 ParentLoopDirectiveForScanRegion ScanRegion(CGF, D);
8252 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
8253 } else {
8254 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
8255 for (const Expr *E : LD->counters()) {
8256 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
8257 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
8258 LValue GlobLVal = CGF.EmitLValue(E);
8259 GlobalsScope.addPrivate(VD, GlobLVal.getAddress());
8260 }
8261 if (isa<OMPCapturedExprDecl>(VD)) {
8262 // Emit only those that were not explicitly referenced in clauses.
8263 if (!CGF.LocalDeclMap.count(VD))
8264 CGF.EmitVarDecl(*VD);
8265 }
8266 }
8267 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
8268 if (!C->getNumForLoops())
8269 continue;
8270 for (unsigned I = LD->getLoopsNumber(),
8271 E = C->getLoopNumIterations().size();
8272 I < E; ++I) {
8273 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
8274 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
8275 // Emit only those that were not explicitly referenced in clauses.
8276 if (!CGF.LocalDeclMap.count(VD))
8277 CGF.EmitVarDecl(*VD);
8278 }
8279 }
8280 }
8281 }
8282 (void)GlobalsScope.Privatize();
8283 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
8284 }
8285 };
8286 if (D.getDirectiveKind() == OMPD_atomic ||
8287 D.getDirectiveKind() == OMPD_critical ||
8288 D.getDirectiveKind() == OMPD_section ||
8289 D.getDirectiveKind() == OMPD_master ||
8290 D.getDirectiveKind() == OMPD_masked ||
8291 D.getDirectiveKind() == OMPD_unroll ||
8292 D.getDirectiveKind() == OMPD_assume) {
8293 EmitStmt(D.getAssociatedStmt());
8294 } else {
8295 auto LPCRegion =
8297 OMPSimdLexicalScope Scope(*this, D);
8299 *this,
8300 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
8301 : D.getDirectiveKind(),
8302 CodeGen);
8303 }
8304 // Check for outer lastprivate conditional update.
8306}
8307
8309 EmitStmt(S.getAssociatedStmt());
8310}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
#define SM(sm)
Definition: Cuda.cpp:83
static bool isAllocatableDecl(const VarDecl *VD)
static const VarDecl * getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE)
static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, PrePostActionTy &Action)
static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, PrePostActionTy &Action)
static llvm::Function * emitOutlinedOrderedFunction(CodeGenModule &CGM, const CapturedStmt *S, SourceLocation Loc)
static const VarDecl * getBaseDecl(const Expr *Ref)
static void emitTargetTeamsGenericLoopRegionAsParallel(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsGenericLoopDirective &S)
static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, const Expr *X, const Expr *V, SourceLocation Loc)
static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, bool IsPostfixUpdate, const Expr *V, const Expr *X, const Expr *E, const Expr *UE, bool IsXLHSInRHSPart, SourceLocation Loc)
static void emitScanBasedDirective(CodeGenFunction &CGF, const OMPLoopDirective &S, llvm::function_ref< llvm::Value *(CodeGenFunction &)> NumIteratorsGen, llvm::function_ref< void(CodeGenFunction &)> FirstGen, llvm::function_ref< void(CodeGenFunction &)> SecondGen)
Emits the code for the directive with inscan reductions.
static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, LValue LVal, RValue RVal)
static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc, QualType DstType, StringRef Name, LValue AddrLV)
static void emitDistributeParallelForDistributeInnerBoundParams(CodeGenFunction &CGF, const OMPExecutableDirective &S, llvm::SmallVectorImpl< llvm::Value * > &CapturedVars)
static void emitScanBasedDirectiveFinals(CodeGenFunction &CGF, const OMPLoopDirective &S, llvm::function_ref< llvm::Value *(CodeGenFunction &)> NumIteratorsGen)
Copies final inscan reductions values to the original variables.
static void checkForLastprivateConditionalUpdate(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static std::pair< LValue, LValue > emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S)
The following two functions generate expressions for the loop lower and upper bounds in case of stati...
static void emitTargetParallelForRegion(CodeGenFunction &CGF, const OMPTargetParallelForDirective &S, PrePostActionTy &Action)
static LValue EmitOMPHelperVar(CodeGenFunction &CGF, const DeclRefExpr *Helper)
Emit a helper variable and return corresponding lvalue.
static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, const Expr *X, const Expr *E, const Expr *UE, bool IsXLHSInRHSPart, SourceLocation Loc)
static llvm::Value * convertToScalarValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, QualType DestType, SourceLocation Loc)
static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
static std::pair< bool, RValue > emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RValue Update, BinaryOperatorKind BO, llvm::AtomicOrdering AO, bool IsXLHSInRHSPart)
static std::pair< LValue, LValue > emitDistributeParallelForInnerBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitTargetTeamsGenericLoopRegionAsDistribute(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsGenericLoopDirective &S)
static void emitTargetParallelRegion(CodeGenFunction &CGF, const OMPTargetParallelDirective &S, PrePostActionTy &Action)
static std::pair< llvm::Value *, llvm::Value * > emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, Address LB, Address UB)
When dealing with dispatch schedules (e.g.
static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitRestoreIP(CodeGenFunction &CGF, const T *C, llvm::OpenMPIRBuilder::InsertPointTy AllocaIP, llvm::OpenMPIRBuilder &OMPBuilder)
static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, const OMPExecutableDirective &S, const RegionCodeGenTy &CodeGen)
static void emitSimdlenSafelenClause(CodeGenFunction &CGF, const OMPExecutableDirective &D)
static void emitAlignedClause(CodeGenFunction &CGF, const OMPExecutableDirective &D)
static bool isSimdSupportedByOpenMPIRBuilder(const OMPLoopDirective &S)
static void emitCommonOMPParallelDirective(CodeGenFunction &CGF, const OMPExecutableDirective &S, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, const CodeGenBoundParametersTy &CodeGenBoundParameters)
static bool emitWorksharingDirective(CodeGenFunction &CGF, const OMPLoopDirective &S, bool HasCancel)
static void emitPostUpdateForReductionClause(CodeGenFunction &CGF, const OMPExecutableDirective &D, const llvm::function_ref< llvm::Value *(CodeGenFunction &)> CondGen)
static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc, const unsigned IVSize, const bool IVSigned)
static void emitTargetTeamsLoopCodegenStatus(CodeGenFunction &CGF, std::string StatusMsg, const OMPExecutableDirective &D)
static bool isForSupportedByOpenMPIRBuilder(const OMPLoopDirective &S, bool HasCancel)
static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, llvm::AtomicOrdering AO, LValue LVal, SourceLocation Loc)
static std::pair< llvm::Value *, llvm::Value * > emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, Address LB, Address UB)
if the 'for' loop has a dispatch schedule (e.g.
void emitOMPDistributeDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM)
static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, llvm::AtomicOrdering AO, llvm::AtomicOrdering FailAO, bool IsPostfixUpdate, const Expr *X, const Expr *V, const Expr *R, const Expr *E, const Expr *UE, const Expr *D, const Expr *CE, bool IsXLHSInRHSPart, bool IsFailOnly, SourceLocation Loc)
bool isSupportedByOpenMPIRBuilder(const OMPTaskgroupDirective &T)
#define TTL_CODEGEN_TYPE
static CodeGenFunction::ComplexPairTy convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, QualType DestType, SourceLocation Loc)
static ImplicitParamDecl * createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, QualType Ty, CapturedDecl *CD, SourceLocation Loc)
static EmittedClosureTy emitCapturedStmtFunc(CodeGenFunction &ParentCGF, const CapturedStmt *S)
Emit a captured statement and return the function as well as its captured closure context.
static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF, const OMPLoopDirective &S, CodeGenFunction::JumpDest LoopExit)
static void emitOMPCopyinClause(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitTargetTeamsDistributeParallelForRegion(CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, PrePostActionTy &Action)
static llvm::CallInst * emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap, llvm::ArrayRef< llvm::Value * > Args)
Emit a call to a previously captured closure.
static void emitMasked(CodeGenFunction &CGF, const OMPExecutableDirective &S)
static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop, int MaxLevel, int Level=0)
static void emitEmptyBoundParameters(CodeGenFunction &, const OMPExecutableDirective &, llvm::SmallVectorImpl< llvm::Value * > &)
static void emitTargetParallelForSimdRegion(CodeGenFunction &CGF, const OMPTargetParallelForSimdDirective &S, PrePostActionTy &Action)
static void emitOMPAtomicCompareExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, llvm::AtomicOrdering FailAO, const Expr *X, const Expr *V, const Expr *R, const Expr *E, const Expr *D, const Expr *CE, bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly, SourceLocation Loc)
std::pair< llvm::Function *, llvm::Value * > EmittedClosureTy
static OpenMPDirectiveKind getEffectiveDirectiveKind(const OMPExecutableDirective &S)
static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsDirective &S)
void emitOMPSimdDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM)
static void buildDependences(const OMPExecutableDirective &S, OMPTaskDataTy &Data)
static RValue convertToType(CodeGenFunction &CGF, RValue Value, QualType SourceType, QualType ResType, SourceLocation Loc)
static void emitScanBasedDirectiveDecls(CodeGenFunction &CGF, const OMPLoopDirective &S, llvm::function_ref< llvm::Value *(CodeGenFunction &)> NumIteratorsGen)
Emits internal temp array declarations for the directive with inscan reductions.
static void emitTargetTeamsDistributeParallelForSimdRegion(CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForSimdDirective &S, PrePostActionTy &Action)
static void emitTargetTeamsDistributeSimdRegion(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsDistributeSimdDirective &S)
static llvm::MapVector< llvm::Value *, llvm::Value * > GetAlignedMapping(const OMPLoopDirective &S, CodeGenFunction &CGF)
static llvm::omp::ScheduleKind convertClauseKindToSchedKind(OpenMPScheduleClauseKind ScheduleClauseKind)
void emitOMPForDirective(const OMPLoopDirective &S, CodeGenFunction &CGF, CodeGenModule &CGM, bool HasCancel)
static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, const ImplicitParamDecl *PVD, CodeGenFunction::OMPPrivateScope &Privates)
Emit a helper variable and return corresponding lvalue.
static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, const OMPExecutableDirective &S, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
static void emitTargetParallelGenericLoopRegion(CodeGenFunction &CGF, const OMPTargetParallelGenericLoopDirective &S, PrePostActionTy &Action)
static QualType getCanonicalParamType(ASTContext &C, QualType T)
static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S, const RegionCodeGenTy &SimdInitGen, const RegionCodeGenTy &BodyCodeGen)
static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, const Twine &Name, llvm::Value *Init=nullptr)
static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, const Expr *X, const Expr *E, SourceLocation Loc)
static llvm::Function * emitOutlinedFunctionPrologue(CodeGenFunction &CGF, FunctionArgList &Args, llvm::MapVector< const Decl *, std::pair< const VarDecl *, Address > > &LocalAddrs, llvm::DenseMap< const Decl *, std::pair< const Expr *, llvm::Value * > > &VLASizes, llvm::Value *&CXXThisValue, const FunctionOptions &FO)
static void emitInnerParallelForWhenCombined(CodeGenFunction &CGF, const OMPLoopDirective &S, CodeGenFunction::JumpDest LoopExit)
static void emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, const OMPTargetTeamsDistributeDirective &S)
const Decl * D
enum clang::sema::@1655::IndirectLocalPathEntry::EntryKind Kind
Expr * E
This file defines OpenMP nodes for declarative directives.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:143
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the SourceManager interface.
This file defines OpenMP AST classes for executable directives and clauses.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
SourceManager & getSourceManager()
Definition: ASTContext.h:721
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
QualType getRecordType(const RecordDecl *Decl) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
IdentifierTable & Idents
Definition: ASTContext.h:660
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1119
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
Represents an attribute applied to a statement.
Definition: Stmt.h:2090
ArrayRef< const Attr * > getAttrs() const
Definition: Stmt.h:2124
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4859
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6365
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4670
unsigned getContextParamPosition() const
Definition: Decl.h:4741
bool isNothrow() const
Definition: Decl.cpp:5442
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition: Decl.cpp:5427
param_iterator param_end() const
Retrieve an iterator one past the last parameter decl.
Definition: Decl.h:4749
param_iterator param_begin() const
Retrieve an iterator pointing to the first parameter decl.
Definition: Decl.h:4747
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.cpp:5439
ImplicitParamDecl * getParam(unsigned i) const
Definition: Decl.h:4714
This captures a statement into a function.
Definition: Stmt.h:3767
CapturedDecl * getCapturedDecl()
Retrieve the outlined function declaration.
Definition: Stmt.cpp:1407
child_range children()
Definition: Stmt.cpp:1398
const RecordDecl * getCapturedRecordDecl() const
Retrieve the record declaration for captured variables.
Definition: Stmt.h:3888
Stmt * getCapturedStmt()
Retrieve the statement being captured.
Definition: Stmt.h:3871
capture_range captures()
Definition: Stmt.h:3905
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition: Stmt.h:3931
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition: CharUnits.h:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
static Address invalid()
Definition: Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:251
CharUnits getAlignment() const
Definition: Address.h:189
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:207
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
Address withAlignment(CharUnits NewAlignment) const
Return address with different alignment, but same pointer and element type.
Definition: Address.h:267
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:199
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition: CGValue.h:572
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:902
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Definition: CGBuilder.h:354
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition: CGBuilder.h:202
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:107
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition: CGBuilder.h:344
CGFunctionInfo - Class to encapsulate the information about a function definition.
Manages list of lastprivate conditional decls for the specified directive.
static LastprivateConditionalRAII disable(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Manages list of nontemporal decls for the specified directive.
Struct that keeps all the relevant information that should be kept throughout a 'target data' region.
Manages list of nontemporal decls for the specified directive.
virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data)
Emit task region for the task directive.
virtual llvm::Value * emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST)
Call __kmpc_dispatch_next( ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, kmp_int[32|64] *p_lowe...
virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device)
Emit the data mapping/movement code associated with the directive D that should be of the form 'targe...
virtual void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc)
Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_threads)...
virtual void emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef< const Expr * > CopyprivateVars, ArrayRef< const Expr * > DestExprs, ArrayRef< const Expr * > SrcExprs, ArrayRef< const Expr * > AssignmentOps)
Emits a single region.
virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal)
Get the address of void * type of the privatue copy of the reduction item specified by the SharedLVal...
virtual void emitForDispatchDeinit(CodeGenFunction &CGF, SourceLocation Loc)
This is used for non static scheduled types and when the ordered clause is present on the loop constr...
virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const
Choose default schedule type and chunk value for the schedule clause.
virtual void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef< llvm::Value * > CapturedVars)
Emits code for teams call of the OutlinedFn with variables captured in a record which address is stor...
virtual void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind CancelRegion)
Emit code for 'cancellation point' construct.
virtual const VarDecl * translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const
Translates the native parameter of outlined function if this is required for target.
virtual llvm::Function * emitTeamsOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
Emits outlined function for the specified OpenMP teams directive D.
virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef< Expr * > NumIterations)
Emit initialization for doacross loop nesting support.
virtual void adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, const OMPExecutableDirective &D) const
Adjust some parameters for the target-based directives, like addresses of the variables captured by r...
virtual void emitTargetDataCalls(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device, const RegionCodeGenTy &CodeGen, CGOpenMPRuntime::TargetDataInfo &Info)
Emit the target data mapping code associated with D.
virtual Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const
Gets the address of the native argument basing on the address of the target-specific parameter.
virtual void emitTaskgroupRegion(CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, SourceLocation Loc)
Emit a taskgroup region.
virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc)
Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_teams,...
virtual llvm::Value * emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef< const Expr * > LHSExprs, ArrayRef< const Expr * > RHSExprs, const OMPTaskDataTy &Data)
Emit a code for initialization of task reduction clause.
void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, OpenMPDependClauseKind NewDepKind, SourceLocation Loc)
Updates the dependency kind in the specified depobj object.
virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF, LValue PrivLVal, const VarDecl *VD, SourceLocation Loc)
Gets the address of the global copy used for lastprivate conditional update, if any.
virtual void emitErrorCall(CodeGenFunction &CGF, SourceLocation Loc, Expr *ME, bool IsFatal)
Emit __kmpc_error call for error directive extern void __kmpc_error(ident_t *loc, int severity,...
virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc)
Emits code for a taskyield directive.
virtual void emitFlush(CodeGenFunction &CGF, ArrayRef< const Expr * > Vars, SourceLocation Loc, llvm::AtomicOrdering AO)
Emit flush of the variables specified in 'omp flush' directive.
virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPTaskDataTy &Data)
Emit code for 'taskwait' directive.
virtual void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc)
Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, int proc_bind) to generat...
virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks=true, bool ForceSimpleCall=false)
Emit an implicit/explicit barrier for OpenMP threads.
virtual void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values)
virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind)
Call the appropriate runtime routine to notify that we finished all the work with current loop.
void emitIfClause(CodeGenFunction &CGF, const Expr *Cond, const RegionCodeGenTy &ThenGen, const RegionCodeGenTy &ElseGen)
Emits code for OpenMP 'if' clause using specified CodeGen function.
Address emitDepobjDependClause(CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies, SourceLocation Loc)
Emits list of dependecies based on the provided data (array of dependence/expression pairs) for depob...
virtual llvm::Function * emitParallelOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
Emits outlined function for the specified OpenMP parallel directive D.
virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values)
Call the appropriate runtime routine to initialize it before start of loop.
llvm::AtomicOrdering getDefaultMemoryOrdering() const
Gets default memory ordering as specified in requires directive.
virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const
Check if the specified ScheduleKind is static non-chunked.
virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, const Expr *IfCond, OpenMPDirectiveKind CancelRegion)
Emit code for 'cancel' construct.
virtual void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc)
Emits a master region.
virtual llvm::Function * emitTaskOutlinedFunction(const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, const VarDecl *PartIDVar, const VarDecl *TaskTVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool Tied, unsigned &NumberOfParts)
Emits outlined function for the OpenMP task directive D.
void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, SourceLocation Loc)
Emits the code to destroy the dependency object provided in depobj directive.
virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N)
Required to resolve existing problems in the runtime.
virtual void emitDoacrossOrdered(CodeGenFunction &CGF, const OMPDependClause *C)
Emit code for doacross ordered directive with 'depend' clause.
virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, const Expr *LHS)
Checks if the provided LVal is lastprivate conditional and emits the code to update the value of the ...
virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const
Choose default schedule type and chunk value for the dist_schedule clause.
llvm::OpenMPIRBuilder & getOMPBuilder()
virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen)
Emit outilined function for 'target' directive.
virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint=nullptr)
Emits a critical region.
virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned)
Call the appropriate runtime routine to notify that we finished iteration of the ordered loop with th...
virtual void checkAndEmitSharedLastprivateConditional(CodeGenFunction &CGF, const OMPExecutableDirective &D, const llvm::DenseSet< CanonicalDeclPtr< const VarDecl > > &IgnoredDecls)
Checks if the lastprivate conditional was updated in inner region and writes the value.
virtual void emitInlinedDirective(CodeGenFunction &CGF, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool HasCancel=false)
Emit code for the directive that does not require outlining.
virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef< llvm::Value * > CapturedVars, const Expr *IfCond, llvm::Value *NumThreads)
Emits code for parallel or serial call of the OutlinedFn with variables captured in a record which ad...
virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const
Check if the specified ScheduleKind is static chunked.
virtual void emitTargetCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair< const Expr *, 2, OpenMPDeviceClauseModifier > Device, llvm::function_ref< llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter)
Emit the target offloading code associated with D.
virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef< const Expr * > Privates, ArrayRef< const Expr * > LHSExprs, ArrayRef< const Expr * > RHSExprs, ArrayRef< const Expr * > ReductionOps, ReductionOptionsTy Options)
Emit a code for reduction clause.
std::pair< llvm::Value *, Address > emitDependClause(CodeGenFunction &CGF, ArrayRef< OMPTaskDataTy::DependData > Dependencies, SourceLocation Loc)
Emits list of dependecies based on the provided data (array of dependence/expression pairs).
virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const
Check if the specified ScheduleKind is dynamic.
Address emitLastprivateConditionalInit(CodeGenFunction &CGF, const VarDecl *VD)
Create specialized alloca to handle lastprivate conditionals.
virtual void emitOrderedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &OrderedOpGen, SourceLocation Loc, bool IsThreads)
Emit an ordered region.
virtual void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef< llvm::Value * > Args=std::nullopt) const
Emits call of the outlined function with the provided arguments, translating these arguments to corre...
virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, bool IsWorksharingReduction)
Emits the following code for reduction clause with task modifier:
virtual void emitMaskedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc, const Expr *Filter=nullptr)
Emits a masked region.
virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues)
Call the appropriate runtime routine to initialize it before start of loop.
virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S)
Emit the captured statement body.
virtual StringRef getHelperName() const
Get the name of the capture helper.
virtual const FieldDecl * lookup(const VarDecl *VD) const
Lookup the captured field decl for a variable.
RAII for preserving necessary info during inlined region body codegen.
RAII for preserving necessary info during Outlined region body codegen.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, OMPTaskDataTy &Data)
void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitOMPParallelGenericLoopDirective(const OMPLoopDirective &S)
void EmitOMPAggregateAssign(Address DestAddr, Address SrcAddr, QualType OriginalType, const llvm::function_ref< void(Address, Address)> CopyGen)
Perform element by element copying of arrays with type OriginalType from SrcAddr to DestAddr using co...
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
void EmitOMPCopy(QualType OriginalType, Address DestAddr, Address SrcAddr, const VarDecl *DestVD, const VarDecl *SrcVD, const Expr *Copy)
Emit proper copying of data from one variable to another.
void EmitOMPOrderedDirective(const OMPOrderedDirective &S)
void EmitOMPTargetDirective(const OMPTargetDirective &S)
bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope)
void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope, bool ForInscan=false)
Emit initial code for reduction variables.
void EmitOMPAtomicDirective(const OMPAtomicDirective &S)
void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S)
void EmitOMPParallelMasterTaskLoopDirective(const OMPParallelMasterTaskLoopDirective &S)
void EmitAutoVarDecl(const VarDecl &D)
EmitAutoVarDecl - Emit an auto variable declaration.
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
static void EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDirective &S)
Emit device code for the target teams directive.
void EmitOMPReverseDirective(const OMPReverseDirective &S)
static bool hasScalarEvaluationKind(QualType T)
llvm::function_ref< std::pair< llvm::Value *, llvm::Value * >(CodeGenFunction &, const OMPExecutableDirective &S, Address LB, Address UB)> CodeGenDispatchBoundsTy
CGCapturedStmtInfo * CapturedStmtInfo
void EmitDecl(const Decl &D)
EmitDecl - Emit a declaration.
static void EmitOMPTargetTeamsDistributeDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeDirective &S)
Emit device code for the target teams distribute directive.
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
static void EmitOMPTargetParallelForSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelForSimdDirective &S)
Emit device code for the target parallel for simd directive.
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
const OMPExecutableDirective * OMPParentLoopDirectiveForScan
Parent loop-based directive for scan directive.
void EmitOMPTeamsDistributeParallelForDirective(const OMPTeamsDistributeParallelForDirective &S)
void EmitOMPTaskDirective(const OMPTaskDirective &S)
void EmitOMPScanDirective(const OMPScanDirective &S)
void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S)
JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind)
void EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S)
void EmitOMPUseDevicePtrClause(const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, const llvm::DenseMap< const ValueDecl *, llvm::Value * > CaptureDeviceAddrMap)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
void EmitOMPDistributeLoop(const OMPLoopDirective &S, const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr)
Emit code for the distribute loop-based directive.
void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S)
static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetDirective &S)
Emit device code for the target directive.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, const llvm::function_ref< RValue(RValue)> &UpdateOp, bool IsVolatile)
const LangOptions & getLangOpts() const
static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S)
Emit device code for the target simd directive.
void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S)
void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, OMPPrivateScope &LoopScope)
Emit initial code for loop counters of loop-based directives.
void EmitOMPDistributeParallelForDirective(const OMPDistributeParallelForDirective &S)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, bool NoFinals, llvm::Value *IsLastIterCond=nullptr)
Emit final copying of lastprivate values to original variables at the end of the worksharing or simd ...
void EmitOMPInterchangeDirective(const OMPInterchangeDirective &S)
void EmitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &S)
void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S)
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
EmitExprAsInit - Emits the code necessary to initialize a location in memory with the given initializ...
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
void EmitOMPParallelDirective(const OMPParallelDirective &S)
void EmitOMPSimdFinal(const OMPLoopDirective &D, const llvm::function_ref< llvm::Value *(CodeGenFunction &)> CondGen)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
llvm::Type * ConvertTypeForMem(QualType T)
void EmitOMPDistributeParallelForSimdDirective(const OMPDistributeParallelForSimdDirective &S)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
void EmitOMPForSimdDirective(const OMPForSimdDirective &S)
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy)
Emit an aggregate assignment.
void GenerateOpenMPCapturedVars(const CapturedStmt &S, SmallVectorImpl< llvm::Value * > &CapturedVars)
JumpDest ReturnBlock
ReturnBlock - Unified return block.
const llvm::function_ref< void(CodeGenFunction &, llvm::Function *, const OMPTaskDataTy &)> TaskGenTy
static void EmitOMPTargetTeamsGenericLoopDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsGenericLoopDirective &S)
Emit device code for the target teams loop directive.
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
void EmitOMPFlushDirective(const OMPFlushDirective &S)
llvm::BasicBlock * OMPBeforeScanBlock
void EmitOMPCancelDirective(const OMPCancelDirective &S)
void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &S)
void EmitOMPTargetTeamsDistributeDirective(const OMPTargetTeamsDistributeDirective &S)
ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr)
void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S)
static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeParallelForDirective &S)
void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, SourceLocation Loc)
void EmitOMPInnerLoop(const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond, const Expr *IncExpr, const llvm::function_ref< void(CodeGenFunction &)> BodyGen, const llvm::function_ref< void(CodeGenFunction &)> PostIncGen)
Emit inner loop of the worksharing/simd construct.
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
void EmitOMPDepobjDirective(const OMPDepobjDirective &S)
void EmitOMPSingleDirective(const OMPSingleDirective &S)
void EmitOMPTargetTeamsGenericLoopDirective(const OMPTargetTeamsGenericLoopDirective &S)
llvm::CanonicalLoopInfo * EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, int Depth)
Emit the Stmt S and return its topmost canonical loop, if any.
void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D)
Emit simple code for OpenMP directives in Simd-only mode.
void EmitOMPDistributeDirective(const OMPDistributeDirective &S)
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
void EmitOMPParallelForDirective(const OMPParallelForDirective &S)
void EmitOMPTeamsDirective(const OMPTeamsDirective &S)
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void EmitOMPUnrollDirective(const OMPUnrollDirective &S)
void EmitOMPParallelMasterTaskLoopSimdDirective(const OMPParallelMasterTaskLoopSimdDirective &S)
void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
void EmitOMPTargetTeamsDistributeParallelForSimdDirective(const OMPTargetTeamsDistributeParallelForSimdDirective &S)
void EmitOMPTeamsDistributeParallelForSimdDirective(const OMPTeamsDistributeParallelForSimdDirective &S)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
llvm::Function * GenerateCapturedStmtFunction(const CapturedStmt &S)
void EmitOMPInteropDirective(const OMPInteropDirective &S)
void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind)
Emit final update of reduction values to original variables at the end of the directive.
llvm::BasicBlock * OMPScanDispatch
llvm::AtomicRMWInst * emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val, llvm::AtomicOrdering Order=llvm::AtomicOrdering::SequentiallyConsistent, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Emit an atomicrmw instruction, and applying relevant metadata when applicable.
llvm::function_ref< std::pair< LValue, LValue >(CodeGenFunction &, const OMPExecutableDirective &S)> CodeGenLoopBoundsTy
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, OMPTargetDataInfo &InputInfo)
void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S)
void EmitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &S)
static void EmitOMPTargetParallelForDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelForDirective &S)
Emit device code for the target parallel for directive.
void EmitOMPSimdInit(const OMPLoopDirective &D)
Helpers for the OpenMP loop directives.
int ExpectedOMPLoopDepth
Number of nested loop to be consumed by the last surrounding loop-associated directive.
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S)
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeSimdDirective &S)
Emit device code for the target teams distribute simd directive.
SmallVector< llvm::CanonicalLoopInfo *, 4 > OMPLoopNestStack
List of recently emitted OMPCanonicalLoops.
bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB, const CodeGenLoopBoundsTy &CodeGenLoopBounds, const CodeGenDispatchBoundsTy &CGDispatchBounds)
Emit code for the worksharing loop-based directive.
void EmitOMPLinearClause(const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope)
Emit initial code for linear clauses.
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void EmitAutoVarCleanups(const AutoVarEmission &emission)
void EmitOMPTileDirective(const OMPTileDirective &S)
bool EmitOMPLinearClauseInit(const OMPLoopDirective &D)
Emit initial code for linear variables.
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit)
Helper for the OpenMP loop directives.
void EmitOMPLinearClauseFinal(const OMPLoopDirective &D, const llvm::function_ref< llvm::Value *(CodeGenFunction &)> CondGen)
Emit final code for linear clauses.
void EmitOMPSectionsDirective(const OMPSectionsDirective &S)
llvm::BasicBlock * OMPScanExitBlock
static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetTeamsDistributeParallelForSimdDirective &S)
Emit device code for the target teams distribute parallel for simd directive.
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
void EmitOMPUseDeviceAddrClause(const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, const llvm::DenseMap< const ValueDecl *, llvm::Value * > CaptureDeviceAddrMap)
void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S)
void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S)
void EmitOMPSimdDirective(const OMPSimdDirective &S)
void EmitOMPCriticalDirective(const OMPCriticalDirective &S)
void EmitOMPForDirective(const OMPForDirective &S)
void EmitOMPMetaDirective(const OMPMetaDirective &S)
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S)
LValue InitCapturedStruct(const CapturedStmt &S)
void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S)
void EmitOMPTargetTeamsDistributeSimdDirective(const OMPTargetTeamsDistributeSimdDirective &S)
void processInReduction(const OMPExecutableDirective &S, OMPTaskDataTy &Data, CodeGenFunction &CGF, const CapturedStmt *CS, OMPPrivateScope &Scope)
void EmitOMPMasterDirective(const OMPMasterDirective &S)
void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S)
void EmitOMPTargetParallelGenericLoopDirective(const OMPTargetParallelGenericLoopDirective &S)
void EmitOMPAssumeDirective(const OMPAssumeDirective &S)
bool EmitOMPCopyinClause(const OMPExecutableDirective &D)
Emit code for copyin clause in D directive.
void EmitOMPMaskedDirective(const OMPMaskedDirective &S)
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
void EmitOMPPrivateClause(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope)
void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S)
llvm::Function * GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, SourceLocation Loc)
void EmitOMPTargetParallelForSimdDirective(const OMPTargetParallelForSimdDirective &S)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
Address GenerateCapturedStmtArgument(const CapturedStmt &S)
static void EmitOMPTargetParallelGenericLoopDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelGenericLoopDirective &S)
Emit device code for the target parallel loop directive.
llvm::function_ref< void(CodeGenFunction &, SourceLocation, const unsigned, const bool)> CodeGenOrderedTy
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
llvm::BasicBlock * OMPAfterScanBlock
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S)
void EmitOMPErrorDirective(const OMPErrorDirective &S)
void EmitOMPSectionDirective(const OMPSectionDirective &S)
static void EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName, const OMPTargetParallelDirective &S)
void EmitOMPBarrierDirective(const OMPBarrierDirective &S)
void EmitStopPoint(const Stmt *S)
EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
void EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S)
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs=std::nullopt)
EmitStmt - Emit the code for the statement.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
void EmitOMPTargetTeamsDistributeParallelForDirective(const OMPTargetTeamsDistributeParallelForDirective &S)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope)
Emit initial code for lastprivate variables.
void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S)
llvm::function_ref< void(CodeGenFunction &, const OMPLoopDirective &, JumpDest)> CodeGenLoopTy
void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S)
Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
void EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S)
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S)
std::pair< bool, RValue > EmitOMPAtomicSimpleUpdateExpr(LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, llvm::AtomicOrdering AO, SourceLocation Loc, const llvm::function_ref< RValue(RValue)> CommonGen)
Emit atomic update code for constructs: X = X BO E or X = E BO E.
This class organizes the cross-function state that is used while generating LLVM code.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
llvm::Module & getModule() const
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
const llvm::DataLayout & getDataLayout() const
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * getStaticLocalDeclAddress(const VarDecl *D)
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void assignRegionCounters(GlobalDecl GD, llvm::Function *Fn)
Assign counters to regions and configure them for PGO of a given function.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1606
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:679
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:368
LValue - This represents an lvalue references.
Definition: CGValue.h:182
llvm::Value * getPointer(CodeGenFunction &CGF) const
bool isVolatile() const
Definition: CGValue.h:328
bool isGlobalReg() const
Definition: CGValue.h:282
Address getAddress() const
Definition: CGValue.h:361
QualType getType() const
Definition: CGValue.h:291
void setAddress(Address address)
Definition: CGValue.h:363
void setUnrollCount(unsigned C)
Set the unroll count for the next loop pushed.
Definition: CGLoopInfo.h:279
void setVectorizeWidth(unsigned W)
Set the vectorize width for the next loop pushed.
Definition: CGLoopInfo.h:269
void setParallel(bool Enable=true)
Set the next pushed loop as parallel.
Definition: CGLoopInfo.h:239
void setUnrollState(const LoopAttributes::LVEnableState &State)
Set the next pushed loop unroll state.
Definition: CGLoopInfo.h:254
void pop()
End the current loop.
Definition: CGLoopInfo.cpp:834
void push(llvm::BasicBlock *Header, const llvm::DebugLoc &StartLoc, const llvm::DebugLoc &EndLoc)
Begin a new structured loop.
void setVectorizeEnable(bool Enable=true)
Set the next pushed loop 'vectorize.enable'.
Definition: CGLoopInfo.h:242
A basic class for pre|post-action for advanced codegen sequence for OpenMP region.
virtual void Enter(CodeGenFunction &CGF)
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
bool isScalar() const
Definition: CGValue.h:64
static RValue get(llvm::Value *V)
Definition: CGValue.h:98
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:108
bool isAggregate() const
Definition: CGValue.h:66
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:71
llvm::Value * second
Definition: CGValue.h:51
bool isComplex() const
Definition: CGValue.h:65
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:78
An abstract representation of an aligned address.
Definition: Address.h:42
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:72
llvm::Value * getPointer() const
Definition: Address.h:66
Class intended to support codegen of all kind of the reduction clauses.
void emitAggregateType(CodeGenFunction &CGF, unsigned N)
Emits the code for the variable-modified type, if required.
void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N)
Emits lvalue for the shared and original reduction item.
Class provides a way to call simple version of codegen for OpenMP region, or an advanced with possibl...
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1611
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
ValueDecl * getDecl()
Definition: Expr.h:1333
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1502
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:442
T * getAttr() const
Definition: DeclBase.h:580
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1077
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:1067
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:1083
SourceLocation getLocation() const
Definition: DeclBase.h:446
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool hasAttr() const
Definition: DeclBase.h:584
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3062
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Represents a function declaration or definition.
Definition: Decl.h:1932
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2121
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:5378
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:550
Represents a point when we exit a loop.
Definition: ProgramPoint.h:711
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
A C++ nested-name-specifier augmented with source location information.
This represents 'acq_rel' clause in the '#pragma omp atomic|flush' directives.
This represents 'acquire' clause in the '#pragma omp atomic|flush' directives.
This represents clause 'aligned' in the '#pragma omp ...' directives.
This represents '#pragma omp atomic' directive.
Definition: StmtOpenMP.h:2947
This represents '#pragma omp barrier' directive.
Definition: StmtOpenMP.h:2625
This represents 'bind' clause in the '#pragma omp ...' directives.
This represents '#pragma omp cancel' directive.
Definition: StmtOpenMP.h:3655
This represents '#pragma omp cancellation point' directive.
Definition: StmtOpenMP.h:3597
Representation of an OpenMP canonical loop.
Definition: StmtOpenMP.h:142
static OMPClauseWithPreInit * get(OMPClause *C)
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
This represents clause 'copyin' in the '#pragma omp ...' directives.
This represents clause 'copyprivate' in the '#pragma omp ...' directives.
This represents '#pragma omp critical' directive.
Definition: StmtOpenMP.h:2076
This represents implicit clause 'depend' for the '#pragma omp task' directive.
This represents implicit clause 'depobj' for the '#pragma omp depobj' directive.
This represents '#pragma omp depobj' directive.
Definition: StmtOpenMP.h:2841
This represents 'destroy' clause in the '#pragma omp depobj' directive or the '#pragma omp interop' d...
This represents 'device' clause in the '#pragma omp ...' directive.
This represents 'dist_schedule' clause in the '#pragma omp ...' directive.
This represents '#pragma omp distribute' directive.
Definition: StmtOpenMP.h:4425
This represents '#pragma omp distribute parallel for' composite directive.
Definition: StmtOpenMP.h:4547
This represents '#pragma omp distribute parallel for simd' composite directive.
Definition: StmtOpenMP.h:4643
This represents '#pragma omp distribute simd' composite directive.
Definition: StmtOpenMP.h:4708
This represents the 'doacross' clause for the '#pragma omp ordered' directive.
This represents '#pragma omp error' directive.
Definition: StmtOpenMP.h:6432
This is a basic class for representing single OpenMP executable directive.
Definition: StmtOpenMP.h:266
OpenMPDirectiveKind getDirectiveKind() const
Definition: StmtOpenMP.h:556
SourceLocation getEndLoc() const
Returns ending location of directive.
Definition: StmtOpenMP.h:491
static llvm::iterator_range< specific_clause_iterator< SpecificClause > > getClausesOfKind(ArrayRef< OMPClause * > Clauses)
Definition: StmtOpenMP.h:446
This represents 'fail' clause in the '#pragma omp atomic' directive.
OpenMPClauseKind getFailParameter() const
Gets the parameter (type memory-order-clause) in Fail clause.
This represents 'filter' clause in the '#pragma omp ...' directive.
This represents 'final' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:690
This represents clause 'firstprivate' in the '#pragma omp ...' directives.
This represents implicit clause 'flush' for the '#pragma omp flush' directive.
This represents '#pragma omp flush' directive.
Definition: StmtOpenMP.h:2789
This represents '#pragma omp for' directive.
Definition: StmtOpenMP.h:1634
This represents '#pragma omp for simd' directive.
Definition: StmtOpenMP.h:1724
Representation of the 'full' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:939
This represents '#pragma omp loop' directive.
Definition: StmtOpenMP.h:6103
This represents 'grainsize' clause in the '#pragma omp ...' directive.
This represents 'hint' clause in the '#pragma omp ...' directive.
This represents 'if' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:587
This represents clause 'in_reduction' in the '#pragma omp task' directives.
This represents clause 'inclusive' in the '#pragma omp scan' directive.
This represents the 'init' clause in '#pragma omp ...' directives.
Represents the '#pragma omp interchange' loop transformation directive.
Definition: StmtOpenMP.h:5769
This represents '#pragma omp interop' directive.
Definition: StmtOpenMP.h:5895
This represents clause 'lastprivate' in the '#pragma omp ...' directives.
This represents clause 'linear' in the '#pragma omp ...' directives.
The base class for all loop-based directives, including loop transformation directives.
Definition: StmtOpenMP.h:683
static Stmt * tryToFindNextInnerLoop(Stmt *CurStmt, bool TryImperfectlyNestedLoops)
Try to find the next loop sub-statement in the specified statement CurStmt.
Definition: StmtOpenMP.cpp:78
static bool doForAllLoops(Stmt *CurStmt, bool TryImperfectlyNestedLoops, unsigned NumLoops, llvm::function_ref< bool(unsigned, Stmt *)> Callback, llvm::function_ref< void(OMPLoopTransformationDirective *)> OnTransformationCallback)
Calls the specified callback function for all the loops in CurStmt, from the outermost to the innermo...
Definition: StmtOpenMP.cpp:125
This is a common base class for loop directives ('omp simd', 'omp for', 'omp for simd' etc....
Definition: StmtOpenMP.h:1004
Expr * getPrevUpperBoundVariable() const
Definition: StmtOpenMP.h:1407
Expr * getPrevLowerBoundVariable() const
Definition: StmtOpenMP.h:1402
Expr * getIterationVariable() const
Definition: StmtOpenMP.h:1319
Expr * getUpperBoundVariable() const
Definition: StmtOpenMP.h:1354
Expr * getLowerBoundVariable() const
Definition: StmtOpenMP.h:1346
This represents '#pragma omp masked' directive.
Definition: StmtOpenMP.h:6013
This represents '#pragma omp master' directive.
Definition: StmtOpenMP.h:2028
This represents '#pragma omp master taskloop' directive.
Definition: StmtOpenMP.h:3854
This represents '#pragma omp master taskloop simd' directive.
Definition: StmtOpenMP.h:4006
This represents 'message' clause in the '#pragma omp error' directive.
Expr * getMessageString() const
Returns message string of the clause.
This represents '#pragma omp metadirective' directive.
Definition: StmtOpenMP.h:6064
This represents 'nogroup' clause in the '#pragma omp ...' directive.
This represents 'nowait' clause in the '#pragma omp ...' directive.
This represents 'num_tasks' clause in the '#pragma omp ...' directive.
This represents 'num_teams' clause in the '#pragma omp ...' directive.
This represents 'num_threads' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:736
This represents 'order' clause in the '#pragma omp ...' directive.
This represents 'ordered' clause in the '#pragma omp ...' directive.
This represents '#pragma omp ordered' directive.
Definition: StmtOpenMP.h:2893
This represents '#pragma omp parallel' directive.
Definition: StmtOpenMP.h:612
This represents '#pragma omp parallel for' directive.
Definition: StmtOpenMP.h:2147
This represents '#pragma omp parallel for simd' directive.
Definition: StmtOpenMP.h:2244
This represents '#pragma omp parallel masked' directive.
Definition: StmtOpenMP.h:2372
This represents '#pragma omp parallel master' directive.
Definition: StmtOpenMP.h:2309
This represents '#pragma omp parallel master taskloop' directive.
Definition: StmtOpenMP.h:4137
This represents '#pragma omp parallel master taskloop simd' directive.
Definition: StmtOpenMP.h:4293
This represents '#pragma omp parallel sections' directive.
Definition: StmtOpenMP.h:2436
Representation of the 'partial' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:967
This represents 'priority' clause in the '#pragma omp ...' directive.
This represents clause 'private' in the '#pragma omp ...' directives.
This represents 'proc_bind' clause in the '#pragma omp ...' directive.
This represents clause 'reduction' in the '#pragma omp ...' directives.
This represents 'relaxed' clause in the '#pragma omp atomic' directives.
This represents 'release' clause in the '#pragma omp atomic|flush' directives.
Represents the '#pragma omp reverse' loop transformation directive.
Definition: StmtOpenMP.h:5704
This represents 'simd' clause in the '#pragma omp ...' directive.
This represents 'safelen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:781
This represents '#pragma omp scan' directive.
Definition: StmtOpenMP.h:5842
This represents 'schedule' clause in the '#pragma omp ...' directive.
This represents '#pragma omp section' directive.
Definition: StmtOpenMP.h:1864
This represents '#pragma omp sections' directive.
Definition: StmtOpenMP.h:1787
This represents 'seq_cst' clause in the '#pragma omp atomic' directive.
This represents 'severity' clause in the '#pragma omp error' directive.
OpenMPSeverityClauseKind getSeverityKind() const
Returns kind of the clause.
This represents '#pragma omp simd' directive.
Definition: StmtOpenMP.h:1571
This represents 'simdlen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:816
This represents '#pragma omp single' directive.
Definition: StmtOpenMP.h:1977
This represents '#pragma omp target data' directive.
Definition: StmtOpenMP.h:3206
This represents '#pragma omp target' directive.
Definition: StmtOpenMP.h:3152
This represents '#pragma omp target enter data' directive.
Definition: StmtOpenMP.h:3260
This represents '#pragma omp target exit data' directive.
Definition: StmtOpenMP.h:3315
This represents '#pragma omp target parallel' directive.
Definition: StmtOpenMP.h:3369
This represents '#pragma omp target parallel for' directive.
Definition: StmtOpenMP.h:3449
This represents '#pragma omp target parallel for simd' directive.
Definition: StmtOpenMP.h:4774
This represents '#pragma omp target parallel loop' directive.
Definition: StmtOpenMP.h:6370
This represents '#pragma omp target simd' directive.
Definition: StmtOpenMP.h:4841
This represents '#pragma omp target teams' directive.
Definition: StmtOpenMP.h:5199
This represents '#pragma omp target teams distribute' combined directive.
Definition: StmtOpenMP.h:5255
This represents '#pragma omp target teams distribute parallel for' combined directive.
Definition: StmtOpenMP.h:5322
This represents '#pragma omp target teams distribute parallel for simd' combined directive.
Definition: StmtOpenMP.h:5420
This represents '#pragma omp target teams distribute simd' combined directive.
Definition: StmtOpenMP.h:5490
This represents '#pragma omp target teams loop' directive.
Definition: StmtOpenMP.h:6230
This represents '#pragma omp target update' directive.
Definition: StmtOpenMP.h:4491
This represents '#pragma omp task' directive.
Definition: StmtOpenMP.h:2517
This represents '#pragma omp taskloop' directive.
Definition: StmtOpenMP.h:3715
This represents '#pragma omp taskloop simd' directive.
Definition: StmtOpenMP.h:3788
This represents clause 'task_reduction' in the '#pragma omp taskgroup' directives.
This represents '#pragma omp taskgroup' directive.
Definition: StmtOpenMP.h:2722
This represents '#pragma omp taskwait' directive.
Definition: StmtOpenMP.h:2671
This represents '#pragma omp taskyield' directive.
Definition: StmtOpenMP.h:2579
This represents '#pragma omp teams' directive.
Definition: StmtOpenMP.h:3544
This represents '#pragma omp teams distribute' directive.
Definition: StmtOpenMP.h:4906
This represents '#pragma omp teams distribute parallel for' composite directive.
Definition: StmtOpenMP.h:5106
This represents '#pragma omp teams distribute parallel for simd' composite directive.
Definition: StmtOpenMP.h:5040
This represents '#pragma omp teams distribute simd' combined directive.
Definition: StmtOpenMP.h:4972
This represents '#pragma omp teams loop' directive.
Definition: StmtOpenMP.h:6165
This represents 'thread_limit' clause in the '#pragma omp ...' directive.
This represents the '#pragma omp tile' loop transformation directive.
Definition: StmtOpenMP.h:5548
This represents the '#pragma omp unroll' loop transformation directive.
Definition: StmtOpenMP.h:5630
This represents 'untied' clause in the '#pragma omp ...' directive.
This represents 'update' clause in the '#pragma omp atomic' directive.
This represents the 'use' clause in '#pragma omp ...' directives.
This represents clause 'use_device_addr' in the '#pragma omp ...' directives.
This represents clause 'use_device_ptr' in the '#pragma omp ...' directives.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2903
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
bool isValid() const
unsigned getLine() const
Return the presumed line number of this location.
If a crash happens while one of these objects are live, the message is printed out along with the spe...
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7834
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7951
Represents a struct/union/class.
Definition: Decl.h:4145
field_range fields() const
Definition: Decl.h:4351
field_iterator field_begin() const
Definition: Decl.cpp:5068
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:287
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2398
virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits, uint64_t AlignmentInBits) const
Returns true if the given target supports lock-free atomic operations at the specified width and alig...
Definition: TargetInfo.h:840
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1576
The base class of the type hierarchy.
Definition: Type.h:1829
bool isArrayType() const
Definition: Type.h:8075
bool isPointerType() const
Definition: Type.h:8003
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isScalarType() const
Definition: Type.h:8418
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isLValueReferenceType() const
Definition: Type.h:8025
bool isAnyComplexType() const
Definition: Type.h:8111
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2186
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2713
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8593
bool isAnyPointerType() const
Definition: Type.h:8011
bool isRecordType() const
Definition: Type.h:8103
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4916
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
TLSKind getTLSKind() const
Definition: Decl.cpp:2150
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2239
@ CInit
C-style initialization with assignment.
Definition: Decl.h:884
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1174
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
const Expr * getInit() const
Definition: Decl.h:1316
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
@ TLS_None
Not a TLS variable.
Definition: Decl.h:899
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3795
Expr * getSizeExpr() const
Definition: Type.h:3814
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:771
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
bool isOpenMPWorksharingDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a worksharing directive.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
bool needsTaskBasedThreadLimit(OpenMPDirectiveKind DKind)
Checks if the specified target directive, combined or not, needs task based thread_limit.
@ Ctor_Complete
Complete object ctor.
Definition: ABI.h:25
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition: OpenMPKinds.h:24
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
bool isOpenMPDistributeDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a distribute directive.
BinaryOperatorKind
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition: OpenMPKinds.h:38
@ OMPC_SCHEDULE_MODIFIER_unknown
Definition: OpenMPKinds.h:39
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
@ CR_OpenMP
Definition: CapturedStmt.h:19
bool isOpenMPParallelDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a parallel-kind directive.
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
Definition: OpenMPKinds.h:103
@ OMPC_DIST_SCHEDULE_unknown
Definition: OpenMPKinds.h:106
bool isOpenMPTaskingDirective(OpenMPDirectiveKind Kind)
Checks if the specified directive kind is one of tasking directives - task, taskloop,...
bool isOpenMPTargetExecutionDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a target code offload directive.
@ Result
The result type of a method or function.
bool isOpenMPTeamsDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a teams-kind directive.
bool isOpenMPGenericLoopDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive constitutes a 'loop' directive in the outermost nest.
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
Definition: OpenMPKinds.h:200
@ OMPC_BIND_unknown
Definition: OpenMPKinds.h:203
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition: OpenMPKinds.h:54
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
bool isOpenMPLoopBoundSharingDirective(OpenMPDirectiveKind Kind)
Checks if the specified directive kind is one of the composite or combined directives that need loop ...
bool isOpenMPSimdDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a simd directive.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void getOpenMPCaptureRegions(llvm::SmallVectorImpl< OpenMPDirectiveKind > &CaptureRegions, OpenMPDirectiveKind DKind)
Return the captured regions of an OpenMP directive.
@ OMPC_DEVICE_unknown
Definition: OpenMPKinds.h:50
@ ThreadPrivateVar
Parameter for Thread private variable.
@ Other
Other implicit parameter.
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition: OpenMPKinds.h:30
@ OMPC_SCHEDULE_unknown
Definition: OpenMPKinds.h:34
bool isOpenMPTaskLoopDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a taskloop directive.
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
struct with the values to be passed to the dispatch runtime function
llvm::Value * Chunk
Chunk size specified using 'schedule' clause (nullptr if chunk was not specified)
Struct with the values to be passed to the static runtime function.
QualType getType() const
Definition: CGCall.h:248
static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
llvm::OpenMPIRBuilder::InsertPointTy InsertPointTy
static void EmitOMPOutlinedRegionBody(CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Twine RegionName)
Emit the body of an OMP region that will be outlined in OpenMPIRBuilder::finalize().
static Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD)
Gets the OpenMP-specific address of the local variable /p VD.
static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP, llvm::BasicBlock &FiniBB, llvm::Function *Fn, ArrayRef< llvm::Value * > Args)
static std::string getNameWithSeparators(ArrayRef< StringRef > Parts, StringRef FirstSeparator=".", StringRef Separator=".")
Get the platform-specific name separator.
static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP)
Emit the Finalization for an OMP region.
static void EmitOMPInlinedRegionBody(CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Twine RegionName)
Emit the body of an OMP region.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
SmallVector< const Expr *, 4 > DepExprs
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:5087
Scheduling data for loop-based OpenMP directives.
Definition: OpenMPKinds.h:179
OpenMPScheduleClauseModifier M2
Definition: OpenMPKinds.h:182
OpenMPScheduleClauseModifier M1
Definition: OpenMPKinds.h:181
OpenMPScheduleClauseKind Schedule
Definition: OpenMPKinds.h:180