Bug Summary

File:tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp
Warning:line 8180, column 58
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGOpenMPRuntime.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp
1//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCXXABI.h"
15#include "CGCleanup.h"
16#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
18#include "clang/CodeGen/ConstantInitBuilder.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/StmtOpenMP.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/BitmaskEnum.h"
23#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/IR/CallSite.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
28#include "llvm/Support/Format.h"
29#include "llvm/Support/raw_ostream.h"
30#include <cassert>
31
32using namespace clang;
33using namespace CodeGen;
34
35namespace {
36/// \brief Base class for handling code generation inside OpenMP regions.
37class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
39 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
49 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
51 };
52
53 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
55 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
57 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
58 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
59
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
61 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
63 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
64 Kind(Kind), HasCancel(HasCancel) {}
65
66 /// \brief Get a variable or parameter for storing global thread id
67 /// inside OpenMP construct.
68 virtual const VarDecl *getThreadIDVariable() const = 0;
69
70 /// \brief Emit the captured statement body.
71 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
72
73 /// \brief Get an LValue for the current ThreadID variable.
74 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
76
77 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
79 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
80
81 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
83 bool hasCancel() const { return HasCancel; }
84
85 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
88
89 ~CGOpenMPRegionInfo() override = default;
90
91protected:
92 CGOpenMPRegionKind RegionKind;
93 RegionCodeGenTy CodeGen;
94 OpenMPDirectiveKind Kind;
95 bool HasCancel;
96};
97
98/// \brief API for captured statement code generation in OpenMP constructs.
99class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
100public:
101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
102 const RegionCodeGenTy &CodeGen,
103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.")(static_cast <bool> (ThreadIDVar != nullptr && "No ThreadID in OpenMP region."
) ? void (0) : __assert_fail ("ThreadIDVar != nullptr && \"No ThreadID in OpenMP region.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 108, __extension__ __PRETTY_FUNCTION__))
;
109 }
110
111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
114
115 /// \brief Get the name of the capture helper.
116 StringRef getHelperName() const override { return HelperName; }
117
118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
128 StringRef HelperName;
129};
130
131/// \brief API for captured statement code generation in OpenMP constructs.
132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
133public:
134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
182 const VarDecl *ThreadIDVar,
183 const RegionCodeGenTy &CodeGen,
184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
187 ThreadIDVar(ThreadIDVar), Action(Action) {
188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.")(static_cast <bool> (ThreadIDVar != nullptr && "No ThreadID in OpenMP region."
) ? void (0) : __assert_fail ("ThreadIDVar != nullptr && \"No ThreadID in OpenMP region.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 188, __extension__ __PRETTY_FUNCTION__))
;
189 }
190
191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
194
195 /// \brief Get an LValue for the current ThreadID variable.
196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
197
198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
217};
218
219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
224 const RegionCodeGenTy &CodeGen,
225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
229
230 // \brief Retrieve the value of the context parameter.
231 llvm::Value *getContextValue() const override {
232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region")::llvm::llvm_unreachable_internal("No context value for inlined OpenMP region"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 234)
;
235 }
236
237 void setContextValue(llvm::Value *V) override {
238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region")::llvm::llvm_unreachable_internal("No context value for inlined OpenMP region"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 242)
;
243 }
244
245 /// \brief Lookup the captured field decl for a variable.
246 const FieldDecl *lookup(const VarDecl *VD) const override {
247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
252 }
253
254 FieldDecl *getThisFieldDecl() const override {
255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
259
260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
262 const VarDecl *getThreadIDVariable() const override {
263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
267
268 /// \brief Get an LValue for the current ThreadID variable.
269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct")::llvm::llvm_unreachable_internal("No LValue for inlined OpenMP construct"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 272)
;
273 }
274
275 /// \brief Get the name of the capture helper.
276 StringRef getHelperName() const override {
277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
279 llvm_unreachable("No helper name for inlined OpenMP construct")::llvm::llvm_unreachable_internal("No helper name for inlined OpenMP construct"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 279)
;
280 }
281
282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
294 ~CGOpenMPInlinedRegionInfo() override = default;
295
296private:
297 /// \brief CodeGen info about outer OpenMP region.
298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
300};
301
302/// \brief API for captured statement code generation in OpenMP target
303/// constructs. For this captures, implicit parameters are used instead of the
304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
314
315 /// \brief This is unused for target regions because each starts executing
316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
319 /// \brief Get the name of the capture helper.
320 StringRef getHelperName() const override { return HelperName; }
321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
326
327private:
328 StringRef HelperName;
329};
330
331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
332 llvm_unreachable("No codegen for expressions")::llvm::llvm_unreachable_internal("No codegen for expressions"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 332)
;
333}
334/// \brief API for generation of expressions captured in a innermost OpenMP
335/// region.
336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
346 for (auto &C : CS.captures()) {
347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
354 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
357 C.getLocation());
358 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
359 return CGF.EmitLValue(&DRE).getAddress();
360 });
361 }
362 (void)PrivScope.Privatize();
363 }
364
365 /// \brief Lookup the captured field decl for a variable.
366 const FieldDecl *lookup(const VarDecl *VD) const override {
367 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
368 return FD;
369 return nullptr;
370 }
371
372 /// \brief Emit the captured statement body.
373 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
374 llvm_unreachable("No body for expressions")::llvm::llvm_unreachable_internal("No body for expressions", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 374)
;
375 }
376
377 /// \brief Get a variable or parameter for storing global thread id
378 /// inside OpenMP construct.
379 const VarDecl *getThreadIDVariable() const override {
380 llvm_unreachable("No thread id for expressions")::llvm::llvm_unreachable_internal("No thread id for expressions"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 380)
;
381 }
382
383 /// \brief Get the name of the capture helper.
384 StringRef getHelperName() const override {
385 llvm_unreachable("No helper name for expressions")::llvm::llvm_unreachable_internal("No helper name for expressions"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 385)
;
386 }
387
388 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
389
390private:
391 /// Private scope to capture global variables.
392 CodeGenFunction::OMPPrivateScope PrivScope;
393};
394
395/// \brief RAII for emitting code of OpenMP constructs.
396class InlinedOpenMPRegionRAII {
397 CodeGenFunction &CGF;
398 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
399 FieldDecl *LambdaThisCaptureField = nullptr;
400 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
401
402public:
403 /// \brief Constructs region for combined constructs.
404 /// \param CodeGen Code generation sequence for combined directives. Includes
405 /// a list of functions used for code generation of implicitly inlined
406 /// regions.
407 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
408 OpenMPDirectiveKind Kind, bool HasCancel)
409 : CGF(CGF) {
410 // Start emission for the construct.
411 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
412 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
415 CGF.LambdaThisCaptureField = nullptr;
416 BlockInfo = CGF.BlockInfo;
417 CGF.BlockInfo = nullptr;
418 }
419
420 ~InlinedOpenMPRegionRAII() {
421 // Restore original CapturedStmtInfo only if we're done with code emission.
422 auto *OldCSI =
423 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
424 delete CGF.CapturedStmtInfo;
425 CGF.CapturedStmtInfo = OldCSI;
426 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
427 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
428 CGF.BlockInfo = BlockInfo;
429 }
430};
431
432/// \brief Values for bit flags used in the ident_t to describe the fields.
433/// All enumeric elements are named and described in accordance with the code
434/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
435enum OpenMPLocationFlags : unsigned {
436 /// \brief Use trampoline for internal microtask.
437 OMP_IDENT_IMD = 0x01,
438 /// \brief Use c-style ident structure.
439 OMP_IDENT_KMPC = 0x02,
440 /// \brief Atomic reduction option for kmpc_reduce.
441 OMP_ATOMIC_REDUCE = 0x10,
442 /// \brief Explicit 'barrier' directive.
443 OMP_IDENT_BARRIER_EXPL = 0x20,
444 /// \brief Implicit barrier in code.
445 OMP_IDENT_BARRIER_IMPL = 0x40,
446 /// \brief Implicit barrier in 'for' directive.
447 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
448 /// \brief Implicit barrier in 'sections' directive.
449 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
450 /// \brief Implicit barrier in 'single' directive.
451 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
452 /// Call of __kmp_for_static_init for static loop.
453 OMP_IDENT_WORK_LOOP = 0x200,
454 /// Call of __kmp_for_static_init for sections.
455 OMP_IDENT_WORK_SECTIONS = 0x400,
456 /// Call of __kmp_for_static_init for distribute.
457 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
458 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)LLVM_BITMASK_LARGEST_ENUMERATOR = OMP_IDENT_WORK_DISTRIBUTE
459};
460
461/// \brief Describes ident structure that describes a source location.
462/// All descriptions are taken from
463/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
464/// Original structure:
465/// typedef struct ident {
466/// kmp_int32 reserved_1; /**< might be used in Fortran;
467/// see above */
468/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
469/// KMP_IDENT_KMPC identifies this union
470/// member */
471/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
472/// see above */
473///#if USE_ITT_BUILD
474/// /* but currently used for storing
475/// region-specific ITT */
476/// /* contextual information. */
477///#endif /* USE_ITT_BUILD */
478/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
479/// C++ */
480/// char const *psource; /**< String describing the source location.
481/// The string is composed of semi-colon separated
482// fields which describe the source file,
483/// the function and a pair of line numbers that
484/// delimit the construct.
485/// */
486/// } ident_t;
487enum IdentFieldIndex {
488 /// \brief might be used in Fortran
489 IdentField_Reserved_1,
490 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
491 IdentField_Flags,
492 /// \brief Not really used in Fortran any more
493 IdentField_Reserved_2,
494 /// \brief Source[4] in Fortran, do not use for C++
495 IdentField_Reserved_3,
496 /// \brief String describing the source location. The string is composed of
497 /// semi-colon separated fields which describe the source file, the function
498 /// and a pair of line numbers that delimit the construct.
499 IdentField_PSource
500};
501
502/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
503/// the enum sched_type in kmp.h).
504enum OpenMPSchedType {
505 /// \brief Lower bound for default (unordered) versions.
506 OMP_sch_lower = 32,
507 OMP_sch_static_chunked = 33,
508 OMP_sch_static = 34,
509 OMP_sch_dynamic_chunked = 35,
510 OMP_sch_guided_chunked = 36,
511 OMP_sch_runtime = 37,
512 OMP_sch_auto = 38,
513 /// static with chunk adjustment (e.g., simd)
514 OMP_sch_static_balanced_chunked = 45,
515 /// \brief Lower bound for 'ordered' versions.
516 OMP_ord_lower = 64,
517 OMP_ord_static_chunked = 65,
518 OMP_ord_static = 66,
519 OMP_ord_dynamic_chunked = 67,
520 OMP_ord_guided_chunked = 68,
521 OMP_ord_runtime = 69,
522 OMP_ord_auto = 70,
523 OMP_sch_default = OMP_sch_static,
524 /// \brief dist_schedule types
525 OMP_dist_sch_static_chunked = 91,
526 OMP_dist_sch_static = 92,
527 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
528 /// Set if the monotonic schedule modifier was present.
529 OMP_sch_modifier_monotonic = (1 << 29),
530 /// Set if the nonmonotonic schedule modifier was present.
531 OMP_sch_modifier_nonmonotonic = (1 << 30),
532};
533
534enum OpenMPRTLFunction {
535 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
536 /// kmpc_micro microtask, ...);
537 OMPRTL__kmpc_fork_call,
538 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
539 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
540 OMPRTL__kmpc_threadprivate_cached,
541 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
542 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
543 OMPRTL__kmpc_threadprivate_register,
544 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
545 OMPRTL__kmpc_global_thread_num,
546 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
547 // kmp_critical_name *crit);
548 OMPRTL__kmpc_critical,
549 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
550 // global_tid, kmp_critical_name *crit, uintptr_t hint);
551 OMPRTL__kmpc_critical_with_hint,
552 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
553 // kmp_critical_name *crit);
554 OMPRTL__kmpc_end_critical,
555 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
556 // global_tid);
557 OMPRTL__kmpc_cancel_barrier,
558 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
559 OMPRTL__kmpc_barrier,
560 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
561 OMPRTL__kmpc_for_static_fini,
562 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
563 // global_tid);
564 OMPRTL__kmpc_serialized_parallel,
565 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
566 // global_tid);
567 OMPRTL__kmpc_end_serialized_parallel,
568 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
569 // kmp_int32 num_threads);
570 OMPRTL__kmpc_push_num_threads,
571 // Call to void __kmpc_flush(ident_t *loc);
572 OMPRTL__kmpc_flush,
573 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
574 OMPRTL__kmpc_master,
575 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
576 OMPRTL__kmpc_end_master,
577 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
578 // int end_part);
579 OMPRTL__kmpc_omp_taskyield,
580 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
581 OMPRTL__kmpc_single,
582 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
583 OMPRTL__kmpc_end_single,
584 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
585 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
586 // kmp_routine_entry_t *task_entry);
587 OMPRTL__kmpc_omp_task_alloc,
588 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
589 // new_task);
590 OMPRTL__kmpc_omp_task,
591 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
592 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
593 // kmp_int32 didit);
594 OMPRTL__kmpc_copyprivate,
595 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
596 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
597 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
598 OMPRTL__kmpc_reduce,
599 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
600 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
601 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
602 // *lck);
603 OMPRTL__kmpc_reduce_nowait,
604 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
605 // kmp_critical_name *lck);
606 OMPRTL__kmpc_end_reduce,
607 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
608 // kmp_critical_name *lck);
609 OMPRTL__kmpc_end_reduce_nowait,
610 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
611 // kmp_task_t * new_task);
612 OMPRTL__kmpc_omp_task_begin_if0,
613 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
614 // kmp_task_t * new_task);
615 OMPRTL__kmpc_omp_task_complete_if0,
616 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
617 OMPRTL__kmpc_ordered,
618 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
619 OMPRTL__kmpc_end_ordered,
620 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
621 // global_tid);
622 OMPRTL__kmpc_omp_taskwait,
623 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
624 OMPRTL__kmpc_taskgroup,
625 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
626 OMPRTL__kmpc_end_taskgroup,
627 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
628 // int proc_bind);
629 OMPRTL__kmpc_push_proc_bind,
630 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
632 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_task_with_deps,
634 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
635 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
636 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
637 OMPRTL__kmpc_omp_wait_deps,
638 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
639 // global_tid, kmp_int32 cncl_kind);
640 OMPRTL__kmpc_cancellationpoint,
641 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
642 // kmp_int32 cncl_kind);
643 OMPRTL__kmpc_cancel,
644 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
645 // kmp_int32 num_teams, kmp_int32 thread_limit);
646 OMPRTL__kmpc_push_num_teams,
647 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
648 // microtask, ...);
649 OMPRTL__kmpc_fork_teams,
650 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
651 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
652 // sched, kmp_uint64 grainsize, void *task_dup);
653 OMPRTL__kmpc_taskloop,
654 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
655 // num_dims, struct kmp_dim *dims);
656 OMPRTL__kmpc_doacross_init,
657 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
658 OMPRTL__kmpc_doacross_fini,
659 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
660 // *vec);
661 OMPRTL__kmpc_doacross_post,
662 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
663 // *vec);
664 OMPRTL__kmpc_doacross_wait,
665 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
666 // *data);
667 OMPRTL__kmpc_task_reduction_init,
668 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
669 // *d);
670 OMPRTL__kmpc_task_reduction_get_th_data,
671
672 //
673 // Offloading related calls
674 //
675 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
676 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
677 // *arg_types);
678 OMPRTL__tgt_target,
679 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
680 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
681 // *arg_types);
682 OMPRTL__tgt_target_nowait,
683 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
684 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
685 // *arg_types, int32_t num_teams, int32_t thread_limit);
686 OMPRTL__tgt_target_teams,
687 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
688 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
689 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
690 OMPRTL__tgt_target_teams_nowait,
691 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
692 OMPRTL__tgt_register_lib,
693 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
694 OMPRTL__tgt_unregister_lib,
695 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
696 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
697 OMPRTL__tgt_target_data_begin,
698 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
699 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
700 // *arg_types);
701 OMPRTL__tgt_target_data_begin_nowait,
702 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
703 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
704 OMPRTL__tgt_target_data_end,
705 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
706 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
707 // *arg_types);
708 OMPRTL__tgt_target_data_end_nowait,
709 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
710 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
711 OMPRTL__tgt_target_data_update,
712 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
713 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
714 // *arg_types);
715 OMPRTL__tgt_target_data_update_nowait,
716};
717
718/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
719/// region.
720class CleanupTy final : public EHScopeStack::Cleanup {
721 PrePostActionTy *Action;
722
723public:
724 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
725 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
726 if (!CGF.HaveInsertPoint())
727 return;
728 Action->Exit(CGF);
729 }
730};
731
732} // anonymous namespace
733
734void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
735 CodeGenFunction::RunCleanupsScope Scope(CGF);
736 if (PrePostAction) {
737 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
738 Callback(CodeGen, CGF, *PrePostAction);
739 } else {
740 PrePostActionTy Action;
741 Callback(CodeGen, CGF, Action);
742 }
743}
744
745/// Check if the combiner is a call to UDR combiner and if it is so return the
746/// UDR decl used for reduction.
747static const OMPDeclareReductionDecl *
748getReductionInit(const Expr *ReductionOp) {
749 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
750 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
751 if (auto *DRE =
752 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
753 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
754 return DRD;
755 return nullptr;
756}
757
758static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
759 const OMPDeclareReductionDecl *DRD,
760 const Expr *InitOp,
761 Address Private, Address Original,
762 QualType Ty) {
763 if (DRD->getInitializer()) {
764 std::pair<llvm::Function *, llvm::Function *> Reduction =
765 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
766 auto *CE = cast<CallExpr>(InitOp);
767 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
768 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
769 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
770 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
771 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
772 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
773 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
774 [=]() -> Address { return Private; });
775 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
776 [=]() -> Address { return Original; });
777 (void)PrivateScope.Privatize();
778 RValue Func = RValue::get(Reduction.second);
779 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
780 CGF.EmitIgnoredExpr(InitOp);
781 } else {
782 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
783 auto *GV = new llvm::GlobalVariable(
784 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
785 llvm::GlobalValue::PrivateLinkage, Init, ".init");
786 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
787 RValue InitRVal;
788 switch (CGF.getEvaluationKind(Ty)) {
789 case TEK_Scalar:
790 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
791 break;
792 case TEK_Complex:
793 InitRVal =
794 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
795 break;
796 case TEK_Aggregate:
797 InitRVal = RValue::getAggregate(LV.getAddress());
798 break;
799 }
800 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
801 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
802 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
803 /*IsInitializer=*/false);
804 }
805}
806
807/// \brief Emit initialization of arrays of complex types.
808/// \param DestAddr Address of the array.
809/// \param Type Type of array.
810/// \param Init Initial expression of array.
811/// \param SrcAddr Address of the original array.
812static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
813 QualType Type, bool EmitDeclareReductionInit,
814 const Expr *Init,
815 const OMPDeclareReductionDecl *DRD,
816 Address SrcAddr = Address::invalid()) {
817 // Perform element-by-element initialization.
818 QualType ElementTy;
819
820 // Drill down to the base element type on both arrays.
821 auto ArrayTy = Type->getAsArrayTypeUnsafe();
822 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
823 DestAddr =
824 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
825 if (DRD)
826 SrcAddr =
827 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
828
829 llvm::Value *SrcBegin = nullptr;
830 if (DRD)
831 SrcBegin = SrcAddr.getPointer();
832 auto DestBegin = DestAddr.getPointer();
833 // Cast from pointer to array type to pointer to single element.
834 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
835 // The basic structure here is a while-do loop.
836 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
837 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
838 auto IsEmpty =
839 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
840 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
841
842 // Enter the loop body, making that address the current address.
843 auto EntryBB = CGF.Builder.GetInsertBlock();
844 CGF.EmitBlock(BodyBB);
845
846 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
847
848 llvm::PHINode *SrcElementPHI = nullptr;
849 Address SrcElementCurrent = Address::invalid();
850 if (DRD) {
851 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
852 "omp.arraycpy.srcElementPast");
853 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
854 SrcElementCurrent =
855 Address(SrcElementPHI,
856 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
857 }
858 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
859 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
860 DestElementPHI->addIncoming(DestBegin, EntryBB);
861 Address DestElementCurrent =
862 Address(DestElementPHI,
863 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
864
865 // Emit copy.
866 {
867 CodeGenFunction::RunCleanupsScope InitScope(CGF);
868 if (EmitDeclareReductionInit) {
869 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
870 SrcElementCurrent, ElementTy);
871 } else
872 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
873 /*IsInitializer=*/false);
874 }
875
876 if (DRD) {
877 // Shift the address forward by one element.
878 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
879 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
880 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
881 }
882
883 // Shift the address forward by one element.
884 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
885 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
886 // Check whether we've reached the end.
887 auto Done =
888 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
889 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
890 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
891
892 // Done.
893 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
894}
895
896static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
897isDeclareTargetDeclaration(const ValueDecl *VD) {
898 for (const auto *D : VD->redecls()) {
899 if (!D->hasAttrs())
900 continue;
901 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
902 return Attr->getMapType();
903 }
904 return llvm::None;
905}
906
907LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
908 return CGF.EmitOMPSharedLValue(E);
909}
910
911LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
912 const Expr *E) {
913 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
914 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
915 return LValue();
916}
917
918void ReductionCodeGen::emitAggregateInitialization(
919 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
920 const OMPDeclareReductionDecl *DRD) {
921 // Emit VarDecl with copy init for arrays.
922 // Get the address of the original variable captured in current
923 // captured region.
924 auto *PrivateVD =
925 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
926 bool EmitDeclareReductionInit =
927 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
928 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
929 EmitDeclareReductionInit,
930 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
931 : PrivateVD->getInit(),
932 DRD, SharedLVal.getAddress());
933}
934
935ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
936 ArrayRef<const Expr *> Privates,
937 ArrayRef<const Expr *> ReductionOps) {
938 ClausesData.reserve(Shareds.size());
939 SharedAddresses.reserve(Shareds.size());
940 Sizes.reserve(Shareds.size());
941 BaseDecls.reserve(Shareds.size());
942 auto IPriv = Privates.begin();
943 auto IRed = ReductionOps.begin();
944 for (const auto *Ref : Shareds) {
945 ClausesData.emplace_back(Ref, *IPriv, *IRed);
946 std::advance(IPriv, 1);
947 std::advance(IRed, 1);
948 }
949}
950
951void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
952 assert(SharedAddresses.size() == N &&(static_cast <bool> (SharedAddresses.size() == N &&
"Number of generated lvalues must be exactly N.") ? void (0)
: __assert_fail ("SharedAddresses.size() == N && \"Number of generated lvalues must be exactly N.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 953, __extension__ __PRETTY_FUNCTION__))
953 "Number of generated lvalues must be exactly N.")(static_cast <bool> (SharedAddresses.size() == N &&
"Number of generated lvalues must be exactly N.") ? void (0)
: __assert_fail ("SharedAddresses.size() == N && \"Number of generated lvalues must be exactly N.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 953, __extension__ __PRETTY_FUNCTION__))
;
954 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
955 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
956 SharedAddresses.emplace_back(First, Second);
957}
958
959void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
960 auto *PrivateVD =
961 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
962 QualType PrivateType = PrivateVD->getType();
963 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
964 if (!PrivateType->isVariablyModifiedType()) {
965 Sizes.emplace_back(
966 CGF.getTypeSize(
967 SharedAddresses[N].first.getType().getNonReferenceType()),
968 nullptr);
969 return;
970 }
971 llvm::Value *Size;
972 llvm::Value *SizeInChars;
973 llvm::Type *ElemType =
974 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
975 ->getElementType();
976 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
977 if (AsArraySection) {
978 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
979 SharedAddresses[N].first.getPointer());
980 Size = CGF.Builder.CreateNUWAdd(
981 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
982 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
983 } else {
984 SizeInChars = CGF.getTypeSize(
985 SharedAddresses[N].first.getType().getNonReferenceType());
986 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
987 }
988 Sizes.emplace_back(SizeInChars, Size);
989 CodeGenFunction::OpaqueValueMapping OpaqueMap(
990 CGF,
991 cast<OpaqueValueExpr>(
992 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
993 RValue::get(Size));
994 CGF.EmitVariablyModifiedType(PrivateType);
995}
996
997void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
998 llvm::Value *Size) {
999 auto *PrivateVD =
1000 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1001 QualType PrivateType = PrivateVD->getType();
1002 if (!PrivateType->isVariablyModifiedType()) {
1003 assert(!Size && !Sizes[N].second &&(static_cast <bool> (!Size && !Sizes[N].second &&
"Size should be nullptr for non-variably modified reduction "
"items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1005, __extension__ __PRETTY_FUNCTION__))
1004 "Size should be nullptr for non-variably modified reduction "(static_cast <bool> (!Size && !Sizes[N].second &&
"Size should be nullptr for non-variably modified reduction "
"items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1005, __extension__ __PRETTY_FUNCTION__))
1005 "items.")(static_cast <bool> (!Size && !Sizes[N].second &&
"Size should be nullptr for non-variably modified reduction "
"items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1005, __extension__ __PRETTY_FUNCTION__))
;
1006 return;
1007 }
1008 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1009 CGF,
1010 cast<OpaqueValueExpr>(
1011 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1012 RValue::get(Size));
1013 CGF.EmitVariablyModifiedType(PrivateType);
1014}
1015
1016void ReductionCodeGen::emitInitialization(
1017 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1018 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1019 assert(SharedAddresses.size() > N && "No variable was generated")(static_cast <bool> (SharedAddresses.size() > N &&
"No variable was generated") ? void (0) : __assert_fail ("SharedAddresses.size() > N && \"No variable was generated\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1019, __extension__ __PRETTY_FUNCTION__))
;
1020 auto *PrivateVD =
1021 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1022 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1023 QualType PrivateType = PrivateVD->getType();
1024 PrivateAddr = CGF.Builder.CreateElementBitCast(
1025 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1026 QualType SharedType = SharedAddresses[N].first.getType();
1027 SharedLVal = CGF.MakeAddrLValue(
1028 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1029 CGF.ConvertTypeForMem(SharedType)),
1030 SharedType, SharedAddresses[N].first.getBaseInfo(),
1031 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
1032 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
1033 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
1034 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1035 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1036 PrivateAddr, SharedLVal.getAddress(),
1037 SharedLVal.getType());
1038 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1039 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1040 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1041 PrivateVD->getType().getQualifiers(),
1042 /*IsInitializer=*/false);
1043 }
1044}
1045
1046bool ReductionCodeGen::needCleanups(unsigned N) {
1047 auto *PrivateVD =
1048 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1049 QualType PrivateType = PrivateVD->getType();
1050 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1051 return DTorKind != QualType::DK_none;
1052}
1053
1054void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1055 Address PrivateAddr) {
1056 auto *PrivateVD =
1057 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1058 QualType PrivateType = PrivateVD->getType();
1059 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1060 if (needCleanups(N)) {
1061 PrivateAddr = CGF.Builder.CreateElementBitCast(
1062 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1063 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1064 }
1065}
1066
1067static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1068 LValue BaseLV) {
1069 BaseTy = BaseTy.getNonReferenceType();
1070 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1071 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1072 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1073 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1074 else {
1075 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1076 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
1077 }
1078 BaseTy = BaseTy->getPointeeType();
1079 }
1080 return CGF.MakeAddrLValue(
1081 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1082 CGF.ConvertTypeForMem(ElTy)),
1083 BaseLV.getType(), BaseLV.getBaseInfo(),
1084 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
1085}
1086
1087static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1088 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1089 llvm::Value *Addr) {
1090 Address Tmp = Address::invalid();
1091 Address TopTmp = Address::invalid();
1092 Address MostTopTmp = Address::invalid();
1093 BaseTy = BaseTy.getNonReferenceType();
1094 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1095 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1096 Tmp = CGF.CreateMemTemp(BaseTy);
1097 if (TopTmp.isValid())
1098 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1099 else
1100 MostTopTmp = Tmp;
1101 TopTmp = Tmp;
1102 BaseTy = BaseTy->getPointeeType();
1103 }
1104 llvm::Type *Ty = BaseLVType;
1105 if (Tmp.isValid())
1106 Ty = Tmp.getElementType();
1107 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1108 if (Tmp.isValid()) {
1109 CGF.Builder.CreateStore(Addr, Tmp);
1110 return MostTopTmp;
1111 }
1112 return Address(Addr, BaseLVAlignment);
1113}
1114
1115static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
1116 const VarDecl *OrigVD = nullptr;
1117 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1118 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1119 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1120 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1121 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1122 Base = TempASE->getBase()->IgnoreParenImpCasts();
1123 DE = cast<DeclRefExpr>(Base);
1124 OrigVD = cast<VarDecl>(DE->getDecl());
1125 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1126 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1127 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1128 Base = TempASE->getBase()->IgnoreParenImpCasts();
1129 DE = cast<DeclRefExpr>(Base);
1130 OrigVD = cast<VarDecl>(DE->getDecl());
1131 }
1132 return OrigVD;
1133}
1134
1135Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1136 Address PrivateAddr) {
1137 const DeclRefExpr *DE;
1138 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
1139 BaseDecls.emplace_back(OrigVD);
1140 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1141 LValue BaseLValue =
1142 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1143 OriginalBaseLValue);
1144 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1145 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1146 llvm::Value *PrivatePointer =
1147 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1148 PrivateAddr.getPointer(),
1149 SharedAddresses[N].first.getAddress().getType());
1150 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
1151 return castToBase(CGF, OrigVD->getType(),
1152 SharedAddresses[N].first.getType(),
1153 OriginalBaseLValue.getAddress().getType(),
1154 OriginalBaseLValue.getAlignment(), Ptr);
1155 }
1156 BaseDecls.emplace_back(
1157 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1158 return PrivateAddr;
1159}
1160
1161bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1162 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1163 return DRD && DRD->getInitializer();
1164}
1165
1166LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
1167 return CGF.EmitLoadOfPointerLValue(
1168 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1169 getThreadIDVariable()->getType()->castAs<PointerType>());
1170}
1171
1172void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
1173 if (!CGF.HaveInsertPoint())
1174 return;
1175 // 1.2.2 OpenMP Language Terminology
1176 // Structured block - An executable statement with a single entry at the
1177 // top and a single exit at the bottom.
1178 // The point of exit cannot be a branch out of the structured block.
1179 // longjmp() and throw() must not violate the entry/exit criteria.
1180 CGF.EHStack.pushTerminate();
1181 CodeGen(CGF);
1182 CGF.EHStack.popTerminate();
1183}
1184
1185LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1186 CodeGenFunction &CGF) {
1187 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1188 getThreadIDVariable()->getType(),
1189 AlignmentSource::Decl);
1190}
1191
1192CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
1193 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
1194 IdentTy = llvm::StructType::create(
1195 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1196 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
1197 CGM.Int8PtrTy /* psource */);
1198 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
1199
1200 loadOffloadInfoMetadata();
1201}
1202
1203void CGOpenMPRuntime::clear() {
1204 InternalVars.clear();
1205}
1206
1207static llvm::Function *
1208emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1209 const Expr *CombinerInitializer, const VarDecl *In,
1210 const VarDecl *Out, bool IsCombiner) {
1211 // void .omp_combiner.(Ty *in, Ty *out);
1212 auto &C = CGM.getContext();
1213 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1214 FunctionArgList Args;
1215 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
1216 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1217 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
1218 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1219 Args.push_back(&OmpOutParm);
1220 Args.push_back(&OmpInParm);
1221 auto &FnInfo =
1222 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1223 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1224 auto *Fn = llvm::Function::Create(
1225 FnTy, llvm::GlobalValue::InternalLinkage,
1226 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1227 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
1228 Fn->removeFnAttr(llvm::Attribute::NoInline);
1229 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
1230 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
1231 CodeGenFunction CGF(CGM);
1232 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1233 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1234 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1235 Out->getLocation());
1236 CodeGenFunction::OMPPrivateScope Scope(CGF);
1237 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1238 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1239 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1240 .getAddress();
1241 });
1242 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1243 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1244 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1245 .getAddress();
1246 });
1247 (void)Scope.Privatize();
1248 if (!IsCombiner && Out->hasInit() &&
1249 !CGF.isTrivialInitializer(Out->getInit())) {
1250 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1251 Out->getType().getQualifiers(),
1252 /*IsInitializer=*/true);
1253 }
1254 if (CombinerInitializer)
1255 CGF.EmitIgnoredExpr(CombinerInitializer);
1256 Scope.ForceCleanup();
1257 CGF.FinishFunction();
1258 return Fn;
1259}
1260
1261void CGOpenMPRuntime::emitUserDefinedReduction(
1262 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1263 if (UDRMap.count(D) > 0)
1264 return;
1265 auto &C = CGM.getContext();
1266 if (!In || !Out) {
1267 In = &C.Idents.get("omp_in");
1268 Out = &C.Idents.get("omp_out");
1269 }
1270 llvm::Function *Combiner = emitCombinerOrInitializer(
1271 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1272 cast<VarDecl>(D->lookup(Out).front()),
1273 /*IsCombiner=*/true);
1274 llvm::Function *Initializer = nullptr;
1275 if (auto *Init = D->getInitializer()) {
1276 if (!Priv || !Orig) {
1277 Priv = &C.Idents.get("omp_priv");
1278 Orig = &C.Idents.get("omp_orig");
1279 }
1280 Initializer = emitCombinerOrInitializer(
1281 CGM, D->getType(),
1282 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1283 : nullptr,
1284 cast<VarDecl>(D->lookup(Orig).front()),
1285 cast<VarDecl>(D->lookup(Priv).front()),
1286 /*IsCombiner=*/false);
1287 }
1288 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1289 if (CGF) {
1290 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1291 Decls.second.push_back(D);
1292 }
1293}
1294
1295std::pair<llvm::Function *, llvm::Function *>
1296CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1297 auto I = UDRMap.find(D);
1298 if (I != UDRMap.end())
1299 return I->second;
1300 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1301 return UDRMap.lookup(D);
1302}
1303
1304// Layout information for ident_t.
1305static CharUnits getIdentAlign(CodeGenModule &CGM) {
1306 return CGM.getPointerAlign();
1307}
1308static CharUnits getIdentSize(CodeGenModule &CGM) {
1309 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()))(static_cast <bool> ((4 * CGM.getPointerSize()).isMultipleOf
(CGM.getPointerAlign())) ? void (0) : __assert_fail ("(4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign())"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1309, __extension__ __PRETTY_FUNCTION__))
;
1310 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1311}
1312static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
1313 // All the fields except the last are i32, so this works beautifully.
1314 return unsigned(Field) * CharUnits::fromQuantity(4);
1315}
1316static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
1317 IdentFieldIndex Field,
1318 const llvm::Twine &Name = "") {
1319 auto Offset = getOffsetOfIdentField(Field);
1320 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1321}
1322
1323static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1324 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1325 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1326 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1327 assert(ThreadIDVar->getType()->isPointerType() &&(static_cast <bool> (ThreadIDVar->getType()->isPointerType
() && "thread id variable must be of type kmp_int32 *"
) ? void (0) : __assert_fail ("ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 *\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1328, __extension__ __PRETTY_FUNCTION__))
1328 "thread id variable must be of type kmp_int32 *")(static_cast <bool> (ThreadIDVar->getType()->isPointerType
() && "thread id variable must be of type kmp_int32 *"
) ? void (0) : __assert_fail ("ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 *\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1328, __extension__ __PRETTY_FUNCTION__))
;
1329 CodeGenFunction CGF(CGM, true);
1330 bool HasCancel = false;
1331 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1332 HasCancel = OPD->hasCancel();
1333 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1334 HasCancel = OPSD->hasCancel();
1335 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1336 HasCancel = OPFD->hasCancel();
1337 else if (auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1338 HasCancel = OPFD->hasCancel();
1339 else if (auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1340 HasCancel = OPFD->hasCancel();
1341 else if (auto *OPFD = dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1342 HasCancel = OPFD->hasCancel();
1343 else if (auto *OPFD =
1344 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1345 HasCancel = OPFD->hasCancel();
1346 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1347 HasCancel, OutlinedHelperName);
1348 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1349 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
1350}
1351
1352llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1353 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1354 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1355 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1356 return emitParallelOrTeamsOutlinedFunction(
1357 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1358}
1359
1360llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1361 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1362 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1363 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1364 return emitParallelOrTeamsOutlinedFunction(
1365 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1366}
1367
1368llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1369 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1370 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1371 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1372 bool Tied, unsigned &NumberOfParts) {
1373 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1374 PrePostActionTy &) {
1375 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1376 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1377 llvm::Value *TaskArgs[] = {
1378 UpLoc, ThreadID,
1379 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1380 TaskTVar->getType()->castAs<PointerType>())
1381 .getPointer()};
1382 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1383 };
1384 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1385 UntiedCodeGen);
1386 CodeGen.setAction(Action);
1387 assert(!ThreadIDVar->getType()->isPointerType() &&(static_cast <bool> (!ThreadIDVar->getType()->isPointerType
() && "thread id variable must be of type kmp_int32 for tasks"
) ? void (0) : __assert_fail ("!ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 for tasks\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1388, __extension__ __PRETTY_FUNCTION__))
1388 "thread id variable must be of type kmp_int32 for tasks")(static_cast <bool> (!ThreadIDVar->getType()->isPointerType
() && "thread id variable must be of type kmp_int32 for tasks"
) ? void (0) : __assert_fail ("!ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 for tasks\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1388, __extension__ __PRETTY_FUNCTION__))
;
1389 const OpenMPDirectiveKind Region =
1390 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1391 : OMPD_task;
1392 auto *CS = D.getCapturedStmt(Region);
1393 auto *TD = dyn_cast<OMPTaskDirective>(&D);
1394 CodeGenFunction CGF(CGM, true);
1395 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1396 InnermostKind,
1397 TD ? TD->hasCancel() : false, Action);
1398 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1399 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1400 if (!Tied)
1401 NumberOfParts = Action.getNumberOfParts();
1402 return Res;
1403}
1404
1405Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
1406 CharUnits Align = getIdentAlign(CGM);
1407 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
1408 if (!Entry) {
1409 if (!DefaultOpenMPPSource) {
1410 // Initialize default location for psource field of ident_t structure of
1411 // all ident_t objects. Format is ";file;function;line;column;;".
1412 // Taken from
1413 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1414 DefaultOpenMPPSource =
1415 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
1416 DefaultOpenMPPSource =
1417 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1418 }
1419
1420 ConstantInitBuilder builder(CGM);
1421 auto fields = builder.beginStruct(IdentTy);
1422 fields.addInt(CGM.Int32Ty, 0);
1423 fields.addInt(CGM.Int32Ty, Flags);
1424 fields.addInt(CGM.Int32Ty, 0);
1425 fields.addInt(CGM.Int32Ty, 0);
1426 fields.add(DefaultOpenMPPSource);
1427 auto DefaultOpenMPLocation =
1428 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1429 llvm::GlobalValue::PrivateLinkage);
1430 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1431
1432 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
1433 }
1434 return Address(Entry, Align);
1435}
1436
1437llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1438 SourceLocation Loc,
1439 unsigned Flags) {
1440 Flags |= OMP_IDENT_KMPC;
1441 // If no debug info is generated - return global default location.
1442 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
1443 Loc.isInvalid())
1444 return getOrCreateDefaultLocation(Flags).getPointer();
1445
1446 assert(CGF.CurFn && "No function in current CodeGenFunction.")(static_cast <bool> (CGF.CurFn && "No function in current CodeGenFunction."
) ? void (0) : __assert_fail ("CGF.CurFn && \"No function in current CodeGenFunction.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1446, __extension__ __PRETTY_FUNCTION__))
;
1447
1448 Address LocValue = Address::invalid();
1449 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1450 if (I != OpenMPLocThreadIDMap.end())
1451 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1452
1453 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1454 // GetOpenMPThreadID was called before this routine.
1455 if (!LocValue.isValid()) {
1456 // Generate "ident_t .kmpc_loc.addr;"
1457 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1458 ".kmpc_loc.addr");
1459 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1460 Elem.second.DebugLoc = AI.getPointer();
1461 LocValue = AI;
1462
1463 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1464 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1465 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
1466 CGM.getSize(getIdentSize(CGF.CGM)));
1467 }
1468
1469 // char **psource = &.kmpc_loc_<flags>.addr.psource;
1470 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
1471
1472 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1473 if (OMPDebugLoc == nullptr) {
1474 SmallString<128> Buffer2;
1475 llvm::raw_svector_ostream OS2(Buffer2);
1476 // Build debug location
1477 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1478 OS2 << ";" << PLoc.getFilename() << ";";
1479 if (const FunctionDecl *FD =
1480 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1481 OS2 << FD->getQualifiedNameAsString();
1482 }
1483 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1484 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1485 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
1486 }
1487 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
1488 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1489
1490 // Our callers always pass this to a runtime function, so for
1491 // convenience, go ahead and return a naked pointer.
1492 return LocValue.getPointer();
1493}
1494
1495llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1496 SourceLocation Loc) {
1497 assert(CGF.CurFn && "No function in current CodeGenFunction.")(static_cast <bool> (CGF.CurFn && "No function in current CodeGenFunction."
) ? void (0) : __assert_fail ("CGF.CurFn && \"No function in current CodeGenFunction.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1497, __extension__ __PRETTY_FUNCTION__))
;
1498
1499 llvm::Value *ThreadID = nullptr;
1500 // Check whether we've already cached a load of the thread id in this
1501 // function.
1502 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1503 if (I != OpenMPLocThreadIDMap.end()) {
1504 ThreadID = I->second.ThreadID;
1505 if (ThreadID != nullptr)
1506 return ThreadID;
1507 }
1508 // If exceptions are enabled, do not use parameter to avoid possible crash.
1509 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1510 !CGF.getLangOpts().CXXExceptions ||
1511 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1512 if (auto *OMPRegionInfo =
1513 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1514 if (OMPRegionInfo->getThreadIDVariable()) {
1515 // Check if this an outlined function with thread id passed as argument.
1516 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1517 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
1518 // If value loaded in entry block, cache it and use it everywhere in
1519 // function.
1520 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1521 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1522 Elem.second.ThreadID = ThreadID;
1523 }
1524 return ThreadID;
1525 }
1526 }
1527 }
1528
1529 // This is not an outlined function region - need to call __kmpc_int32
1530 // kmpc_global_thread_num(ident_t *loc).
1531 // Generate thread id value and cache this value for use across the
1532 // function.
1533 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1534 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1535 auto *Call = CGF.Builder.CreateCall(
1536 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1537 emitUpdateLocation(CGF, Loc));
1538 Call->setCallingConv(CGF.getRuntimeCC());
1539 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1540 Elem.second.ThreadID = Call;
1541 return Call;
1542}
1543
1544void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1545 assert(CGF.CurFn && "No function in current CodeGenFunction.")(static_cast <bool> (CGF.CurFn && "No function in current CodeGenFunction."
) ? void (0) : __assert_fail ("CGF.CurFn && \"No function in current CodeGenFunction.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1545, __extension__ __PRETTY_FUNCTION__))
;
1546 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1547 OpenMPLocThreadIDMap.erase(CGF.CurFn);
1548 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1549 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1550 UDRMap.erase(D);
1551 }
1552 FunctionUDRMap.erase(CGF.CurFn);
1553 }
1554}
1555
1556llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1557 if (!IdentTy) {
1558 }
1559 return llvm::PointerType::getUnqual(IdentTy);
1560}
1561
1562llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
1563 if (!Kmpc_MicroTy) {
1564 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1565 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1566 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1567 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1568 }
1569 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1570}
1571
1572llvm::Constant *
1573CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1574 llvm::Constant *RTLFn = nullptr;
1575 switch (static_cast<OpenMPRTLFunction>(Function)) {
1576 case OMPRTL__kmpc_fork_call: {
1577 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1578 // microtask, ...);
1579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1580 getKmpc_MicroPointerTy()};
1581 llvm::FunctionType *FnTy =
1582 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1583 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1584 break;
1585 }
1586 case OMPRTL__kmpc_global_thread_num: {
1587 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1588 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1589 llvm::FunctionType *FnTy =
1590 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1592 break;
1593 }
1594 case OMPRTL__kmpc_threadprivate_cached: {
1595 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1596 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1597 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1598 CGM.VoidPtrTy, CGM.SizeTy,
1599 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1600 llvm::FunctionType *FnTy =
1601 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1602 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1603 break;
1604 }
1605 case OMPRTL__kmpc_critical: {
1606 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1607 // kmp_critical_name *crit);
1608 llvm::Type *TypeParams[] = {
1609 getIdentTyPointerTy(), CGM.Int32Ty,
1610 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1611 llvm::FunctionType *FnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1613 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1614 break;
1615 }
1616 case OMPRTL__kmpc_critical_with_hint: {
1617 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1618 // kmp_critical_name *crit, uintptr_t hint);
1619 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1620 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1621 CGM.IntPtrTy};
1622 llvm::FunctionType *FnTy =
1623 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1625 break;
1626 }
1627 case OMPRTL__kmpc_threadprivate_register: {
1628 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1629 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1630 // typedef void *(*kmpc_ctor)(void *);
1631 auto KmpcCtorTy =
1632 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1633 /*isVarArg*/ false)->getPointerTo();
1634 // typedef void *(*kmpc_cctor)(void *, void *);
1635 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1636 auto KmpcCopyCtorTy =
1637 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1638 /*isVarArg*/ false)->getPointerTo();
1639 // typedef void (*kmpc_dtor)(void *);
1640 auto KmpcDtorTy =
1641 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1642 ->getPointerTo();
1643 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1644 KmpcCopyCtorTy, KmpcDtorTy};
1645 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1646 /*isVarArg*/ false);
1647 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1648 break;
1649 }
1650 case OMPRTL__kmpc_end_critical: {
1651 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1652 // kmp_critical_name *crit);
1653 llvm::Type *TypeParams[] = {
1654 getIdentTyPointerTy(), CGM.Int32Ty,
1655 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1656 llvm::FunctionType *FnTy =
1657 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1658 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1659 break;
1660 }
1661 case OMPRTL__kmpc_cancel_barrier: {
1662 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1663 // global_tid);
1664 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1665 llvm::FunctionType *FnTy =
1666 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1667 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1668 break;
1669 }
1670 case OMPRTL__kmpc_barrier: {
1671 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1673 llvm::FunctionType *FnTy =
1674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1676 break;
1677 }
1678 case OMPRTL__kmpc_for_static_fini: {
1679 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1680 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1681 llvm::FunctionType *FnTy =
1682 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1683 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1684 break;
1685 }
1686 case OMPRTL__kmpc_push_num_threads: {
1687 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1688 // kmp_int32 num_threads)
1689 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1690 CGM.Int32Ty};
1691 llvm::FunctionType *FnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1694 break;
1695 }
1696 case OMPRTL__kmpc_serialized_parallel: {
1697 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1698 // global_tid);
1699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1700 llvm::FunctionType *FnTy =
1701 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1702 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1703 break;
1704 }
1705 case OMPRTL__kmpc_end_serialized_parallel: {
1706 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1707 // global_tid);
1708 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1709 llvm::FunctionType *FnTy =
1710 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1712 break;
1713 }
1714 case OMPRTL__kmpc_flush: {
1715 // Build void __kmpc_flush(ident_t *loc);
1716 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1717 llvm::FunctionType *FnTy =
1718 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1719 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1720 break;
1721 }
1722 case OMPRTL__kmpc_master: {
1723 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1724 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1725 llvm::FunctionType *FnTy =
1726 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1727 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1728 break;
1729 }
1730 case OMPRTL__kmpc_end_master: {
1731 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1732 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1733 llvm::FunctionType *FnTy =
1734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1735 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1736 break;
1737 }
1738 case OMPRTL__kmpc_omp_taskyield: {
1739 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1740 // int end_part);
1741 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1742 llvm::FunctionType *FnTy =
1743 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1745 break;
1746 }
1747 case OMPRTL__kmpc_single: {
1748 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1749 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1750 llvm::FunctionType *FnTy =
1751 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1753 break;
1754 }
1755 case OMPRTL__kmpc_end_single: {
1756 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1757 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1758 llvm::FunctionType *FnTy =
1759 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1760 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1761 break;
1762 }
1763 case OMPRTL__kmpc_omp_task_alloc: {
1764 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1765 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1766 // kmp_routine_entry_t *task_entry);
1767 assert(KmpRoutineEntryPtrTy != nullptr &&(static_cast <bool> (KmpRoutineEntryPtrTy != nullptr &&
"Type kmp_routine_entry_t must be created.") ? void (0) : __assert_fail
("KmpRoutineEntryPtrTy != nullptr && \"Type kmp_routine_entry_t must be created.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1768, __extension__ __PRETTY_FUNCTION__))
1768 "Type kmp_routine_entry_t must be created.")(static_cast <bool> (KmpRoutineEntryPtrTy != nullptr &&
"Type kmp_routine_entry_t must be created.") ? void (0) : __assert_fail
("KmpRoutineEntryPtrTy != nullptr && \"Type kmp_routine_entry_t must be created.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 1768, __extension__ __PRETTY_FUNCTION__))
;
1769 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1770 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1771 // Return void * and then cast to particular kmp_task_t type.
1772 llvm::FunctionType *FnTy =
1773 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1775 break;
1776 }
1777 case OMPRTL__kmpc_omp_task: {
1778 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1779 // *new_task);
1780 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1781 CGM.VoidPtrTy};
1782 llvm::FunctionType *FnTy =
1783 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1785 break;
1786 }
1787 case OMPRTL__kmpc_copyprivate: {
1788 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1789 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1790 // kmp_int32 didit);
1791 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1792 auto *CpyFnTy =
1793 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1794 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1795 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1796 CGM.Int32Ty};
1797 llvm::FunctionType *FnTy =
1798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1799 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1800 break;
1801 }
1802 case OMPRTL__kmpc_reduce: {
1803 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1804 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1805 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1806 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1807 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1808 /*isVarArg=*/false);
1809 llvm::Type *TypeParams[] = {
1810 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1811 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1812 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1813 llvm::FunctionType *FnTy =
1814 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1815 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1816 break;
1817 }
1818 case OMPRTL__kmpc_reduce_nowait: {
1819 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1820 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1821 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1822 // *lck);
1823 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1824 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1825 /*isVarArg=*/false);
1826 llvm::Type *TypeParams[] = {
1827 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1828 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1829 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1830 llvm::FunctionType *FnTy =
1831 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1832 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1833 break;
1834 }
1835 case OMPRTL__kmpc_end_reduce: {
1836 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1837 // kmp_critical_name *lck);
1838 llvm::Type *TypeParams[] = {
1839 getIdentTyPointerTy(), CGM.Int32Ty,
1840 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1841 llvm::FunctionType *FnTy =
1842 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1843 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1844 break;
1845 }
1846 case OMPRTL__kmpc_end_reduce_nowait: {
1847 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1848 // kmp_critical_name *lck);
1849 llvm::Type *TypeParams[] = {
1850 getIdentTyPointerTy(), CGM.Int32Ty,
1851 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1852 llvm::FunctionType *FnTy =
1853 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1854 RTLFn =
1855 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1856 break;
1857 }
1858 case OMPRTL__kmpc_omp_task_begin_if0: {
1859 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1860 // *new_task);
1861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1862 CGM.VoidPtrTy};
1863 llvm::FunctionType *FnTy =
1864 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1865 RTLFn =
1866 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1867 break;
1868 }
1869 case OMPRTL__kmpc_omp_task_complete_if0: {
1870 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1871 // *new_task);
1872 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1873 CGM.VoidPtrTy};
1874 llvm::FunctionType *FnTy =
1875 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1876 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1877 /*Name=*/"__kmpc_omp_task_complete_if0");
1878 break;
1879 }
1880 case OMPRTL__kmpc_ordered: {
1881 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1882 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1883 llvm::FunctionType *FnTy =
1884 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1885 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1886 break;
1887 }
1888 case OMPRTL__kmpc_end_ordered: {
1889 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1890 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1891 llvm::FunctionType *FnTy =
1892 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1894 break;
1895 }
1896 case OMPRTL__kmpc_omp_taskwait: {
1897 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1898 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1899 llvm::FunctionType *FnTy =
1900 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1901 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1902 break;
1903 }
1904 case OMPRTL__kmpc_taskgroup: {
1905 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1907 llvm::FunctionType *FnTy =
1908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1910 break;
1911 }
1912 case OMPRTL__kmpc_end_taskgroup: {
1913 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1914 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1915 llvm::FunctionType *FnTy =
1916 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1917 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1918 break;
1919 }
1920 case OMPRTL__kmpc_push_proc_bind: {
1921 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1922 // int proc_bind)
1923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1924 llvm::FunctionType *FnTy =
1925 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1926 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1927 break;
1928 }
1929 case OMPRTL__kmpc_omp_task_with_deps: {
1930 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1931 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1932 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1933 llvm::Type *TypeParams[] = {
1934 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1935 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1936 llvm::FunctionType *FnTy =
1937 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1938 RTLFn =
1939 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1940 break;
1941 }
1942 case OMPRTL__kmpc_omp_wait_deps: {
1943 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1944 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1945 // kmp_depend_info_t *noalias_dep_list);
1946 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1947 CGM.Int32Ty, CGM.VoidPtrTy,
1948 CGM.Int32Ty, CGM.VoidPtrTy};
1949 llvm::FunctionType *FnTy =
1950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1952 break;
1953 }
1954 case OMPRTL__kmpc_cancellationpoint: {
1955 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1956 // global_tid, kmp_int32 cncl_kind)
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1958 llvm::FunctionType *FnTy =
1959 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1960 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1961 break;
1962 }
1963 case OMPRTL__kmpc_cancel: {
1964 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1965 // kmp_int32 cncl_kind)
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1967 llvm::FunctionType *FnTy =
1968 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1970 break;
1971 }
1972 case OMPRTL__kmpc_push_num_teams: {
1973 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1974 // kmp_int32 num_teams, kmp_int32 num_threads)
1975 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1976 CGM.Int32Ty};
1977 llvm::FunctionType *FnTy =
1978 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1979 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1980 break;
1981 }
1982 case OMPRTL__kmpc_fork_teams: {
1983 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1984 // microtask, ...);
1985 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1986 getKmpc_MicroPointerTy()};
1987 llvm::FunctionType *FnTy =
1988 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1989 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1990 break;
1991 }
1992 case OMPRTL__kmpc_taskloop: {
1993 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1994 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1995 // sched, kmp_uint64 grainsize, void *task_dup);
1996 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1997 CGM.IntTy,
1998 CGM.VoidPtrTy,
1999 CGM.IntTy,
2000 CGM.Int64Ty->getPointerTo(),
2001 CGM.Int64Ty->getPointerTo(),
2002 CGM.Int64Ty,
2003 CGM.IntTy,
2004 CGM.IntTy,
2005 CGM.Int64Ty,
2006 CGM.VoidPtrTy};
2007 llvm::FunctionType *FnTy =
2008 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2009 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2010 break;
2011 }
2012 case OMPRTL__kmpc_doacross_init: {
2013 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2014 // num_dims, struct kmp_dim *dims);
2015 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2016 CGM.Int32Ty,
2017 CGM.Int32Ty,
2018 CGM.VoidPtrTy};
2019 llvm::FunctionType *FnTy =
2020 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2021 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2022 break;
2023 }
2024 case OMPRTL__kmpc_doacross_fini: {
2025 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2026 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2027 llvm::FunctionType *FnTy =
2028 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2029 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2030 break;
2031 }
2032 case OMPRTL__kmpc_doacross_post: {
2033 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2034 // *vec);
2035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2036 CGM.Int64Ty->getPointerTo()};
2037 llvm::FunctionType *FnTy =
2038 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2039 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2040 break;
2041 }
2042 case OMPRTL__kmpc_doacross_wait: {
2043 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2044 // *vec);
2045 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2046 CGM.Int64Ty->getPointerTo()};
2047 llvm::FunctionType *FnTy =
2048 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2049 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2050 break;
2051 }
2052 case OMPRTL__kmpc_task_reduction_init: {
2053 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2054 // *data);
2055 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2056 llvm::FunctionType *FnTy =
2057 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2058 RTLFn =
2059 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2060 break;
2061 }
2062 case OMPRTL__kmpc_task_reduction_get_th_data: {
2063 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2064 // *d);
2065 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2066 llvm::FunctionType *FnTy =
2067 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2068 RTLFn = CGM.CreateRuntimeFunction(
2069 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2070 break;
2071 }
2072 case OMPRTL__tgt_target: {
2073 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2074 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2075 // *arg_types);
2076 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2077 CGM.VoidPtrTy,
2078 CGM.Int32Ty,
2079 CGM.VoidPtrPtrTy,
2080 CGM.VoidPtrPtrTy,
2081 CGM.SizeTy->getPointerTo(),
2082 CGM.Int64Ty->getPointerTo()};
2083 llvm::FunctionType *FnTy =
2084 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2085 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2086 break;
2087 }
2088 case OMPRTL__tgt_target_nowait: {
2089 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2090 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2091 // int64_t *arg_types);
2092 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2093 CGM.VoidPtrTy,
2094 CGM.Int32Ty,
2095 CGM.VoidPtrPtrTy,
2096 CGM.VoidPtrPtrTy,
2097 CGM.SizeTy->getPointerTo(),
2098 CGM.Int64Ty->getPointerTo()};
2099 llvm::FunctionType *FnTy =
2100 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2101 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2102 break;
2103 }
2104 case OMPRTL__tgt_target_teams: {
2105 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
2106 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2107 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2108 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2109 CGM.VoidPtrTy,
2110 CGM.Int32Ty,
2111 CGM.VoidPtrPtrTy,
2112 CGM.VoidPtrPtrTy,
2113 CGM.SizeTy->getPointerTo(),
2114 CGM.Int64Ty->getPointerTo(),
2115 CGM.Int32Ty,
2116 CGM.Int32Ty};
2117 llvm::FunctionType *FnTy =
2118 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2119 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2120 break;
2121 }
2122 case OMPRTL__tgt_target_teams_nowait: {
2123 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2124 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2125 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2126 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2127 CGM.VoidPtrTy,
2128 CGM.Int32Ty,
2129 CGM.VoidPtrPtrTy,
2130 CGM.VoidPtrPtrTy,
2131 CGM.SizeTy->getPointerTo(),
2132 CGM.Int64Ty->getPointerTo(),
2133 CGM.Int32Ty,
2134 CGM.Int32Ty};
2135 llvm::FunctionType *FnTy =
2136 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2137 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2138 break;
2139 }
2140 case OMPRTL__tgt_register_lib: {
2141 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2142 QualType ParamTy =
2143 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2144 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2145 llvm::FunctionType *FnTy =
2146 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2147 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2148 break;
2149 }
2150 case OMPRTL__tgt_unregister_lib: {
2151 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2152 QualType ParamTy =
2153 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2154 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2155 llvm::FunctionType *FnTy =
2156 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2157 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2158 break;
2159 }
2160 case OMPRTL__tgt_target_data_begin: {
2161 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2162 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2163 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2164 CGM.Int32Ty,
2165 CGM.VoidPtrPtrTy,
2166 CGM.VoidPtrPtrTy,
2167 CGM.SizeTy->getPointerTo(),
2168 CGM.Int64Ty->getPointerTo()};
2169 llvm::FunctionType *FnTy =
2170 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2171 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2172 break;
2173 }
2174 case OMPRTL__tgt_target_data_begin_nowait: {
2175 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2176 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2177 // *arg_types);
2178 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2179 CGM.Int32Ty,
2180 CGM.VoidPtrPtrTy,
2181 CGM.VoidPtrPtrTy,
2182 CGM.SizeTy->getPointerTo(),
2183 CGM.Int64Ty->getPointerTo()};
2184 auto *FnTy =
2185 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2186 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2187 break;
2188 }
2189 case OMPRTL__tgt_target_data_end: {
2190 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2191 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2192 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2193 CGM.Int32Ty,
2194 CGM.VoidPtrPtrTy,
2195 CGM.VoidPtrPtrTy,
2196 CGM.SizeTy->getPointerTo(),
2197 CGM.Int64Ty->getPointerTo()};
2198 llvm::FunctionType *FnTy =
2199 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2200 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2201 break;
2202 }
2203 case OMPRTL__tgt_target_data_end_nowait: {
2204 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2205 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2206 // *arg_types);
2207 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2208 CGM.Int32Ty,
2209 CGM.VoidPtrPtrTy,
2210 CGM.VoidPtrPtrTy,
2211 CGM.SizeTy->getPointerTo(),
2212 CGM.Int64Ty->getPointerTo()};
2213 auto *FnTy =
2214 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2215 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2216 break;
2217 }
2218 case OMPRTL__tgt_target_data_update: {
2219 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2220 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2221 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2222 CGM.Int32Ty,
2223 CGM.VoidPtrPtrTy,
2224 CGM.VoidPtrPtrTy,
2225 CGM.SizeTy->getPointerTo(),
2226 CGM.Int64Ty->getPointerTo()};
2227 llvm::FunctionType *FnTy =
2228 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2229 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2230 break;
2231 }
2232 case OMPRTL__tgt_target_data_update_nowait: {
2233 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2234 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2235 // *arg_types);
2236 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2237 CGM.Int32Ty,
2238 CGM.VoidPtrPtrTy,
2239 CGM.VoidPtrPtrTy,
2240 CGM.SizeTy->getPointerTo(),
2241 CGM.Int64Ty->getPointerTo()};
2242 auto *FnTy =
2243 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2244 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2245 break;
2246 }
2247 }
2248 assert(RTLFn && "Unable to find OpenMP runtime function")(static_cast <bool> (RTLFn && "Unable to find OpenMP runtime function"
) ? void (0) : __assert_fail ("RTLFn && \"Unable to find OpenMP runtime function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2248, __extension__ __PRETTY_FUNCTION__))
;
2249 return RTLFn;
2250}
2251
2252llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2253 bool IVSigned) {
2254 assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2255, __extension__ __PRETTY_FUNCTION__))
2255 "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2255, __extension__ __PRETTY_FUNCTION__))
;
2256 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2257 : "__kmpc_for_static_init_4u")
2258 : (IVSigned ? "__kmpc_for_static_init_8"
2259 : "__kmpc_for_static_init_8u");
2260 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2261 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2262 llvm::Type *TypeParams[] = {
2263 getIdentTyPointerTy(), // loc
2264 CGM.Int32Ty, // tid
2265 CGM.Int32Ty, // schedtype
2266 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2267 PtrTy, // p_lower
2268 PtrTy, // p_upper
2269 PtrTy, // p_stride
2270 ITy, // incr
2271 ITy // chunk
2272 };
2273 llvm::FunctionType *FnTy =
2274 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2275 return CGM.CreateRuntimeFunction(FnTy, Name);
2276}
2277
2278llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2279 bool IVSigned) {
2280 assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2281, __extension__ __PRETTY_FUNCTION__))
2281 "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2281, __extension__ __PRETTY_FUNCTION__))
;
2282 auto Name =
2283 IVSize == 32
2284 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2285 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2286 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2287 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2288 CGM.Int32Ty, // tid
2289 CGM.Int32Ty, // schedtype
2290 ITy, // lower
2291 ITy, // upper
2292 ITy, // stride
2293 ITy // chunk
2294 };
2295 llvm::FunctionType *FnTy =
2296 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2297 return CGM.CreateRuntimeFunction(FnTy, Name);
2298}
2299
2300llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2301 bool IVSigned) {
2302 assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
2303 "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
;
2304 auto Name =
2305 IVSize == 32
2306 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2307 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2308 llvm::Type *TypeParams[] = {
2309 getIdentTyPointerTy(), // loc
2310 CGM.Int32Ty, // tid
2311 };
2312 llvm::FunctionType *FnTy =
2313 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2314 return CGM.CreateRuntimeFunction(FnTy, Name);
2315}
2316
2317llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2318 bool IVSigned) {
2319 assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2320, __extension__ __PRETTY_FUNCTION__))
2320 "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) &&
"IV size is not compatible with the omp runtime") ? void (0)
: __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2320, __extension__ __PRETTY_FUNCTION__))
;
2321 auto Name =
2322 IVSize == 32
2323 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2324 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2325 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2326 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2327 llvm::Type *TypeParams[] = {
2328 getIdentTyPointerTy(), // loc
2329 CGM.Int32Ty, // tid
2330 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2331 PtrTy, // p_lower
2332 PtrTy, // p_upper
2333 PtrTy // p_stride
2334 };
2335 llvm::FunctionType *FnTy =
2336 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2337 return CGM.CreateRuntimeFunction(FnTy, Name);
2338}
2339
2340Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2341 if (CGM.getLangOpts().OpenMPSimd)
2342 return Address::invalid();
2343 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2344 isDeclareTargetDeclaration(VD);
2345 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2346 SmallString<64> PtrName;
2347 {
2348 llvm::raw_svector_ostream OS(PtrName);
2349 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2350 }
2351 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2352 if (!Ptr) {
2353 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2354 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2355 PtrName);
2356 if (!CGM.getLangOpts().OpenMPIsDevice) {
2357 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2358 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2359 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2360 }
2361 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2362 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
2363 }
2364 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2365 }
2366 return Address::invalid();
2367}
2368
2369llvm::Constant *
2370CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
2371 assert(!CGM.getLangOpts().OpenMPUseTLS ||(static_cast <bool> (!CGM.getLangOpts().OpenMPUseTLS ||
!CGM.getContext().getTargetInfo().isTLSSupported()) ? void (
0) : __assert_fail ("!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2372, __extension__ __PRETTY_FUNCTION__))
2372 !CGM.getContext().getTargetInfo().isTLSSupported())(static_cast <bool> (!CGM.getLangOpts().OpenMPUseTLS ||
!CGM.getContext().getTargetInfo().isTLSSupported()) ? void (
0) : __assert_fail ("!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2372, __extension__ __PRETTY_FUNCTION__))
;
2373 // Lookup the entry, lazily creating it if necessary.
2374 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
2375 Twine(CGM.getMangledName(VD)) + ".cache.");
2376}
2377
2378Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2379 const VarDecl *VD,
2380 Address VDAddr,
2381 SourceLocation Loc) {
2382 if (CGM.getLangOpts().OpenMPUseTLS &&
2383 CGM.getContext().getTargetInfo().isTLSSupported())
2384 return VDAddr;
2385
2386 auto VarTy = VDAddr.getElementType();
2387 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2388 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2389 CGM.Int8PtrTy),
2390 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2391 getOrCreateThreadPrivateCache(VD)};
2392 return Address(CGF.EmitRuntimeCall(
2393 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2394 VDAddr.getAlignment());
2395}
2396
2397void CGOpenMPRuntime::emitThreadPrivateVarInit(
2398 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
2399 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2400 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2401 // library.
2402 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2403 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
2404 OMPLoc);
2405 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2406 // to register constructor/destructor for variable.
2407 llvm::Value *Args[] = {OMPLoc,
2408 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2409 CGM.VoidPtrTy),
2410 Ctor, CopyCtor, Dtor};
2411 CGF.EmitRuntimeCall(
2412 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
2413}
2414
2415llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
2416 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
2417 bool PerformInit, CodeGenFunction *CGF) {
2418 if (CGM.getLangOpts().OpenMPUseTLS &&
2419 CGM.getContext().getTargetInfo().isTLSSupported())
2420 return nullptr;
2421
2422 VD = VD->getDefinition(CGM.getContext());
2423 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2424 ThreadPrivateWithDefinition.insert(VD);
2425 QualType ASTTy = VD->getType();
2426
2427 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2428 auto Init = VD->getAnyInitializer();
2429 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2430 // Generate function that re-emits the declaration's initializer into the
2431 // threadprivate copy of the variable VD
2432 CodeGenFunction CtorCGF(CGM);
2433 FunctionArgList Args;
2434 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2435 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2436 ImplicitParamDecl::Other);
2437 Args.push_back(&Dst);
2438
2439 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2440 CGM.getContext().VoidPtrTy, Args);
2441 auto FTy = CGM.getTypes().GetFunctionType(FI);
2442 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
2443 FTy, ".__kmpc_global_ctor_.", FI, Loc);
2444 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2445 Args, Loc, Loc);
2446 auto ArgVal = CtorCGF.EmitLoadOfScalar(
2447 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2448 CGM.getContext().VoidPtrTy, Dst.getLocation());
2449 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2450 Arg = CtorCGF.Builder.CreateElementBitCast(
2451 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
2452 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2453 /*IsInitializer=*/true);
2454 ArgVal = CtorCGF.EmitLoadOfScalar(
2455 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2456 CGM.getContext().VoidPtrTy, Dst.getLocation());
2457 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2458 CtorCGF.FinishFunction();
2459 Ctor = Fn;
2460 }
2461 if (VD->getType().isDestructedType() != QualType::DK_none) {
2462 // Generate function that emits destructor call for the threadprivate copy
2463 // of the variable VD
2464 CodeGenFunction DtorCGF(CGM);
2465 FunctionArgList Args;
2466 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2467 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2468 ImplicitParamDecl::Other);
2469 Args.push_back(&Dst);
2470
2471 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2472 CGM.getContext().VoidTy, Args);
2473 auto FTy = CGM.getTypes().GetFunctionType(FI);
2474 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
2475 FTy, ".__kmpc_global_dtor_.", FI, Loc);
2476 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2477 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2478 Loc, Loc);
2479 // Create a scope with an artificial location for the body of this function.
2480 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2481 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2482 DtorCGF.GetAddrOfLocalVar(&Dst),
2483 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2484 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
2485 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2486 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2487 DtorCGF.FinishFunction();
2488 Dtor = Fn;
2489 }
2490 // Do not emit init function if it is not required.
2491 if (!Ctor && !Dtor)
2492 return nullptr;
2493
2494 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2495 auto CopyCtorTy =
2496 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2497 /*isVarArg=*/false)->getPointerTo();
2498 // Copying constructor for the threadprivate variable.
2499 // Must be NULL - reserved by runtime, but currently it requires that this
2500 // parameter is always NULL. Otherwise it fires assertion.
2501 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2502 if (Ctor == nullptr) {
2503 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2504 /*isVarArg=*/false)->getPointerTo();
2505 Ctor = llvm::Constant::getNullValue(CtorTy);
2506 }
2507 if (Dtor == nullptr) {
2508 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2509 /*isVarArg=*/false)->getPointerTo();
2510 Dtor = llvm::Constant::getNullValue(DtorTy);
2511 }
2512 if (!CGF) {
2513 auto InitFunctionTy =
2514 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2515 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
2516 InitFunctionTy, ".__omp_threadprivate_init_.",
2517 CGM.getTypes().arrangeNullaryFunction());
2518 CodeGenFunction InitCGF(CGM);
2519 FunctionArgList ArgList;
2520 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2521 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2522 Loc, Loc);
2523 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2524 InitCGF.FinishFunction();
2525 return InitFunction;
2526 }
2527 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2528 }
2529 return nullptr;
2530}
2531
2532/// \brief Obtain information that uniquely identifies a target entry. This
2533/// consists of the file and device IDs as well as line number associated with
2534/// the relevant entry source location.
2535static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2536 unsigned &DeviceID, unsigned &FileID,
2537 unsigned &LineNum) {
2538
2539 auto &SM = C.getSourceManager();
2540
2541 // The loc should be always valid and have a file ID (the user cannot use
2542 // #pragma directives in macros)
2543
2544 assert(Loc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (Loc.isValid() && "Source location is expected to be always valid."
) ? void (0) : __assert_fail ("Loc.isValid() && \"Source location is expected to be always valid.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2544, __extension__ __PRETTY_FUNCTION__))
;
2545 assert(Loc.isFileID() && "Source location is expected to refer to a file.")(static_cast <bool> (Loc.isFileID() && "Source location is expected to refer to a file."
) ? void (0) : __assert_fail ("Loc.isFileID() && \"Source location is expected to refer to a file.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2545, __extension__ __PRETTY_FUNCTION__))
;
2546
2547 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2548 assert(PLoc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (PLoc.isValid() && "Source location is expected to be always valid."
) ? void (0) : __assert_fail ("PLoc.isValid() && \"Source location is expected to be always valid.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2548, __extension__ __PRETTY_FUNCTION__))
;
2549
2550 llvm::sys::fs::UniqueID ID;
2551 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2552 llvm_unreachable("Source file with target region no longer exists!")::llvm::llvm_unreachable_internal("Source file with target region no longer exists!"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2552)
;
2553
2554 DeviceID = ID.getDevice();
2555 FileID = ID.getFile();
2556 LineNum = PLoc.getLine();
2557}
2558
2559bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2560 llvm::GlobalVariable *Addr,
2561 bool PerformInit) {
2562 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2563 isDeclareTargetDeclaration(VD);
2564 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2565 return false;
2566 VD = VD->getDefinition(CGM.getContext());
2567 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2568 return CGM.getLangOpts().OpenMPIsDevice;
2569
2570 QualType ASTTy = VD->getType();
2571
2572 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2573 // Produce the unique prefix to identify the new target regions. We use
2574 // the source location of the variable declaration which we know to not
2575 // conflict with any target region.
2576 unsigned DeviceID;
2577 unsigned FileID;
2578 unsigned Line;
2579 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2580 SmallString<128> Buffer, Out;
2581 {
2582 llvm::raw_svector_ostream OS(Buffer);
2583 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2584 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2585 }
2586
2587 const Expr *Init = VD->getAnyInitializer();
2588 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2589 llvm::Constant *Ctor;
2590 llvm::Constant *ID;
2591 if (CGM.getLangOpts().OpenMPIsDevice) {
2592 // Generate function that re-emits the declaration's initializer into
2593 // the threadprivate copy of the variable VD
2594 CodeGenFunction CtorCGF(CGM);
2595
2596 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2597 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2598 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2599 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2600 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2601 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2602 FunctionArgList(), Loc, Loc);
2603 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2604 CtorCGF.EmitAnyExprToMem(Init,
2605 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2606 Init->getType().getQualifiers(),
2607 /*IsInitializer=*/true);
2608 CtorCGF.FinishFunction();
2609 Ctor = Fn;
2610 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2611 } else {
2612 Ctor = new llvm::GlobalVariable(
2613 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2614 llvm::GlobalValue::PrivateLinkage,
2615 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2616 ID = Ctor;
2617 }
2618
2619 // Register the information for the entry associated with the constructor.
2620 Out.clear();
2621 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2622 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
2623 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
2624 }
2625 if (VD->getType().isDestructedType() != QualType::DK_none) {
2626 llvm::Constant *Dtor;
2627 llvm::Constant *ID;
2628 if (CGM.getLangOpts().OpenMPIsDevice) {
2629 // Generate function that emits destructor call for the threadprivate
2630 // copy of the variable VD
2631 CodeGenFunction DtorCGF(CGM);
2632
2633 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2634 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2635 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2636 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2637 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2638 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2639 FunctionArgList(), Loc, Loc);
2640 // Create a scope with an artificial location for the body of this
2641 // function.
2642 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2643 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2644 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2645 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2646 DtorCGF.FinishFunction();
2647 Dtor = Fn;
2648 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2649 } else {
2650 Dtor = new llvm::GlobalVariable(
2651 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2652 llvm::GlobalValue::PrivateLinkage,
2653 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2654 ID = Dtor;
2655 }
2656 // Register the information for the entry associated with the destructor.
2657 Out.clear();
2658 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2659 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
2660 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
2661 }
2662 return CGM.getLangOpts().OpenMPIsDevice;
2663}
2664
2665Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2666 QualType VarType,
2667 StringRef Name) {
2668 llvm::Twine VarName(Name, ".artificial.");
2669 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2670 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2671 llvm::Value *Args[] = {
2672 emitUpdateLocation(CGF, SourceLocation()),
2673 getThreadID(CGF, SourceLocation()),
2674 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2675 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2676 /*IsSigned=*/false),
2677 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2678 return Address(
2679 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2680 CGF.EmitRuntimeCall(
2681 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2682 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2683 CGM.getPointerAlign());
2684}
2685
2686/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2687/// function. Here is the logic:
2688/// if (Cond) {
2689/// ThenGen();
2690/// } else {
2691/// ElseGen();
2692/// }
2693void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2694 const RegionCodeGenTy &ThenGen,
2695 const RegionCodeGenTy &ElseGen) {
2696 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2697
2698 // If the condition constant folds and can be elided, try to avoid emitting
2699 // the condition and the dead arm of the if/else.
2700 bool CondConstant;
2701 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
2702 if (CondConstant)
2703 ThenGen(CGF);
2704 else
2705 ElseGen(CGF);
2706 return;
2707 }
2708
2709 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2710 // emit the conditional branch.
2711 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2712 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2713 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2714 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2715
2716 // Emit the 'then' code.
2717 CGF.EmitBlock(ThenBlock);
2718 ThenGen(CGF);
2719 CGF.EmitBranch(ContBlock);
2720 // Emit the 'else' code if present.
2721 // There is no need to emit line number for unconditional branch.
2722 (void)ApplyDebugLocation::CreateEmpty(CGF);
2723 CGF.EmitBlock(ElseBlock);
2724 ElseGen(CGF);
2725 // There is no need to emit line number for unconditional branch.
2726 (void)ApplyDebugLocation::CreateEmpty(CGF);
2727 CGF.EmitBranch(ContBlock);
2728 // Emit the continuation block for code after the if.
2729 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
2730}
2731
2732void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2733 llvm::Value *OutlinedFn,
2734 ArrayRef<llvm::Value *> CapturedVars,
2735 const Expr *IfCond) {
2736 if (!CGF.HaveInsertPoint())
2737 return;
2738 auto *RTLoc = emitUpdateLocation(CGF, Loc);
2739 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2740 PrePostActionTy &) {
2741 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
2742 auto &RT = CGF.CGM.getOpenMPRuntime();
2743 llvm::Value *Args[] = {
2744 RTLoc,
2745 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
2746 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
2747 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2748 RealArgs.append(std::begin(Args), std::end(Args));
2749 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2750
2751 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
2752 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2753 };
2754 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2755 PrePostActionTy &) {
2756 auto &RT = CGF.CGM.getOpenMPRuntime();
2757 auto ThreadID = RT.getThreadID(CGF, Loc);
2758 // Build calls:
2759 // __kmpc_serialized_parallel(&Loc, GTid);
2760 llvm::Value *Args[] = {RTLoc, ThreadID};
2761 CGF.EmitRuntimeCall(
2762 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
2763
2764 // OutlinedFn(&GTid, &zero, CapturedStruct);
2765 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
2766 Address ZeroAddr =
2767 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2768 /*Name*/ ".zero.addr");
2769 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2770 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2771 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2772 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2773 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2774 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2775
2776 // __kmpc_end_serialized_parallel(&Loc, GTid);
2777 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2778 CGF.EmitRuntimeCall(
2779 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2780 EndArgs);
2781 };
2782 if (IfCond)
2783 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
2784 else {
2785 RegionCodeGenTy ThenRCG(ThenGen);
2786 ThenRCG(CGF);
2787 }
2788}
2789
2790// If we're inside an (outlined) parallel region, use the region info's
2791// thread-ID variable (it is passed in a first argument of the outlined function
2792// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2793// regular serial code region, get thread ID by calling kmp_int32
2794// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2795// return the address of that temp.
2796Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2797 SourceLocation Loc) {
2798 if (auto *OMPRegionInfo =
2799 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2800 if (OMPRegionInfo->getThreadIDVariable())
2801 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2802
2803 auto ThreadID = getThreadID(CGF, Loc);
2804 auto Int32Ty =
2805 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2806 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2807 CGF.EmitStoreOfScalar(ThreadID,
2808 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2809
2810 return ThreadIDTemp;
2811}
2812
2813llvm::Constant *
2814CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
2815 const llvm::Twine &Name) {
2816 SmallString<256> Buffer;
2817 llvm::raw_svector_ostream Out(Buffer);
2818 Out << Name;
2819 auto RuntimeName = Out.str();
2820 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2821 if (Elem.second) {
2822 assert(Elem.second->getType()->getPointerElementType() == Ty &&(static_cast <bool> (Elem.second->getType()->getPointerElementType
() == Ty && "OMP internal variable has different type than requested"
) ? void (0) : __assert_fail ("Elem.second->getType()->getPointerElementType() == Ty && \"OMP internal variable has different type than requested\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2823, __extension__ __PRETTY_FUNCTION__))
2823 "OMP internal variable has different type than requested")(static_cast <bool> (Elem.second->getType()->getPointerElementType
() == Ty && "OMP internal variable has different type than requested"
) ? void (0) : __assert_fail ("Elem.second->getType()->getPointerElementType() == Ty && \"OMP internal variable has different type than requested\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 2823, __extension__ __PRETTY_FUNCTION__))
;
2824 return &*Elem.second;
2825 }
2826
2827 return Elem.second = new llvm::GlobalVariable(
2828 CGM.getModule(), Ty, /*IsConstant*/ false,
2829 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2830 Elem.first());
2831}
2832
2833llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2834 llvm::Twine Name(".gomp_critical_user_", CriticalName);
2835 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
2836}
2837
2838namespace {
2839/// Common pre(post)-action for different OpenMP constructs.
2840class CommonActionTy final : public PrePostActionTy {
2841 llvm::Value *EnterCallee;
2842 ArrayRef<llvm::Value *> EnterArgs;
2843 llvm::Value *ExitCallee;
2844 ArrayRef<llvm::Value *> ExitArgs;
2845 bool Conditional;
2846 llvm::BasicBlock *ContBlock = nullptr;
2847
2848public:
2849 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2850 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2851 bool Conditional = false)
2852 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2853 ExitArgs(ExitArgs), Conditional(Conditional) {}
2854 void Enter(CodeGenFunction &CGF) override {
2855 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2856 if (Conditional) {
2857 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2858 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2859 ContBlock = CGF.createBasicBlock("omp_if.end");
2860 // Generate the branch (If-stmt)
2861 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2862 CGF.EmitBlock(ThenBlock);
2863 }
2864 }
2865 void Done(CodeGenFunction &CGF) {
2866 // Emit the rest of blocks/branches
2867 CGF.EmitBranch(ContBlock);
2868 CGF.EmitBlock(ContBlock, true);
2869 }
2870 void Exit(CodeGenFunction &CGF) override {
2871 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2872 }
2873};
2874} // anonymous namespace
2875
2876void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2877 StringRef CriticalName,
2878 const RegionCodeGenTy &CriticalOpGen,
2879 SourceLocation Loc, const Expr *Hint) {
2880 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2881 // CriticalOpGen();
2882 // __kmpc_end_critical(ident_t *, gtid, Lock);
2883 // Prepare arguments and build a call to __kmpc_critical
2884 if (!CGF.HaveInsertPoint())
2885 return;
2886 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2887 getCriticalRegionLock(CriticalName)};
2888 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2889 std::end(Args));
2890 if (Hint) {
2891 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2892 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2893 }
2894 CommonActionTy Action(
2895 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2896 : OMPRTL__kmpc_critical),
2897 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2898 CriticalOpGen.setAction(Action);
2899 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2900}
2901
2902void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2903 const RegionCodeGenTy &MasterOpGen,
2904 SourceLocation Loc) {
2905 if (!CGF.HaveInsertPoint())
2906 return;
2907 // if(__kmpc_master(ident_t *, gtid)) {
2908 // MasterOpGen();
2909 // __kmpc_end_master(ident_t *, gtid);
2910 // }
2911 // Prepare arguments and build a call to __kmpc_master
2912 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2913 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2914 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2915 /*Conditional=*/true);
2916 MasterOpGen.setAction(Action);
2917 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2918 Action.Done(CGF);
2919}
2920
2921void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2922 SourceLocation Loc) {
2923 if (!CGF.HaveInsertPoint())
2924 return;
2925 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2926 llvm::Value *Args[] = {
2927 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2928 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2929 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
2930 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2931 Region->emitUntiedSwitch(CGF);
2932}
2933
2934void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2935 const RegionCodeGenTy &TaskgroupOpGen,
2936 SourceLocation Loc) {
2937 if (!CGF.HaveInsertPoint())
2938 return;
2939 // __kmpc_taskgroup(ident_t *, gtid);
2940 // TaskgroupOpGen();
2941 // __kmpc_end_taskgroup(ident_t *, gtid);
2942 // Prepare arguments and build a call to __kmpc_taskgroup
2943 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2944 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2945 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2946 Args);
2947 TaskgroupOpGen.setAction(Action);
2948 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2949}
2950
2951/// Given an array of pointers to variables, project the address of a
2952/// given variable.
2953static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2954 unsigned Index, const VarDecl *Var) {
2955 // Pull out the pointer to the variable.
2956 Address PtrAddr =
2957 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
2958 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2959
2960 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
2961 Addr = CGF.Builder.CreateElementBitCast(
2962 Addr, CGF.ConvertTypeForMem(Var->getType()));
2963 return Addr;
2964}
2965
2966static llvm::Value *emitCopyprivateCopyFunction(
2967 CodeGenModule &CGM, llvm::Type *ArgsType,
2968 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2969 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2970 SourceLocation Loc) {
2971 auto &C = CGM.getContext();
2972 // void copy_func(void *LHSArg, void *RHSArg);
2973 FunctionArgList Args;
2974 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2975 ImplicitParamDecl::Other);
2976 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2977 ImplicitParamDecl::Other);
2978 Args.push_back(&LHSArg);
2979 Args.push_back(&RHSArg);
2980 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2981 auto *Fn = llvm::Function::Create(
2982 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2983 ".omp.copyprivate.copy_func", &CGM.getModule());
2984 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2985 CodeGenFunction CGF(CGM);
2986 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2987 // Dest = (void*[n])(LHSArg);
2988 // Src = (void*[n])(RHSArg);
2989 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2990 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2991 ArgsType), CGF.getPointerAlign());
2992 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2993 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2994 ArgsType), CGF.getPointerAlign());
2995 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2996 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2997 // ...
2998 // *(Typen*)Dst[n] = *(Typen*)Src[n];
2999 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
3000 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
3001 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3002
3003 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
3004 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3005
3006 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
3007 QualType Type = VD->getType();
3008 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
3009 }
3010 CGF.FinishFunction();
3011 return Fn;
3012}
3013
3014void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
3015 const RegionCodeGenTy &SingleOpGen,
3016 SourceLocation Loc,
3017 ArrayRef<const Expr *> CopyprivateVars,
3018 ArrayRef<const Expr *> SrcExprs,
3019 ArrayRef<const Expr *> DstExprs,
3020 ArrayRef<const Expr *> AssignmentOps) {
3021 if (!CGF.HaveInsertPoint())
3022 return;
3023 assert(CopyprivateVars.size() == SrcExprs.size() &&(static_cast <bool> (CopyprivateVars.size() == SrcExprs
.size() && CopyprivateVars.size() == DstExprs.size() &&
CopyprivateVars.size() == AssignmentOps.size()) ? void (0) :
__assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3025, __extension__ __PRETTY_FUNCTION__))
3024 CopyprivateVars.size() == DstExprs.size() &&(static_cast <bool> (CopyprivateVars.size() == SrcExprs
.size() && CopyprivateVars.size() == DstExprs.size() &&
CopyprivateVars.size() == AssignmentOps.size()) ? void (0) :
__assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3025, __extension__ __PRETTY_FUNCTION__))
3025 CopyprivateVars.size() == AssignmentOps.size())(static_cast <bool> (CopyprivateVars.size() == SrcExprs
.size() && CopyprivateVars.size() == DstExprs.size() &&
CopyprivateVars.size() == AssignmentOps.size()) ? void (0) :
__assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3025, __extension__ __PRETTY_FUNCTION__))
;
3026 auto &C = CGM.getContext();
3027 // int32 did_it = 0;
3028 // if(__kmpc_single(ident_t *, gtid)) {
3029 // SingleOpGen();
3030 // __kmpc_end_single(ident_t *, gtid);
3031 // did_it = 1;
3032 // }
3033 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3034 // <copy_func>, did_it);
3035
3036 Address DidIt = Address::invalid();
3037 if (!CopyprivateVars.empty()) {
3038 // int32 did_it = 0;
3039 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3040 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
3041 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
3042 }
3043 // Prepare arguments and build a call to __kmpc_single
3044 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3045 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3046 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3047 /*Conditional=*/true);
3048 SingleOpGen.setAction(Action);
3049 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3050 if (DidIt.isValid()) {
3051 // did_it = 1;
3052 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3053 }
3054 Action.Done(CGF);
3055 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3056 // <copy_func>, did_it);
3057 if (DidIt.isValid()) {
3058 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
3059 auto CopyprivateArrayTy =
3060 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3061 /*IndexTypeQuals=*/0);
3062 // Create a list of all private variables for copyprivate.
3063 Address CopyprivateList =
3064 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3065 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
3066 Address Elem = CGF.Builder.CreateConstArrayGEP(
3067 CopyprivateList, I, CGF.getPointerSize());
3068 CGF.Builder.CreateStore(
3069 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3070 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3071 Elem);
3072 }
3073 // Build function that copies private values from single region to all other
3074 // threads in the corresponding parallel region.
3075 auto *CpyFn = emitCopyprivateCopyFunction(
3076 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
3077 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
3078 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
3079 Address CL =
3080 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3081 CGF.VoidPtrTy);
3082 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
3083 llvm::Value *Args[] = {
3084 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3085 getThreadID(CGF, Loc), // i32 <gtid>
3086 BufSize, // size_t <buf_size>
3087 CL.getPointer(), // void *<copyprivate list>
3088 CpyFn, // void (*) (void *, void *) <copy_func>
3089 DidItVal // i32 did_it
3090 };
3091 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3092 }
3093}
3094
3095void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3096 const RegionCodeGenTy &OrderedOpGen,
3097 SourceLocation Loc, bool IsThreads) {
3098 if (!CGF.HaveInsertPoint())
3099 return;
3100 // __kmpc_ordered(ident_t *, gtid);
3101 // OrderedOpGen();
3102 // __kmpc_end_ordered(ident_t *, gtid);
3103 // Prepare arguments and build a call to __kmpc_ordered
3104 if (IsThreads) {
3105 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3106 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3107 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3108 Args);
3109 OrderedOpGen.setAction(Action);
3110 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3111 return;
3112 }
3113 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3114}
3115
3116void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3117 OpenMPDirectiveKind Kind, bool EmitChecks,
3118 bool ForceSimpleCall) {
3119 if (!CGF.HaveInsertPoint())
3120 return;
3121 // Build call __kmpc_cancel_barrier(loc, thread_id);
3122 // Build call __kmpc_barrier(loc, thread_id);
3123 unsigned Flags;
3124 if (Kind == OMPD_for)
3125 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3126 else if (Kind == OMPD_sections)
3127 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3128 else if (Kind == OMPD_single)
3129 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3130 else if (Kind == OMPD_barrier)
3131 Flags = OMP_IDENT_BARRIER_EXPL;
3132 else
3133 Flags = OMP_IDENT_BARRIER_IMPL;
3134 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3135 // thread_id);
3136 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3137 getThreadID(CGF, Loc)};
3138 if (auto *OMPRegionInfo =
3139 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
3140 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
3141 auto *Result = CGF.EmitRuntimeCall(
3142 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
3143 if (EmitChecks) {
3144 // if (__kmpc_cancel_barrier()) {
3145 // exit from construct;
3146 // }
3147 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3148 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3149 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3150 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3151 CGF.EmitBlock(ExitBB);
3152 // exit from construct;
3153 auto CancelDestination =
3154 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3155 CGF.EmitBranchThroughCleanup(CancelDestination);
3156 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3157 }
3158 return;
3159 }
3160 }
3161 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
3162}
3163
3164/// \brief Map the OpenMP loop schedule to the runtime enumeration.
3165static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
3166 bool Chunked, bool Ordered) {
3167 switch (ScheduleKind) {
3168 case OMPC_SCHEDULE_static:
3169 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3170 : (Ordered ? OMP_ord_static : OMP_sch_static);
3171 case OMPC_SCHEDULE_dynamic:
3172 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
3173 case OMPC_SCHEDULE_guided:
3174 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
3175 case OMPC_SCHEDULE_runtime:
3176 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3177 case OMPC_SCHEDULE_auto:
3178 return Ordered ? OMP_ord_auto : OMP_sch_auto;
3179 case OMPC_SCHEDULE_unknown:
3180 assert(!Chunked && "chunk was specified but schedule kind not known")(static_cast <bool> (!Chunked && "chunk was specified but schedule kind not known"
) ? void (0) : __assert_fail ("!Chunked && \"chunk was specified but schedule kind not known\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3180, __extension__ __PRETTY_FUNCTION__))
;
3181 return Ordered ? OMP_ord_static : OMP_sch_static;
3182 }
3183 llvm_unreachable("Unexpected runtime schedule")::llvm::llvm_unreachable_internal("Unexpected runtime schedule"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3183)
;
3184}
3185
3186/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3187static OpenMPSchedType
3188getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3189 // only static is allowed for dist_schedule
3190 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3191}
3192
3193bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3194 bool Chunked) const {
3195 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3196 return Schedule == OMP_sch_static;
3197}
3198
3199bool CGOpenMPRuntime::isStaticNonchunked(
3200 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3201 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3202 return Schedule == OMP_dist_sch_static;
3203}
3204
3205
3206bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
3207 auto Schedule =
3208 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
3209 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here")(static_cast <bool> (Schedule != OMP_sch_static_chunked
&& "cannot be chunked here") ? void (0) : __assert_fail
("Schedule != OMP_sch_static_chunked && \"cannot be chunked here\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3209, __extension__ __PRETTY_FUNCTION__))
;
3210 return Schedule != OMP_sch_static;
3211}
3212
3213static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3214 OpenMPScheduleClauseModifier M1,
3215 OpenMPScheduleClauseModifier M2) {
3216 int Modifier = 0;
3217 switch (M1) {
3218 case OMPC_SCHEDULE_MODIFIER_monotonic:
3219 Modifier = OMP_sch_modifier_monotonic;
3220 break;
3221 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3222 Modifier = OMP_sch_modifier_nonmonotonic;
3223 break;
3224 case OMPC_SCHEDULE_MODIFIER_simd:
3225 if (Schedule == OMP_sch_static_chunked)
3226 Schedule = OMP_sch_static_balanced_chunked;
3227 break;
3228 case OMPC_SCHEDULE_MODIFIER_last:
3229 case OMPC_SCHEDULE_MODIFIER_unknown:
3230 break;
3231 }
3232 switch (M2) {
3233 case OMPC_SCHEDULE_MODIFIER_monotonic:
3234 Modifier = OMP_sch_modifier_monotonic;
3235 break;
3236 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3237 Modifier = OMP_sch_modifier_nonmonotonic;
3238 break;
3239 case OMPC_SCHEDULE_MODIFIER_simd:
3240 if (Schedule == OMP_sch_static_chunked)
3241 Schedule = OMP_sch_static_balanced_chunked;
3242 break;
3243 case OMPC_SCHEDULE_MODIFIER_last:
3244 case OMPC_SCHEDULE_MODIFIER_unknown:
3245 break;
3246 }
3247 return Schedule | Modifier;
3248}
3249
3250void CGOpenMPRuntime::emitForDispatchInit(
3251 CodeGenFunction &CGF, SourceLocation Loc,
3252 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3253 bool Ordered, const DispatchRTInput &DispatchValues) {
3254 if (!CGF.HaveInsertPoint())
3255 return;
3256 OpenMPSchedType Schedule = getRuntimeSchedule(
3257 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
3258 assert(Ordered ||(static_cast <bool> (Ordered || (Schedule != OMP_sch_static
&& Schedule != OMP_sch_static_chunked && Schedule
!= OMP_ord_static && Schedule != OMP_ord_static_chunked
&& Schedule != OMP_sch_static_balanced_chunked)) ? void
(0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3261, __extension__ __PRETTY_FUNCTION__))
3259 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&(static_cast <bool> (Ordered || (Schedule != OMP_sch_static
&& Schedule != OMP_sch_static_chunked && Schedule
!= OMP_ord_static && Schedule != OMP_ord_static_chunked
&& Schedule != OMP_sch_static_balanced_chunked)) ? void
(0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3261, __extension__ __PRETTY_FUNCTION__))
3260 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&(static_cast <bool> (Ordered || (Schedule != OMP_sch_static
&& Schedule != OMP_sch_static_chunked && Schedule
!= OMP_ord_static && Schedule != OMP_ord_static_chunked
&& Schedule != OMP_sch_static_balanced_chunked)) ? void
(0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3261, __extension__ __PRETTY_FUNCTION__))
3261 Schedule != OMP_sch_static_balanced_chunked))(static_cast <bool> (Ordered || (Schedule != OMP_sch_static
&& Schedule != OMP_sch_static_chunked && Schedule
!= OMP_ord_static && Schedule != OMP_ord_static_chunked
&& Schedule != OMP_sch_static_balanced_chunked)) ? void
(0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3261, __extension__ __PRETTY_FUNCTION__))
;
3262 // Call __kmpc_dispatch_init(
3263 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3264 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3265 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
3266
3267 // If the Chunk was not specified in the clause - use default value 1.
3268 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3269 : CGF.Builder.getIntN(IVSize, 1);
3270 llvm::Value *Args[] = {
3271 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3272 CGF.Builder.getInt32(addMonoNonMonoModifier(
3273 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
3274 DispatchValues.LB, // Lower
3275 DispatchValues.UB, // Upper
3276 CGF.Builder.getIntN(IVSize, 1), // Stride
3277 Chunk // Chunk
3278 };
3279 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3280}
3281
3282static void emitForStaticInitCall(
3283 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3284 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3285 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
3286 const CGOpenMPRuntime::StaticRTInput &Values) {
3287 if (!CGF.HaveInsertPoint())
3288 return;
3289
3290 assert(!Values.Ordered)(static_cast <bool> (!Values.Ordered) ? void (0) : __assert_fail
("!Values.Ordered", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3290, __extension__ __PRETTY_FUNCTION__))
;
3291 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule
== OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked
|| Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked
|| Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked
) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3295, __extension__ __PRETTY_FUNCTION__))
3292 Schedule == OMP_sch_static_balanced_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule
== OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked
|| Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked
|| Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked
) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3295, __extension__ __PRETTY_FUNCTION__))
3293 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule
== OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked
|| Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked
|| Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked
) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3295, __extension__ __PRETTY_FUNCTION__))
3294 Schedule == OMP_dist_sch_static ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule
== OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked
|| Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked
|| Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked
) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3295, __extension__ __PRETTY_FUNCTION__))
3295 Schedule == OMP_dist_sch_static_chunked)(static_cast <bool> (Schedule == OMP_sch_static || Schedule
== OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked
|| Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked
|| Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked
) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3295, __extension__ __PRETTY_FUNCTION__))
;
3296
3297 // Call __kmpc_for_static_init(
3298 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3299 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3300 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3301 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3302 llvm::Value *Chunk = Values.Chunk;
3303 if (Chunk == nullptr) {
3304 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||(static_cast <bool> ((Schedule == OMP_sch_static || Schedule
== OMP_ord_static || Schedule == OMP_dist_sch_static) &&
"expected static non-chunked schedule") ? void (0) : __assert_fail
("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3306, __extension__ __PRETTY_FUNCTION__))
3305 Schedule == OMP_dist_sch_static) &&(static_cast <bool> ((Schedule == OMP_sch_static || Schedule
== OMP_ord_static || Schedule == OMP_dist_sch_static) &&
"expected static non-chunked schedule") ? void (0) : __assert_fail
("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3306, __extension__ __PRETTY_FUNCTION__))
3306 "expected static non-chunked schedule")(static_cast <bool> ((Schedule == OMP_sch_static || Schedule
== OMP_ord_static || Schedule == OMP_dist_sch_static) &&
"expected static non-chunked schedule") ? void (0) : __assert_fail
("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3306, __extension__ __PRETTY_FUNCTION__))
;
3307 // If the Chunk was not specified in the clause - use default value 1.
3308 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3309 } else {
3310 assert((Schedule == OMP_sch_static_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked
|| Schedule == OMP_sch_static_balanced_chunked || Schedule ==
OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked
) && "expected static chunked schedule") ? void (0) :
__assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3314, __extension__ __PRETTY_FUNCTION__))
3311 Schedule == OMP_sch_static_balanced_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked
|| Schedule == OMP_sch_static_balanced_chunked || Schedule ==
OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked
) && "expected static chunked schedule") ? void (0) :
__assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3314, __extension__ __PRETTY_FUNCTION__))
3312 Schedule == OMP_ord_static_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked
|| Schedule == OMP_sch_static_balanced_chunked || Schedule ==
OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked
) && "expected static chunked schedule") ? void (0) :
__assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3314, __extension__ __PRETTY_FUNCTION__))
3313 Schedule == OMP_dist_sch_static_chunked) &&(static_cast <bool> ((Schedule == OMP_sch_static_chunked
|| Schedule == OMP_sch_static_balanced_chunked || Schedule ==
OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked
) && "expected static chunked schedule") ? void (0) :
__assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3314, __extension__ __PRETTY_FUNCTION__))
3314 "expected static chunked schedule")(static_cast <bool> ((Schedule == OMP_sch_static_chunked
|| Schedule == OMP_sch_static_balanced_chunked || Schedule ==
OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked
) && "expected static chunked schedule") ? void (0) :
__assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3314, __extension__ __PRETTY_FUNCTION__))
;
3315 }
3316 llvm::Value *Args[] = {
3317 UpdateLocation,
3318 ThreadId,
3319 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3320 M2)), // Schedule type
3321 Values.IL.getPointer(), // &isLastIter
3322 Values.LB.getPointer(), // &LB
3323 Values.UB.getPointer(), // &UB
3324 Values.ST.getPointer(), // &Stride
3325 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3326 Chunk // Chunk
3327 };
3328 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
3329}
3330
3331void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3332 SourceLocation Loc,
3333 OpenMPDirectiveKind DKind,
3334 const OpenMPScheduleTy &ScheduleKind,
3335 const StaticRTInput &Values) {
3336 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3337 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3338 assert(isOpenMPWorksharingDirective(DKind) &&(static_cast <bool> (isOpenMPWorksharingDirective(DKind
) && "Expected loop-based or sections-based directive."
) ? void (0) : __assert_fail ("isOpenMPWorksharingDirective(DKind) && \"Expected loop-based or sections-based directive.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3339, __extension__ __PRETTY_FUNCTION__))
3339 "Expected loop-based or sections-based directive.")(static_cast <bool> (isOpenMPWorksharingDirective(DKind
) && "Expected loop-based or sections-based directive."
) ? void (0) : __assert_fail ("isOpenMPWorksharingDirective(DKind) && \"Expected loop-based or sections-based directive.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3339, __extension__ __PRETTY_FUNCTION__))
;
3340 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3341 isOpenMPLoopDirective(DKind)
3342 ? OMP_IDENT_WORK_LOOP
3343 : OMP_IDENT_WORK_SECTIONS);
3344 auto *ThreadId = getThreadID(CGF, Loc);
3345 auto *StaticInitFunction =
3346 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3347 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3348 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
3349}
3350
3351void CGOpenMPRuntime::emitDistributeStaticInit(
3352 CodeGenFunction &CGF, SourceLocation Loc,
3353 OpenMPDistScheduleClauseKind SchedKind,
3354 const CGOpenMPRuntime::StaticRTInput &Values) {
3355 OpenMPSchedType ScheduleNum =
3356 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3357 auto *UpdatedLocation =
3358 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
3359 auto *ThreadId = getThreadID(CGF, Loc);
3360 auto *StaticInitFunction =
3361 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3362 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3363 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
3364 OMPC_SCHEDULE_MODIFIER_unknown, Values);
3365}
3366
3367void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
3368 SourceLocation Loc,
3369 OpenMPDirectiveKind DKind) {
3370 if (!CGF.HaveInsertPoint())
3371 return;
3372 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
3373 llvm::Value *Args[] = {
3374 emitUpdateLocation(CGF, Loc,
3375 isOpenMPDistributeDirective(DKind)
3376 ? OMP_IDENT_WORK_DISTRIBUTE
3377 : isOpenMPLoopDirective(DKind)
3378 ? OMP_IDENT_WORK_LOOP
3379 : OMP_IDENT_WORK_SECTIONS),
3380 getThreadID(CGF, Loc)};
3381 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3382 Args);
3383}
3384
3385void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3386 SourceLocation Loc,
3387 unsigned IVSize,
3388 bool IVSigned) {
3389 if (!CGF.HaveInsertPoint())
3390 return;
3391 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
3392 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3393 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3394}
3395
3396llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3397 SourceLocation Loc, unsigned IVSize,
3398 bool IVSigned, Address IL,
3399 Address LB, Address UB,
3400 Address ST) {
3401 // Call __kmpc_dispatch_next(
3402 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3403 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3404 // kmp_int[32|64] *p_stride);
3405 llvm::Value *Args[] = {
3406 emitUpdateLocation(CGF, Loc),
3407 getThreadID(CGF, Loc),
3408 IL.getPointer(), // &isLastIter
3409 LB.getPointer(), // &Lower
3410 UB.getPointer(), // &Upper
3411 ST.getPointer() // &Stride
3412 };
3413 llvm::Value *Call =
3414 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3415 return CGF.EmitScalarConversion(
3416 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
3417 CGF.getContext().BoolTy, Loc);
3418}
3419
3420void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3421 llvm::Value *NumThreads,
3422 SourceLocation Loc) {
3423 if (!CGF.HaveInsertPoint())
3424 return;
3425 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3426 llvm::Value *Args[] = {
3427 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3428 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
3429 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3430 Args);
3431}
3432
3433void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3434 OpenMPProcBindClauseKind ProcBind,
3435 SourceLocation Loc) {
3436 if (!CGF.HaveInsertPoint())
3437 return;
3438 // Constants for proc bind value accepted by the runtime.
3439 enum ProcBindTy {
3440 ProcBindFalse = 0,
3441 ProcBindTrue,
3442 ProcBindMaster,
3443 ProcBindClose,
3444 ProcBindSpread,
3445 ProcBindIntel,
3446 ProcBindDefault
3447 } RuntimeProcBind;
3448 switch (ProcBind) {
3449 case OMPC_PROC_BIND_master:
3450 RuntimeProcBind = ProcBindMaster;
3451 break;
3452 case OMPC_PROC_BIND_close:
3453 RuntimeProcBind = ProcBindClose;
3454 break;
3455 case OMPC_PROC_BIND_spread:
3456 RuntimeProcBind = ProcBindSpread;
3457 break;
3458 case OMPC_PROC_BIND_unknown:
3459 llvm_unreachable("Unsupported proc_bind value.")::llvm::llvm_unreachable_internal("Unsupported proc_bind value."
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3459)
;
3460 }
3461 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3462 llvm::Value *Args[] = {
3463 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3464 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3465 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3466}
3467
3468void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3469 SourceLocation Loc) {
3470 if (!CGF.HaveInsertPoint())
3471 return;
3472 // Build call void __kmpc_flush(ident_t *loc)
3473 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3474 emitUpdateLocation(CGF, Loc));
3475}
3476
3477namespace {
3478/// \brief Indexes of fields for type kmp_task_t.
3479enum KmpTaskTFields {
3480 /// \brief List of shared variables.
3481 KmpTaskTShareds,
3482 /// \brief Task routine.
3483 KmpTaskTRoutine,
3484 /// \brief Partition id for the untied tasks.
3485 KmpTaskTPartId,
3486 /// Function with call of destructors for private variables.
3487 Data1,
3488 /// Task priority.
3489 Data2,
3490 /// (Taskloops only) Lower bound.
3491 KmpTaskTLowerBound,
3492 /// (Taskloops only) Upper bound.
3493 KmpTaskTUpperBound,
3494 /// (Taskloops only) Stride.
3495 KmpTaskTStride,
3496 /// (Taskloops only) Is last iteration flag.
3497 KmpTaskTLastIter,
3498 /// (Taskloops only) Reduction data.
3499 KmpTaskTReductions,
3500};
3501} // anonymous namespace
3502
3503bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3504 return OffloadEntriesTargetRegion.empty() &&
3505 OffloadEntriesDeviceGlobalVar.empty();
3506}
3507
3508/// \brief Initialize target region entry.
3509void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3510 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3511 StringRef ParentName, unsigned LineNum,
3512 unsigned Order) {
3513 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "(static_cast <bool> (CGM.getLangOpts().OpenMPIsDevice &&
"Initialization of entries is " "only required for the device "
"code generation.") ? void (0) : __assert_fail ("CGM.getLangOpts().OpenMPIsDevice && \"Initialization of entries is \" \"only required for the device \" \"code generation.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3515, __extension__ __PRETTY_FUNCTION__))
3514 "only required for the device "(static_cast <bool> (CGM.getLangOpts().OpenMPIsDevice &&
"Initialization of entries is " "only required for the device "
"code generation.") ? void (0) : __assert_fail ("CGM.getLangOpts().OpenMPIsDevice && \"Initialization of entries is \" \"only required for the device \" \"code generation.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3515, __extension__ __PRETTY_FUNCTION__))
3515 "code generation.")(static_cast <bool> (CGM.getLangOpts().OpenMPIsDevice &&
"Initialization of entries is " "only required for the device "
"code generation.") ? void (0) : __assert_fail ("CGM.getLangOpts().OpenMPIsDevice && \"Initialization of entries is \" \"only required for the device \" \"code generation.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3515, __extension__ __PRETTY_FUNCTION__))
;
3516 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
3517 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3518 OMPTargetRegionEntryTargetRegion);
3519 ++OffloadingEntriesNum;
3520}
3521
3522void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3523 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3524 StringRef ParentName, unsigned LineNum,
3525 llvm::Constant *Addr, llvm::Constant *ID,
3526 OMPTargetRegionEntryKind Flags) {
3527 // If we are emitting code for a target, the entry is already initialized,
3528 // only has to be registered.
3529 if (CGM.getLangOpts().OpenMPIsDevice) {
3530 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&(static_cast <bool> (hasTargetRegionEntryInfo(DeviceID,
FileID, ParentName, LineNum) && "Entry must exist.")
? void (0) : __assert_fail ("hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) && \"Entry must exist.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3531, __extension__ __PRETTY_FUNCTION__))
3531 "Entry must exist.")(static_cast <bool> (hasTargetRegionEntryInfo(DeviceID,
FileID, ParentName, LineNum) && "Entry must exist.")
? void (0) : __assert_fail ("hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) && \"Entry must exist.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3531, __extension__ __PRETTY_FUNCTION__))
;
3532 auto &Entry =
3533 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
3534 assert(Entry.isValid() && "Entry not initialized!")(static_cast <bool> (Entry.isValid() && "Entry not initialized!"
) ? void (0) : __assert_fail ("Entry.isValid() && \"Entry not initialized!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3534, __extension__ __PRETTY_FUNCTION__))
;
3535 Entry.setAddress(Addr);
3536 Entry.setID(ID);
3537 Entry.setFlags(Flags);
3538 } else {
3539 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
3540 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
3541 ++OffloadingEntriesNum;
3542 }
3543}
3544
3545bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
3546 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3547 unsigned LineNum) const {
3548 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3549 if (PerDevice == OffloadEntriesTargetRegion.end())
3550 return false;
3551 auto PerFile = PerDevice->second.find(FileID);
3552 if (PerFile == PerDevice->second.end())
3553 return false;
3554 auto PerParentName = PerFile->second.find(ParentName);
3555 if (PerParentName == PerFile->second.end())
3556 return false;
3557 auto PerLine = PerParentName->second.find(LineNum);
3558 if (PerLine == PerParentName->second.end())
3559 return false;
3560 // Fail if this entry is already registered.
3561 if (PerLine->second.getAddress() || PerLine->second.getID())
3562 return false;
3563 return true;
3564}
3565
3566void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3567 const OffloadTargetRegionEntryInfoActTy &Action) {
3568 // Scan all target region entries and perform the provided action.
3569 for (const auto &D : OffloadEntriesTargetRegion)
3570 for (const auto &F : D.second)
3571 for (const auto &P : F.second)
3572 for (const auto &L : P.second)
3573 Action(D.first, F.first, P.first(), L.first, L.second);
3574}
3575
3576void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3577 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3578 OMPTargetGlobalVarEntryKind Flags,
3579 unsigned Order) {
3580 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "(static_cast <bool> (CGM.getLangOpts().OpenMPIsDevice &&
"Initialization of entries is " "only required for the device "
"code generation.") ? void (0) : __assert_fail ("CGM.getLangOpts().OpenMPIsDevice && \"Initialization of entries is \" \"only required for the device \" \"code generation.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3582, __extension__ __PRETTY_FUNCTION__))
3581 "only required for the device "(static_cast <bool> (CGM.getLangOpts().OpenMPIsDevice &&
"Initialization of entries is " "only required for the device "
"code generation.") ? void (0) : __assert_fail ("CGM.getLangOpts().OpenMPIsDevice && \"Initialization of entries is \" \"only required for the device \" \"code generation.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3582, __extension__ __PRETTY_FUNCTION__))
3582 "code generation.")(static_cast <bool> (CGM.getLangOpts().OpenMPIsDevice &&
"Initialization of entries is " "only required for the device "
"code generation.") ? void (0) : __assert_fail ("CGM.getLangOpts().OpenMPIsDevice && \"Initialization of entries is \" \"only required for the device \" \"code generation.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3582, __extension__ __PRETTY_FUNCTION__))
;
3583 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3584 ++OffloadingEntriesNum;
3585}
3586
3587void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3588 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3589 CharUnits VarSize,
3590 OMPTargetGlobalVarEntryKind Flags,
3591 llvm::GlobalValue::LinkageTypes Linkage) {
3592 if (CGM.getLangOpts().OpenMPIsDevice) {
3593 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3594 assert(Entry.isValid() && Entry.getFlags() == Flags &&(static_cast <bool> (Entry.isValid() && Entry.getFlags
() == Flags && "Entry not initialized!") ? void (0) :
__assert_fail ("Entry.isValid() && Entry.getFlags() == Flags && \"Entry not initialized!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3595, __extension__ __PRETTY_FUNCTION__))
3595 "Entry not initialized!")(static_cast <bool> (Entry.isValid() && Entry.getFlags
() == Flags && "Entry not initialized!") ? void (0) :
__assert_fail ("Entry.isValid() && Entry.getFlags() == Flags && \"Entry not initialized!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3595, __extension__ __PRETTY_FUNCTION__))
;
3596 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&(static_cast <bool> ((!Entry.getAddress() || Entry.getAddress
() == Addr) && "Resetting with the new address.") ? void
(0) : __assert_fail ("(!Entry.getAddress() || Entry.getAddress() == Addr) && \"Resetting with the new address.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3597, __extension__ __PRETTY_FUNCTION__))
3597 "Resetting with the new address.")(static_cast <bool> ((!Entry.getAddress() || Entry.getAddress
() == Addr) && "Resetting with the new address.") ? void
(0) : __assert_fail ("(!Entry.getAddress() || Entry.getAddress() == Addr) && \"Resetting with the new address.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3597, __extension__ __PRETTY_FUNCTION__))
;
3598 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3599 return;
3600 Entry.setAddress(Addr);
3601 Entry.setVarSize(VarSize);
3602 Entry.setLinkage(Linkage);
3603 } else {
3604 if (hasDeviceGlobalVarEntryInfo(VarName))
3605 return;
3606 OffloadEntriesDeviceGlobalVar.try_emplace(
3607 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3608 ++OffloadingEntriesNum;
3609 }
3610}
3611
3612void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3613 actOnDeviceGlobalVarEntriesInfo(
3614 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3615 // Scan all target region entries and perform the provided action.
3616 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3617 Action(E.getKey(), E.getValue());
3618}
3619
3620llvm::Function *
3621CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3622 // If we don't have entries or if we are emitting code for the device, we
3623 // don't need to do anything.
3624 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3625 return nullptr;
3626
3627 auto &M = CGM.getModule();
3628 auto &C = CGM.getContext();
3629
3630 // Get list of devices we care about
3631 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3632
3633 // We should be creating an offloading descriptor only if there are devices
3634 // specified.
3635 assert(!Devices.empty() && "No OpenMP offloading devices??")(static_cast <bool> (!Devices.empty() && "No OpenMP offloading devices??"
) ? void (0) : __assert_fail ("!Devices.empty() && \"No OpenMP offloading devices??\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3635, __extension__ __PRETTY_FUNCTION__))
;
3636
3637 // Create the external variables that will point to the begin and end of the
3638 // host entries section. These will be defined by the linker.
3639 auto *OffloadEntryTy =
3640 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3641 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3642 M, OffloadEntryTy, /*isConstant=*/true,
3643 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
3644 ".omp_offloading.entries_begin");
3645 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3646 M, OffloadEntryTy, /*isConstant=*/true,
3647 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
3648 ".omp_offloading.entries_end");
3649
3650 // Create all device images
3651 auto *DeviceImageTy = cast<llvm::StructType>(
3652 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
3653 ConstantInitBuilder DeviceImagesBuilder(CGM);
3654 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
3655
3656 for (llvm::Triple Device : Devices) {
3657 StringRef T = Device.getTriple();
3658 auto *ImgBegin = new llvm::GlobalVariable(
3659 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
3660 /*Initializer=*/nullptr,
3661 Twine(".omp_offloading.img_start.") + Twine(T));
3662 auto *ImgEnd = new llvm::GlobalVariable(
3663 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
3664 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
3665
3666 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3667 Dev.add(ImgBegin);
3668 Dev.add(ImgEnd);
3669 Dev.add(HostEntriesBegin);
3670 Dev.add(HostEntriesEnd);
3671 Dev.finishAndAddTo(DeviceImagesEntries);
3672 }
3673
3674 // Create device images global array.
3675 llvm::GlobalVariable *DeviceImages =
3676 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3677 CGM.getPointerAlign(),
3678 /*isConstant=*/true);
3679 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3680
3681 // This is a Zero array to be used in the creation of the constant expressions
3682 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3683 llvm::Constant::getNullValue(CGM.Int32Ty)};
3684
3685 // Create the target region descriptor.
3686 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3687 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
3688 ConstantInitBuilder DescBuilder(CGM);
3689 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3690 DescInit.addInt(CGM.Int32Ty, Devices.size());
3691 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3692 DeviceImages,
3693 Index));
3694 DescInit.add(HostEntriesBegin);
3695 DescInit.add(HostEntriesEnd);
3696
3697 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3698 CGM.getPointerAlign(),
3699 /*isConstant=*/true);
3700
3701 // Emit code to register or unregister the descriptor at execution
3702 // startup or closing, respectively.
3703
3704 llvm::Function *UnRegFn;
3705 {
3706 FunctionArgList Args;
3707 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3708 Args.push_back(&DummyPtr);
3709
3710 CodeGenFunction CGF(CGM);
3711 // Disable debug info for global (de-)initializer because they are not part
3712 // of some particular construct.
3713 CGF.disableDebugInfo();
3714 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3715 auto FTy = CGM.getTypes().GetFunctionType(FI);
3716 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(
3717 FTy, ".omp_offloading.descriptor_unreg", FI);
3718 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3719 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3720 Desc);
3721 CGF.FinishFunction();
3722 }
3723 llvm::Function *RegFn;
3724 {
3725 CodeGenFunction CGF(CGM);
3726 // Disable debug info for global (de-)initializer because they are not part
3727 // of some particular construct.
3728 CGF.disableDebugInfo();
3729 auto &FI = CGM.getTypes().arrangeNullaryFunction();
3730 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3731 RegFn = CGM.CreateGlobalInitOrDestructFunction(
3732 FTy, ".omp_offloading.descriptor_reg", FI);
3733 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3734 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3735 // Create a variable to drive the registration and unregistration of the
3736 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3737 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3738 SourceLocation(), nullptr, C.CharTy,
3739 ImplicitParamDecl::Other);
3740 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3741 CGF.FinishFunction();
3742 }
3743 if (CGM.supportsCOMDAT()) {
3744 // It is sufficient to call registration function only once, so create a
3745 // COMDAT group for registration/unregistration functions and associated
3746 // data. That would reduce startup time and code size. Registration
3747 // function serves as a COMDAT group key.
3748 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3749 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3750 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3751 RegFn->setComdat(ComdatKey);
3752 UnRegFn->setComdat(ComdatKey);
3753 DeviceImages->setComdat(ComdatKey);
3754 Desc->setComdat(ComdatKey);
3755 }
3756 return RegFn;
3757}
3758
3759void CGOpenMPRuntime::createOffloadEntry(
3760 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3761 llvm::GlobalValue::LinkageTypes Linkage) {
3762 StringRef Name = Addr->getName();
3763 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3764 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3765 llvm::LLVMContext &C = CGM.getModule().getContext();
3766 llvm::Module &M = CGM.getModule();
3767
3768 // Make sure the address has the right type.
3769 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
3770
3771 // Create constant string with the name.
3772 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3773
3774 llvm::GlobalVariable *Str =
3775 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3776 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3777 ".omp_offloading.entry_name");
3778 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3779 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3780
3781 // We can't have any padding between symbols, so we need to have 1-byte
3782 // alignment.
3783 auto Align = CharUnits::fromQuantity(1);
3784
3785 // Create the entry struct.
3786 ConstantInitBuilder EntryBuilder(CGM);
3787 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3788 EntryInit.add(AddrPtr);
3789 EntryInit.add(StrPtr);
3790 EntryInit.addInt(CGM.SizeTy, Size);
3791 EntryInit.addInt(CGM.Int32Ty, Flags);
3792 EntryInit.addInt(CGM.Int32Ty, 0);
3793 llvm::GlobalVariable *Entry = EntryInit.finishAndCreateGlobal(
3794 Twine(".omp_offloading.entry.", Name), Align,
3795 /*Constant=*/true, Linkage);
3796
3797 // The entry has to be created in the section the linker expects it to be.
3798 Entry->setSection(".omp_offloading.entries");
3799}
3800
3801void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3802 // Emit the offloading entries and metadata so that the device codegen side
3803 // can easily figure out what to emit. The produced metadata looks like
3804 // this:
3805 //
3806 // !omp_offload.info = !{!1, ...}
3807 //
3808 // Right now we only generate metadata for function that contain target
3809 // regions.
3810
3811 // If we do not have entries, we don't need to do anything.
3812 if (OffloadEntriesInfoManager.empty())
3813 return;
3814
3815 llvm::Module &M = CGM.getModule();
3816 llvm::LLVMContext &C = M.getContext();
3817 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3818 OrderedEntries(OffloadEntriesInfoManager.size());
3819
3820 // Auxiliary methods to create metadata values and strings.
3821 auto &&GetMDInt = [&C](unsigned V) {
3822 return llvm::ConstantAsMetadata::get(
3823 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), V));
3824 };
3825
3826 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3827
3828 // Create the offloading info metadata node.
3829 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3830
3831 // Create function that emits metadata for each target region entry;
3832 auto &&TargetRegionMetadataEmitter =
3833 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3834 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3835 unsigned Line,
3836 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3837 // Generate metadata for target regions. Each entry of this metadata
3838 // contains:
3839 // - Entry 0 -> Kind of this type of metadata (0).
3840 // - Entry 1 -> Device ID of the file where the entry was identified.
3841 // - Entry 2 -> File ID of the file where the entry was identified.
3842 // - Entry 3 -> Mangled name of the function where the entry was
3843 // identified.
3844 // - Entry 4 -> Line in the file where the entry was identified.
3845 // - Entry 5 -> Order the entry was created.
3846 // The first element of the metadata node is the kind.
3847 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3848 GetMDInt(FileID), GetMDString(ParentName),
3849 GetMDInt(Line), GetMDInt(E.getOrder())};
3850
3851 // Save this entry in the right position of the ordered entries array.
3852 OrderedEntries[E.getOrder()] = &E;
3853
3854 // Add metadata to the named metadata node.
3855 MD->addOperand(llvm::MDNode::get(C, Ops));
3856 };
3857
3858 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3859 TargetRegionMetadataEmitter);
3860
3861 // Create function that emits metadata for each device global variable entry;
3862 auto &&DeviceGlobalVarMetadataEmitter =
3863 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3864 MD](StringRef MangledName,
3865 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3866 &E) {
3867 // Generate metadata for global variables. Each entry of this metadata
3868 // contains:
3869 // - Entry 0 -> Kind of this type of metadata (1).
3870 // - Entry 1 -> Mangled name of the variable.
3871 // - Entry 2 -> Declare target kind.
3872 // - Entry 3 -> Order the entry was created.
3873 // The first element of the metadata node is the kind.
3874 llvm::Metadata *Ops[] = {
3875 GetMDInt(E.getKind()), GetMDString(MangledName),
3876 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3877
3878 // Save this entry in the right position of the ordered entries array.
3879 OrderedEntries[E.getOrder()] = &E;
3880
3881 // Add metadata to the named metadata node.
3882 MD->addOperand(llvm::MDNode::get(C, Ops));
3883 };
3884
3885 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3886 DeviceGlobalVarMetadataEmitter);
3887
3888 for (const auto *E : OrderedEntries) {
3889 assert(E && "All ordered entries must exist!")(static_cast <bool> (E && "All ordered entries must exist!"
) ? void (0) : __assert_fail ("E && \"All ordered entries must exist!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3889, __extension__ __PRETTY_FUNCTION__))
;
3890 if (const auto *CE =
3891 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3892 E)) {
3893 assert(CE->getID() && CE->getAddress() &&(static_cast <bool> (CE->getID() && CE->getAddress
() && "Entry ID and Addr are invalid!") ? void (0) : __assert_fail
("CE->getID() && CE->getAddress() && \"Entry ID and Addr are invalid!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3894, __extension__ __PRETTY_FUNCTION__))
3894 "Entry ID and Addr are invalid!")(static_cast <bool> (CE->getID() && CE->getAddress
() && "Entry ID and Addr are invalid!") ? void (0) : __assert_fail
("CE->getID() && CE->getAddress() && \"Entry ID and Addr are invalid!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3894, __extension__ __PRETTY_FUNCTION__))
;
3895 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
3896 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3897 } else if (const auto *CE =
3898 dyn_cast<OffloadEntriesInfoManagerTy::
3899 OffloadEntryInfoDeviceGlobalVar>(E)) {
3900 assert(CE->getAddress() && "Entry Addr is invalid!")(static_cast <bool> (CE->getAddress() && "Entry Addr is invalid!"
) ? void (0) : __assert_fail ("CE->getAddress() && \"Entry Addr is invalid!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3900, __extension__ __PRETTY_FUNCTION__))
;
3901 createOffloadEntry(CE->getAddress(), CE->getAddress(),
3902 CE->getVarSize().getQuantity(), CE->getFlags(),
3903 CE->getLinkage());
3904 } else {
3905 llvm_unreachable("Unsupported entry kind.")::llvm::llvm_unreachable_internal("Unsupported entry kind.", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3905)
;
3906 }
3907 }
3908}
3909
3910/// \brief Loads all the offload entries information from the host IR
3911/// metadata.
3912void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3913 // If we are in target mode, load the metadata from the host IR. This code has
3914 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3915
3916 if (!CGM.getLangOpts().OpenMPIsDevice)
3917 return;
3918
3919 if (CGM.getLangOpts().OMPHostIRFile.empty())
3920 return;
3921
3922 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3923 if (Buf.getError())
3924 return;
3925
3926 llvm::LLVMContext C;
3927 auto ME = expectedToErrorOrAndEmitErrors(
3928 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
3929
3930 if (ME.getError())
3931 return;
3932
3933 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3934 if (!MD)
3935 return;
3936
3937 for (llvm::MDNode *MN : MD->operands()) {
3938 auto GetMDInt = [MN](unsigned Idx) {
3939 llvm::ConstantAsMetadata *V =
3940 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3941 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3942 };
3943
3944 auto GetMDString = [MN](unsigned Idx) {
3945 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3946 return V->getString();
3947 };
3948
3949 switch (GetMDInt(0)) {
3950 default:
3951 llvm_unreachable("Unexpected metadata!")::llvm::llvm_unreachable_internal("Unexpected metadata!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 3951)
;
3952 break;
3953 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3954 OffloadingEntryInfoTargetRegion:
3955 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3956 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
3957 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
3958 /*Order=*/GetMDInt(5));
3959 break;
3960 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3961 OffloadingEntryInfoDeviceGlobalVar:
3962 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
3963 /*MangledName=*/GetMDString(1),
3964 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
3965 /*Flags=*/GetMDInt(2)),
3966 /*Order=*/GetMDInt(3));
3967 break;
3968 }
3969 }
3970}
3971
3972void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3973 if (!KmpRoutineEntryPtrTy) {
3974 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3975 auto &C = CGM.getContext();
3976 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3977 FunctionProtoType::ExtProtoInfo EPI;
3978 KmpRoutineEntryPtrQTy = C.getPointerType(
3979 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3980 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3981 }
3982}
3983
3984static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3985 QualType FieldTy) {
3986 auto *Field = FieldDecl::Create(
3987 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3988 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3989 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3990 Field->setAccess(AS_public);
3991 DC->addDecl(Field);
3992 return Field;
3993}
3994
3995QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3996
3997 // Make sure the type of the entry is already created. This is the type we
3998 // have to create:
3999 // struct __tgt_offload_entry{
4000 // void *addr; // Pointer to the offload entry info.
4001 // // (function or global)
4002 // char *name; // Name of the function or global.
4003 // size_t size; // Size of the entry info (0 if it a function).
4004 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4005 // int32_t reserved; // Reserved, to use by the runtime library.
4006 // };
4007 if (TgtOffloadEntryQTy.isNull()) {
4008 ASTContext &C = CGM.getContext();
4009 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
4010 RD->startDefinition();
4011 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4012 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4013 addFieldToRecordDecl(C, RD, C.getSizeType());
4014 addFieldToRecordDecl(
4015 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4016 addFieldToRecordDecl(
4017 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4018 RD->completeDefinition();
4019 RD->addAttr(PackedAttr::CreateImplicit(C));
4020 TgtOffloadEntryQTy = C.getRecordType(RD);
4021 }
4022 return TgtOffloadEntryQTy;
4023}
4024
4025QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4026 // These are the types we need to build:
4027 // struct __tgt_device_image{
4028 // void *ImageStart; // Pointer to the target code start.
4029 // void *ImageEnd; // Pointer to the target code end.
4030 // // We also add the host entries to the device image, as it may be useful
4031 // // for the target runtime to have access to that information.
4032 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4033 // // the entries.
4034 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4035 // // entries (non inclusive).
4036 // };
4037 if (TgtDeviceImageQTy.isNull()) {
4038 ASTContext &C = CGM.getContext();
4039 auto *RD = C.buildImplicitRecord("__tgt_device_image");
4040 RD->startDefinition();
4041 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4042 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4043 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4044 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4045 RD->completeDefinition();
4046 TgtDeviceImageQTy = C.getRecordType(RD);
4047 }
4048 return TgtDeviceImageQTy;
4049}
4050
4051QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4052 // struct __tgt_bin_desc{
4053 // int32_t NumDevices; // Number of devices supported.
4054 // __tgt_device_image *DeviceImages; // Arrays of device images
4055 // // (one per device).
4056 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4057 // // entries.
4058 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4059 // // entries (non inclusive).
4060 // };
4061 if (TgtBinaryDescriptorQTy.isNull()) {
4062 ASTContext &C = CGM.getContext();
4063 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
4064 RD->startDefinition();
4065 addFieldToRecordDecl(
4066 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4067 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4068 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4069 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4070 RD->completeDefinition();
4071 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4072 }
4073 return TgtBinaryDescriptorQTy;
4074}
4075
4076namespace {
4077struct PrivateHelpersTy {
4078 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4079 const VarDecl *PrivateElemInit)
4080 : Original(Original), PrivateCopy(PrivateCopy),
4081 PrivateElemInit(PrivateElemInit) {}
4082 const VarDecl *Original;
4083 const VarDecl *PrivateCopy;
4084 const VarDecl *PrivateElemInit;
4085};
4086typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
4087} // anonymous namespace
4088
4089static RecordDecl *
4090createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
4091 if (!Privates.empty()) {
4092 auto &C = CGM.getContext();
4093 // Build struct .kmp_privates_t. {
4094 // /* private vars */
4095 // };
4096 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
4097 RD->startDefinition();
4098 for (auto &&Pair : Privates) {
4099 auto *VD = Pair.second.Original;
4100 auto Type = VD->getType();
4101 Type = Type.getNonReferenceType();
4102 auto *FD = addFieldToRecordDecl(C, RD, Type);
4103 if (VD->hasAttrs()) {
4104 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4105 E(VD->getAttrs().end());
4106 I != E; ++I)
4107 FD->addAttr(*I);
4108 }
4109 }
4110 RD->completeDefinition();
4111 return RD;
4112 }
4113 return nullptr;
4114}
4115
4116static RecordDecl *
4117createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4118 QualType KmpInt32Ty,
4119 QualType KmpRoutineEntryPointerQTy) {
4120 auto &C = CGM.getContext();
4121 // Build struct kmp_task_t {
4122 // void * shareds;
4123 // kmp_routine_entry_t routine;
4124 // kmp_int32 part_id;
4125 // kmp_cmplrdata_t data1;
4126 // kmp_cmplrdata_t data2;
4127 // For taskloops additional fields:
4128 // kmp_uint64 lb;
4129 // kmp_uint64 ub;
4130 // kmp_int64 st;
4131 // kmp_int32 liter;
4132 // void * reductions;
4133 // };
4134 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
4135 UD->startDefinition();
4136 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4137 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4138 UD->completeDefinition();
4139 QualType KmpCmplrdataTy = C.getRecordType(UD);
4140 auto *RD = C.buildImplicitRecord("kmp_task_t");
4141 RD->startDefinition();
4142 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4143 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4144 addFieldToRecordDecl(C, RD, KmpInt32Ty);
4145 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4146 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4147 if (isOpenMPTaskLoopDirective(Kind)) {
4148 QualType KmpUInt64Ty =
4149 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4150 QualType KmpInt64Ty =
4151 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4152 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4153 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4154 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4155 addFieldToRecordDecl(C, RD, KmpInt32Ty);
4156 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4157 }
4158 RD->completeDefinition();
4159 return RD;
4160}
4161
4162static RecordDecl *
4163createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
4164 ArrayRef<PrivateDataTy> Privates) {
4165 auto &C = CGM.getContext();
4166 // Build struct kmp_task_t_with_privates {
4167 // kmp_task_t task_data;
4168 // .kmp_privates_t. privates;
4169 // };
4170 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
4171 RD->startDefinition();
4172 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
4173 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
4174 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
4175 }
4176 RD->completeDefinition();
4177 return RD;
4178}
4179
4180/// \brief Emit a proxy function which accepts kmp_task_t as the second
4181/// argument.
4182/// \code
4183/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
4184/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
4185/// For taskloops:
4186/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4187/// tt->reductions, tt->shareds);
4188/// return 0;
4189/// }
4190/// \endcode
4191static llvm::Value *
4192emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
4193 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4194 QualType KmpTaskTWithPrivatesPtrQTy,
4195 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
4196 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4197 llvm::Value *TaskPrivatesMap) {
4198 auto &C = CGM.getContext();
4199 FunctionArgList Args;
4200 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4201 ImplicitParamDecl::Other);
4202 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4203 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4204 ImplicitParamDecl::Other);
4205 Args.push_back(&GtidArg);
4206 Args.push_back(&TaskTypeArg);
4207 auto &TaskEntryFnInfo =
4208 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4209 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
4210 auto *TaskEntry =
4211 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
4212 ".omp_task_entry.", &CGM.getModule());
4213 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
4214 CodeGenFunction CGF(CGM);
4215 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4216 Loc, Loc);
4217
4218 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
4219 // tt,
4220 // For taskloops:
4221 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4222 // tt->task_data.shareds);
4223 auto *GtidParam = CGF.EmitLoadOfScalar(
4224 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
4225 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4226 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4227 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4228 auto *KmpTaskTWithPrivatesQTyRD =
4229 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4230 LValue Base =
4231 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4232 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4233 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4234 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4235 auto *PartidParam = PartIdLVal.getPointer();
4236
4237 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
4238 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4239 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4240 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
4241 CGF.ConvertTypeForMem(SharedsPtrTy));
4242
4243 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4244 llvm::Value *PrivatesParam;
4245 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
4246 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
4247 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4248 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
4249 } else
4250 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4251
4252 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4253 TaskPrivatesMap,
4254 CGF.Builder
4255 .CreatePointerBitCastOrAddrSpaceCast(
4256 TDBase.getAddress(), CGF.VoidPtrTy)
4257 .getPointer()};
4258 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4259 std::end(CommonArgs));
4260 if (isOpenMPTaskLoopDirective(Kind)) {
4261 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
4262 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4263 auto *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
4264 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4265 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4266 auto *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
4267 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4268 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
4269 auto *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
4270 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4271 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
4272 auto *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
4273 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4274 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
4275 auto *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
4276 CallArgs.push_back(LBParam);
4277 CallArgs.push_back(UBParam);
4278 CallArgs.push_back(StParam);
4279 CallArgs.push_back(LIParam);
4280 CallArgs.push_back(RParam);
4281 }
4282 CallArgs.push_back(SharedsParam);
4283
4284 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4285 CallArgs);
4286 CGF.EmitStoreThroughLValue(
4287 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4288 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
4289 CGF.FinishFunction();
4290 return TaskEntry;
4291}
4292
4293static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4294 SourceLocation Loc,
4295 QualType KmpInt32Ty,
4296 QualType KmpTaskTWithPrivatesPtrQTy,
4297 QualType KmpTaskTWithPrivatesQTy) {
4298 auto &C = CGM.getContext();
4299 FunctionArgList Args;
4300 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4301 ImplicitParamDecl::Other);
4302 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4303 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4304 ImplicitParamDecl::Other);
4305 Args.push_back(&GtidArg);
4306 Args.push_back(&TaskTypeArg);
4307 auto &DestructorFnInfo =
4308 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4309 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
4310 auto *DestructorFn =
4311 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4312 ".omp_task_destructor.", &CGM.getModule());
4313 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
4314 DestructorFnInfo);
4315 CodeGenFunction CGF(CGM);
4316 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
4317 Args, Loc, Loc);
4318
4319 LValue Base = CGF.EmitLoadOfPointerLValue(
4320 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4321 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4322 auto *KmpTaskTWithPrivatesQTyRD =
4323 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4324 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4325 Base = CGF.EmitLValueForField(Base, *FI);
4326 for (auto *Field :
4327 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4328 if (auto DtorKind = Field->getType().isDestructedType()) {
4329 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
4330 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4331 }
4332 }
4333 CGF.FinishFunction();
4334 return DestructorFn;
4335}
4336
4337/// \brief Emit a privates mapping function for correct handling of private and
4338/// firstprivate variables.
4339/// \code
4340/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4341/// **noalias priv1,..., <tyn> **noalias privn) {
4342/// *priv1 = &.privates.priv1;
4343/// ...;
4344/// *privn = &.privates.privn;
4345/// }
4346/// \endcode
4347static llvm::Value *
4348emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
4349 ArrayRef<const Expr *> PrivateVars,
4350 ArrayRef<const Expr *> FirstprivateVars,
4351 ArrayRef<const Expr *> LastprivateVars,
4352 QualType PrivatesQTy,
4353 ArrayRef<PrivateDataTy> Privates) {
4354 auto &C = CGM.getContext();
4355 FunctionArgList Args;
4356 ImplicitParamDecl TaskPrivatesArg(
4357 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4358 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4359 ImplicitParamDecl::Other);
4360 Args.push_back(&TaskPrivatesArg);
4361 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4362 unsigned Counter = 1;
4363 for (auto *E: PrivateVars) {
4364 Args.push_back(ImplicitParamDecl::Create(
4365 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4366 C.getPointerType(C.getPointerType(E->getType()))
4367 .withConst()
4368 .withRestrict(),
4369 ImplicitParamDecl::Other));
4370 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4371 PrivateVarsPos[VD] = Counter;
4372 ++Counter;
4373 }
4374 for (auto *E : FirstprivateVars) {
4375 Args.push_back(ImplicitParamDecl::Create(
4376 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4377 C.getPointerType(C.getPointerType(E->getType()))
4378 .withConst()
4379 .withRestrict(),
4380 ImplicitParamDecl::Other));
4381 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4382 PrivateVarsPos[VD] = Counter;
4383 ++Counter;
4384 }
4385 for (auto *E: LastprivateVars) {
4386 Args.push_back(ImplicitParamDecl::Create(
4387 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4388 C.getPointerType(C.getPointerType(E->getType()))
4389 .withConst()
4390 .withRestrict(),
4391 ImplicitParamDecl::Other));
4392 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4393 PrivateVarsPos[VD] = Counter;
4394 ++Counter;
4395 }
4396 auto &TaskPrivatesMapFnInfo =
4397 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4398 auto *TaskPrivatesMapTy =
4399 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4400 auto *TaskPrivatesMap = llvm::Function::Create(
4401 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4402 ".omp_task_privates_map.", &CGM.getModule());
4403 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
4404 TaskPrivatesMapFnInfo);
4405 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
4406 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
4407 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
4408 CodeGenFunction CGF(CGM);
4409 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4410 TaskPrivatesMapFnInfo, Args, Loc, Loc);
4411
4412 // *privi = &.privates.privi;
4413 LValue Base = CGF.EmitLoadOfPointerLValue(
4414 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4415 TaskPrivatesArg.getType()->castAs<PointerType>());
4416 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4417 Counter = 0;
4418 for (auto *Field : PrivatesQTyRD->fields()) {
4419 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4420 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4421 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4422 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4423 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
4424 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
4425 ++Counter;
4426 }
4427 CGF.FinishFunction();
4428 return TaskPrivatesMap;
4429}
4430
4431static bool stable_sort_comparator(const PrivateDataTy P1,
4432 const PrivateDataTy P2) {
4433 return P1.first > P2.first;
4434}
4435
4436/// Emit initialization for private variables in task-based directives.
4437static void emitPrivatesInit(CodeGenFunction &CGF,
4438 const OMPExecutableDirective &D,
4439 Address KmpTaskSharedsPtr, LValue TDBase,
4440 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4441 QualType SharedsTy, QualType SharedsPtrTy,
4442 const OMPTaskDataTy &Data,
4443 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4444 auto &C = CGF.getContext();
4445 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4446 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4447 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4448 ? OMPD_taskloop
4449 : OMPD_task;
4450 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4451 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
4452 LValue SrcBase;
4453 bool IsTargetTask =
4454 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4455 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4456 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4457 // PointersArray and SizesArray. The original variables for these arrays are
4458 // not captured and we get their addresses explicitly.
4459 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
4460 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
4461 SrcBase = CGF.MakeAddrLValue(
4462 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4463 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4464 SharedsTy);
4465 }
4466 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4467 for (auto &&Pair : Privates) {
4468 auto *VD = Pair.second.PrivateCopy;
4469 auto *Init = VD->getAnyInitializer();
4470 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4471 !CGF.isTrivialInitializer(Init)))) {
4472 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
4473 if (auto *Elem = Pair.second.PrivateElemInit) {
4474 auto *OriginalVD = Pair.second.Original;
4475 // Check if the variable is the target-based BasePointersArray,
4476 // PointersArray or SizesArray.
4477 LValue SharedRefLValue;
4478 QualType Type = OriginalVD->getType();
4479 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4480 if (IsTargetTask && !SharedField) {
4481 assert(isa<ImplicitParamDecl>(OriginalVD) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
4482 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
4483 cast<CapturedDecl>(OriginalVD->getDeclContext())(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
4484 ->getNumParams() == 0 &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
4485 isa<TranslationUnitDecl>((static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
4486 cast<CapturedDecl>(OriginalVD->getDeclContext())(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
4487 ->getDeclContext()) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
4488 "Expected artificial target data variable.")(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD
) && isa<CapturedDecl>(OriginalVD->getDeclContext
()) && cast<CapturedDecl>(OriginalVD->getDeclContext
()) ->getNumParams() == 0 && isa<TranslationUnitDecl
>( cast<CapturedDecl>(OriginalVD->getDeclContext(
)) ->getDeclContext()) && "Expected artificial target data variable."
) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4488, __extension__ __PRETTY_FUNCTION__))
;
4489 SharedRefLValue =
4490 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4491 } else {
4492 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4493 SharedRefLValue = CGF.MakeAddrLValue(
4494 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4495 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4496 SharedRefLValue.getTBAAInfo());
4497 }
4498 if (Type->isArrayType()) {
4499 // Initialize firstprivate array.
4500 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4501 // Perform simple memcpy.
4502 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
4503 } else {
4504 // Initialize firstprivate array using element-by-element
4505 // initialization.
4506 CGF.EmitOMPAggregateAssign(
4507 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4508 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4509 Address SrcElement) {
4510 // Clean up any temporaries needed by the initialization.
4511 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4512 InitScope.addPrivate(
4513 Elem, [SrcElement]() -> Address { return SrcElement; });
4514 (void)InitScope.Privatize();
4515 // Emit initialization for single element.
4516 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4517 CGF, &CapturesInfo);
4518 CGF.EmitAnyExprToMem(Init, DestElement,
4519 Init->getType().getQualifiers(),
4520 /*IsInitializer=*/false);
4521 });
4522 }
4523 } else {
4524 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4525 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4526 return SharedRefLValue.getAddress();
4527 });
4528 (void)InitScope.Privatize();
4529 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4530 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4531 /*capturedByInit=*/false);
4532 }
4533 } else
4534 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4535 }
4536 ++FI;
4537 }
4538}
4539
4540/// Check if duplication function is required for taskloops.
4541static bool checkInitIsRequired(CodeGenFunction &CGF,
4542 ArrayRef<PrivateDataTy> Privates) {
4543 bool InitRequired = false;
4544 for (auto &&Pair : Privates) {
4545 auto *VD = Pair.second.PrivateCopy;
4546 auto *Init = VD->getAnyInitializer();
4547 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4548 !CGF.isTrivialInitializer(Init));
4549 }
4550 return InitRequired;
4551}
4552
4553
4554/// Emit task_dup function (for initialization of
4555/// private/firstprivate/lastprivate vars and last_iter flag)
4556/// \code
4557/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4558/// lastpriv) {
4559/// // setup lastprivate flag
4560/// task_dst->last = lastpriv;
4561/// // could be constructor calls here...
4562/// }
4563/// \endcode
4564static llvm::Value *
4565emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4566 const OMPExecutableDirective &D,
4567 QualType KmpTaskTWithPrivatesPtrQTy,
4568 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4569 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4570 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4571 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4572 auto &C = CGM.getContext();
4573 FunctionArgList Args;
4574 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4575 KmpTaskTWithPrivatesPtrQTy,
4576 ImplicitParamDecl::Other);
4577 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4578 KmpTaskTWithPrivatesPtrQTy,
4579 ImplicitParamDecl::Other);
4580 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4581 ImplicitParamDecl::Other);
4582 Args.push_back(&DstArg);
4583 Args.push_back(&SrcArg);
4584 Args.push_back(&LastprivArg);
4585 auto &TaskDupFnInfo =
4586 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4587 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4588 auto *TaskDup =
4589 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4590 ".omp_task_dup.", &CGM.getModule());
4591 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
4592 CodeGenFunction CGF(CGM);
4593 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4594 Loc);
4595
4596 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4597 CGF.GetAddrOfLocalVar(&DstArg),
4598 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4599 // task_dst->liter = lastpriv;
4600 if (WithLastIter) {
4601 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4602 LValue Base = CGF.EmitLValueForField(
4603 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4604 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4605 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4606 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4607 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4608 }
4609
4610 // Emit initial values for private copies (if any).
4611 assert(!Privates.empty())(static_cast <bool> (!Privates.empty()) ? void (0) : __assert_fail
("!Privates.empty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4611, __extension__ __PRETTY_FUNCTION__))
;
4612 Address KmpTaskSharedsPtr = Address::invalid();
4613 if (!Data.FirstprivateVars.empty()) {
4614 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4615 CGF.GetAddrOfLocalVar(&SrcArg),
4616 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4617 LValue Base = CGF.EmitLValueForField(
4618 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4619 KmpTaskSharedsPtr = Address(
4620 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4621 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4622 KmpTaskTShareds)),
4623 Loc),
4624 CGF.getNaturalTypeAlignment(SharedsTy));
4625 }
4626 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4627 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
4628 CGF.FinishFunction();
4629 return TaskDup;
4630}
4631
4632/// Checks if destructor function is required to be generated.
4633/// \return true if cleanups are required, false otherwise.
4634static bool
4635checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4636 bool NeedsCleanup = false;
4637 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4638 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4639 for (auto *FD : PrivateRD->fields()) {
4640 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4641 if (NeedsCleanup)
4642 break;
4643 }
4644 return NeedsCleanup;
4645}
4646
4647CGOpenMPRuntime::TaskResultTy
4648CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4649 const OMPExecutableDirective &D,
4650 llvm::Value *TaskFunction, QualType SharedsTy,
4651 Address Shareds, const OMPTaskDataTy &Data) {
4652 auto &C = CGM.getContext();
4653 llvm::SmallVector<PrivateDataTy, 4> Privates;
4654 // Aggregate privates and sort them by the alignment.
4655 auto I = Data.PrivateCopies.begin();
4656 for (auto *E : Data.PrivateVars) {
4657 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4658 Privates.push_back(std::make_pair(
4659 C.getDeclAlign(VD),
4660 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4661 /*PrivateElemInit=*/nullptr)));
4662 ++I;
4663 }
4664 I = Data.FirstprivateCopies.begin();
4665 auto IElemInitRef = Data.FirstprivateInits.begin();
4666 for (auto *E : Data.FirstprivateVars) {
4667 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4668 Privates.push_back(std::make_pair(
4669 C.getDeclAlign(VD),
4670 PrivateHelpersTy(
4671 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4672 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
4673 ++I;
4674 ++IElemInitRef;
4675 }
4676 I = Data.LastprivateCopies.begin();
4677 for (auto *E : Data.LastprivateVars) {
4678 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4679 Privates.push_back(std::make_pair(
4680 C.getDeclAlign(VD),
4681 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4682 /*PrivateElemInit=*/nullptr)));
4683 ++I;
4684 }
4685 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
4686 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4687 // Build type kmp_routine_entry_t (if not built yet).
4688 emitKmpRoutineEntryT(KmpInt32Ty);
4689 // Build type kmp_task_t (if not built yet).
4690 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4691 if (SavedKmpTaskloopTQTy.isNull()) {
4692 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4693 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4694 }
4695 KmpTaskTQTy = SavedKmpTaskloopTQTy;
4696 } else {
4697 assert((D.getDirectiveKind() == OMPD_task ||(static_cast <bool> ((D.getDirectiveKind() == OMPD_task
|| isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
isOpenMPTargetDataManagementDirective(D.getDirectiveKind()))
&& "Expected taskloop, task or target directive") ? void
(0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4700, __extension__ __PRETTY_FUNCTION__))
4698 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||(static_cast <bool> ((D.getDirectiveKind() == OMPD_task
|| isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
isOpenMPTargetDataManagementDirective(D.getDirectiveKind()))
&& "Expected taskloop, task or target directive") ? void
(0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4700, __extension__ __PRETTY_FUNCTION__))
4699 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&(static_cast <bool> ((D.getDirectiveKind() == OMPD_task
|| isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
isOpenMPTargetDataManagementDirective(D.getDirectiveKind()))
&& "Expected taskloop, task or target directive") ? void
(0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4700, __extension__ __PRETTY_FUNCTION__))
4700 "Expected taskloop, task or target directive")(static_cast <bool> ((D.getDirectiveKind() == OMPD_task
|| isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
isOpenMPTargetDataManagementDirective(D.getDirectiveKind()))
&& "Expected taskloop, task or target directive") ? void
(0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4700, __extension__ __PRETTY_FUNCTION__))
;
4701 if (SavedKmpTaskTQTy.isNull()) {
4702 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4703 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4704 }
4705 KmpTaskTQTy = SavedKmpTaskTQTy;
4706 }
4707 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4708 // Build particular struct kmp_task_t for the given task.
4709 auto *KmpTaskTWithPrivatesQTyRD =
4710 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4711 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4712 QualType KmpTaskTWithPrivatesPtrQTy =
4713 C.getPointerType(KmpTaskTWithPrivatesQTy);
4714 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4715 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
4716 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
4717 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4718
4719 // Emit initial values for private copies (if any).
4720 llvm::Value *TaskPrivatesMap = nullptr;
4721 auto *TaskPrivatesMapTy =
4722 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
4723 if (!Privates.empty()) {
4724 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4725 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4726 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4727 FI->getType(), Privates);
4728 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4729 TaskPrivatesMap, TaskPrivatesMapTy);
4730 } else {
4731 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4732 cast<llvm::PointerType>(TaskPrivatesMapTy));
4733 }
4734 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4735 // kmp_task_t *tt);
4736 auto *TaskEntry = emitProxyTaskFunction(
4737 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4738 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4739 TaskPrivatesMap);
4740
4741 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4742 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4743 // kmp_routine_entry_t *task_entry);
4744 // Task flags. Format is taken from
4745 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4746 // description of kmp_tasking_flags struct.
4747 enum {
4748 TiedFlag = 0x1,
4749 FinalFlag = 0x2,
4750 DestructorsFlag = 0x8,
4751 PriorityFlag = 0x20
4752 };
4753 unsigned Flags = Data.Tied ? TiedFlag : 0;
4754 bool NeedsCleanup = false;
4755 if (!Privates.empty()) {
4756 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4757 if (NeedsCleanup)
4758 Flags = Flags | DestructorsFlag;
4759 }
4760 if (Data.Priority.getInt())
4761 Flags = Flags | PriorityFlag;
4762 auto *TaskFlags =
4763 Data.Final.getPointer()
4764 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
4765 CGF.Builder.getInt32(FinalFlag),
4766 CGF.Builder.getInt32(/*C=*/0))
4767 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
4768 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
4769 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
4770 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4771 getThreadID(CGF, Loc), TaskFlags,
4772 KmpTaskTWithPrivatesTySize, SharedsSize,
4773 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4774 TaskEntry, KmpRoutineEntryPtrTy)};
4775 auto *NewTask = CGF.EmitRuntimeCall(
4776 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
4777 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4778 NewTask, KmpTaskTWithPrivatesPtrTy);
4779 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4780 KmpTaskTWithPrivatesQTy);
4781 LValue TDBase =
4782 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
4783 // Fill the data in the resulting kmp_task_t record.
4784 // Copy shareds if there are any.
4785 Address KmpTaskSharedsPtr = Address::invalid();
4786 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
4787 KmpTaskSharedsPtr =
4788 Address(CGF.EmitLoadOfScalar(
4789 CGF.EmitLValueForField(
4790 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4791 KmpTaskTShareds)),
4792 Loc),
4793 CGF.getNaturalTypeAlignment(SharedsTy));
4794 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4795 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
4796 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
4797 }
4798 // Emit initial values for private copies (if any).
4799 TaskResultTy Result;
4800 if (!Privates.empty()) {
4801 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4802 SharedsTy, SharedsPtrTy, Data, Privates,
4803 /*ForDup=*/false);
4804 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4805 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4806 Result.TaskDupFn = emitTaskDupFunction(
4807 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4808 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4809 /*WithLastIter=*/!Data.LastprivateVars.empty());
4810 }
4811 }
4812 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4813 enum { Priority = 0, Destructors = 1 };
4814 // Provide pointer to function with destructors for privates.
4815 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4816 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4817 if (NeedsCleanup) {
4818 llvm::Value *DestructorFn = emitDestructorsFunction(
4819 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4820 KmpTaskTWithPrivatesQTy);
4821 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4822 LValue DestructorsLV = CGF.EmitLValueForField(
4823 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4824 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4825 DestructorFn, KmpRoutineEntryPtrTy),
4826 DestructorsLV);
4827 }
4828 // Set priority.
4829 if (Data.Priority.getInt()) {
4830 LValue Data2LV = CGF.EmitLValueForField(
4831 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4832 LValue PriorityLV = CGF.EmitLValueForField(
4833 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4834 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4835 }
4836 Result.NewTask = NewTask;
4837 Result.TaskEntry = TaskEntry;
4838 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4839 Result.TDBase = TDBase;
4840 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4841 return Result;
4842}
4843
4844void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4845 const OMPExecutableDirective &D,
4846 llvm::Value *TaskFunction,
4847 QualType SharedsTy, Address Shareds,
4848 const Expr *IfCond,
4849 const OMPTaskDataTy &Data) {
4850 if (!CGF.HaveInsertPoint())
4851 return;
4852
4853 TaskResultTy Result =
4854 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4855 llvm::Value *NewTask = Result.NewTask;
4856 llvm::Value *TaskEntry = Result.TaskEntry;
4857 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4858 LValue TDBase = Result.TDBase;
4859 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4860 auto &C = CGM.getContext();
4861 // Process list of dependences.
4862 Address DependenciesArray = Address::invalid();
4863 unsigned NumDependencies = Data.Dependences.size();
4864 if (NumDependencies) {
4865 // Dependence kind for RTL.
4866 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
4867 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4868 RecordDecl *KmpDependInfoRD;
4869 QualType FlagsTy =
4870 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
4871 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4872 if (KmpDependInfoTy.isNull()) {
4873 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4874 KmpDependInfoRD->startDefinition();
4875 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4876 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4877 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4878 KmpDependInfoRD->completeDefinition();
4879 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
4880 } else
4881 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4882 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
4883 // Define type kmp_depend_info[<Dependences.size()>];
4884 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
4885 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
4886 ArrayType::Normal, /*IndexTypeQuals=*/0);
4887 // kmp_depend_info[<Dependences.size()>] deps;
4888 DependenciesArray =
4889 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
4890 for (unsigned i = 0; i < NumDependencies; ++i) {
4891 const Expr *E = Data.Dependences[i].second;
4892 auto Addr = CGF.EmitLValue(E);
4893 llvm::Value *Size;
4894 QualType Ty = E->getType();
4895 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4896 LValue UpAddrLVal =
4897 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4898 llvm::Value *UpAddr =
4899 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
4900 llvm::Value *LowIntPtr =
4901 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
4902 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4903 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
4904 } else
4905 Size = CGF.getTypeSize(Ty);
4906 auto Base = CGF.MakeAddrLValue(
4907 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
4908 KmpDependInfoTy);
4909 // deps[i].base_addr = &<Dependences[i].second>;
4910 auto BaseAddrLVal = CGF.EmitLValueForField(
4911 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
4912 CGF.EmitStoreOfScalar(
4913 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4914 BaseAddrLVal);
4915 // deps[i].len = sizeof(<Dependences[i].second>);
4916 auto LenLVal = CGF.EmitLValueForField(
4917 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4918 CGF.EmitStoreOfScalar(Size, LenLVal);
4919 // deps[i].flags = <Dependences[i].first>;
4920 RTLDependenceKindTy DepKind;
4921 switch (Data.Dependences[i].first) {
4922 case OMPC_DEPEND_in:
4923 DepKind = DepIn;
4924 break;
4925 // Out and InOut dependencies must use the same code.
4926 case OMPC_DEPEND_out:
4927 case OMPC_DEPEND_inout:
4928 DepKind = DepInOut;
4929 break;
4930 case OMPC_DEPEND_source:
4931 case OMPC_DEPEND_sink:
4932 case OMPC_DEPEND_unknown:
4933 llvm_unreachable("Unknown task dependence type")::llvm::llvm_unreachable_internal("Unknown task dependence type"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp"
, 4933)
;
4934 }
4935 auto FlagsLVal = CGF.EmitLValueForField(
4936 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4937 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4938 FlagsLVal);
4939 }
4940 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4941 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
4942 CGF.VoidPtrTy);
4943 }
4944
4945 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
4946 // libcall.
4947 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4948 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4949 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4950 // list is not empty
4951 auto *ThreadID = getThreadID(CGF, Loc);
4952 auto *UpLoc = emitUpdateLocation(CGF, Loc);
4953 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4954 llvm::Value *DepTaskArgs[7];
4955 if (NumDependencies) {
4956 DepTaskArgs[0] = UpLoc;
4957 DepTaskArgs[1] = ThreadID;
4958 DepTaskArgs[2] = NewTask;
4959 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4960 DepTaskArgs[4] = DependenciesArray.getPointer();
4961 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4962 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4963 }
4964 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4965 &TaskArgs,
4966 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
4967 if (!Data.Tied) {
4968 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4969 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4970 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4971 }
4972 if (NumDependencies) {
4973 CGF.EmitRuntimeCall(
4974 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
4975 } else {
4976 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
4977 TaskArgs);
4978 }
4979 // Check if parent region is untied and build return for untied task;
4980 if (auto *Region =
4981 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4982 Region->emitUntiedSwitch(CGF);
4983 };
4984
4985 llvm::Value *DepWaitTaskArgs[6];
4986 if (NumDependencies) {
4987 DepWaitTaskArgs[0] = UpLoc;
4988 DepWaitTaskArgs[1] = ThreadID;
4989 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4990 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4991 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4992 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4993 }
4994 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4995 NumDependencies, &DepWaitTaskArgs,
4996 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
4997 auto &RT = CGF.CGM.getOpenMPRuntime();
4998 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4999 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5000 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5001 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5002 // is specified.
5003 if (NumDependencies)
5004 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
5005 DepWaitTaskArgs);
5006 // Call proxy_task_entry(gtid, new_task);
5007 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5008 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
5009 Action.Enter(CGF);
5010 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
5011 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
5012 OutlinedFnArgs);
5013 };
5014
5015 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5016 // kmp_task_t *new_task);
5017 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5018 // kmp_task_t *new_task);
5019 RegionCodeGenTy RCG(CodeGen);
5020 CommonActionTy Action(
5021 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5022 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5023 RCG.setAction(Action);
5024 RCG(CGF);
5025 };
5026
5027 if (IfCond)
5028 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
5029 else {
5030 RegionCodeGenTy ThenRCG(ThenCodeGen);
5031 ThenRCG(CGF);
5032 }
5033}
5034
5035void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5036 const OMPLoopDirective &D,
5037 llvm::Value *TaskFunction,
5038 QualType SharedsTy, Address Shareds,
5039 const Expr *IfCond,
5040 const OMPTaskDataTy &Data) {
5041 if (!CGF.HaveInsertPoint())
5042 return;
5043 TaskResultTy Result =
5044 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5045 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
5046 // libcall.
5047 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5048 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5049 // sched, kmp_uint64 grainsize, void *task_dup);
5050 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5051 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5052 llvm::Value *IfVal;
5053 if (IfCond) {
5054 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5055 /*isSigned=*/true);
5056 } else
5057 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
5058
5059 LValue LBLVal = CGF.EmitLValueForField(
5060 Result.TDBase,
5061 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
5062 auto *LBVar =
5063 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5064 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5065 /*IsInitializer=*/true);
5066 LValue UBLVal = CGF.EmitLValueForField(
5067 Result.TDBase,
5068 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
5069 auto *UBVar =
5070 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5071 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5072 /*IsInitializer=*/true);
5073 LValue StLVal = CGF.EmitLValueForField(
5074 Result.TDBase,
5075 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
5076 auto *StVar =
5077 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5078 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5079 /*IsInitializer=*/true);
5080 // Store reductions address.
5081 LValue RedLVal = CGF.EmitLValueForField(
5082 Result.TDBase,
5083 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
5084 if (Data.Reductions)
5085 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
5086 else {
5087 CGF.EmitNullInitialization(RedLVal.getAddress(),
5088 CGF.getContext().VoidPtrTy);
5089 }
5090 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
5091 llvm::Value *TaskArgs[] = {
5092 UpLoc,
5093 ThreadID,
5094 Result.NewTask,
5095 IfVal,
5096 LBLVal.getPointer(),
5097 UBLVal.getPointer(),
5098 CGF.EmitLoadOfScalar(StLVal, Loc),
5099 llvm::ConstantInt::getNullValue(
5100 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
5101 llvm::ConstantInt::getSigned(
5102 CGF.IntTy, Data.Schedule.getPointer()
5103 ? Data.Schedule.getInt() ? NumTasks : Grainsize
5104 : NoSchedule),
5105 Data.Schedule.getPointer()
5106 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
5107 /*isSigned=*/false)
5108 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
5109 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5110 Result.TaskDupFn, CGF.VoidPtrTy)
5111 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
5112 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5113}
5114
5115/// \brief Emit reduction operation for each element of array (required for
5116/// array sections) LHS op = RHS.
5117/// \param Type Type of array.
5118/// \param LHSVar Variable on the left side of the reduction operation
5119/// (references element of array in original variable).
5120/// \param RHSVar Variable on the right side of the reduction operation
5121/// (references element of array in original variable).
5122/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5123/// RHSVar.
5124static void EmitOMPAggregateReduction(
5125 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5126 const VarDecl *RHSVar,
5127 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5128 const Expr *, const Expr *)> &RedOpGen,
5129 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5130 const Expr *UpExpr = nullptr) {
5131 // Perform element-by-element initialization.
5132 QualType ElementTy;
5133 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5134 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5135
5136 // Drill down to the base element type on both arrays.
5137 auto ArrayTy = Type->getAsArrayTypeUnsafe();
5138 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
5139
5140 auto RHSBegin = RHSAddr.getPointer();
5141 auto LHSBegin = LHSAddr.getPointer();
5142 // Cast from pointer to array type to pointer to single element.
5143 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
5144 // The basic structure here is a while-do loop.
5145 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5146 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5147 auto IsEmpty =
5148 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5149 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5150
5151 // Enter the loop body, making that address the current address.
5152 auto EntryBB = CGF.Builder.GetInsertBlock();
5153 CGF.EmitBlock(BodyBB);
5154
5155 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5156
5157 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5158 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5159 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5160 Address RHSElementCurrent =
5161 Address(RHSElementPHI,
5162 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5163
5164 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5165 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5166 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5167 Address LHSElementCurrent =
5168 Address(LHSElementPHI,
5169 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5170
5171 // Emit copy.
5172 CodeGenFunction::OMPPrivateScope Scope(CGF);
5173 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
5174 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
5175 Scope.Privatize();
5176 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5177 Scope.ForceCleanup();
5178
5179 // Shift the address forward by one element.
5180 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
5181 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
5182 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
5183 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5184 // Check whether we've reached the end.
5185 auto Done =
5186 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5187 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5188 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5189 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5190
5191 // Done.
5192 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5193}
5194
5195/// Emit reduction combiner. If the combiner is a simple expression emit it as
5196/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5197/// UDR combiner function.
5198static void emitReductionCombiner(CodeGenFunction &CGF,
5199 const Expr *ReductionOp) {
5200 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
5201 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5202 if (auto *DRE =
5203 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
5204 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
5205 std::pair<llvm::Function *, llvm::Function *> Reduction =
5206 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5207 RValue Func = RValue::get(Reduction.first);
5208 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5209 CGF.EmitIgnoredExpr(ReductionOp);
5210 return;
5211 }
5212 CGF.EmitIgnoredExpr(ReductionOp);
5213}
5214
5215llvm::Value *CGOpenMPRuntime::emitReductionFunction(
5216 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5217 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5218 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
5219 auto &C = CGM.getContext();
5220
5221 // void reduction_func(void *LHSArg, void *RHSArg);
5222 FunctionArgList Args;
5223 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5224 ImplicitParamDecl::Other);
5225 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5226 ImplicitParamDecl::Other);
5227 Args.push_back(&LHSArg);
5228 Args.push_back(&RHSArg);
5229 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5230 auto *Fn = llvm::Function::Create(
5231 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
5232 ".omp.reduction.reduction_func", &CGM.getModule());
5233 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
5234 CodeGenFunction CGF(CGM);
5235 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
5236
5237 // Dst = (void*[n])(LHSArg);
5238 // Src = (void*[n])(RHSArg);
5239 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5240 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5241 ArgsType), CGF.getPointerAlign());
5242 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5243 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5244 ArgsType), CGF.getPointerAlign());
5245
5246 // ...
5247 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5248 // ...
5249 CodeGenFunction::OMPPrivateScope Scope(CGF);
5250 auto IPriv = Privates.begin();
5251 unsigned Idx = 0;
5252 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
5253 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5254 Scope.addPrivate(RHSVar, [&]() -> Address {
5255 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
5256 });
5257 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5258 Scope.addPrivate(LHSVar, [&]() -> Address {
5259 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
5260 });
5261 QualType PrivTy = (*IPriv)->getType();
5262 if (PrivTy->isVariablyModifiedType()) {
5263 // Get array size and emit VLA type.
5264 ++Idx;
5265 Address Elem =
5266 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5267 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
5268 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
5269 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
5270 CodeGenFunction::OpaqueValueMapping OpaqueMap(
5271 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
5272 CGF.EmitVariablyModifiedType(PrivTy);
5273 }
5274 }
5275 Scope.Privatize();
5276 IPriv = Privates.begin();
5277 auto ILHS = LHSExprs.begin();
5278 auto IRHS = RHSExprs.begin();
5279 for (auto *E : ReductionOps) {
5280 if ((*IPriv)->getType()->isArrayType()) {
5281 // Emit reduction for array section.
5282 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5283 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5284 EmitOMPAggregateReduction(
5285 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5286 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5287 emitReductionCombiner(CGF, E);
5288 });
5289 } else
5290 // Emit reduction for array subscript or single variable.
5291 emitReductionCombiner(CGF, E);
5292 ++IPriv;
5293 ++ILHS;
5294 ++IRHS;
5295 }
5296 Scope.ForceCleanup();
5297 CGF.FinishFunction();
5298 return Fn;
5299}
5300
5301void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5302 const Expr *ReductionOp,
5303 const Expr *PrivateRef,
5304 const DeclRefExpr *LHS,
5305 const DeclRefExpr *RHS) {
5306 if (PrivateRef->getType()->isArrayType()) {
5307 // Emit reduction for array section.
5308 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5309 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5310 EmitOMPAggregateReduction(
5311 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5312 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5313 emitReductionCombiner(CGF, ReductionOp);
5314 });
5315 } else
5316 // Emit reduction for array subscript or single variable.
5317 emitReductionCombiner(CGF, ReductionOp);
5318}
5319
5320void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
5321 ArrayRef<const Expr *> Privates,
5322 ArrayRef<const Expr *> LHSExprs,
5323 ArrayRef<const Expr *> RHSExprs,
5324 ArrayRef<const Expr *> ReductionOps,
5325 ReductionOptionsTy Options) {
5326 if (!CGF.HaveInsertPoint())
5327 return;
5328
5329 bool WithNowait = Options.WithNowait;
5330 bool SimpleReduction = Options.SimpleReduction;
5331
5332 // Next code should be emitted for reduction:
5333 //
5334 // static kmp_critical_name lock = { 0 };
5335 //
5336 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5337 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5338 // ...
5339 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5340 // *(Type<n>-1*)rhs[<n>-1]);
5341 // }
5342 //
5343 // ...
5344 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5345 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5346 // RedList, reduce_func, &<lock>)) {
5347 // case 1:
5348 // ...
5349 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5350 // ...
5351 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5352 // break;
5353 // case 2:
5354 // ...
5355 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5356 // ...
5357 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
5358 // break;
5359 // default:;
5360 // }
5361 //
5362 // if SimpleReduction is true, only the next code is generated:
5363 // ...
5364 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5365 // ...
5366
5367 auto &C = CGM.getContext();
5368
5369 if (SimpleReduction) {
5370 CodeGenFunction::RunCleanupsScope Scope(CGF);
5371 auto IPriv = Privates.begin();
5372 auto ILHS = LHSExprs.begin();
5373 auto IRHS = RHSExprs.begin();
5374 for (auto *E : ReductionOps) {
5375 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5376 cast<DeclRefExpr>(*IRHS));
5377 ++IPriv;
5378 ++ILHS;
5379 ++IRHS;
5380 }
5381 return;
5382 }
5383
5384 // 1. Build a list of reduction variables.
5385 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
5386 auto Size = RHSExprs.size();
5387 for (auto *E : Privates) {
5388 if (E->getType()->isVariablyModifiedType())
5389 // Reserve place for array size.
5390 ++Size;
5391 }
5392 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
5393 QualType ReductionArrayTy =
5394 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5395 /*IndexTypeQuals=*/0);
5396 Address ReductionList =
5397 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
5398 auto IPriv = Privates.begin();
5399 unsigned Idx = 0;
5400 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
5401 Address Elem =
5402 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
5403 CGF.Builder.CreateStore(
5404 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5405 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5406 Elem);
5407 if ((*IPriv)->getType()->isVariablyModifiedType()) {
5408 // Store array size.
5409 ++Idx;
5410 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5411 CGF.getPointerSize());
5412 llvm::Value *Size = CGF.Builder.CreateIntCast(
5413 CGF.getVLASize(
5414 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5415 .NumElts,
5416 CGF.SizeTy, /*isSigned=*/false);
5417 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5418 Elem);
5419 }
5420 }
5421
5422 // 2. Emit reduce_func().
5423 auto *ReductionFn = emitReductionFunction(
5424 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5425 Privates, LHSExprs, RHSExprs, ReductionOps);
5426
5427 // 3. Create static kmp_critical_name lock = { 0 };
5428 auto *Lock = getCriticalRegionLock(".reduction");
5429
5430 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5431 // RedList, reduce_func, &<lock>);
5432 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5433 auto *ThreadId = getThreadID(CGF, Loc);
5434 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5435 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5436 ReductionList.getPointer(), CGF.VoidPtrTy);
5437 llvm::Value *Args[] = {
5438 IdentTLoc, // ident_t *<loc>
5439 ThreadId, // i32 <gtid>
5440 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5441 ReductionArrayTySize, // size_type sizeof(RedList)
5442 RL, // void *RedList
5443 ReductionFn, // void (*) (void *, void *) <reduce_func>
5444 Lock // kmp_critical_name *&<lock>
5445 };
5446 auto Res = CGF.EmitRuntimeCall(
5447 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5448 : OMPRTL__kmpc_reduce),
5449 Args);
5450
5451 // 5. Build switch(res)
5452 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5453 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5454
5455 // 6. Build case 1:
5456 // ...
5457 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5458 // ...
5459 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5460 // break;
5461 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5462 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5463 CGF.EmitBlock(Case1BB);
5464
5465 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5466 llvm::Value *EndArgs[] = {
5467 IdentTLoc, // ident_t *<loc>
5468 ThreadId, // i32 <gtid>
5469 Lock // kmp_critical_name *&<lock>
5470 };
5471 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5472 CodeGenFunction &CGF, PrePostActionTy &Action) {
5473 auto &RT = CGF.CGM.getOpenMPRuntime();
5474 auto IPriv = Privates.begin();
5475 auto ILHS = LHSExprs.begin();
5476 auto IRHS = RHSExprs.begin();
5477 for (auto *E : ReductionOps) {
5478 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5479 cast<DeclRefExpr>(*IRHS));
5480 ++IPriv;
5481 ++ILHS;
5482 ++IRHS;
5483 }
5484 };
5485 RegionCodeGenTy RCG(CodeGen);
5486 CommonActionTy Action(
5487 nullptr, llvm::None,
5488 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5489 : OMPRTL__kmpc_end_reduce),
5490 EndArgs);
5491 RCG.setAction(Action);
5492 RCG(CGF);
5493
5494 CGF.EmitBranch(DefaultBB);
5495
5496 // 7. Build case 2:
5497 // ...
5498 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5499 // ...
5500 // break;
5501 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5502 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5503 CGF.EmitBlock(Case2BB);
5504
5505 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5506 CodeGenFunction &CGF, PrePostActionTy &Action) {
5507 auto ILHS = LHSExprs.begin();
5508 auto IRHS = RHSExprs.begin();
5509 auto IPriv = Privates.begin();
5510 for (auto *E : ReductionOps) {
5511 const Expr *XExpr = nullptr;
5512 const Expr *EExpr = nullptr;
5513 const Expr *UpExpr = nullptr;
5514 BinaryOperatorKind BO = BO_Comma;
5515 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5516 if (BO->getOpcode() == BO_Assign) {
5517 XExpr = BO->getLHS();
5518 UpExpr = BO->getRHS();
5519 }
5520 }
5521 // Try to emit update expression as a simple atomic.
5522 auto *RHSExpr = UpExpr;
5523 if (RHSExpr) {
5524 // Analyze RHS part of the whole expression.
5525 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5526 RHSExpr->IgnoreParenImpCasts())) {
5527 // If this is a conditional operator, analyze its condition for
5528 // min/max reduction operator.
5529 RHSExpr = ACO->getCond();
5530 }
5531 if (auto *BORHS =
5532 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5533 EExpr = BORHS->getRHS();
5534 BO = BORHS->getOpcode();
5535 }
5536 }
5537 if (XExpr) {
5538 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5539 auto &&AtomicRedGen = [BO, VD,
5540 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5541 const Expr *EExpr, const Expr *UpExpr) {
5542 LValue X = CGF.EmitLValue(XExpr);
5543 RValue E;
5544 if (EExpr)
5545 E = CGF.EmitAnyExpr(EExpr);
5546 CGF.EmitOMPAtomicSimpleUpdateExpr(
5547 X, E, BO, /*IsXLHSInRHSPart=*/true,
5548 llvm::AtomicOrdering::Monotonic, Loc,
5549 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
5550 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5551 PrivateScope.addPrivate(
5552 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5553 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5554 CGF.emitOMPSimpleStore(
5555 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5556 VD->getType().getNonReferenceType(), Loc);
5557 return LHSTemp;
5558 });
5559 (void)PrivateScope.Privatize();
5560 return CGF.EmitAnyExpr(UpExpr);
5561 });
5562 };
5563 if ((*IPriv)->getType()->isArrayType()) {
5564 // Emit atomic reduction for array section.
5565 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5566 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5567 AtomicRedGen, XExpr, EExpr, UpExpr);
5568 } else
5569 // Emit atomic reduction for array subscript or single variable.
5570 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5571 } else {
5572 // Emit as a critical region.
5573 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5574 const Expr *, const Expr *) {
5575 auto &RT = CGF.CGM.getOpenMPRuntime();
5576 RT.emitCriticalRegion(
5577 CGF, ".atomic_reduction",
5578 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5579 Action.Enter(CGF);
5580 emitReductionCombiner(CGF, E);
5581 },
5582 Loc);
5583 };
5584 if ((*IPriv)->getType()->isArrayType()) {
5585 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5586 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5587 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5588 CritRedGen);
5589 } else
5590 CritRedGen(CGF, nullptr, nullptr, nullptr);
5591 }
5592 ++ILHS;
5593 ++IRHS;
5594 ++IPriv;
5595 }
5596 };
5597 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5598 if (!WithNowait) {
5599 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5600 llvm::Value *EndArgs[] = {
5601 IdentTLoc, // ident_t *<loc>
5602 ThreadId, // i32 <gtid>
5603 Lock // kmp_critical_name *&<lock>
5604 };
5605 CommonActionTy Action(nullptr, llvm::None,
5606 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5607 EndArgs);
5608 AtomicRCG.setAction(Action);
5609 AtomicRCG(CGF);
5610 } else
5611 AtomicRCG(CGF);
5612
5613 CGF.EmitBranch(DefaultBB);
5614 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5615}
5616
5617/// Generates unique name for artificial threadprivate variables.
5618/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5619static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5620 const Expr *Ref) {
5621 SmallString<256> Buffer;
5622 llvm::raw_svector_ostream Out(Buffer);
5623 const clang::DeclRefExpr *DE;
5624 const VarDecl *D = ::getBaseDecl(Ref, DE);
5625 if (!D)
5626 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5627 D = D->getCanonicalDecl();
5628 Out << Prefix << "."
5629 << (D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D))
5630 << "_" << D->getCanonicalDecl()->getLocStart().getRawEncoding();
5631 return Out.str();
5632}
5633
5634/// Emits reduction initializer function:
5635/// \code
5636/// void @.red_init(void* %arg) {
5637/// %0 = bitcast void* %arg to <type>*
5638/// store <type> <init>, <type>* %0
5639/// ret void
5640/// }
5641/// \endcode
5642static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5643 SourceLocation Loc,
5644 ReductionCodeGen &RCG, unsigned N) {
5645 auto &C = CGM.getContext();
5646 FunctionArgList Args;
5647 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5648 ImplicitParamDecl::Other);
5649 Args.emplace_back(&Param);
5650 auto &FnInfo =
5651 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5652 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5653 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5654 ".red_init.", &CGM.getModule());
5655 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5656 CodeGenFunction CGF(CGM);
5657 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5658 Address PrivateAddr = CGF.EmitLoadOfPointer(
5659 CGF.GetAddrOfLocalVar(&Param),
5660 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5661 llvm::Value *Size = nullptr;
5662 // If the size of the reduction item is non-constant, load it from global
5663 // threadprivate variable.
5664 if (RCG.getSizes(N).second) {
5665 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5666 CGF, CGM.getContext().getSizeType(),
5667 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5668 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5669 CGM.getContext().getSizeType(), Loc);
5670 }
5671 RCG.emitAggregateType(CGF, N, Size);
5672 LValue SharedLVal;
5673 // If initializer uses initializer from declare reduction construct, emit a
5674 // pointer to the address of the original reduction item (reuired by reduction
5675 // initializer)
5676 if (RCG.usesReductionInitializer(N)) {
5677 Address SharedAddr =
5678 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5679 CGF, CGM.getContext().VoidPtrTy,
5680 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
5681 SharedAddr = CGF.EmitLoadOfPointer(
5682 SharedAddr,
5683 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
5684 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5685 } else {
5686 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5687 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5688 CGM.getContext().VoidPtrTy);
5689 }
5690 // Emit the initializer:
5691 // %0 = bitcast void* %arg to <type>*
5692 // store <type> <init>, <type>* %0
5693 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5694 [](CodeGenFunction &) { return false; });
5695 CGF.FinishFunction();
5696 return Fn;
5697}
5698
5699/// Emits reduction combiner function:
5700/// \code
5701/// void @.red_comb(void* %arg0, void* %arg1) {
5702/// %lhs = bitcast void* %arg0 to <type>*
5703/// %rhs = bitcast void* %arg1 to <type>*
5704/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5705/// store <type> %2, <type>* %lhs
5706/// ret void
5707/// }
5708/// \endcode
5709static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5710 SourceLocation Loc,
5711 ReductionCodeGen &RCG, unsigned N,
5712 const Expr *ReductionOp,
5713 const Expr *LHS, const Expr *RHS,
5714 const Expr *PrivateRef) {
5715 auto &C = CGM.getContext();
5716 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5717 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5718 FunctionArgList Args;
5719 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5720 C.VoidPtrTy, ImplicitParamDecl::Other);
5721 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5722 ImplicitParamDecl::Other);
5723 Args.emplace_back(&ParamInOut);
5724 Args.emplace_back(&ParamIn);
5725 auto &FnInfo =
5726 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5727 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5728 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5729 ".red_comb.", &CGM.getModule());
5730 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5731 CodeGenFunction CGF(CGM);
5732 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5733 llvm::Value *Size = nullptr;
5734 // If the size of the reduction item is non-constant, load it from global
5735 // threadprivate variable.
5736 if (RCG.getSizes(N).second) {
5737 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5738 CGF, CGM.getContext().getSizeType(),
5739 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5740 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5741 CGM.getContext().getSizeType(), Loc);
5742 }
5743 RCG.emitAggregateType(CGF, N, Size);
5744 // Remap lhs and rhs variables to the addresses of the function arguments.
5745 // %lhs = bitcast void* %arg0 to <type>*
5746 // %rhs = bitcast void* %arg1 to <type>*
5747 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5748 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5749 // Pull out the pointer to the variable.
5750 Address PtrAddr = CGF.EmitLoadOfPointer(
5751 CGF.GetAddrOfLocalVar(&ParamInOut),
5752 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5753 return CGF.Builder.CreateElementBitCast(
5754 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5755 });
5756 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5757 // Pull out the pointer to the variable.
5758 Address PtrAddr = CGF.EmitLoadOfPointer(
5759 CGF.GetAddrOfLocalVar(&ParamIn),
5760 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5761 return CGF.Builder.CreateElementBitCast(
5762 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5763 });
5764 PrivateScope.Privatize();
5765 // Emit the combiner body:
5766 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5767 // store <type> %2, <type>* %lhs
5768 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5769 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5770 cast<DeclRefExpr>(RHS));