Bug Summary

File:tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp
Warning:line 7614, column 15
Called C++ object pointer is null

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-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-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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-8~svn345461/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-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp -faddrsig

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