blob: 0433115fc12f2ad22886f40995699bed6dfa7316 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- 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
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "llvm/ADT/ArrayRef.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000021#include "llvm/Bitcode/ReaderWriter.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000026#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000028#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000029
30using namespace clang;
31using namespace CodeGen;
32
Benjamin Kramerc52193f2014-10-10 13:57:57 +000033namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000035class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000037 /// \brief Kinds of OpenMP regions used in codegen.
38 enum CGOpenMPRegionKind {
39 /// \brief Region with outlined function for standalone 'parallel'
40 /// directive.
41 ParallelOutlinedRegion,
42 /// \brief Region with outlined function for standalone 'task' directive.
43 TaskOutlinedRegion,
44 /// \brief Region for constructs that do not require function outlining,
45 /// like 'for', 'sections', 'atomic' etc. directives.
46 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000047 /// \brief Region with outlined function for standalone 'target' directive.
48 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 };
Alexey Bataev18095712014-10-10 12:19:54 +000050
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 CGOpenMPRegionInfo(const CapturedStmt &CS,
52 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000055 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057
58 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000061 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000063
64 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000065 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000069 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000071 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000072 /// \return LValue for thread id variable. This LValue always has type int32*.
73 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000074
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000076
Alexey Bataev81c7ea02015-07-03 09:56:58 +000077 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
78
Alexey Bataev25e5b442015-09-15 12:52:43 +000079 bool hasCancel() const { return HasCancel; }
80
Alexey Bataev18095712014-10-10 12:19:54 +000081 static bool classof(const CGCapturedStmtInfo *Info) {
82 return Info->getKind() == CR_OpenMP;
83 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000084
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000085protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000086 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000087 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000088 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000089 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090};
Alexey Bataev18095712014-10-10 12:19:54 +000091
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092/// \brief API for captured statement code generation in OpenMP constructs.
93class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
94public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000096 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +000097 OpenMPDirectiveKind Kind, bool HasCancel)
98 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
99 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
102 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000103
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000104 /// \brief Get a variable or parameter for storing global thread id
105 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000106 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000107
Alexey Bataev18095712014-10-10 12:19:54 +0000108 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000109 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000110
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000111 static bool classof(const CGCapturedStmtInfo *Info) {
112 return CGOpenMPRegionInfo::classof(Info) &&
113 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
114 ParallelOutlinedRegion;
115 }
116
Alexey Bataev18095712014-10-10 12:19:54 +0000117private:
118 /// \brief A variable or parameter storing global thread id for OpenMP
119 /// constructs.
120 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000121};
122
Alexey Bataev62b63b12015-03-10 07:28:44 +0000123/// \brief API for captured statement code generation in OpenMP constructs.
124class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
125public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000126 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000127 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000128 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000129 OpenMPDirectiveKind Kind, bool HasCancel)
130 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000131 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
133 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000134
Alexey Bataev62b63b12015-03-10 07:28:44 +0000135 /// \brief Get a variable or parameter for storing global thread id
136 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000137 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000138
139 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000140 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000141
Alexey Bataev62b63b12015-03-10 07:28:44 +0000142 /// \brief Get the name of the capture helper.
143 StringRef getHelperName() const override { return ".omp_outlined."; }
144
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000145 static bool classof(const CGCapturedStmtInfo *Info) {
146 return CGOpenMPRegionInfo::classof(Info) &&
147 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
148 TaskOutlinedRegion;
149 }
150
Alexey Bataev62b63b12015-03-10 07:28:44 +0000151private:
152 /// \brief A variable or parameter storing global thread id for OpenMP
153 /// constructs.
154 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000155};
156
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000157/// \brief API for inlined captured statement code generation in OpenMP
158/// constructs.
159class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
160public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000161 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000162 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000163 OpenMPDirectiveKind Kind, bool HasCancel)
164 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
165 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000166 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000167
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000168 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000169 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000170 if (OuterRegionInfo)
171 return OuterRegionInfo->getContextValue();
172 llvm_unreachable("No context value for inlined OpenMP region");
173 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000174
Hans Wennborg7eb54642015-09-10 17:07:54 +0000175 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000176 if (OuterRegionInfo) {
177 OuterRegionInfo->setContextValue(V);
178 return;
179 }
180 llvm_unreachable("No context value for inlined OpenMP region");
181 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000182
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000183 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000184 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 if (OuterRegionInfo)
186 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000187 // If there is no outer outlined region,no need to lookup in a list of
188 // captured variables, we can use the original one.
189 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000190 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000191
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000193 if (OuterRegionInfo)
194 return OuterRegionInfo->getThisFieldDecl();
195 return nullptr;
196 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000197
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000198 /// \brief Get a variable or parameter for storing global thread id
199 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000200 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000201 if (OuterRegionInfo)
202 return OuterRegionInfo->getThreadIDVariable();
203 return nullptr;
204 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000205
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000206 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000207 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000208 if (auto *OuterRegionInfo = getOldCSI())
209 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000210 llvm_unreachable("No helper name for inlined OpenMP construct");
211 }
212
213 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
214
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000215 static bool classof(const CGCapturedStmtInfo *Info) {
216 return CGOpenMPRegionInfo::classof(Info) &&
217 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
218 }
219
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000220private:
221 /// \brief CodeGen info about outer OpenMP region.
222 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
223 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000224};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225
Samuel Antaobed3c462015-10-02 16:14:20 +0000226/// \brief API for captured statement code generation in OpenMP target
227/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000228/// captured fields. The name of the target region has to be unique in a given
229/// application so it is provided by the client, because only the client has
230/// the information to generate that.
Samuel Antaobed3c462015-10-02 16:14:20 +0000231class CGOpenMPTargetRegionInfo : public CGOpenMPRegionInfo {
232public:
233 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000234 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000235 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000236 /*HasCancel=*/false),
237 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000238
239 /// \brief This is unused for target regions because each starts executing
240 /// with a single thread.
241 const VarDecl *getThreadIDVariable() const override { return nullptr; }
242
243 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000244 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000245
246 static bool classof(const CGCapturedStmtInfo *Info) {
247 return CGOpenMPRegionInfo::classof(Info) &&
248 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
249 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000250
251private:
252 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000253};
254
Samuel Antaob68e2db2016-03-03 16:20:23 +0000255static void EmptyCodeGen(CodeGenFunction &) {
256 llvm_unreachable("No codegen for expressions");
257}
258/// \brief API for generation of expressions captured in a innermost OpenMP
259/// region.
260class CGOpenMPInnerExprInfo : public CGOpenMPInlinedRegionInfo {
261public:
262 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
263 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
264 OMPD_unknown,
265 /*HasCancel=*/false),
266 PrivScope(CGF) {
267 // Make sure the globals captured in the provided statement are local by
268 // using the privatization logic. We assume the same variable is not
269 // captured more than once.
270 for (auto &C : CS.captures()) {
271 if (!C.capturesVariable() && !C.capturesVariableByCopy())
272 continue;
273
274 const VarDecl *VD = C.getCapturedVar();
275 if (VD->isLocalVarDeclOrParm())
276 continue;
277
278 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
279 /*RefersToEnclosingVariableOrCapture=*/false,
280 VD->getType().getNonReferenceType(), VK_LValue,
281 SourceLocation());
282 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
283 return CGF.EmitLValue(&DRE).getAddress();
284 });
285 }
286 (void)PrivScope.Privatize();
287 }
288
289 /// \brief Lookup the captured field decl for a variable.
290 const FieldDecl *lookup(const VarDecl *VD) const override {
291 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
292 return FD;
293 return nullptr;
294 }
295
296 /// \brief Emit the captured statement body.
297 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
298 llvm_unreachable("No body for expressions");
299 }
300
301 /// \brief Get a variable or parameter for storing global thread id
302 /// inside OpenMP construct.
303 const VarDecl *getThreadIDVariable() const override {
304 llvm_unreachable("No thread id for expressions");
305 }
306
307 /// \brief Get the name of the capture helper.
308 StringRef getHelperName() const override {
309 llvm_unreachable("No helper name for expressions");
310 }
311
312 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
313
314private:
315 /// Private scope to capture global variables.
316 CodeGenFunction::OMPPrivateScope PrivScope;
317};
318
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000319/// \brief RAII for emitting code of OpenMP constructs.
320class InlinedOpenMPRegionRAII {
321 CodeGenFunction &CGF;
322
323public:
324 /// \brief Constructs region for combined constructs.
325 /// \param CodeGen Code generation sequence for combined directives. Includes
326 /// a list of functions used for code generation of implicitly inlined
327 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000328 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000329 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000330 : CGF(CGF) {
331 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000332 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
333 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000334 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000335
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000336 ~InlinedOpenMPRegionRAII() {
337 // Restore original CapturedStmtInfo only if we're done with code emission.
338 auto *OldCSI =
339 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
340 delete CGF.CapturedStmtInfo;
341 CGF.CapturedStmtInfo = OldCSI;
342 }
343};
344
Alexey Bataev50b3c952016-02-19 10:38:26 +0000345/// \brief Values for bit flags used in the ident_t to describe the fields.
346/// All enumeric elements are named and described in accordance with the code
347/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
348enum OpenMPLocationFlags {
349 /// \brief Use trampoline for internal microtask.
350 OMP_IDENT_IMD = 0x01,
351 /// \brief Use c-style ident structure.
352 OMP_IDENT_KMPC = 0x02,
353 /// \brief Atomic reduction option for kmpc_reduce.
354 OMP_ATOMIC_REDUCE = 0x10,
355 /// \brief Explicit 'barrier' directive.
356 OMP_IDENT_BARRIER_EXPL = 0x20,
357 /// \brief Implicit barrier in code.
358 OMP_IDENT_BARRIER_IMPL = 0x40,
359 /// \brief Implicit barrier in 'for' directive.
360 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
361 /// \brief Implicit barrier in 'sections' directive.
362 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
363 /// \brief Implicit barrier in 'single' directive.
364 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
365};
366
367/// \brief Describes ident structure that describes a source location.
368/// All descriptions are taken from
369/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
370/// Original structure:
371/// typedef struct ident {
372/// kmp_int32 reserved_1; /**< might be used in Fortran;
373/// see above */
374/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
375/// KMP_IDENT_KMPC identifies this union
376/// member */
377/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
378/// see above */
379///#if USE_ITT_BUILD
380/// /* but currently used for storing
381/// region-specific ITT */
382/// /* contextual information. */
383///#endif /* USE_ITT_BUILD */
384/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
385/// C++ */
386/// char const *psource; /**< String describing the source location.
387/// The string is composed of semi-colon separated
388// fields which describe the source file,
389/// the function and a pair of line numbers that
390/// delimit the construct.
391/// */
392/// } ident_t;
393enum IdentFieldIndex {
394 /// \brief might be used in Fortran
395 IdentField_Reserved_1,
396 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
397 IdentField_Flags,
398 /// \brief Not really used in Fortran any more
399 IdentField_Reserved_2,
400 /// \brief Source[4] in Fortran, do not use for C++
401 IdentField_Reserved_3,
402 /// \brief String describing the source location. The string is composed of
403 /// semi-colon separated fields which describe the source file, the function
404 /// and a pair of line numbers that delimit the construct.
405 IdentField_PSource
406};
407
408/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
409/// the enum sched_type in kmp.h).
410enum OpenMPSchedType {
411 /// \brief Lower bound for default (unordered) versions.
412 OMP_sch_lower = 32,
413 OMP_sch_static_chunked = 33,
414 OMP_sch_static = 34,
415 OMP_sch_dynamic_chunked = 35,
416 OMP_sch_guided_chunked = 36,
417 OMP_sch_runtime = 37,
418 OMP_sch_auto = 38,
419 /// \brief Lower bound for 'ordered' versions.
420 OMP_ord_lower = 64,
421 OMP_ord_static_chunked = 65,
422 OMP_ord_static = 66,
423 OMP_ord_dynamic_chunked = 67,
424 OMP_ord_guided_chunked = 68,
425 OMP_ord_runtime = 69,
426 OMP_ord_auto = 70,
427 OMP_sch_default = OMP_sch_static,
428};
429
430enum OpenMPRTLFunction {
431 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
432 /// kmpc_micro microtask, ...);
433 OMPRTL__kmpc_fork_call,
434 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
435 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
436 OMPRTL__kmpc_threadprivate_cached,
437 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
438 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
439 OMPRTL__kmpc_threadprivate_register,
440 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
441 OMPRTL__kmpc_global_thread_num,
442 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
443 // kmp_critical_name *crit);
444 OMPRTL__kmpc_critical,
445 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
446 // global_tid, kmp_critical_name *crit, uintptr_t hint);
447 OMPRTL__kmpc_critical_with_hint,
448 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
449 // kmp_critical_name *crit);
450 OMPRTL__kmpc_end_critical,
451 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
452 // global_tid);
453 OMPRTL__kmpc_cancel_barrier,
454 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
455 OMPRTL__kmpc_barrier,
456 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
457 OMPRTL__kmpc_for_static_fini,
458 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
459 // global_tid);
460 OMPRTL__kmpc_serialized_parallel,
461 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
462 // global_tid);
463 OMPRTL__kmpc_end_serialized_parallel,
464 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
465 // kmp_int32 num_threads);
466 OMPRTL__kmpc_push_num_threads,
467 // Call to void __kmpc_flush(ident_t *loc);
468 OMPRTL__kmpc_flush,
469 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
470 OMPRTL__kmpc_master,
471 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
472 OMPRTL__kmpc_end_master,
473 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
474 // int end_part);
475 OMPRTL__kmpc_omp_taskyield,
476 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
477 OMPRTL__kmpc_single,
478 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
479 OMPRTL__kmpc_end_single,
480 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
481 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
482 // kmp_routine_entry_t *task_entry);
483 OMPRTL__kmpc_omp_task_alloc,
484 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
485 // new_task);
486 OMPRTL__kmpc_omp_task,
487 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
488 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
489 // kmp_int32 didit);
490 OMPRTL__kmpc_copyprivate,
491 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
492 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
493 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
494 OMPRTL__kmpc_reduce,
495 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
496 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
497 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
498 // *lck);
499 OMPRTL__kmpc_reduce_nowait,
500 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
501 // kmp_critical_name *lck);
502 OMPRTL__kmpc_end_reduce,
503 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
504 // kmp_critical_name *lck);
505 OMPRTL__kmpc_end_reduce_nowait,
506 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
507 // kmp_task_t * new_task);
508 OMPRTL__kmpc_omp_task_begin_if0,
509 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
510 // kmp_task_t * new_task);
511 OMPRTL__kmpc_omp_task_complete_if0,
512 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
513 OMPRTL__kmpc_ordered,
514 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
515 OMPRTL__kmpc_end_ordered,
516 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
517 // global_tid);
518 OMPRTL__kmpc_omp_taskwait,
519 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
520 OMPRTL__kmpc_taskgroup,
521 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
522 OMPRTL__kmpc_end_taskgroup,
523 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
524 // int proc_bind);
525 OMPRTL__kmpc_push_proc_bind,
526 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
527 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
528 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
529 OMPRTL__kmpc_omp_task_with_deps,
530 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
531 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
532 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
533 OMPRTL__kmpc_omp_wait_deps,
534 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
535 // global_tid, kmp_int32 cncl_kind);
536 OMPRTL__kmpc_cancellationpoint,
537 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
538 // kmp_int32 cncl_kind);
539 OMPRTL__kmpc_cancel,
540
541 //
542 // Offloading related calls
543 //
544 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
545 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
546 // *arg_types);
547 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000548 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
549 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
550 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
551 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000552 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
553 OMPRTL__tgt_register_lib,
554 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
555 OMPRTL__tgt_unregister_lib,
556};
557
Hans Wennborg7eb54642015-09-10 17:07:54 +0000558} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000559
560LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000561 return CGF.EmitLoadOfPointerLValue(
562 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
563 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000564}
565
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000566void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000567 if (!CGF.HaveInsertPoint())
568 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000569 // 1.2.2 OpenMP Language Terminology
570 // Structured block - An executable statement with a single entry at the
571 // top and a single exit at the bottom.
572 // The point of exit cannot be a branch out of the structured block.
573 // longjmp() and throw() must not violate the entry/exit criteria.
574 CGF.EHStack.pushTerminate();
575 {
576 CodeGenFunction::RunCleanupsScope Scope(CGF);
577 CodeGen(CGF);
578 }
579 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000580}
581
Alexey Bataev62b63b12015-03-10 07:28:44 +0000582LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
583 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000584 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
585 getThreadIDVariable()->getType(),
586 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000587}
588
Alexey Bataev9959db52014-05-06 10:08:46 +0000589CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Samuel Antaoee8fb302016-01-06 13:42:12 +0000590 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr),
591 OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000592 IdentTy = llvm::StructType::create(
593 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
594 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000595 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000596 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000597 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
598 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000599 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000600 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000601
602 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000603}
604
Alexey Bataev91797552015-03-18 04:13:55 +0000605void CGOpenMPRuntime::clear() {
606 InternalVars.clear();
607}
608
John McCall7f416cc2015-09-08 08:05:57 +0000609// Layout information for ident_t.
610static CharUnits getIdentAlign(CodeGenModule &CGM) {
611 return CGM.getPointerAlign();
612}
613static CharUnits getIdentSize(CodeGenModule &CGM) {
614 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
615 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
616}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000617static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000618 // All the fields except the last are i32, so this works beautifully.
619 return unsigned(Field) * CharUnits::fromQuantity(4);
620}
621static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000622 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000623 const llvm::Twine &Name = "") {
624 auto Offset = getOffsetOfIdentField(Field);
625 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
626}
627
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000628llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
629 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
630 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000631 assert(ThreadIDVar->getType()->isPointerType() &&
632 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000633 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
634 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000635 bool HasCancel = false;
636 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
637 HasCancel = OPD->hasCancel();
638 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
639 HasCancel = OPSD->hasCancel();
640 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
641 HasCancel = OPFD->hasCancel();
642 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
643 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000644 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000645 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000646}
647
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000648llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
649 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
650 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000651 assert(!ThreadIDVar->getType()->isPointerType() &&
652 "thread id variable must be of type kmp_int32 for tasks");
653 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
654 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000655 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000656 InnermostKind,
657 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000658 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000659 return CGF.GenerateCapturedStmtFunction(*CS);
660}
661
Alexey Bataev50b3c952016-02-19 10:38:26 +0000662Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000663 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000664 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000665 if (!Entry) {
666 if (!DefaultOpenMPPSource) {
667 // Initialize default location for psource field of ident_t structure of
668 // all ident_t objects. Format is ";file;function;line;column;;".
669 // Taken from
670 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
671 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000672 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000673 DefaultOpenMPPSource =
674 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
675 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000676 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
677 CGM.getModule(), IdentTy, /*isConstant*/ true,
678 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000679 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000680 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000681
682 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000683 llvm::Constant *Values[] = {Zero,
684 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
685 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000686 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
687 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000688 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000689 }
John McCall7f416cc2015-09-08 08:05:57 +0000690 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000691}
692
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000693llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
694 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000695 unsigned Flags) {
696 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000697 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000698 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000699 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000700 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000701
702 assert(CGF.CurFn && "No function in current CodeGenFunction.");
703
John McCall7f416cc2015-09-08 08:05:57 +0000704 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000705 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
706 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000707 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
708
Alexander Musmanc6388682014-12-15 07:07:06 +0000709 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
710 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000711 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000712 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000713 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
714 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000715 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000716 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000717 LocValue = AI;
718
719 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
720 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000721 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000722 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000723 }
724
725 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000726 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000727
Alexey Bataevf002aca2014-05-30 05:48:40 +0000728 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
729 if (OMPDebugLoc == nullptr) {
730 SmallString<128> Buffer2;
731 llvm::raw_svector_ostream OS2(Buffer2);
732 // Build debug location
733 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
734 OS2 << ";" << PLoc.getFilename() << ";";
735 if (const FunctionDecl *FD =
736 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
737 OS2 << FD->getQualifiedNameAsString();
738 }
739 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
740 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
741 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000742 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000743 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000744 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
745
John McCall7f416cc2015-09-08 08:05:57 +0000746 // Our callers always pass this to a runtime function, so for
747 // convenience, go ahead and return a naked pointer.
748 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000749}
750
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000751llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
752 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000753 assert(CGF.CurFn && "No function in current CodeGenFunction.");
754
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000755 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000756 // Check whether we've already cached a load of the thread id in this
757 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000758 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000759 if (I != OpenMPLocThreadIDMap.end()) {
760 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000761 if (ThreadID != nullptr)
762 return ThreadID;
763 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000764 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000765 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000766 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000767 // Check if this an outlined function with thread id passed as argument.
768 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000769 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
770 // If value loaded in entry block, cache it and use it everywhere in
771 // function.
772 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
773 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
774 Elem.second.ThreadID = ThreadID;
775 }
776 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000777 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000778 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000779
780 // This is not an outlined function region - need to call __kmpc_int32
781 // kmpc_global_thread_num(ident_t *loc).
782 // Generate thread id value and cache this value for use across the
783 // function.
784 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
785 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
786 ThreadID =
787 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
788 emitUpdateLocation(CGF, Loc));
789 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
790 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000791 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000792}
793
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000794void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000795 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000796 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
797 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000798}
799
800llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
801 return llvm::PointerType::getUnqual(IdentTy);
802}
803
804llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
805 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
806}
807
808llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +0000809CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000810 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +0000811 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000812 case OMPRTL__kmpc_fork_call: {
813 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
814 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000815 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
816 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000817 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000818 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000819 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
820 break;
821 }
822 case OMPRTL__kmpc_global_thread_num: {
823 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000824 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000825 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000826 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000827 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
828 break;
829 }
Alexey Bataev97720002014-11-11 04:05:39 +0000830 case OMPRTL__kmpc_threadprivate_cached: {
831 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
832 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
833 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
834 CGM.VoidPtrTy, CGM.SizeTy,
835 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
836 llvm::FunctionType *FnTy =
837 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
838 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
839 break;
840 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000841 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000842 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
843 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000844 llvm::Type *TypeParams[] = {
845 getIdentTyPointerTy(), CGM.Int32Ty,
846 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
847 llvm::FunctionType *FnTy =
848 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
849 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
850 break;
851 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000852 case OMPRTL__kmpc_critical_with_hint: {
853 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
854 // kmp_critical_name *crit, uintptr_t hint);
855 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
856 llvm::PointerType::getUnqual(KmpCriticalNameTy),
857 CGM.IntPtrTy};
858 llvm::FunctionType *FnTy =
859 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
860 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
861 break;
862 }
Alexey Bataev97720002014-11-11 04:05:39 +0000863 case OMPRTL__kmpc_threadprivate_register: {
864 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
865 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
866 // typedef void *(*kmpc_ctor)(void *);
867 auto KmpcCtorTy =
868 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
869 /*isVarArg*/ false)->getPointerTo();
870 // typedef void *(*kmpc_cctor)(void *, void *);
871 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
872 auto KmpcCopyCtorTy =
873 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
874 /*isVarArg*/ false)->getPointerTo();
875 // typedef void (*kmpc_dtor)(void *);
876 auto KmpcDtorTy =
877 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
878 ->getPointerTo();
879 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
880 KmpcCopyCtorTy, KmpcDtorTy};
881 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
882 /*isVarArg*/ false);
883 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
884 break;
885 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000886 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000887 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
888 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000889 llvm::Type *TypeParams[] = {
890 getIdentTyPointerTy(), CGM.Int32Ty,
891 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
892 llvm::FunctionType *FnTy =
893 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
894 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
895 break;
896 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000897 case OMPRTL__kmpc_cancel_barrier: {
898 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
899 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000900 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
901 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000902 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
903 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000904 break;
905 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000906 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000907 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000908 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
909 llvm::FunctionType *FnTy =
910 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
911 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
912 break;
913 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000914 case OMPRTL__kmpc_for_static_fini: {
915 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
916 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
917 llvm::FunctionType *FnTy =
918 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
919 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
920 break;
921 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000922 case OMPRTL__kmpc_push_num_threads: {
923 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
924 // kmp_int32 num_threads)
925 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
926 CGM.Int32Ty};
927 llvm::FunctionType *FnTy =
928 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
929 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
930 break;
931 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000932 case OMPRTL__kmpc_serialized_parallel: {
933 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
934 // global_tid);
935 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
936 llvm::FunctionType *FnTy =
937 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
938 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
939 break;
940 }
941 case OMPRTL__kmpc_end_serialized_parallel: {
942 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
943 // global_tid);
944 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
945 llvm::FunctionType *FnTy =
946 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
947 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
948 break;
949 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000950 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000951 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000952 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
953 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000954 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000955 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
956 break;
957 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000958 case OMPRTL__kmpc_master: {
959 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
960 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
961 llvm::FunctionType *FnTy =
962 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
963 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
964 break;
965 }
966 case OMPRTL__kmpc_end_master: {
967 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
968 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
969 llvm::FunctionType *FnTy =
970 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
971 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
972 break;
973 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000974 case OMPRTL__kmpc_omp_taskyield: {
975 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
976 // int end_part);
977 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
978 llvm::FunctionType *FnTy =
979 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
980 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
981 break;
982 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000983 case OMPRTL__kmpc_single: {
984 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
985 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
986 llvm::FunctionType *FnTy =
987 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
988 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
989 break;
990 }
991 case OMPRTL__kmpc_end_single: {
992 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
993 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
994 llvm::FunctionType *FnTy =
995 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
996 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
997 break;
998 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000999 case OMPRTL__kmpc_omp_task_alloc: {
1000 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1001 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1002 // kmp_routine_entry_t *task_entry);
1003 assert(KmpRoutineEntryPtrTy != nullptr &&
1004 "Type kmp_routine_entry_t must be created.");
1005 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1006 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1007 // Return void * and then cast to particular kmp_task_t type.
1008 llvm::FunctionType *FnTy =
1009 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1010 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1011 break;
1012 }
1013 case OMPRTL__kmpc_omp_task: {
1014 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1015 // *new_task);
1016 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1017 CGM.VoidPtrTy};
1018 llvm::FunctionType *FnTy =
1019 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1020 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1021 break;
1022 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001023 case OMPRTL__kmpc_copyprivate: {
1024 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001025 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001026 // kmp_int32 didit);
1027 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1028 auto *CpyFnTy =
1029 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001030 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001031 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1032 CGM.Int32Ty};
1033 llvm::FunctionType *FnTy =
1034 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1035 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1036 break;
1037 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001038 case OMPRTL__kmpc_reduce: {
1039 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1040 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1041 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1042 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1043 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1044 /*isVarArg=*/false);
1045 llvm::Type *TypeParams[] = {
1046 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1047 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1048 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1049 llvm::FunctionType *FnTy =
1050 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1051 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1052 break;
1053 }
1054 case OMPRTL__kmpc_reduce_nowait: {
1055 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1056 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1057 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1058 // *lck);
1059 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1060 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1061 /*isVarArg=*/false);
1062 llvm::Type *TypeParams[] = {
1063 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1064 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1065 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1066 llvm::FunctionType *FnTy =
1067 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1068 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1069 break;
1070 }
1071 case OMPRTL__kmpc_end_reduce: {
1072 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1073 // kmp_critical_name *lck);
1074 llvm::Type *TypeParams[] = {
1075 getIdentTyPointerTy(), CGM.Int32Ty,
1076 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1077 llvm::FunctionType *FnTy =
1078 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1079 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1080 break;
1081 }
1082 case OMPRTL__kmpc_end_reduce_nowait: {
1083 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1084 // kmp_critical_name *lck);
1085 llvm::Type *TypeParams[] = {
1086 getIdentTyPointerTy(), CGM.Int32Ty,
1087 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1088 llvm::FunctionType *FnTy =
1089 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1090 RTLFn =
1091 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1092 break;
1093 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001094 case OMPRTL__kmpc_omp_task_begin_if0: {
1095 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1096 // *new_task);
1097 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1098 CGM.VoidPtrTy};
1099 llvm::FunctionType *FnTy =
1100 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1101 RTLFn =
1102 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1103 break;
1104 }
1105 case OMPRTL__kmpc_omp_task_complete_if0: {
1106 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1107 // *new_task);
1108 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1109 CGM.VoidPtrTy};
1110 llvm::FunctionType *FnTy =
1111 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1112 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1113 /*Name=*/"__kmpc_omp_task_complete_if0");
1114 break;
1115 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001116 case OMPRTL__kmpc_ordered: {
1117 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1118 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1119 llvm::FunctionType *FnTy =
1120 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1121 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1122 break;
1123 }
1124 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001125 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001126 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1127 llvm::FunctionType *FnTy =
1128 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1129 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1130 break;
1131 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001132 case OMPRTL__kmpc_omp_taskwait: {
1133 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1134 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1135 llvm::FunctionType *FnTy =
1136 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1137 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1138 break;
1139 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001140 case OMPRTL__kmpc_taskgroup: {
1141 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1142 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1143 llvm::FunctionType *FnTy =
1144 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1145 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1146 break;
1147 }
1148 case OMPRTL__kmpc_end_taskgroup: {
1149 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1150 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1151 llvm::FunctionType *FnTy =
1152 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1153 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1154 break;
1155 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001156 case OMPRTL__kmpc_push_proc_bind: {
1157 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1158 // int proc_bind)
1159 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1160 llvm::FunctionType *FnTy =
1161 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1162 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1163 break;
1164 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001165 case OMPRTL__kmpc_omp_task_with_deps: {
1166 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1167 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1168 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1169 llvm::Type *TypeParams[] = {
1170 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1171 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1172 llvm::FunctionType *FnTy =
1173 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1174 RTLFn =
1175 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1176 break;
1177 }
1178 case OMPRTL__kmpc_omp_wait_deps: {
1179 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1180 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1181 // kmp_depend_info_t *noalias_dep_list);
1182 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1183 CGM.Int32Ty, CGM.VoidPtrTy,
1184 CGM.Int32Ty, CGM.VoidPtrTy};
1185 llvm::FunctionType *FnTy =
1186 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1187 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1188 break;
1189 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001190 case OMPRTL__kmpc_cancellationpoint: {
1191 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1192 // global_tid, kmp_int32 cncl_kind)
1193 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1194 llvm::FunctionType *FnTy =
1195 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1196 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1197 break;
1198 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001199 case OMPRTL__kmpc_cancel: {
1200 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1201 // kmp_int32 cncl_kind)
1202 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1203 llvm::FunctionType *FnTy =
1204 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1205 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1206 break;
1207 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001208 case OMPRTL__tgt_target: {
1209 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1210 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1211 // *arg_types);
1212 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1213 CGM.VoidPtrTy,
1214 CGM.Int32Ty,
1215 CGM.VoidPtrPtrTy,
1216 CGM.VoidPtrPtrTy,
1217 CGM.SizeTy->getPointerTo(),
1218 CGM.Int32Ty->getPointerTo()};
1219 llvm::FunctionType *FnTy =
1220 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1221 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1222 break;
1223 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001224 case OMPRTL__tgt_target_teams: {
1225 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1226 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1227 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1228 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1229 CGM.VoidPtrTy,
1230 CGM.Int32Ty,
1231 CGM.VoidPtrPtrTy,
1232 CGM.VoidPtrPtrTy,
1233 CGM.SizeTy->getPointerTo(),
1234 CGM.Int32Ty->getPointerTo(),
1235 CGM.Int32Ty,
1236 CGM.Int32Ty};
1237 llvm::FunctionType *FnTy =
1238 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1239 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1240 break;
1241 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001242 case OMPRTL__tgt_register_lib: {
1243 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1244 QualType ParamTy =
1245 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1246 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1247 llvm::FunctionType *FnTy =
1248 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1249 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1250 break;
1251 }
1252 case OMPRTL__tgt_unregister_lib: {
1253 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1254 QualType ParamTy =
1255 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1256 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1257 llvm::FunctionType *FnTy =
1258 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1259 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1260 break;
1261 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001262 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001263 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001264 return RTLFn;
1265}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001266
Alexander Musman21212e42015-03-13 10:38:23 +00001267llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1268 bool IVSigned) {
1269 assert((IVSize == 32 || IVSize == 64) &&
1270 "IV size is not compatible with the omp runtime");
1271 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1272 : "__kmpc_for_static_init_4u")
1273 : (IVSigned ? "__kmpc_for_static_init_8"
1274 : "__kmpc_for_static_init_8u");
1275 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1276 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1277 llvm::Type *TypeParams[] = {
1278 getIdentTyPointerTy(), // loc
1279 CGM.Int32Ty, // tid
1280 CGM.Int32Ty, // schedtype
1281 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1282 PtrTy, // p_lower
1283 PtrTy, // p_upper
1284 PtrTy, // p_stride
1285 ITy, // incr
1286 ITy // chunk
1287 };
1288 llvm::FunctionType *FnTy =
1289 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1290 return CGM.CreateRuntimeFunction(FnTy, Name);
1291}
1292
Alexander Musman92bdaab2015-03-12 13:37:50 +00001293llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1294 bool IVSigned) {
1295 assert((IVSize == 32 || IVSize == 64) &&
1296 "IV size is not compatible with the omp runtime");
1297 auto Name =
1298 IVSize == 32
1299 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1300 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1301 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1302 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1303 CGM.Int32Ty, // tid
1304 CGM.Int32Ty, // schedtype
1305 ITy, // lower
1306 ITy, // upper
1307 ITy, // stride
1308 ITy // chunk
1309 };
1310 llvm::FunctionType *FnTy =
1311 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1312 return CGM.CreateRuntimeFunction(FnTy, Name);
1313}
1314
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001315llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1316 bool IVSigned) {
1317 assert((IVSize == 32 || IVSize == 64) &&
1318 "IV size is not compatible with the omp runtime");
1319 auto Name =
1320 IVSize == 32
1321 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1322 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1323 llvm::Type *TypeParams[] = {
1324 getIdentTyPointerTy(), // loc
1325 CGM.Int32Ty, // tid
1326 };
1327 llvm::FunctionType *FnTy =
1328 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1329 return CGM.CreateRuntimeFunction(FnTy, Name);
1330}
1331
Alexander Musman92bdaab2015-03-12 13:37:50 +00001332llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1333 bool IVSigned) {
1334 assert((IVSize == 32 || IVSize == 64) &&
1335 "IV size is not compatible with the omp runtime");
1336 auto Name =
1337 IVSize == 32
1338 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1339 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1340 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1341 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1342 llvm::Type *TypeParams[] = {
1343 getIdentTyPointerTy(), // loc
1344 CGM.Int32Ty, // tid
1345 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1346 PtrTy, // p_lower
1347 PtrTy, // p_upper
1348 PtrTy // p_stride
1349 };
1350 llvm::FunctionType *FnTy =
1351 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1352 return CGM.CreateRuntimeFunction(FnTy, Name);
1353}
1354
Alexey Bataev97720002014-11-11 04:05:39 +00001355llvm::Constant *
1356CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001357 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1358 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001359 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001360 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001361 Twine(CGM.getMangledName(VD)) + ".cache.");
1362}
1363
John McCall7f416cc2015-09-08 08:05:57 +00001364Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1365 const VarDecl *VD,
1366 Address VDAddr,
1367 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001368 if (CGM.getLangOpts().OpenMPUseTLS &&
1369 CGM.getContext().getTargetInfo().isTLSSupported())
1370 return VDAddr;
1371
John McCall7f416cc2015-09-08 08:05:57 +00001372 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001373 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001374 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1375 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001376 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1377 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001378 return Address(CGF.EmitRuntimeCall(
1379 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1380 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001381}
1382
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001383void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001384 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001385 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1386 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1387 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001388 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1389 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001390 OMPLoc);
1391 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1392 // to register constructor/destructor for variable.
1393 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001394 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1395 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001396 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001397 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001398 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001399}
1400
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001401llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001402 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001403 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001404 if (CGM.getLangOpts().OpenMPUseTLS &&
1405 CGM.getContext().getTargetInfo().isTLSSupported())
1406 return nullptr;
1407
Alexey Bataev97720002014-11-11 04:05:39 +00001408 VD = VD->getDefinition(CGM.getContext());
1409 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1410 ThreadPrivateWithDefinition.insert(VD);
1411 QualType ASTTy = VD->getType();
1412
1413 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1414 auto Init = VD->getAnyInitializer();
1415 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1416 // Generate function that re-emits the declaration's initializer into the
1417 // threadprivate copy of the variable VD
1418 CodeGenFunction CtorCGF(CGM);
1419 FunctionArgList Args;
1420 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1421 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1422 Args.push_back(&Dst);
1423
1424 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1425 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1426 /*isVariadic=*/false);
1427 auto FTy = CGM.getTypes().GetFunctionType(FI);
1428 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001429 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001430 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1431 Args, SourceLocation());
1432 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001433 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001434 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001435 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1436 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1437 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001438 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1439 /*IsInitializer=*/true);
1440 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001441 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001442 CGM.getContext().VoidPtrTy, Dst.getLocation());
1443 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1444 CtorCGF.FinishFunction();
1445 Ctor = Fn;
1446 }
1447 if (VD->getType().isDestructedType() != QualType::DK_none) {
1448 // Generate function that emits destructor call for the threadprivate copy
1449 // of the variable VD
1450 CodeGenFunction DtorCGF(CGM);
1451 FunctionArgList Args;
1452 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1453 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1454 Args.push_back(&Dst);
1455
1456 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1457 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1458 /*isVariadic=*/false);
1459 auto FTy = CGM.getTypes().GetFunctionType(FI);
1460 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001461 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001462 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1463 SourceLocation());
1464 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1465 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001466 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1467 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001468 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1469 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1470 DtorCGF.FinishFunction();
1471 Dtor = Fn;
1472 }
1473 // Do not emit init function if it is not required.
1474 if (!Ctor && !Dtor)
1475 return nullptr;
1476
1477 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1478 auto CopyCtorTy =
1479 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1480 /*isVarArg=*/false)->getPointerTo();
1481 // Copying constructor for the threadprivate variable.
1482 // Must be NULL - reserved by runtime, but currently it requires that this
1483 // parameter is always NULL. Otherwise it fires assertion.
1484 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1485 if (Ctor == nullptr) {
1486 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1487 /*isVarArg=*/false)->getPointerTo();
1488 Ctor = llvm::Constant::getNullValue(CtorTy);
1489 }
1490 if (Dtor == nullptr) {
1491 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1492 /*isVarArg=*/false)->getPointerTo();
1493 Dtor = llvm::Constant::getNullValue(DtorTy);
1494 }
1495 if (!CGF) {
1496 auto InitFunctionTy =
1497 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1498 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001499 InitFunctionTy, ".__omp_threadprivate_init_.",
1500 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001501 CodeGenFunction InitCGF(CGM);
1502 FunctionArgList ArgList;
1503 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1504 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1505 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001506 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001507 InitCGF.FinishFunction();
1508 return InitFunction;
1509 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001510 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001511 }
1512 return nullptr;
1513}
1514
Alexey Bataev1d677132015-04-22 13:57:31 +00001515/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1516/// function. Here is the logic:
1517/// if (Cond) {
1518/// ThenGen();
1519/// } else {
1520/// ElseGen();
1521/// }
1522static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1523 const RegionCodeGenTy &ThenGen,
1524 const RegionCodeGenTy &ElseGen) {
1525 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1526
1527 // If the condition constant folds and can be elided, try to avoid emitting
1528 // the condition and the dead arm of the if/else.
1529 bool CondConstant;
1530 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1531 CodeGenFunction::RunCleanupsScope Scope(CGF);
1532 if (CondConstant) {
1533 ThenGen(CGF);
1534 } else {
1535 ElseGen(CGF);
1536 }
1537 return;
1538 }
1539
1540 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1541 // emit the conditional branch.
1542 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1543 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1544 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1545 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1546
1547 // Emit the 'then' code.
1548 CGF.EmitBlock(ThenBlock);
1549 {
1550 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1551 ThenGen(CGF);
1552 }
1553 CGF.EmitBranch(ContBlock);
1554 // Emit the 'else' code if present.
1555 {
1556 // There is no need to emit line number for unconditional branch.
1557 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1558 CGF.EmitBlock(ElseBlock);
1559 }
1560 {
1561 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1562 ElseGen(CGF);
1563 }
1564 {
1565 // There is no need to emit line number for unconditional branch.
1566 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1567 CGF.EmitBranch(ContBlock);
1568 }
1569 // Emit the continuation block for code after the if.
1570 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001571}
1572
Alexey Bataev1d677132015-04-22 13:57:31 +00001573void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1574 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001575 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001576 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001577 if (!CGF.HaveInsertPoint())
1578 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001579 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001580 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1581 RTLoc](CodeGenFunction &CGF) {
1582 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1583 llvm::Value *Args[] = {
1584 RTLoc,
1585 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1586 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1587 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1588 RealArgs.append(std::begin(Args), std::end(Args));
1589 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1590
1591 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1592 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1593 };
1594 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1595 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001596 auto ThreadID = getThreadID(CGF, Loc);
1597 // Build calls:
1598 // __kmpc_serialized_parallel(&Loc, GTid);
1599 llvm::Value *Args[] = {RTLoc, ThreadID};
1600 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1601 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001602
Alexey Bataev1d677132015-04-22 13:57:31 +00001603 // OutlinedFn(&GTid, &zero, CapturedStruct);
1604 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001605 Address ZeroAddr =
1606 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1607 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001608 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001609 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1610 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1611 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1612 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001613 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001614
Alexey Bataev1d677132015-04-22 13:57:31 +00001615 // __kmpc_end_serialized_parallel(&Loc, GTid);
1616 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1617 CGF.EmitRuntimeCall(
1618 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1619 };
1620 if (IfCond) {
1621 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1622 } else {
1623 CodeGenFunction::RunCleanupsScope Scope(CGF);
1624 ThenGen(CGF);
1625 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001626}
1627
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001628// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001629// thread-ID variable (it is passed in a first argument of the outlined function
1630// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1631// regular serial code region, get thread ID by calling kmp_int32
1632// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1633// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001634Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1635 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001636 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001637 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001638 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001639 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001640
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001641 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001642 auto Int32Ty =
1643 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1644 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1645 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001646 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001647
1648 return ThreadIDTemp;
1649}
1650
Alexey Bataev97720002014-11-11 04:05:39 +00001651llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001652CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001653 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001654 SmallString<256> Buffer;
1655 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001656 Out << Name;
1657 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001658 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1659 if (Elem.second) {
1660 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001661 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001662 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001663 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001664
David Blaikie13156b62014-11-19 03:06:06 +00001665 return Elem.second = new llvm::GlobalVariable(
1666 CGM.getModule(), Ty, /*IsConstant*/ false,
1667 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1668 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001669}
1670
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001671llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001672 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001673 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001674}
1675
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001676namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001677template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001678 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001679 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001680
1681public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001682 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1683 : Callee(Callee) {
1684 assert(CleanupArgs.size() == N);
1685 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1686 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001687
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001688 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001689 if (!CGF.HaveInsertPoint())
1690 return;
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001691 CGF.EmitRuntimeCall(Callee, Args);
1692 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001693};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001694} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001695
1696void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1697 StringRef CriticalName,
1698 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001699 SourceLocation Loc, const Expr *Hint) {
1700 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001701 // CriticalOpGen();
1702 // __kmpc_end_critical(ident_t *, gtid, Lock);
1703 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001704 if (!CGF.HaveInsertPoint())
1705 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001706 CodeGenFunction::RunCleanupsScope Scope(CGF);
1707 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1708 getCriticalRegionLock(CriticalName)};
1709 if (Hint) {
1710 llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1711 std::end(Args));
1712 auto *HintVal = CGF.EmitScalarExpr(Hint);
1713 ArgsWithHint.push_back(
1714 CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1715 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1716 ArgsWithHint);
1717 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001718 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001719 // Build a call to __kmpc_end_critical
1720 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1721 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1722 llvm::makeArrayRef(Args));
1723 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001724}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001725
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001726static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001727 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001728 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001729 llvm::Value *CallBool = CGF.EmitScalarConversion(
1730 IfCond,
1731 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001732 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001733
1734 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1735 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1736 // Generate the branch (If-stmt)
1737 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1738 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001739 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001740 // Emit the rest of bblocks/branches
1741 CGF.EmitBranch(ContBlock);
1742 CGF.EmitBlock(ContBlock, true);
1743}
1744
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001745void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001746 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001747 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001748 if (!CGF.HaveInsertPoint())
1749 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001750 // if(__kmpc_master(ident_t *, gtid)) {
1751 // MasterOpGen();
1752 // __kmpc_end_master(ident_t *, gtid);
1753 // }
1754 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001755 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001756 auto *IsMaster =
1757 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001758 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1759 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001760 emitIfStmt(
1761 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1762 CodeGenFunction::RunCleanupsScope Scope(CGF);
1763 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1764 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1765 llvm::makeArrayRef(Args));
1766 MasterOpGen(CGF);
1767 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001768}
1769
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001770void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1771 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001772 if (!CGF.HaveInsertPoint())
1773 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001774 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1775 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001776 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001777 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001778 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001779}
1780
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001781void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1782 const RegionCodeGenTy &TaskgroupOpGen,
1783 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001784 if (!CGF.HaveInsertPoint())
1785 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001786 // __kmpc_taskgroup(ident_t *, gtid);
1787 // TaskgroupOpGen();
1788 // __kmpc_end_taskgroup(ident_t *, gtid);
1789 // Prepare arguments and build a call to __kmpc_taskgroup
1790 {
1791 CodeGenFunction::RunCleanupsScope Scope(CGF);
1792 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1793 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1794 // Build a call to __kmpc_end_taskgroup
1795 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1796 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1797 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001798 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001799 }
1800}
1801
John McCall7f416cc2015-09-08 08:05:57 +00001802/// Given an array of pointers to variables, project the address of a
1803/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001804static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1805 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001806 // Pull out the pointer to the variable.
1807 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001808 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001809 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1810
1811 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001812 Addr = CGF.Builder.CreateElementBitCast(
1813 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001814 return Addr;
1815}
1816
Alexey Bataeva63048e2015-03-23 06:18:07 +00001817static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001818 CodeGenModule &CGM, llvm::Type *ArgsType,
1819 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1820 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001821 auto &C = CGM.getContext();
1822 // void copy_func(void *LHSArg, void *RHSArg);
1823 FunctionArgList Args;
1824 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1825 C.VoidPtrTy);
1826 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1827 C.VoidPtrTy);
1828 Args.push_back(&LHSArg);
1829 Args.push_back(&RHSArg);
1830 FunctionType::ExtInfo EI;
1831 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1832 C.VoidTy, Args, EI, /*isVariadic=*/false);
1833 auto *Fn = llvm::Function::Create(
1834 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1835 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001836 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001837 CodeGenFunction CGF(CGM);
1838 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001839 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001840 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001841 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1842 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1843 ArgsType), CGF.getPointerAlign());
1844 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1845 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1846 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001847 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1848 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1849 // ...
1850 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001851 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001852 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1853 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1854
1855 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1856 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1857
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001858 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1859 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001860 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001861 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001862 CGF.FinishFunction();
1863 return Fn;
1864}
1865
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001866void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001867 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001868 SourceLocation Loc,
1869 ArrayRef<const Expr *> CopyprivateVars,
1870 ArrayRef<const Expr *> SrcExprs,
1871 ArrayRef<const Expr *> DstExprs,
1872 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001873 if (!CGF.HaveInsertPoint())
1874 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001875 assert(CopyprivateVars.size() == SrcExprs.size() &&
1876 CopyprivateVars.size() == DstExprs.size() &&
1877 CopyprivateVars.size() == AssignmentOps.size());
1878 auto &C = CGM.getContext();
1879 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001880 // if(__kmpc_single(ident_t *, gtid)) {
1881 // SingleOpGen();
1882 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001883 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001884 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001885 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1886 // <copy_func>, did_it);
1887
John McCall7f416cc2015-09-08 08:05:57 +00001888 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001889 if (!CopyprivateVars.empty()) {
1890 // int32 did_it = 0;
1891 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1892 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00001893 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001894 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001895 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001896 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001897 auto *IsSingle =
1898 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001899 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1900 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001901 emitIfStmt(
1902 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
1903 CodeGenFunction::RunCleanupsScope Scope(CGF);
1904 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
1905 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1906 llvm::makeArrayRef(Args));
1907 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001908 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001909 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00001910 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001911 }
1912 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001913 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1914 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00001915 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001916 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1917 auto CopyprivateArrayTy =
1918 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1919 /*IndexTypeQuals=*/0);
1920 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00001921 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001922 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1923 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001924 Address Elem = CGF.Builder.CreateConstArrayGEP(
1925 CopyprivateList, I, CGF.getPointerSize());
1926 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00001927 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001928 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
1929 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001930 }
1931 // Build function that copies private values from single region to all other
1932 // threads in the corresponding parallel region.
1933 auto *CpyFn = emitCopyprivateCopyFunction(
1934 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001935 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001936 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00001937 Address CL =
1938 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1939 CGF.VoidPtrTy);
1940 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001941 llvm::Value *Args[] = {
1942 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1943 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001944 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00001945 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001946 CpyFn, // void (*) (void *, void *) <copy_func>
1947 DidItVal // i32 did_it
1948 };
1949 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1950 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001951}
1952
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001953void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1954 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00001955 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001956 if (!CGF.HaveInsertPoint())
1957 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001958 // __kmpc_ordered(ident_t *, gtid);
1959 // OrderedOpGen();
1960 // __kmpc_end_ordered(ident_t *, gtid);
1961 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00001962 CodeGenFunction::RunCleanupsScope Scope(CGF);
1963 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001964 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1965 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1966 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001967 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001968 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1969 llvm::makeArrayRef(Args));
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001970 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00001971 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001972}
1973
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001974void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001975 OpenMPDirectiveKind Kind, bool EmitChecks,
1976 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001977 if (!CGF.HaveInsertPoint())
1978 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001979 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001980 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00001981 unsigned Flags;
1982 if (Kind == OMPD_for)
1983 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
1984 else if (Kind == OMPD_sections)
1985 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
1986 else if (Kind == OMPD_single)
1987 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
1988 else if (Kind == OMPD_barrier)
1989 Flags = OMP_IDENT_BARRIER_EXPL;
1990 else
1991 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001992 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
1993 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001994 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1995 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001996 if (auto *OMPRegionInfo =
1997 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00001998 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001999 auto *Result = CGF.EmitRuntimeCall(
2000 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002001 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002002 // if (__kmpc_cancel_barrier()) {
2003 // exit from construct;
2004 // }
2005 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2006 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2007 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2008 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2009 CGF.EmitBlock(ExitBB);
2010 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002011 auto CancelDestination =
2012 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002013 CGF.EmitBranchThroughCleanup(CancelDestination);
2014 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2015 }
2016 return;
2017 }
2018 }
2019 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002020}
2021
Alexander Musmanc6388682014-12-15 07:07:06 +00002022/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2023static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002024 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002025 switch (ScheduleKind) {
2026 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002027 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2028 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002029 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002030 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002031 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002032 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002033 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002034 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2035 case OMPC_SCHEDULE_auto:
2036 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002037 case OMPC_SCHEDULE_unknown:
2038 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002039 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002040 }
2041 llvm_unreachable("Unexpected runtime schedule");
2042}
2043
2044bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2045 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002046 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002047 return Schedule == OMP_sch_static;
2048}
2049
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002050bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002051 auto Schedule =
2052 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002053 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2054 return Schedule != OMP_sch_static;
2055}
2056
John McCall7f416cc2015-09-08 08:05:57 +00002057void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2058 SourceLocation Loc,
2059 OpenMPScheduleClauseKind ScheduleKind,
2060 unsigned IVSize, bool IVSigned,
2061 bool Ordered, llvm::Value *UB,
2062 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002063 if (!CGF.HaveInsertPoint())
2064 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002065 OpenMPSchedType Schedule =
2066 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002067 assert(Ordered ||
2068 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2069 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2070 // Call __kmpc_dispatch_init(
2071 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2072 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2073 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002074
John McCall7f416cc2015-09-08 08:05:57 +00002075 // If the Chunk was not specified in the clause - use default value 1.
2076 if (Chunk == nullptr)
2077 Chunk = CGF.Builder.getIntN(IVSize, 1);
2078 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002079 emitUpdateLocation(CGF, Loc),
2080 getThreadID(CGF, Loc),
2081 CGF.Builder.getInt32(Schedule), // Schedule type
2082 CGF.Builder.getIntN(IVSize, 0), // Lower
2083 UB, // Upper
2084 CGF.Builder.getIntN(IVSize, 1), // Stride
2085 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002086 };
2087 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2088}
2089
2090void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2091 SourceLocation Loc,
2092 OpenMPScheduleClauseKind ScheduleKind,
2093 unsigned IVSize, bool IVSigned,
2094 bool Ordered, Address IL, Address LB,
2095 Address UB, Address ST,
2096 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002097 if (!CGF.HaveInsertPoint())
2098 return;
John McCall7f416cc2015-09-08 08:05:57 +00002099 OpenMPSchedType Schedule =
2100 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
2101 assert(!Ordered);
2102 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2103 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked);
2104
2105 // Call __kmpc_for_static_init(
2106 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2107 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2108 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2109 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2110 if (Chunk == nullptr) {
2111 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
2112 "expected static non-chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00002113 // If the Chunk was not specified in the clause - use default value 1.
Alexander Musman92bdaab2015-03-12 13:37:50 +00002114 Chunk = CGF.Builder.getIntN(IVSize, 1);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002115 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002116 assert((Schedule == OMP_sch_static_chunked ||
2117 Schedule == OMP_ord_static_chunked) &&
2118 "expected static chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00002119 }
John McCall7f416cc2015-09-08 08:05:57 +00002120 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002121 emitUpdateLocation(CGF, Loc),
2122 getThreadID(CGF, Loc),
2123 CGF.Builder.getInt32(Schedule), // Schedule type
2124 IL.getPointer(), // &isLastIter
2125 LB.getPointer(), // &LB
2126 UB.getPointer(), // &UB
2127 ST.getPointer(), // &Stride
2128 CGF.Builder.getIntN(IVSize, 1), // Incr
2129 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002130 };
2131 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002132}
2133
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002134void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2135 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002136 if (!CGF.HaveInsertPoint())
2137 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002138 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002139 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002140 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2141 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002142}
2143
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002144void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2145 SourceLocation Loc,
2146 unsigned IVSize,
2147 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002148 if (!CGF.HaveInsertPoint())
2149 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002150 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002151 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002152 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2153}
2154
Alexander Musman92bdaab2015-03-12 13:37:50 +00002155llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2156 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002157 bool IVSigned, Address IL,
2158 Address LB, Address UB,
2159 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002160 // Call __kmpc_dispatch_next(
2161 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2162 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2163 // kmp_int[32|64] *p_stride);
2164 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002165 emitUpdateLocation(CGF, Loc),
2166 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002167 IL.getPointer(), // &isLastIter
2168 LB.getPointer(), // &Lower
2169 UB.getPointer(), // &Upper
2170 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002171 };
2172 llvm::Value *Call =
2173 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2174 return CGF.EmitScalarConversion(
2175 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002176 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002177}
2178
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002179void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2180 llvm::Value *NumThreads,
2181 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002182 if (!CGF.HaveInsertPoint())
2183 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002184 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2185 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002186 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002187 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002188 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2189 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002190}
2191
Alexey Bataev7f210c62015-06-18 13:40:03 +00002192void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2193 OpenMPProcBindClauseKind ProcBind,
2194 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002195 if (!CGF.HaveInsertPoint())
2196 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002197 // Constants for proc bind value accepted by the runtime.
2198 enum ProcBindTy {
2199 ProcBindFalse = 0,
2200 ProcBindTrue,
2201 ProcBindMaster,
2202 ProcBindClose,
2203 ProcBindSpread,
2204 ProcBindIntel,
2205 ProcBindDefault
2206 } RuntimeProcBind;
2207 switch (ProcBind) {
2208 case OMPC_PROC_BIND_master:
2209 RuntimeProcBind = ProcBindMaster;
2210 break;
2211 case OMPC_PROC_BIND_close:
2212 RuntimeProcBind = ProcBindClose;
2213 break;
2214 case OMPC_PROC_BIND_spread:
2215 RuntimeProcBind = ProcBindSpread;
2216 break;
2217 case OMPC_PROC_BIND_unknown:
2218 llvm_unreachable("Unsupported proc_bind value.");
2219 }
2220 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2221 llvm::Value *Args[] = {
2222 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2223 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2224 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2225}
2226
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002227void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2228 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002229 if (!CGF.HaveInsertPoint())
2230 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002231 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002232 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2233 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002234}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002235
Alexey Bataev62b63b12015-03-10 07:28:44 +00002236namespace {
2237/// \brief Indexes of fields for type kmp_task_t.
2238enum KmpTaskTFields {
2239 /// \brief List of shared variables.
2240 KmpTaskTShareds,
2241 /// \brief Task routine.
2242 KmpTaskTRoutine,
2243 /// \brief Partition id for the untied tasks.
2244 KmpTaskTPartId,
2245 /// \brief Function with call of destructors for private variables.
2246 KmpTaskTDestructors,
2247};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002248} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002249
Samuel Antaoee8fb302016-01-06 13:42:12 +00002250bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2251 // FIXME: Add other entries type when they become supported.
2252 return OffloadEntriesTargetRegion.empty();
2253}
2254
2255/// \brief Initialize target region entry.
2256void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2257 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2258 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002259 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002260 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2261 "only required for the device "
2262 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002263 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002264 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2265 ++OffloadingEntriesNum;
2266}
2267
2268void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2269 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2270 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002271 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002272 // If we are emitting code for a target, the entry is already initialized,
2273 // only has to be registered.
2274 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002275 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002276 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002277 auto &Entry =
2278 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002279 assert(Entry.isValid() && "Entry not initialized!");
2280 Entry.setAddress(Addr);
2281 Entry.setID(ID);
2282 return;
2283 } else {
2284 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002285 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002286 }
2287}
2288
2289bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002290 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2291 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002292 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2293 if (PerDevice == OffloadEntriesTargetRegion.end())
2294 return false;
2295 auto PerFile = PerDevice->second.find(FileID);
2296 if (PerFile == PerDevice->second.end())
2297 return false;
2298 auto PerParentName = PerFile->second.find(ParentName);
2299 if (PerParentName == PerFile->second.end())
2300 return false;
2301 auto PerLine = PerParentName->second.find(LineNum);
2302 if (PerLine == PerParentName->second.end())
2303 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002304 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002305 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002306 return false;
2307 return true;
2308}
2309
2310void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2311 const OffloadTargetRegionEntryInfoActTy &Action) {
2312 // Scan all target region entries and perform the provided action.
2313 for (auto &D : OffloadEntriesTargetRegion)
2314 for (auto &F : D.second)
2315 for (auto &P : F.second)
2316 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002317 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002318}
2319
2320/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2321/// \a Codegen. This is used to emit the two functions that register and
2322/// unregister the descriptor of the current compilation unit.
2323static llvm::Function *
2324createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2325 const RegionCodeGenTy &Codegen) {
2326 auto &C = CGM.getContext();
2327 FunctionArgList Args;
2328 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2329 /*Id=*/nullptr, C.VoidPtrTy);
2330 Args.push_back(&DummyPtr);
2331
2332 CodeGenFunction CGF(CGM);
2333 GlobalDecl();
2334 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2335 C.VoidTy, Args, FunctionType::ExtInfo(),
2336 /*isVariadic=*/false);
2337 auto FTy = CGM.getTypes().GetFunctionType(FI);
2338 auto *Fn =
2339 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2340 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2341 Codegen(CGF);
2342 CGF.FinishFunction();
2343 return Fn;
2344}
2345
2346llvm::Function *
2347CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2348
2349 // If we don't have entries or if we are emitting code for the device, we
2350 // don't need to do anything.
2351 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2352 return nullptr;
2353
2354 auto &M = CGM.getModule();
2355 auto &C = CGM.getContext();
2356
2357 // Get list of devices we care about
2358 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2359
2360 // We should be creating an offloading descriptor only if there are devices
2361 // specified.
2362 assert(!Devices.empty() && "No OpenMP offloading devices??");
2363
2364 // Create the external variables that will point to the begin and end of the
2365 // host entries section. These will be defined by the linker.
2366 auto *OffloadEntryTy =
2367 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2368 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2369 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002370 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002371 ".omp_offloading.entries_begin");
2372 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2373 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002374 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002375 ".omp_offloading.entries_end");
2376
2377 // Create all device images
2378 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2379 auto *DeviceImageTy = cast<llvm::StructType>(
2380 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2381
2382 for (unsigned i = 0; i < Devices.size(); ++i) {
2383 StringRef T = Devices[i].getTriple();
2384 auto *ImgBegin = new llvm::GlobalVariable(
2385 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002386 /*Initializer=*/nullptr,
2387 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002388 auto *ImgEnd = new llvm::GlobalVariable(
2389 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002390 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002391
2392 llvm::Constant *Dev =
2393 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2394 HostEntriesBegin, HostEntriesEnd, nullptr);
2395 DeviceImagesEntires.push_back(Dev);
2396 }
2397
2398 // Create device images global array.
2399 llvm::ArrayType *DeviceImagesInitTy =
2400 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2401 llvm::Constant *DeviceImagesInit =
2402 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2403
2404 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2405 M, DeviceImagesInitTy, /*isConstant=*/true,
2406 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2407 ".omp_offloading.device_images");
2408 DeviceImages->setUnnamedAddr(true);
2409
2410 // This is a Zero array to be used in the creation of the constant expressions
2411 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2412 llvm::Constant::getNullValue(CGM.Int32Ty)};
2413
2414 // Create the target region descriptor.
2415 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2416 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2417 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2418 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2419 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2420 Index),
2421 HostEntriesBegin, HostEntriesEnd, nullptr);
2422
2423 auto *Desc = new llvm::GlobalVariable(
2424 M, BinaryDescriptorTy, /*isConstant=*/true,
2425 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2426 ".omp_offloading.descriptor");
2427
2428 // Emit code to register or unregister the descriptor at execution
2429 // startup or closing, respectively.
2430
2431 // Create a variable to drive the registration and unregistration of the
2432 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2433 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2434 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2435 IdentInfo, C.CharTy);
2436
2437 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2438 CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2439 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2440 Desc);
2441 });
2442 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2443 CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2444 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2445 Desc);
2446 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2447 });
2448 return RegFn;
2449}
2450
Samuel Antao2de62b02016-02-13 23:35:10 +00002451void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2452 llvm::Constant *Addr, uint64_t Size) {
2453 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002454 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2455 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2456 llvm::LLVMContext &C = CGM.getModule().getContext();
2457 llvm::Module &M = CGM.getModule();
2458
2459 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002460 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002461
2462 // Create constant string with the name.
2463 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2464
2465 llvm::GlobalVariable *Str =
2466 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2467 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2468 ".omp_offloading.entry_name");
2469 Str->setUnnamedAddr(true);
2470 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2471
2472 // Create the entry struct.
2473 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2474 TgtOffloadEntryType, AddrPtr, StrPtr,
2475 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2476 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2477 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2478 EntryInit, ".omp_offloading.entry");
2479
2480 // The entry has to be created in the section the linker expects it to be.
2481 Entry->setSection(".omp_offloading.entries");
2482 // We can't have any padding between symbols, so we need to have 1-byte
2483 // alignment.
2484 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002485}
2486
2487void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2488 // Emit the offloading entries and metadata so that the device codegen side
2489 // can
2490 // easily figure out what to emit. The produced metadata looks like this:
2491 //
2492 // !omp_offload.info = !{!1, ...}
2493 //
2494 // Right now we only generate metadata for function that contain target
2495 // regions.
2496
2497 // If we do not have entries, we dont need to do anything.
2498 if (OffloadEntriesInfoManager.empty())
2499 return;
2500
2501 llvm::Module &M = CGM.getModule();
2502 llvm::LLVMContext &C = M.getContext();
2503 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2504 OrderedEntries(OffloadEntriesInfoManager.size());
2505
2506 // Create the offloading info metadata node.
2507 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2508
2509 // Auxiliar methods to create metadata values and strings.
2510 auto getMDInt = [&](unsigned v) {
2511 return llvm::ConstantAsMetadata::get(
2512 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2513 };
2514
2515 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2516
2517 // Create function that emits metadata for each target region entry;
2518 auto &&TargetRegionMetadataEmitter = [&](
2519 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002520 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2521 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2522 // Generate metadata for target regions. Each entry of this metadata
2523 // contains:
2524 // - Entry 0 -> Kind of this type of metadata (0).
2525 // - Entry 1 -> Device ID of the file where the entry was identified.
2526 // - Entry 2 -> File ID of the file where the entry was identified.
2527 // - Entry 3 -> Mangled name of the function where the entry was identified.
2528 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002529 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002530 // The first element of the metadata node is the kind.
2531 Ops.push_back(getMDInt(E.getKind()));
2532 Ops.push_back(getMDInt(DeviceID));
2533 Ops.push_back(getMDInt(FileID));
2534 Ops.push_back(getMDString(ParentName));
2535 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002536 Ops.push_back(getMDInt(E.getOrder()));
2537
2538 // Save this entry in the right position of the ordered entries array.
2539 OrderedEntries[E.getOrder()] = &E;
2540
2541 // Add metadata to the named metadata node.
2542 MD->addOperand(llvm::MDNode::get(C, Ops));
2543 };
2544
2545 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2546 TargetRegionMetadataEmitter);
2547
2548 for (auto *E : OrderedEntries) {
2549 assert(E && "All ordered entries must exist!");
2550 if (auto *CE =
2551 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2552 E)) {
2553 assert(CE->getID() && CE->getAddress() &&
2554 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002555 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002556 } else
2557 llvm_unreachable("Unsupported entry kind.");
2558 }
2559}
2560
2561/// \brief Loads all the offload entries information from the host IR
2562/// metadata.
2563void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2564 // If we are in target mode, load the metadata from the host IR. This code has
2565 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2566
2567 if (!CGM.getLangOpts().OpenMPIsDevice)
2568 return;
2569
2570 if (CGM.getLangOpts().OMPHostIRFile.empty())
2571 return;
2572
2573 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2574 if (Buf.getError())
2575 return;
2576
2577 llvm::LLVMContext C;
2578 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2579
2580 if (ME.getError())
2581 return;
2582
2583 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2584 if (!MD)
2585 return;
2586
2587 for (auto I : MD->operands()) {
2588 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2589
2590 auto getMDInt = [&](unsigned Idx) {
2591 llvm::ConstantAsMetadata *V =
2592 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2593 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2594 };
2595
2596 auto getMDString = [&](unsigned Idx) {
2597 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2598 return V->getString();
2599 };
2600
2601 switch (getMDInt(0)) {
2602 default:
2603 llvm_unreachable("Unexpected metadata!");
2604 break;
2605 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2606 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2607 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2608 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2609 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002610 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002611 break;
2612 }
2613 }
2614}
2615
Alexey Bataev62b63b12015-03-10 07:28:44 +00002616void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2617 if (!KmpRoutineEntryPtrTy) {
2618 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2619 auto &C = CGM.getContext();
2620 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2621 FunctionProtoType::ExtProtoInfo EPI;
2622 KmpRoutineEntryPtrQTy = C.getPointerType(
2623 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2624 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2625 }
2626}
2627
Alexey Bataevc71a4092015-09-11 10:29:41 +00002628static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2629 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002630 auto *Field = FieldDecl::Create(
2631 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2632 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2633 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2634 Field->setAccess(AS_public);
2635 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002636 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002637}
2638
Samuel Antaoee8fb302016-01-06 13:42:12 +00002639QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2640
2641 // Make sure the type of the entry is already created. This is the type we
2642 // have to create:
2643 // struct __tgt_offload_entry{
2644 // void *addr; // Pointer to the offload entry info.
2645 // // (function or global)
2646 // char *name; // Name of the function or global.
2647 // size_t size; // Size of the entry info (0 if it a function).
2648 // };
2649 if (TgtOffloadEntryQTy.isNull()) {
2650 ASTContext &C = CGM.getContext();
2651 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2652 RD->startDefinition();
2653 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2654 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2655 addFieldToRecordDecl(C, RD, C.getSizeType());
2656 RD->completeDefinition();
2657 TgtOffloadEntryQTy = C.getRecordType(RD);
2658 }
2659 return TgtOffloadEntryQTy;
2660}
2661
2662QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2663 // These are the types we need to build:
2664 // struct __tgt_device_image{
2665 // void *ImageStart; // Pointer to the target code start.
2666 // void *ImageEnd; // Pointer to the target code end.
2667 // // We also add the host entries to the device image, as it may be useful
2668 // // for the target runtime to have access to that information.
2669 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2670 // // the entries.
2671 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2672 // // entries (non inclusive).
2673 // };
2674 if (TgtDeviceImageQTy.isNull()) {
2675 ASTContext &C = CGM.getContext();
2676 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2677 RD->startDefinition();
2678 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2679 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2680 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2681 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2682 RD->completeDefinition();
2683 TgtDeviceImageQTy = C.getRecordType(RD);
2684 }
2685 return TgtDeviceImageQTy;
2686}
2687
2688QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2689 // struct __tgt_bin_desc{
2690 // int32_t NumDevices; // Number of devices supported.
2691 // __tgt_device_image *DeviceImages; // Arrays of device images
2692 // // (one per device).
2693 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2694 // // entries.
2695 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2696 // // entries (non inclusive).
2697 // };
2698 if (TgtBinaryDescriptorQTy.isNull()) {
2699 ASTContext &C = CGM.getContext();
2700 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2701 RD->startDefinition();
2702 addFieldToRecordDecl(
2703 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2704 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2705 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2706 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2707 RD->completeDefinition();
2708 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2709 }
2710 return TgtBinaryDescriptorQTy;
2711}
2712
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002713namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002714struct PrivateHelpersTy {
2715 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2716 const VarDecl *PrivateElemInit)
2717 : Original(Original), PrivateCopy(PrivateCopy),
2718 PrivateElemInit(PrivateElemInit) {}
2719 const VarDecl *Original;
2720 const VarDecl *PrivateCopy;
2721 const VarDecl *PrivateElemInit;
2722};
2723typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002724} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002725
Alexey Bataev9e034042015-05-05 04:05:12 +00002726static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002727createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002728 if (!Privates.empty()) {
2729 auto &C = CGM.getContext();
2730 // Build struct .kmp_privates_t. {
2731 // /* private vars */
2732 // };
2733 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2734 RD->startDefinition();
2735 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002736 auto *VD = Pair.second.Original;
2737 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002738 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002739 auto *FD = addFieldToRecordDecl(C, RD, Type);
2740 if (VD->hasAttrs()) {
2741 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2742 E(VD->getAttrs().end());
2743 I != E; ++I)
2744 FD->addAttr(*I);
2745 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002746 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002747 RD->completeDefinition();
2748 return RD;
2749 }
2750 return nullptr;
2751}
2752
Alexey Bataev9e034042015-05-05 04:05:12 +00002753static RecordDecl *
2754createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002755 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002756 auto &C = CGM.getContext();
2757 // Build struct kmp_task_t {
2758 // void * shareds;
2759 // kmp_routine_entry_t routine;
2760 // kmp_int32 part_id;
2761 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002762 // };
2763 auto *RD = C.buildImplicitRecord("kmp_task_t");
2764 RD->startDefinition();
2765 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2766 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2767 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2768 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002769 RD->completeDefinition();
2770 return RD;
2771}
2772
2773static RecordDecl *
2774createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002775 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002776 auto &C = CGM.getContext();
2777 // Build struct kmp_task_t_with_privates {
2778 // kmp_task_t task_data;
2779 // .kmp_privates_t. privates;
2780 // };
2781 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2782 RD->startDefinition();
2783 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002784 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2785 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2786 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002787 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002788 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002789}
2790
2791/// \brief Emit a proxy function which accepts kmp_task_t as the second
2792/// argument.
2793/// \code
2794/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002795/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2796/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002797/// return 0;
2798/// }
2799/// \endcode
2800static llvm::Value *
2801emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002802 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2803 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002804 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2805 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002806 auto &C = CGM.getContext();
2807 FunctionArgList Args;
2808 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2809 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002810 /*Id=*/nullptr,
2811 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002812 Args.push_back(&GtidArg);
2813 Args.push_back(&TaskTypeArg);
2814 FunctionType::ExtInfo Info;
2815 auto &TaskEntryFnInfo =
2816 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2817 /*isVariadic=*/false);
2818 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2819 auto *TaskEntry =
2820 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2821 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002822 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002823 CodeGenFunction CGF(CGM);
2824 CGF.disableDebugInfo();
2825 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2826
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002827 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2828 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002829 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002830 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002831 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2832 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2833 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002834 auto *KmpTaskTWithPrivatesQTyRD =
2835 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002836 LValue Base =
2837 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002838 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2839 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2840 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
2841 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
2842
2843 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
2844 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002845 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002846 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002847 CGF.ConvertTypeForMem(SharedsPtrTy));
2848
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002849 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
2850 llvm::Value *PrivatesParam;
2851 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
2852 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
2853 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002854 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002855 } else {
2856 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2857 }
2858
2859 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
2860 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002861 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2862 CGF.EmitStoreThroughLValue(
2863 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002864 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002865 CGF.FinishFunction();
2866 return TaskEntry;
2867}
2868
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002869static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2870 SourceLocation Loc,
2871 QualType KmpInt32Ty,
2872 QualType KmpTaskTWithPrivatesPtrQTy,
2873 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002874 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002875 FunctionArgList Args;
2876 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2877 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002878 /*Id=*/nullptr,
2879 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002880 Args.push_back(&GtidArg);
2881 Args.push_back(&TaskTypeArg);
2882 FunctionType::ExtInfo Info;
2883 auto &DestructorFnInfo =
2884 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2885 /*isVariadic=*/false);
2886 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2887 auto *DestructorFn =
2888 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2889 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002890 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
2891 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002892 CodeGenFunction CGF(CGM);
2893 CGF.disableDebugInfo();
2894 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
2895 Args);
2896
Alexey Bataev31300ed2016-02-04 11:27:03 +00002897 LValue Base = CGF.EmitLoadOfPointerLValue(
2898 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2899 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002900 auto *KmpTaskTWithPrivatesQTyRD =
2901 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2902 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002903 Base = CGF.EmitLValueForField(Base, *FI);
2904 for (auto *Field :
2905 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
2906 if (auto DtorKind = Field->getType().isDestructedType()) {
2907 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
2908 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
2909 }
2910 }
2911 CGF.FinishFunction();
2912 return DestructorFn;
2913}
2914
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002915/// \brief Emit a privates mapping function for correct handling of private and
2916/// firstprivate variables.
2917/// \code
2918/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
2919/// **noalias priv1,..., <tyn> **noalias privn) {
2920/// *priv1 = &.privates.priv1;
2921/// ...;
2922/// *privn = &.privates.privn;
2923/// }
2924/// \endcode
2925static llvm::Value *
2926emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00002927 ArrayRef<const Expr *> PrivateVars,
2928 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002929 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002930 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002931 auto &C = CGM.getContext();
2932 FunctionArgList Args;
2933 ImplicitParamDecl TaskPrivatesArg(
2934 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2935 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2936 Args.push_back(&TaskPrivatesArg);
2937 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2938 unsigned Counter = 1;
2939 for (auto *E: PrivateVars) {
2940 Args.push_back(ImplicitParamDecl::Create(
2941 C, /*DC=*/nullptr, Loc,
2942 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2943 .withConst()
2944 .withRestrict()));
2945 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2946 PrivateVarsPos[VD] = Counter;
2947 ++Counter;
2948 }
2949 for (auto *E : FirstprivateVars) {
2950 Args.push_back(ImplicitParamDecl::Create(
2951 C, /*DC=*/nullptr, Loc,
2952 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2953 .withConst()
2954 .withRestrict()));
2955 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2956 PrivateVarsPos[VD] = Counter;
2957 ++Counter;
2958 }
2959 FunctionType::ExtInfo Info;
2960 auto &TaskPrivatesMapFnInfo =
2961 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2962 /*isVariadic=*/false);
2963 auto *TaskPrivatesMapTy =
2964 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2965 auto *TaskPrivatesMap = llvm::Function::Create(
2966 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2967 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002968 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
2969 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00002970 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002971 CodeGenFunction CGF(CGM);
2972 CGF.disableDebugInfo();
2973 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2974 TaskPrivatesMapFnInfo, Args);
2975
2976 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00002977 LValue Base = CGF.EmitLoadOfPointerLValue(
2978 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
2979 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002980 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2981 Counter = 0;
2982 for (auto *Field : PrivatesQTyRD->fields()) {
2983 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2984 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00002985 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00002986 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
2987 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002988 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002989 ++Counter;
2990 }
2991 CGF.FinishFunction();
2992 return TaskPrivatesMap;
2993}
2994
Alexey Bataev9e034042015-05-05 04:05:12 +00002995static int array_pod_sort_comparator(const PrivateDataTy *P1,
2996 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002997 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2998}
2999
3000void CGOpenMPRuntime::emitTaskCall(
3001 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3002 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00003003 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003004 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3005 ArrayRef<const Expr *> PrivateCopies,
3006 ArrayRef<const Expr *> FirstprivateVars,
3007 ArrayRef<const Expr *> FirstprivateCopies,
3008 ArrayRef<const Expr *> FirstprivateInits,
3009 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003010 if (!CGF.HaveInsertPoint())
3011 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003012 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00003013 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003014 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003015 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003016 for (auto *E : PrivateVars) {
3017 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3018 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003019 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003020 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3021 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003022 ++I;
3023 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003024 I = FirstprivateCopies.begin();
3025 auto IElemInitRef = FirstprivateInits.begin();
3026 for (auto *E : FirstprivateVars) {
3027 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3028 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003029 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003030 PrivateHelpersTy(
3031 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3032 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003033 ++I;
3034 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003035 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003036 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3037 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003038 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3039 // Build type kmp_routine_entry_t (if not built yet).
3040 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003041 // Build type kmp_task_t (if not built yet).
3042 if (KmpTaskTQTy.isNull()) {
3043 KmpTaskTQTy = C.getRecordType(
3044 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
3045 }
3046 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003047 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003048 auto *KmpTaskTWithPrivatesQTyRD =
3049 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3050 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3051 QualType KmpTaskTWithPrivatesPtrQTy =
3052 C.getPointerType(KmpTaskTWithPrivatesQTy);
3053 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3054 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003055 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003056 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3057
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003058 // Emit initial values for private copies (if any).
3059 llvm::Value *TaskPrivatesMap = nullptr;
3060 auto *TaskPrivatesMapTy =
3061 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3062 3)
3063 ->getType();
3064 if (!Privates.empty()) {
3065 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3066 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3067 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3068 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3069 TaskPrivatesMap, TaskPrivatesMapTy);
3070 } else {
3071 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3072 cast<llvm::PointerType>(TaskPrivatesMapTy));
3073 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003074 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3075 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003076 auto *TaskEntry = emitProxyTaskFunction(
3077 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003078 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003079
3080 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3081 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3082 // kmp_routine_entry_t *task_entry);
3083 // Task flags. Format is taken from
3084 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3085 // description of kmp_tasking_flags struct.
3086 const unsigned TiedFlag = 0x1;
3087 const unsigned FinalFlag = 0x2;
3088 unsigned Flags = Tied ? TiedFlag : 0;
3089 auto *TaskFlags =
3090 Final.getPointer()
3091 ? CGF.Builder.CreateSelect(Final.getPointer(),
3092 CGF.Builder.getInt32(FinalFlag),
3093 CGF.Builder.getInt32(/*C=*/0))
3094 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3095 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003096 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003097 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3098 getThreadID(CGF, Loc), TaskFlags,
3099 KmpTaskTWithPrivatesTySize, SharedsSize,
3100 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3101 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003102 auto *NewTask = CGF.EmitRuntimeCall(
3103 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003104 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3105 NewTask, KmpTaskTWithPrivatesPtrTy);
3106 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3107 KmpTaskTWithPrivatesQTy);
3108 LValue TDBase =
3109 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003110 // Fill the data in the resulting kmp_task_t record.
3111 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003112 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003113 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003114 KmpTaskSharedsPtr =
3115 Address(CGF.EmitLoadOfScalar(
3116 CGF.EmitLValueForField(
3117 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3118 KmpTaskTShareds)),
3119 Loc),
3120 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003121 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003122 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003123 // Emit initial values for private copies (if any).
3124 bool NeedsCleanup = false;
3125 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003126 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3127 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003128 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003129 LValue SharedsBase;
3130 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003131 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003132 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3133 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3134 SharedsTy);
3135 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003136 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3137 cast<CapturedStmt>(*D.getAssociatedStmt()));
3138 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003139 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003140 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003141 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003142 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003143 if (auto *Elem = Pair.second.PrivateElemInit) {
3144 auto *OriginalVD = Pair.second.Original;
3145 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3146 auto SharedRefLValue =
3147 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003148 SharedRefLValue = CGF.MakeAddrLValue(
3149 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3150 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003151 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003152 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003153 // Initialize firstprivate array.
3154 if (!isa<CXXConstructExpr>(Init) ||
3155 CGF.isTrivialInitializer(Init)) {
3156 // Perform simple memcpy.
3157 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003158 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003159 } else {
3160 // Initialize firstprivate array using element-by-element
3161 // intialization.
3162 CGF.EmitOMPAggregateAssign(
3163 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003164 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003165 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003166 // Clean up any temporaries needed by the initialization.
3167 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003168 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003169 return SrcElement;
3170 });
3171 (void)InitScope.Privatize();
3172 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003173 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3174 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003175 CGF.EmitAnyExprToMem(Init, DestElement,
3176 Init->getType().getQualifiers(),
3177 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003178 });
3179 }
3180 } else {
3181 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003182 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003183 return SharedRefLValue.getAddress();
3184 });
3185 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003186 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003187 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3188 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003189 }
3190 } else {
3191 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3192 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003193 }
3194 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003195 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003196 }
3197 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003198 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003199 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003200 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3201 KmpTaskTWithPrivatesPtrQTy,
3202 KmpTaskTWithPrivatesQTy)
3203 : llvm::ConstantPointerNull::get(
3204 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3205 LValue Destructor = CGF.EmitLValueForField(
3206 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3207 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3208 DestructorFn, KmpRoutineEntryPtrTy),
3209 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003210
3211 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003212 Address DependenciesArray = Address::invalid();
3213 unsigned NumDependencies = Dependences.size();
3214 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003215 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003216 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003217 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3218 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003219 QualType FlagsTy =
3220 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003221 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3222 if (KmpDependInfoTy.isNull()) {
3223 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3224 KmpDependInfoRD->startDefinition();
3225 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3226 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3227 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3228 KmpDependInfoRD->completeDefinition();
3229 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3230 } else {
3231 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3232 }
John McCall7f416cc2015-09-08 08:05:57 +00003233 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003234 // Define type kmp_depend_info[<Dependences.size()>];
3235 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003236 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003237 ArrayType::Normal, /*IndexTypeQuals=*/0);
3238 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00003239 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
3240 for (unsigned i = 0; i < NumDependencies; ++i) {
3241 const Expr *E = Dependences[i].second;
3242 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003243 llvm::Value *Size;
3244 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003245 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3246 LValue UpAddrLVal =
3247 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3248 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003249 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003250 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003251 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003252 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3253 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003254 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003255 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003256 auto Base = CGF.MakeAddrLValue(
3257 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003258 KmpDependInfoTy);
3259 // deps[i].base_addr = &<Dependences[i].second>;
3260 auto BaseAddrLVal = CGF.EmitLValueForField(
3261 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003262 CGF.EmitStoreOfScalar(
3263 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3264 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003265 // deps[i].len = sizeof(<Dependences[i].second>);
3266 auto LenLVal = CGF.EmitLValueForField(
3267 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3268 CGF.EmitStoreOfScalar(Size, LenLVal);
3269 // deps[i].flags = <Dependences[i].first>;
3270 RTLDependenceKindTy DepKind;
3271 switch (Dependences[i].first) {
3272 case OMPC_DEPEND_in:
3273 DepKind = DepIn;
3274 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003275 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003276 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003277 case OMPC_DEPEND_inout:
3278 DepKind = DepInOut;
3279 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003280 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003281 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003282 case OMPC_DEPEND_unknown:
3283 llvm_unreachable("Unknown task dependence type");
3284 }
3285 auto FlagsLVal = CGF.EmitLValueForField(
3286 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3287 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3288 FlagsLVal);
3289 }
John McCall7f416cc2015-09-08 08:05:57 +00003290 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3291 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003292 CGF.VoidPtrTy);
3293 }
3294
Alexey Bataev62b63b12015-03-10 07:28:44 +00003295 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3296 // libcall.
3297 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3298 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003299 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3300 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3301 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3302 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003303 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003304 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003305 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3306 llvm::Value *DepTaskArgs[7];
3307 if (NumDependencies) {
3308 DepTaskArgs[0] = UpLoc;
3309 DepTaskArgs[1] = ThreadID;
3310 DepTaskArgs[2] = NewTask;
3311 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3312 DepTaskArgs[4] = DependenciesArray.getPointer();
3313 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3314 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3315 }
3316 auto &&ThenCodeGen = [this, NumDependencies,
3317 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3318 // TODO: add check for untied tasks.
3319 if (NumDependencies) {
3320 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3321 DepTaskArgs);
3322 } else {
3323 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3324 TaskArgs);
3325 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003326 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003327 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3328 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00003329
3330 llvm::Value *DepWaitTaskArgs[6];
3331 if (NumDependencies) {
3332 DepWaitTaskArgs[0] = UpLoc;
3333 DepWaitTaskArgs[1] = ThreadID;
3334 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3335 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3336 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3337 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3338 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003339 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00003340 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003341 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3342 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3343 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3344 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3345 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003346 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003347 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3348 DepWaitTaskArgs);
3349 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3350 // kmp_task_t *new_task);
3351 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3352 TaskArgs);
3353 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3354 // kmp_task_t *new_task);
3355 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3356 NormalAndEHCleanup,
3357 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3358 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00003359
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003360 // Call proxy_task_entry(gtid, new_task);
3361 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3362 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3363 };
John McCall7f416cc2015-09-08 08:05:57 +00003364
Alexey Bataev1d677132015-04-22 13:57:31 +00003365 if (IfCond) {
3366 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3367 } else {
3368 CodeGenFunction::RunCleanupsScope Scope(CGF);
3369 ThenCodeGen(CGF);
3370 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003371}
3372
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003373/// \brief Emit reduction operation for each element of array (required for
3374/// array sections) LHS op = RHS.
3375/// \param Type Type of array.
3376/// \param LHSVar Variable on the left side of the reduction operation
3377/// (references element of array in original variable).
3378/// \param RHSVar Variable on the right side of the reduction operation
3379/// (references element of array in original variable).
3380/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3381/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003382static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003383 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3384 const VarDecl *RHSVar,
3385 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3386 const Expr *, const Expr *)> &RedOpGen,
3387 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3388 const Expr *UpExpr = nullptr) {
3389 // Perform element-by-element initialization.
3390 QualType ElementTy;
3391 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3392 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3393
3394 // Drill down to the base element type on both arrays.
3395 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3396 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3397
3398 auto RHSBegin = RHSAddr.getPointer();
3399 auto LHSBegin = LHSAddr.getPointer();
3400 // Cast from pointer to array type to pointer to single element.
3401 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3402 // The basic structure here is a while-do loop.
3403 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3404 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3405 auto IsEmpty =
3406 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3407 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3408
3409 // Enter the loop body, making that address the current address.
3410 auto EntryBB = CGF.Builder.GetInsertBlock();
3411 CGF.EmitBlock(BodyBB);
3412
3413 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3414
3415 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3416 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3417 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3418 Address RHSElementCurrent =
3419 Address(RHSElementPHI,
3420 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3421
3422 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3423 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3424 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3425 Address LHSElementCurrent =
3426 Address(LHSElementPHI,
3427 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3428
3429 // Emit copy.
3430 CodeGenFunction::OMPPrivateScope Scope(CGF);
3431 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3432 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3433 Scope.Privatize();
3434 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3435 Scope.ForceCleanup();
3436
3437 // Shift the address forward by one element.
3438 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3439 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3440 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3441 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3442 // Check whether we've reached the end.
3443 auto Done =
3444 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3445 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3446 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3447 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3448
3449 // Done.
3450 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3451}
3452
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003453static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3454 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003455 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003456 ArrayRef<const Expr *> LHSExprs,
3457 ArrayRef<const Expr *> RHSExprs,
3458 ArrayRef<const Expr *> ReductionOps) {
3459 auto &C = CGM.getContext();
3460
3461 // void reduction_func(void *LHSArg, void *RHSArg);
3462 FunctionArgList Args;
3463 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3464 C.VoidPtrTy);
3465 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3466 C.VoidPtrTy);
3467 Args.push_back(&LHSArg);
3468 Args.push_back(&RHSArg);
3469 FunctionType::ExtInfo EI;
3470 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3471 C.VoidTy, Args, EI, /*isVariadic=*/false);
3472 auto *Fn = llvm::Function::Create(
3473 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3474 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003475 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003476 CodeGenFunction CGF(CGM);
3477 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3478
3479 // Dst = (void*[n])(LHSArg);
3480 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003481 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3482 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3483 ArgsType), CGF.getPointerAlign());
3484 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3485 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3486 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003487
3488 // ...
3489 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3490 // ...
3491 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003492 auto IPriv = Privates.begin();
3493 unsigned Idx = 0;
3494 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003495 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3496 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003497 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003498 });
3499 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3500 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003501 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003502 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003503 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003504 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003505 // Get array size and emit VLA type.
3506 ++Idx;
3507 Address Elem =
3508 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3509 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003510 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3511 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003512 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003513 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003514 CGF.EmitVariablyModifiedType(PrivTy);
3515 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003516 }
3517 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003518 IPriv = Privates.begin();
3519 auto ILHS = LHSExprs.begin();
3520 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003521 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003522 if ((*IPriv)->getType()->isArrayType()) {
3523 // Emit reduction for array section.
3524 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3525 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3526 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3527 [=](CodeGenFunction &CGF, const Expr *,
3528 const Expr *,
3529 const Expr *) { CGF.EmitIgnoredExpr(E); });
3530 } else
3531 // Emit reduction for array subscript or single variable.
3532 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003533 ++IPriv;
3534 ++ILHS;
3535 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003536 }
3537 Scope.ForceCleanup();
3538 CGF.FinishFunction();
3539 return Fn;
3540}
3541
3542void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003543 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003544 ArrayRef<const Expr *> LHSExprs,
3545 ArrayRef<const Expr *> RHSExprs,
3546 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003547 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003548 if (!CGF.HaveInsertPoint())
3549 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003550 // Next code should be emitted for reduction:
3551 //
3552 // static kmp_critical_name lock = { 0 };
3553 //
3554 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3555 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3556 // ...
3557 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3558 // *(Type<n>-1*)rhs[<n>-1]);
3559 // }
3560 //
3561 // ...
3562 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3563 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3564 // RedList, reduce_func, &<lock>)) {
3565 // case 1:
3566 // ...
3567 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3568 // ...
3569 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3570 // break;
3571 // case 2:
3572 // ...
3573 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3574 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003575 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003576 // break;
3577 // default:;
3578 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003579 //
3580 // if SimpleReduction is true, only the next code is generated:
3581 // ...
3582 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3583 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003584
3585 auto &C = CGM.getContext();
3586
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003587 if (SimpleReduction) {
3588 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003589 auto IPriv = Privates.begin();
3590 auto ILHS = LHSExprs.begin();
3591 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003592 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003593 if ((*IPriv)->getType()->isArrayType()) {
3594 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3595 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3596 EmitOMPAggregateReduction(
3597 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3598 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3599 const Expr *) { CGF.EmitIgnoredExpr(E); });
3600 } else
3601 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003602 ++IPriv;
3603 ++ILHS;
3604 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003605 }
3606 return;
3607 }
3608
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003609 // 1. Build a list of reduction variables.
3610 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003611 auto Size = RHSExprs.size();
3612 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003613 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003614 // Reserve place for array size.
3615 ++Size;
3616 }
3617 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003618 QualType ReductionArrayTy =
3619 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3620 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003621 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003622 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003623 auto IPriv = Privates.begin();
3624 unsigned Idx = 0;
3625 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003626 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003627 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003628 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003629 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003630 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3631 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003632 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003633 // Store array size.
3634 ++Idx;
3635 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3636 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003637 llvm::Value *Size = CGF.Builder.CreateIntCast(
3638 CGF.getVLASize(
3639 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3640 .first,
3641 CGF.SizeTy, /*isSigned=*/false);
3642 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3643 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003644 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003645 }
3646
3647 // 2. Emit reduce_func().
3648 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003649 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3650 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003651
3652 // 3. Create static kmp_critical_name lock = { 0 };
3653 auto *Lock = getCriticalRegionLock(".reduction");
3654
3655 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3656 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003657 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003658 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003659 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003660 auto *RL =
3661 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3662 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003663 llvm::Value *Args[] = {
3664 IdentTLoc, // ident_t *<loc>
3665 ThreadId, // i32 <gtid>
3666 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3667 ReductionArrayTySize, // size_type sizeof(RedList)
3668 RL, // void *RedList
3669 ReductionFn, // void (*) (void *, void *) <reduce_func>
3670 Lock // kmp_critical_name *&<lock>
3671 };
3672 auto Res = CGF.EmitRuntimeCall(
3673 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3674 : OMPRTL__kmpc_reduce),
3675 Args);
3676
3677 // 5. Build switch(res)
3678 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3679 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3680
3681 // 6. Build case 1:
3682 // ...
3683 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3684 // ...
3685 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3686 // break;
3687 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3688 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3689 CGF.EmitBlock(Case1BB);
3690
3691 {
3692 CodeGenFunction::RunCleanupsScope Scope(CGF);
3693 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3694 llvm::Value *EndArgs[] = {
3695 IdentTLoc, // ident_t *<loc>
3696 ThreadId, // i32 <gtid>
3697 Lock // kmp_critical_name *&<lock>
3698 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003699 CGF.EHStack
3700 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3701 NormalAndEHCleanup,
3702 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3703 : OMPRTL__kmpc_end_reduce),
3704 llvm::makeArrayRef(EndArgs));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003705 auto IPriv = Privates.begin();
3706 auto ILHS = LHSExprs.begin();
3707 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003708 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003709 if ((*IPriv)->getType()->isArrayType()) {
3710 // Emit reduction for array section.
3711 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3712 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3713 EmitOMPAggregateReduction(
3714 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3715 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3716 const Expr *) { CGF.EmitIgnoredExpr(E); });
3717 } else
3718 // Emit reduction for array subscript or single variable.
3719 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003720 ++IPriv;
3721 ++ILHS;
3722 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003723 }
3724 }
3725
3726 CGF.EmitBranch(DefaultBB);
3727
3728 // 7. Build case 2:
3729 // ...
3730 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3731 // ...
3732 // break;
3733 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3734 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3735 CGF.EmitBlock(Case2BB);
3736
3737 {
3738 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00003739 if (!WithNowait) {
3740 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3741 llvm::Value *EndArgs[] = {
3742 IdentTLoc, // ident_t *<loc>
3743 ThreadId, // i32 <gtid>
3744 Lock // kmp_critical_name *&<lock>
3745 };
3746 CGF.EHStack
3747 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3748 NormalAndEHCleanup,
3749 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3750 llvm::makeArrayRef(EndArgs));
3751 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003752 auto ILHS = LHSExprs.begin();
3753 auto IRHS = RHSExprs.begin();
3754 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003755 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003756 const Expr *XExpr = nullptr;
3757 const Expr *EExpr = nullptr;
3758 const Expr *UpExpr = nullptr;
3759 BinaryOperatorKind BO = BO_Comma;
3760 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3761 if (BO->getOpcode() == BO_Assign) {
3762 XExpr = BO->getLHS();
3763 UpExpr = BO->getRHS();
3764 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003765 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003766 // Try to emit update expression as a simple atomic.
3767 auto *RHSExpr = UpExpr;
3768 if (RHSExpr) {
3769 // Analyze RHS part of the whole expression.
3770 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3771 RHSExpr->IgnoreParenImpCasts())) {
3772 // If this is a conditional operator, analyze its condition for
3773 // min/max reduction operator.
3774 RHSExpr = ACO->getCond();
3775 }
3776 if (auto *BORHS =
3777 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3778 EExpr = BORHS->getRHS();
3779 BO = BORHS->getOpcode();
3780 }
Alexey Bataev69a47792015-05-07 03:54:03 +00003781 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003782 if (XExpr) {
3783 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3784 auto &&AtomicRedGen = [this, BO, VD, IPriv,
3785 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3786 const Expr *EExpr, const Expr *UpExpr) {
3787 LValue X = CGF.EmitLValue(XExpr);
3788 RValue E;
3789 if (EExpr)
3790 E = CGF.EmitAnyExpr(EExpr);
3791 CGF.EmitOMPAtomicSimpleUpdateExpr(
3792 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
Alexey Bataev8524d152016-01-21 12:35:58 +00003793 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003794 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev8524d152016-01-21 12:35:58 +00003795 PrivateScope.addPrivate(
3796 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3797 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3798 CGF.emitOMPSimpleStore(
3799 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3800 VD->getType().getNonReferenceType(), Loc);
3801 return LHSTemp;
3802 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003803 (void)PrivateScope.Privatize();
3804 return CGF.EmitAnyExpr(UpExpr);
3805 });
3806 };
3807 if ((*IPriv)->getType()->isArrayType()) {
3808 // Emit atomic reduction for array section.
3809 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3810 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3811 AtomicRedGen, XExpr, EExpr, UpExpr);
3812 } else
3813 // Emit atomic reduction for array subscript or single variable.
3814 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3815 } else {
3816 // Emit as a critical region.
3817 auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3818 const Expr *, const Expr *) {
3819 emitCriticalRegion(
3820 CGF, ".atomic_reduction",
3821 [E](CodeGenFunction &CGF) { CGF.EmitIgnoredExpr(E); }, Loc);
3822 };
3823 if ((*IPriv)->getType()->isArrayType()) {
3824 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3825 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3826 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3827 CritRedGen);
3828 } else
3829 CritRedGen(CGF, nullptr, nullptr, nullptr);
3830 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003831 ++ILHS;
3832 ++IRHS;
3833 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003834 }
3835 }
3836
3837 CGF.EmitBranch(DefaultBB);
3838 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3839}
3840
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003841void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
3842 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003843 if (!CGF.HaveInsertPoint())
3844 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003845 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
3846 // global_tid);
3847 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3848 // Ignore return result until untied tasks are supported.
3849 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
3850}
3851
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003852void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003853 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003854 const RegionCodeGenTy &CodeGen,
3855 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003856 if (!CGF.HaveInsertPoint())
3857 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003858 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003859 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00003860}
3861
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003862namespace {
3863enum RTCancelKind {
3864 CancelNoreq = 0,
3865 CancelParallel = 1,
3866 CancelLoop = 2,
3867 CancelSections = 3,
3868 CancelTaskgroup = 4
3869};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003870} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003871
3872static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
3873 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00003874 if (CancelRegion == OMPD_parallel)
3875 CancelKind = CancelParallel;
3876 else if (CancelRegion == OMPD_for)
3877 CancelKind = CancelLoop;
3878 else if (CancelRegion == OMPD_sections)
3879 CancelKind = CancelSections;
3880 else {
3881 assert(CancelRegion == OMPD_taskgroup);
3882 CancelKind = CancelTaskgroup;
3883 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003884 return CancelKind;
3885}
3886
3887void CGOpenMPRuntime::emitCancellationPointCall(
3888 CodeGenFunction &CGF, SourceLocation Loc,
3889 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003890 if (!CGF.HaveInsertPoint())
3891 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003892 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
3893 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003894 if (auto *OMPRegionInfo =
3895 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003896 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003897 llvm::Value *Args[] = {
3898 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3899 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003900 // Ignore return result until untied tasks are supported.
3901 auto *Result = CGF.EmitRuntimeCall(
3902 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
3903 // if (__kmpc_cancellationpoint()) {
3904 // __kmpc_cancel_barrier();
3905 // exit from construct;
3906 // }
3907 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3908 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3909 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3910 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3911 CGF.EmitBlock(ExitBB);
3912 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003913 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003914 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003915 auto CancelDest =
3916 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003917 CGF.EmitBranchThroughCleanup(CancelDest);
3918 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3919 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003920 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003921}
3922
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003923void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00003924 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003925 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003926 if (!CGF.HaveInsertPoint())
3927 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003928 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
3929 // kmp_int32 cncl_kind);
3930 if (auto *OMPRegionInfo =
3931 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003932 auto &&ThenGen = [this, Loc, CancelRegion,
3933 OMPRegionInfo](CodeGenFunction &CGF) {
3934 llvm::Value *Args[] = {
3935 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3936 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
3937 // Ignore return result until untied tasks are supported.
3938 auto *Result =
3939 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
3940 // if (__kmpc_cancel()) {
3941 // __kmpc_cancel_barrier();
3942 // exit from construct;
3943 // }
3944 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3945 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3946 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3947 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3948 CGF.EmitBlock(ExitBB);
3949 // __kmpc_cancel_barrier();
3950 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
3951 // exit from construct;
3952 auto CancelDest =
3953 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3954 CGF.EmitBranchThroughCleanup(CancelDest);
3955 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3956 };
3957 if (IfCond)
3958 emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
3959 else
3960 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003961 }
3962}
Samuel Antaobed3c462015-10-02 16:14:20 +00003963
Samuel Antaoee8fb302016-01-06 13:42:12 +00003964/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00003965/// consists of the file and device IDs as well as line number associated with
3966/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003967static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
3968 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00003969 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003970
3971 auto &SM = C.getSourceManager();
3972
3973 // The loc should be always valid and have a file ID (the user cannot use
3974 // #pragma directives in macros)
3975
3976 assert(Loc.isValid() && "Source location is expected to be always valid.");
3977 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
3978
3979 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3980 assert(PLoc.isValid() && "Source location is expected to be always valid.");
3981
3982 llvm::sys::fs::UniqueID ID;
3983 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
3984 llvm_unreachable("Source file with target region no longer exists!");
3985
3986 DeviceID = ID.getDevice();
3987 FileID = ID.getFile();
3988 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003989}
3990
3991void CGOpenMPRuntime::emitTargetOutlinedFunction(
3992 const OMPExecutableDirective &D, StringRef ParentName,
3993 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
3994 bool IsOffloadEntry) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003995 assert(!ParentName.empty() && "Invalid target region parent name!");
3996
Samuel Antaobed3c462015-10-02 16:14:20 +00003997 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
3998
Samuel Antaoee8fb302016-01-06 13:42:12 +00003999 // Emit target region as a standalone region.
4000 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
4001 CGF.EmitStmt(CS.getCapturedStmt());
4002 };
4003
Samuel Antao2de62b02016-02-13 23:35:10 +00004004 // Create a unique name for the entry function using the source location
4005 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004006 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004007 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004008 //
4009 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004010 // mangled name of the function that encloses the target region and BB is the
4011 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004012
4013 unsigned DeviceID;
4014 unsigned FileID;
4015 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004016 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004017 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004018 SmallString<64> EntryFnName;
4019 {
4020 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004021 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4022 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004023 }
4024
Samuel Antaobed3c462015-10-02 16:14:20 +00004025 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004026 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004027 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004028
4029 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4030
4031 // If this target outline function is not an offload entry, we don't need to
4032 // register it.
4033 if (!IsOffloadEntry)
4034 return;
4035
4036 // The target region ID is used by the runtime library to identify the current
4037 // target region, so it only has to be unique and not necessarily point to
4038 // anything. It could be the pointer to the outlined function that implements
4039 // the target region, but we aren't using that so that the compiler doesn't
4040 // need to keep that, and could therefore inline the host function if proven
4041 // worthwhile during optimization. In the other hand, if emitting code for the
4042 // device, the ID has to be the function address so that it can retrieved from
4043 // the offloading entry and launched by the runtime library. We also mark the
4044 // outlined function to have external linkage in case we are emitting code for
4045 // the device, because these functions will be entry points to the device.
4046
4047 if (CGM.getLangOpts().OpenMPIsDevice) {
4048 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4049 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4050 } else
4051 OutlinedFnID = new llvm::GlobalVariable(
4052 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4053 llvm::GlobalValue::PrivateLinkage,
4054 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4055
4056 // Register the information for the entry associated with this target region.
4057 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004058 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004059}
4060
Samuel Antaob68e2db2016-03-03 16:20:23 +00004061/// \brief Emit the num_teams clause of an enclosed teams directive at the
4062/// target region scope. If there is no teams directive associated with the
4063/// target directive, or if there is no num_teams clause associated with the
4064/// enclosed teams directive, return nullptr.
4065static llvm::Value *
4066emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4067 CodeGenFunction &CGF,
4068 const OMPExecutableDirective &D) {
4069
4070 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4071 "teams directive expected to be "
4072 "emitted only for the host!");
4073
4074 // FIXME: For the moment we do not support combined directives with target and
4075 // teams, so we do not expect to get any num_teams clause in the provided
4076 // directive. Once we support that, this assertion can be replaced by the
4077 // actual emission of the clause expression.
4078 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4079 "Not expecting clause in directive.");
4080
4081 // If the current target region has a teams region enclosed, we need to get
4082 // the number of teams to pass to the runtime function call. This is done
4083 // by generating the expression in a inlined region. This is required because
4084 // the expression is captured in the enclosing target environment when the
4085 // teams directive is not combined with target.
4086
4087 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4088
4089 // FIXME: Accommodate other combined directives with teams when they become
4090 // available.
4091 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4092 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4093 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4094 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4095 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4096 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4097 /*IsSigned=*/true);
4098 }
4099
4100 // If we have an enclosed teams directive but no num_teams clause we use
4101 // the default value 0.
4102 return CGF.Builder.getInt32(0);
4103 }
4104
4105 // No teams associated with the directive.
4106 return nullptr;
4107}
4108
4109/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4110/// target region scope. If there is no teams directive associated with the
4111/// target directive, or if there is no thread_limit clause associated with the
4112/// enclosed teams directive, return nullptr.
4113static llvm::Value *
4114emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4115 CodeGenFunction &CGF,
4116 const OMPExecutableDirective &D) {
4117
4118 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4119 "teams directive expected to be "
4120 "emitted only for the host!");
4121
4122 // FIXME: For the moment we do not support combined directives with target and
4123 // teams, so we do not expect to get any thread_limit clause in the provided
4124 // directive. Once we support that, this assertion can be replaced by the
4125 // actual emission of the clause expression.
4126 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4127 "Not expecting clause in directive.");
4128
4129 // If the current target region has a teams region enclosed, we need to get
4130 // the thread limit to pass to the runtime function call. This is done
4131 // by generating the expression in a inlined region. This is required because
4132 // the expression is captured in the enclosing target environment when the
4133 // teams directive is not combined with target.
4134
4135 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4136
4137 // FIXME: Accommodate other combined directives with teams when they become
4138 // available.
4139 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4140 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4141 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4142 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4143 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4144 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4145 /*IsSigned=*/true);
4146 }
4147
4148 // If we have an enclosed teams directive but no thread_limit clause we use
4149 // the default value 0.
4150 return CGF.Builder.getInt32(0);
4151 }
4152
4153 // No teams associated with the directive.
4154 return nullptr;
4155}
4156
Samuel Antaobed3c462015-10-02 16:14:20 +00004157void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
4158 const OMPExecutableDirective &D,
4159 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004160 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00004161 const Expr *IfCond, const Expr *Device,
4162 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004163 if (!CGF.HaveInsertPoint())
4164 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00004165 /// \brief Values for bit flags used to specify the mapping type for
4166 /// offloading.
4167 enum OpenMPOffloadMappingFlags {
4168 /// \brief Allocate memory on the device and move data from host to device.
4169 OMP_MAP_TO = 0x01,
4170 /// \brief Allocate memory on the device and move data from device to host.
4171 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004172 /// \brief The element passed to the device is a pointer.
4173 OMP_MAP_PTR = 0x20,
4174 /// \brief Pass the element to the device by value.
4175 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00004176 };
4177
4178 enum OpenMPOffloadingReservedDeviceIDs {
4179 /// \brief Device ID if the device was not defined, runtime should get it
4180 /// from environment variables in the spec.
4181 OMP_DEVICEID_UNDEF = -1,
4182 };
4183
Samuel Antaoee8fb302016-01-06 13:42:12 +00004184 assert(OutlinedFn && "Invalid outlined function!");
4185
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004186 auto &Ctx = CGF.getContext();
4187
Samuel Antaobed3c462015-10-02 16:14:20 +00004188 // Fill up the arrays with the all the captured variables.
4189 SmallVector<llvm::Value *, 16> BasePointers;
4190 SmallVector<llvm::Value *, 16> Pointers;
4191 SmallVector<llvm::Value *, 16> Sizes;
4192 SmallVector<unsigned, 16> MapTypes;
4193
4194 bool hasVLACaptures = false;
4195
4196 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4197 auto RI = CS.getCapturedRecordDecl()->field_begin();
4198 // auto II = CS.capture_init_begin();
4199 auto CV = CapturedVars.begin();
4200 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
4201 CE = CS.capture_end();
4202 CI != CE; ++CI, ++RI, ++CV) {
4203 StringRef Name;
4204 QualType Ty;
4205 llvm::Value *BasePointer;
4206 llvm::Value *Pointer;
4207 llvm::Value *Size;
4208 unsigned MapType;
4209
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004210 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00004211 if (CI->capturesVariableArrayType()) {
4212 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00004213 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004214 // Copy to the device as an argument. No need to retrieve it.
4215 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00004216 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00004217 } else if (CI->capturesThis()) {
4218 BasePointer = Pointer = *CV;
4219 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004220 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004221 // Default map type.
4222 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004223 } else if (CI->capturesVariableByCopy()) {
4224 MapType = OMP_MAP_BYCOPY;
4225 if (!RI->getType()->isAnyPointerType()) {
4226 // If the field is not a pointer, we need to save the actual value and
4227 // load it as a void pointer.
4228 auto DstAddr = CGF.CreateMemTemp(
4229 Ctx.getUIntPtrType(),
4230 Twine(CI->getCapturedVar()->getName()) + ".casted");
4231 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
4232
4233 auto *SrcAddrVal = CGF.EmitScalarConversion(
4234 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
4235 Ctx.getPointerType(RI->getType()), SourceLocation());
4236 LValue SrcLV =
4237 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
4238
4239 // Store the value using the source type pointer.
4240 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
4241
4242 // Load the value using the destination type pointer.
4243 BasePointer = Pointer =
4244 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
4245 } else {
4246 MapType |= OMP_MAP_PTR;
4247 BasePointer = Pointer = *CV;
4248 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00004249 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004250 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004251 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00004252 BasePointer = Pointer = *CV;
4253
4254 const ReferenceType *PtrTy =
4255 cast<ReferenceType>(RI->getType().getTypePtr());
4256 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004257 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004258 // The default map type for a scalar/complex type is 'to' because by
4259 // default the value doesn't have to be retrieved. For an aggregate type,
4260 // the default is 'tofrom'.
4261 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
4262 : OMP_MAP_TO;
4263 if (ElementType->isAnyPointerType())
4264 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00004265 }
4266
4267 BasePointers.push_back(BasePointer);
4268 Pointers.push_back(Pointer);
4269 Sizes.push_back(Size);
4270 MapTypes.push_back(MapType);
4271 }
4272
4273 // Keep track on whether the host function has to be executed.
4274 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004275 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004276 auto OffloadError = CGF.MakeAddrLValue(
4277 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
4278 OffloadErrorQType);
4279 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
4280 OffloadError);
4281
4282 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004283 auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004284 hasVLACaptures, Device, OutlinedFnID, OffloadError,
Samuel Antaob68e2db2016-03-03 16:20:23 +00004285 OffloadErrorQType, &D](CodeGenFunction &CGF) {
Samuel Antaobed3c462015-10-02 16:14:20 +00004286 unsigned PointerNumVal = BasePointers.size();
4287 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
4288 llvm::Value *BasePointersArray;
4289 llvm::Value *PointersArray;
4290 llvm::Value *SizesArray;
4291 llvm::Value *MapTypesArray;
4292
4293 if (PointerNumVal) {
4294 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004295 QualType PointerArrayType = Ctx.getConstantArrayType(
4296 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004297 /*IndexTypeQuals=*/0);
4298
4299 BasePointersArray =
4300 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
4301 PointersArray =
4302 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
4303
4304 // If we don't have any VLA types, we can use a constant array for the map
4305 // sizes, otherwise we need to fill up the arrays as we do for the
4306 // pointers.
4307 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004308 QualType SizeArrayType = Ctx.getConstantArrayType(
4309 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004310 /*IndexTypeQuals=*/0);
4311 SizesArray =
4312 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
4313 } else {
4314 // We expect all the sizes to be constant, so we collect them to create
4315 // a constant array.
4316 SmallVector<llvm::Constant *, 16> ConstSizes;
4317 for (auto S : Sizes)
4318 ConstSizes.push_back(cast<llvm::Constant>(S));
4319
4320 auto *SizesArrayInit = llvm::ConstantArray::get(
4321 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
4322 auto *SizesArrayGbl = new llvm::GlobalVariable(
4323 CGM.getModule(), SizesArrayInit->getType(),
4324 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4325 SizesArrayInit, ".offload_sizes");
4326 SizesArrayGbl->setUnnamedAddr(true);
4327 SizesArray = SizesArrayGbl;
4328 }
4329
4330 // The map types are always constant so we don't need to generate code to
4331 // fill arrays. Instead, we create an array constant.
4332 llvm::Constant *MapTypesArrayInit =
4333 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
4334 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
4335 CGM.getModule(), MapTypesArrayInit->getType(),
4336 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4337 MapTypesArrayInit, ".offload_maptypes");
4338 MapTypesArrayGbl->setUnnamedAddr(true);
4339 MapTypesArray = MapTypesArrayGbl;
4340
4341 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004342 llvm::Value *BPVal = BasePointers[i];
4343 if (BPVal->getType()->isPointerTy())
4344 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
4345 else {
4346 assert(BPVal->getType()->isIntegerTy() &&
4347 "If not a pointer, the value type must be an integer.");
4348 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
4349 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004350 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
4351 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
4352 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004353 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4354 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004355
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004356 llvm::Value *PVal = Pointers[i];
4357 if (PVal->getType()->isPointerTy())
4358 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
4359 else {
4360 assert(PVal->getType()->isIntegerTy() &&
4361 "If not a pointer, the value type must be an integer.");
4362 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
4363 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004364 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4365 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4366 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004367 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4368 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004369
4370 if (hasVLACaptures) {
4371 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4372 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4373 /*Idx0=*/0,
4374 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004375 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004376 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4377 Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4378 SAddr);
4379 }
4380 }
4381
4382 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4383 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4384 /*Idx0=*/0, /*Idx1=*/0);
4385 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4386 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4387 /*Idx0=*/0,
4388 /*Idx1=*/0);
4389 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4390 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4391 /*Idx0=*/0, /*Idx1=*/0);
4392 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4393 llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4394 /*Idx0=*/0,
4395 /*Idx1=*/0);
4396
4397 } else {
4398 BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4399 PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4400 SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4401 MapTypesArray =
4402 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4403 }
4404
4405 // On top of the arrays that were filled up, the target offloading call
4406 // takes as arguments the device id as well as the host pointer. The host
4407 // pointer is used by the runtime library to identify the current target
4408 // region, so it only has to be unique and not necessarily point to
4409 // anything. It could be the pointer to the outlined function that
4410 // implements the target region, but we aren't using that so that the
4411 // compiler doesn't need to keep that, and could therefore inline the host
4412 // function if proven worthwhile during optimization.
4413
Samuel Antaoee8fb302016-01-06 13:42:12 +00004414 // From this point on, we need to have an ID of the target region defined.
4415 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004416
4417 // Emit device ID if any.
4418 llvm::Value *DeviceID;
4419 if (Device)
4420 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4421 CGM.Int32Ty, /*isSigned=*/true);
4422 else
4423 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4424
Samuel Antaob68e2db2016-03-03 16:20:23 +00004425 // Return value of the runtime offloading call.
4426 llvm::Value *Return;
4427
4428 auto *NumTeams = emitNumTeamsClauseForTargetDirective(*this, CGF, D);
4429 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(*this, CGF, D);
4430
4431 // If we have NumTeams defined this means that we have an enclosed teams
4432 // region. Therefore we also expect to have ThreadLimit defined. These two
4433 // values should be defined in the presence of a teams directive, regardless
4434 // of having any clauses associated. If the user is using teams but no
4435 // clauses, these two values will be the default that should be passed to
4436 // the runtime library - a 32-bit integer with the value zero.
4437 if (NumTeams) {
4438 assert(ThreadLimit && "Thread limit expression should be available along "
4439 "with number of teams.");
4440 llvm::Value *OffloadingArgs[] = {
4441 DeviceID, OutlinedFnID, PointerNum,
4442 BasePointersArray, PointersArray, SizesArray,
4443 MapTypesArray, NumTeams, ThreadLimit};
4444 Return = CGF.EmitRuntimeCall(
4445 createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
4446 } else {
4447 llvm::Value *OffloadingArgs[] = {
4448 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4449 PointersArray, SizesArray, MapTypesArray};
4450 Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4451 OffloadingArgs);
4452 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004453
4454 CGF.EmitStoreOfScalar(Return, OffloadError);
4455 };
4456
Samuel Antaoee8fb302016-01-06 13:42:12 +00004457 // Notify that the host version must be executed.
4458 auto &&ElseGen = [this, OffloadError,
4459 OffloadErrorQType](CodeGenFunction &CGF) {
4460 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4461 OffloadError);
4462 };
4463
4464 // If we have a target function ID it means that we need to support
4465 // offloading, otherwise, just execute on the host. We need to execute on host
4466 // regardless of the conditional in the if clause if, e.g., the user do not
4467 // specify target triples.
4468 if (OutlinedFnID) {
4469 if (IfCond) {
4470 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4471 } else {
4472 CodeGenFunction::RunCleanupsScope Scope(CGF);
4473 ThenGen(CGF);
4474 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004475 } else {
4476 CodeGenFunction::RunCleanupsScope Scope(CGF);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004477 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004478 }
4479
4480 // Check the error code and execute the host version if required.
4481 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4482 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4483 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4484 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4485 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4486
4487 CGF.EmitBlock(OffloadFailedBlock);
4488 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4489 CGF.EmitBranch(OffloadContBlock);
4490
4491 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004492}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004493
4494void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4495 StringRef ParentName) {
4496 if (!S)
4497 return;
4498
4499 // If we find a OMP target directive, codegen the outline function and
4500 // register the result.
4501 // FIXME: Add other directives with target when they become supported.
4502 bool isTargetDirective = isa<OMPTargetDirective>(S);
4503
4504 if (isTargetDirective) {
4505 auto *E = cast<OMPExecutableDirective>(S);
4506 unsigned DeviceID;
4507 unsigned FileID;
4508 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004509 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004510 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004511
4512 // Is this a target region that should not be emitted as an entry point? If
4513 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00004514 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4515 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004516 return;
4517
4518 llvm::Function *Fn;
4519 llvm::Constant *Addr;
4520 emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4521 /*isOffloadEntry=*/true);
4522 assert(Fn && Addr && "Target region emission failed.");
4523 return;
4524 }
4525
4526 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4527 if (!E->getAssociatedStmt())
4528 return;
4529
4530 scanForTargetRegionsFunctions(
4531 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4532 ParentName);
4533 return;
4534 }
4535
4536 // If this is a lambda function, look into its body.
4537 if (auto *L = dyn_cast<LambdaExpr>(S))
4538 S = L->getBody();
4539
4540 // Keep looking for target regions recursively.
4541 for (auto *II : S->children())
4542 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004543}
4544
4545bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4546 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4547
4548 // If emitting code for the host, we do not process FD here. Instead we do
4549 // the normal code generation.
4550 if (!CGM.getLangOpts().OpenMPIsDevice)
4551 return false;
4552
4553 // Try to detect target regions in the function.
4554 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4555
4556 // We should not emit any function othen that the ones created during the
4557 // scanning. Therefore, we signal that this function is completely dealt
4558 // with.
4559 return true;
4560}
4561
4562bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4563 if (!CGM.getLangOpts().OpenMPIsDevice)
4564 return false;
4565
4566 // Check if there are Ctors/Dtors in this declaration and look for target
4567 // regions in it. We use the complete variant to produce the kernel name
4568 // mangling.
4569 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4570 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4571 for (auto *Ctor : RD->ctors()) {
4572 StringRef ParentName =
4573 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4574 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4575 }
4576 auto *Dtor = RD->getDestructor();
4577 if (Dtor) {
4578 StringRef ParentName =
4579 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4580 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4581 }
4582 }
4583
4584 // If we are in target mode we do not emit any global (declare target is not
4585 // implemented yet). Therefore we signal that GD was processed in this case.
4586 return true;
4587}
4588
4589bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4590 auto *VD = GD.getDecl();
4591 if (isa<FunctionDecl>(VD))
4592 return emitTargetFunctions(GD);
4593
4594 return emitTargetGlobalVariable(GD);
4595}
4596
4597llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4598 // If we have offloading in the current module, we need to emit the entries
4599 // now and register the offloading descriptor.
4600 createOffloadEntriesAndInfoMetadata();
4601
4602 // Create and register the offloading binary descriptors. This is the main
4603 // entity that captures all the information about offloading in the current
4604 // compilation unit.
4605 return createOffloadingBinaryDescriptorRegistration();
4606}