blob: a38d6fdd3afaa3cb27927db217013b8acad7ca3a [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,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000540 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
541 // kmp_int32 num_teams, kmp_int32 thread_limit);
542 OMPRTL__kmpc_push_num_teams,
543 /// \brief Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc,
544 /// kmpc_micro microtask, ...);
545 OMPRTL__kmpc_fork_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000546
547 //
548 // Offloading related calls
549 //
550 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
551 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
552 // *arg_types);
553 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000554 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
555 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
556 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
557 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000558 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
559 OMPRTL__tgt_register_lib,
560 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
561 OMPRTL__tgt_unregister_lib,
562};
563
Hans Wennborg7eb54642015-09-10 17:07:54 +0000564} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000565
566LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000567 return CGF.EmitLoadOfPointerLValue(
568 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
569 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000570}
571
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000572void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000573 if (!CGF.HaveInsertPoint())
574 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000575 // 1.2.2 OpenMP Language Terminology
576 // Structured block - An executable statement with a single entry at the
577 // top and a single exit at the bottom.
578 // The point of exit cannot be a branch out of the structured block.
579 // longjmp() and throw() must not violate the entry/exit criteria.
580 CGF.EHStack.pushTerminate();
581 {
582 CodeGenFunction::RunCleanupsScope Scope(CGF);
583 CodeGen(CGF);
584 }
585 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000586}
587
Alexey Bataev62b63b12015-03-10 07:28:44 +0000588LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
589 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000590 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
591 getThreadIDVariable()->getType(),
592 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000593}
594
Alexey Bataev9959db52014-05-06 10:08:46 +0000595CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000596 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000597 IdentTy = llvm::StructType::create(
598 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
599 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000600 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000601 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000602 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
603 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000604 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000605 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000606
607 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000608}
609
Alexey Bataev91797552015-03-18 04:13:55 +0000610void CGOpenMPRuntime::clear() {
611 InternalVars.clear();
612}
613
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000614static llvm::Function *
615emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
616 const Expr *CombinerInitializer, const VarDecl *In,
617 const VarDecl *Out, bool IsCombiner) {
618 // void .omp_combiner.(Ty *in, Ty *out);
619 auto &C = CGM.getContext();
620 QualType PtrTy = C.getPointerType(Ty).withRestrict();
621 FunctionArgList Args;
622 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
623 /*Id=*/nullptr, PtrTy);
624 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
625 /*Id=*/nullptr, PtrTy);
626 Args.push_back(&OmpInParm);
627 Args.push_back(&OmpOutParm);
628 FunctionType::ExtInfo Info;
629 auto &FnInfo =
630 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
631 /*isVariadic=*/false);
632 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
633 auto *Fn = llvm::Function::Create(
634 FnTy, llvm::GlobalValue::InternalLinkage,
635 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
636 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
637 CodeGenFunction CGF(CGM);
638 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
639 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
640 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
641 CodeGenFunction::OMPPrivateScope Scope(CGF);
642 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
643 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
644 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
645 .getAddress();
646 });
647 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
648 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
649 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
650 .getAddress();
651 });
652 (void)Scope.Privatize();
653 CGF.EmitIgnoredExpr(CombinerInitializer);
654 Scope.ForceCleanup();
655 CGF.FinishFunction();
656 return Fn;
657}
658
659void CGOpenMPRuntime::emitUserDefinedReduction(
660 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
661 if (UDRMap.count(D) > 0)
662 return;
663 auto &C = CGM.getContext();
664 if (!In || !Out) {
665 In = &C.Idents.get("omp_in");
666 Out = &C.Idents.get("omp_out");
667 }
668 llvm::Function *Combiner = emitCombinerOrInitializer(
669 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
670 cast<VarDecl>(D->lookup(Out).front()),
671 /*IsCombiner=*/true);
672 llvm::Function *Initializer = nullptr;
673 if (auto *Init = D->getInitializer()) {
674 if (!Priv || !Orig) {
675 Priv = &C.Idents.get("omp_priv");
676 Orig = &C.Idents.get("omp_orig");
677 }
678 Initializer = emitCombinerOrInitializer(
679 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
680 cast<VarDecl>(D->lookup(Priv).front()),
681 /*IsCombiner=*/false);
682 }
683 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
684 if (CGF) {
685 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
686 Decls.second.push_back(D);
687 }
688}
689
John McCall7f416cc2015-09-08 08:05:57 +0000690// Layout information for ident_t.
691static CharUnits getIdentAlign(CodeGenModule &CGM) {
692 return CGM.getPointerAlign();
693}
694static CharUnits getIdentSize(CodeGenModule &CGM) {
695 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
696 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
697}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000698static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000699 // All the fields except the last are i32, so this works beautifully.
700 return unsigned(Field) * CharUnits::fromQuantity(4);
701}
702static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000703 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000704 const llvm::Twine &Name = "") {
705 auto Offset = getOffsetOfIdentField(Field);
706 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
707}
708
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000709llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000710 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
711 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000712 assert(ThreadIDVar->getType()->isPointerType() &&
713 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000714 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
715 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000716 bool HasCancel = false;
717 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
718 HasCancel = OPD->hasCancel();
719 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
720 HasCancel = OPSD->hasCancel();
721 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
722 HasCancel = OPFD->hasCancel();
723 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
724 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000725 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000726 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000727}
728
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000729llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
730 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
731 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000732 assert(!ThreadIDVar->getType()->isPointerType() &&
733 "thread id variable must be of type kmp_int32 for tasks");
734 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
735 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000736 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000737 InnermostKind,
738 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000739 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000740 return CGF.GenerateCapturedStmtFunction(*CS);
741}
742
Alexey Bataev50b3c952016-02-19 10:38:26 +0000743Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000744 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000745 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000746 if (!Entry) {
747 if (!DefaultOpenMPPSource) {
748 // Initialize default location for psource field of ident_t structure of
749 // all ident_t objects. Format is ";file;function;line;column;;".
750 // Taken from
751 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
752 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000753 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000754 DefaultOpenMPPSource =
755 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
756 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000757 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
758 CGM.getModule(), IdentTy, /*isConstant*/ true,
759 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000760 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000761 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000762
763 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000764 llvm::Constant *Values[] = {Zero,
765 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
766 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000767 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
768 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000769 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000770 }
John McCall7f416cc2015-09-08 08:05:57 +0000771 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000772}
773
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000774llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
775 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000776 unsigned Flags) {
777 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000778 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000779 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000780 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000781 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000782
783 assert(CGF.CurFn && "No function in current CodeGenFunction.");
784
John McCall7f416cc2015-09-08 08:05:57 +0000785 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000786 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
787 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000788 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
789
Alexander Musmanc6388682014-12-15 07:07:06 +0000790 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
791 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000792 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000793 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000794 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
795 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000796 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000797 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000798 LocValue = AI;
799
800 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
801 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000802 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000803 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000804 }
805
806 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000807 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000808
Alexey Bataevf002aca2014-05-30 05:48:40 +0000809 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
810 if (OMPDebugLoc == nullptr) {
811 SmallString<128> Buffer2;
812 llvm::raw_svector_ostream OS2(Buffer2);
813 // Build debug location
814 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
815 OS2 << ";" << PLoc.getFilename() << ";";
816 if (const FunctionDecl *FD =
817 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
818 OS2 << FD->getQualifiedNameAsString();
819 }
820 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
821 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
822 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000823 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000824 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000825 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
826
John McCall7f416cc2015-09-08 08:05:57 +0000827 // Our callers always pass this to a runtime function, so for
828 // convenience, go ahead and return a naked pointer.
829 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000830}
831
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000832llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
833 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000834 assert(CGF.CurFn && "No function in current CodeGenFunction.");
835
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000836 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000837 // Check whether we've already cached a load of the thread id in this
838 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000839 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000840 if (I != OpenMPLocThreadIDMap.end()) {
841 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000842 if (ThreadID != nullptr)
843 return ThreadID;
844 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000845 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000846 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000847 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000848 // Check if this an outlined function with thread id passed as argument.
849 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000850 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
851 // If value loaded in entry block, cache it and use it everywhere in
852 // function.
853 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
854 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
855 Elem.second.ThreadID = ThreadID;
856 }
857 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000858 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000859 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000860
861 // This is not an outlined function region - need to call __kmpc_int32
862 // kmpc_global_thread_num(ident_t *loc).
863 // Generate thread id value and cache this value for use across the
864 // function.
865 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
866 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
867 ThreadID =
868 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
869 emitUpdateLocation(CGF, Loc));
870 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
871 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000872 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000873}
874
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000875void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000876 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000877 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
878 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000879 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
880 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
881 UDRMap.erase(D);
882 }
883 FunctionUDRMap.erase(CGF.CurFn);
884 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000885}
886
887llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
888 return llvm::PointerType::getUnqual(IdentTy);
889}
890
891llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
892 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
893}
894
895llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +0000896CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000897 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +0000898 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000899 case OMPRTL__kmpc_fork_call: {
900 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
901 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000902 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
903 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000904 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000905 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000906 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
907 break;
908 }
909 case OMPRTL__kmpc_global_thread_num: {
910 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000911 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000912 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000913 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000914 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
915 break;
916 }
Alexey Bataev97720002014-11-11 04:05:39 +0000917 case OMPRTL__kmpc_threadprivate_cached: {
918 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
919 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
920 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
921 CGM.VoidPtrTy, CGM.SizeTy,
922 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
923 llvm::FunctionType *FnTy =
924 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
925 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
926 break;
927 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000928 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000929 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
930 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000931 llvm::Type *TypeParams[] = {
932 getIdentTyPointerTy(), CGM.Int32Ty,
933 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
934 llvm::FunctionType *FnTy =
935 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
936 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
937 break;
938 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000939 case OMPRTL__kmpc_critical_with_hint: {
940 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
941 // kmp_critical_name *crit, uintptr_t hint);
942 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
943 llvm::PointerType::getUnqual(KmpCriticalNameTy),
944 CGM.IntPtrTy};
945 llvm::FunctionType *FnTy =
946 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
947 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
948 break;
949 }
Alexey Bataev97720002014-11-11 04:05:39 +0000950 case OMPRTL__kmpc_threadprivate_register: {
951 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
952 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
953 // typedef void *(*kmpc_ctor)(void *);
954 auto KmpcCtorTy =
955 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
956 /*isVarArg*/ false)->getPointerTo();
957 // typedef void *(*kmpc_cctor)(void *, void *);
958 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
959 auto KmpcCopyCtorTy =
960 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
961 /*isVarArg*/ false)->getPointerTo();
962 // typedef void (*kmpc_dtor)(void *);
963 auto KmpcDtorTy =
964 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
965 ->getPointerTo();
966 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
967 KmpcCopyCtorTy, KmpcDtorTy};
968 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
969 /*isVarArg*/ false);
970 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
971 break;
972 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000973 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000974 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
975 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000976 llvm::Type *TypeParams[] = {
977 getIdentTyPointerTy(), CGM.Int32Ty,
978 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
979 llvm::FunctionType *FnTy =
980 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
981 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
982 break;
983 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000984 case OMPRTL__kmpc_cancel_barrier: {
985 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
986 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000987 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
988 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000989 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
990 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000991 break;
992 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000993 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000994 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000995 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
996 llvm::FunctionType *FnTy =
997 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
998 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
999 break;
1000 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001001 case OMPRTL__kmpc_for_static_fini: {
1002 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1003 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1004 llvm::FunctionType *FnTy =
1005 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1006 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1007 break;
1008 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001009 case OMPRTL__kmpc_push_num_threads: {
1010 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1011 // kmp_int32 num_threads)
1012 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1013 CGM.Int32Ty};
1014 llvm::FunctionType *FnTy =
1015 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1016 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1017 break;
1018 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001019 case OMPRTL__kmpc_serialized_parallel: {
1020 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1021 // global_tid);
1022 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1023 llvm::FunctionType *FnTy =
1024 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1025 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1026 break;
1027 }
1028 case OMPRTL__kmpc_end_serialized_parallel: {
1029 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1030 // global_tid);
1031 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1032 llvm::FunctionType *FnTy =
1033 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1034 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1035 break;
1036 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001037 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001038 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001039 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1040 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001041 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001042 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1043 break;
1044 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001045 case OMPRTL__kmpc_master: {
1046 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1047 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1048 llvm::FunctionType *FnTy =
1049 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1050 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1051 break;
1052 }
1053 case OMPRTL__kmpc_end_master: {
1054 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1055 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1056 llvm::FunctionType *FnTy =
1057 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1058 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1059 break;
1060 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001061 case OMPRTL__kmpc_omp_taskyield: {
1062 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1063 // int end_part);
1064 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1065 llvm::FunctionType *FnTy =
1066 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1067 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1068 break;
1069 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001070 case OMPRTL__kmpc_single: {
1071 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1072 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1073 llvm::FunctionType *FnTy =
1074 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1075 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1076 break;
1077 }
1078 case OMPRTL__kmpc_end_single: {
1079 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1080 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1081 llvm::FunctionType *FnTy =
1082 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1083 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1084 break;
1085 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001086 case OMPRTL__kmpc_omp_task_alloc: {
1087 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1088 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1089 // kmp_routine_entry_t *task_entry);
1090 assert(KmpRoutineEntryPtrTy != nullptr &&
1091 "Type kmp_routine_entry_t must be created.");
1092 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1093 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1094 // Return void * and then cast to particular kmp_task_t type.
1095 llvm::FunctionType *FnTy =
1096 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1097 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1098 break;
1099 }
1100 case OMPRTL__kmpc_omp_task: {
1101 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1102 // *new_task);
1103 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1104 CGM.VoidPtrTy};
1105 llvm::FunctionType *FnTy =
1106 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1107 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1108 break;
1109 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001110 case OMPRTL__kmpc_copyprivate: {
1111 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001112 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001113 // kmp_int32 didit);
1114 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1115 auto *CpyFnTy =
1116 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001117 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001118 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1119 CGM.Int32Ty};
1120 llvm::FunctionType *FnTy =
1121 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1122 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1123 break;
1124 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001125 case OMPRTL__kmpc_reduce: {
1126 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1127 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1128 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1129 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1130 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1131 /*isVarArg=*/false);
1132 llvm::Type *TypeParams[] = {
1133 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1134 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1135 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1136 llvm::FunctionType *FnTy =
1137 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1138 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1139 break;
1140 }
1141 case OMPRTL__kmpc_reduce_nowait: {
1142 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1143 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1144 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1145 // *lck);
1146 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1147 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1148 /*isVarArg=*/false);
1149 llvm::Type *TypeParams[] = {
1150 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1151 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1152 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1153 llvm::FunctionType *FnTy =
1154 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1155 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1156 break;
1157 }
1158 case OMPRTL__kmpc_end_reduce: {
1159 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1160 // kmp_critical_name *lck);
1161 llvm::Type *TypeParams[] = {
1162 getIdentTyPointerTy(), CGM.Int32Ty,
1163 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1164 llvm::FunctionType *FnTy =
1165 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1166 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1167 break;
1168 }
1169 case OMPRTL__kmpc_end_reduce_nowait: {
1170 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1171 // kmp_critical_name *lck);
1172 llvm::Type *TypeParams[] = {
1173 getIdentTyPointerTy(), CGM.Int32Ty,
1174 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1175 llvm::FunctionType *FnTy =
1176 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1177 RTLFn =
1178 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1179 break;
1180 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001181 case OMPRTL__kmpc_omp_task_begin_if0: {
1182 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1183 // *new_task);
1184 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1185 CGM.VoidPtrTy};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1188 RTLFn =
1189 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1190 break;
1191 }
1192 case OMPRTL__kmpc_omp_task_complete_if0: {
1193 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1194 // *new_task);
1195 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1196 CGM.VoidPtrTy};
1197 llvm::FunctionType *FnTy =
1198 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1199 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1200 /*Name=*/"__kmpc_omp_task_complete_if0");
1201 break;
1202 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001203 case OMPRTL__kmpc_ordered: {
1204 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1205 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1206 llvm::FunctionType *FnTy =
1207 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1208 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1209 break;
1210 }
1211 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001212 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001213 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1214 llvm::FunctionType *FnTy =
1215 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1216 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1217 break;
1218 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001219 case OMPRTL__kmpc_omp_taskwait: {
1220 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1221 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1222 llvm::FunctionType *FnTy =
1223 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1224 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1225 break;
1226 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001227 case OMPRTL__kmpc_taskgroup: {
1228 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1229 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1230 llvm::FunctionType *FnTy =
1231 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1232 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1233 break;
1234 }
1235 case OMPRTL__kmpc_end_taskgroup: {
1236 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1237 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1238 llvm::FunctionType *FnTy =
1239 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1241 break;
1242 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001243 case OMPRTL__kmpc_push_proc_bind: {
1244 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1245 // int proc_bind)
1246 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1247 llvm::FunctionType *FnTy =
1248 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1249 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1250 break;
1251 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001252 case OMPRTL__kmpc_omp_task_with_deps: {
1253 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1254 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1255 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1256 llvm::Type *TypeParams[] = {
1257 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1258 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1259 llvm::FunctionType *FnTy =
1260 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1261 RTLFn =
1262 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1263 break;
1264 }
1265 case OMPRTL__kmpc_omp_wait_deps: {
1266 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1267 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1268 // kmp_depend_info_t *noalias_dep_list);
1269 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1270 CGM.Int32Ty, CGM.VoidPtrTy,
1271 CGM.Int32Ty, CGM.VoidPtrTy};
1272 llvm::FunctionType *FnTy =
1273 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1274 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1275 break;
1276 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001277 case OMPRTL__kmpc_cancellationpoint: {
1278 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1279 // global_tid, kmp_int32 cncl_kind)
1280 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1281 llvm::FunctionType *FnTy =
1282 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1283 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1284 break;
1285 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001286 case OMPRTL__kmpc_cancel: {
1287 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1288 // kmp_int32 cncl_kind)
1289 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1290 llvm::FunctionType *FnTy =
1291 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1292 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1293 break;
1294 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001295 case OMPRTL__kmpc_push_num_teams: {
1296 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1297 // kmp_int32 num_teams, kmp_int32 num_threads)
1298 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1299 CGM.Int32Ty};
1300 llvm::FunctionType *FnTy =
1301 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1302 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1303 break;
1304 }
1305 case OMPRTL__kmpc_fork_teams: {
1306 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1307 // microtask, ...);
1308 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1309 getKmpc_MicroPointerTy()};
1310 llvm::FunctionType *FnTy =
1311 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1312 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1313 break;
1314 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001315 case OMPRTL__tgt_target: {
1316 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1317 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1318 // *arg_types);
1319 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1320 CGM.VoidPtrTy,
1321 CGM.Int32Ty,
1322 CGM.VoidPtrPtrTy,
1323 CGM.VoidPtrPtrTy,
1324 CGM.SizeTy->getPointerTo(),
1325 CGM.Int32Ty->getPointerTo()};
1326 llvm::FunctionType *FnTy =
1327 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1328 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1329 break;
1330 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001331 case OMPRTL__tgt_target_teams: {
1332 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1333 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1334 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1335 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1336 CGM.VoidPtrTy,
1337 CGM.Int32Ty,
1338 CGM.VoidPtrPtrTy,
1339 CGM.VoidPtrPtrTy,
1340 CGM.SizeTy->getPointerTo(),
1341 CGM.Int32Ty->getPointerTo(),
1342 CGM.Int32Ty,
1343 CGM.Int32Ty};
1344 llvm::FunctionType *FnTy =
1345 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1346 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1347 break;
1348 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001349 case OMPRTL__tgt_register_lib: {
1350 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1351 QualType ParamTy =
1352 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1353 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1354 llvm::FunctionType *FnTy =
1355 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1356 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1357 break;
1358 }
1359 case OMPRTL__tgt_unregister_lib: {
1360 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1361 QualType ParamTy =
1362 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1363 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1364 llvm::FunctionType *FnTy =
1365 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1366 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1367 break;
1368 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001369 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001370 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001371 return RTLFn;
1372}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001373
Alexander Musman21212e42015-03-13 10:38:23 +00001374llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1375 bool IVSigned) {
1376 assert((IVSize == 32 || IVSize == 64) &&
1377 "IV size is not compatible with the omp runtime");
1378 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1379 : "__kmpc_for_static_init_4u")
1380 : (IVSigned ? "__kmpc_for_static_init_8"
1381 : "__kmpc_for_static_init_8u");
1382 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1383 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1384 llvm::Type *TypeParams[] = {
1385 getIdentTyPointerTy(), // loc
1386 CGM.Int32Ty, // tid
1387 CGM.Int32Ty, // schedtype
1388 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1389 PtrTy, // p_lower
1390 PtrTy, // p_upper
1391 PtrTy, // p_stride
1392 ITy, // incr
1393 ITy // chunk
1394 };
1395 llvm::FunctionType *FnTy =
1396 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1397 return CGM.CreateRuntimeFunction(FnTy, Name);
1398}
1399
Alexander Musman92bdaab2015-03-12 13:37:50 +00001400llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1401 bool IVSigned) {
1402 assert((IVSize == 32 || IVSize == 64) &&
1403 "IV size is not compatible with the omp runtime");
1404 auto Name =
1405 IVSize == 32
1406 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1407 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1408 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1409 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1410 CGM.Int32Ty, // tid
1411 CGM.Int32Ty, // schedtype
1412 ITy, // lower
1413 ITy, // upper
1414 ITy, // stride
1415 ITy // chunk
1416 };
1417 llvm::FunctionType *FnTy =
1418 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1419 return CGM.CreateRuntimeFunction(FnTy, Name);
1420}
1421
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001422llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1423 bool IVSigned) {
1424 assert((IVSize == 32 || IVSize == 64) &&
1425 "IV size is not compatible with the omp runtime");
1426 auto Name =
1427 IVSize == 32
1428 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1429 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1430 llvm::Type *TypeParams[] = {
1431 getIdentTyPointerTy(), // loc
1432 CGM.Int32Ty, // tid
1433 };
1434 llvm::FunctionType *FnTy =
1435 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1436 return CGM.CreateRuntimeFunction(FnTy, Name);
1437}
1438
Alexander Musman92bdaab2015-03-12 13:37:50 +00001439llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1440 bool IVSigned) {
1441 assert((IVSize == 32 || IVSize == 64) &&
1442 "IV size is not compatible with the omp runtime");
1443 auto Name =
1444 IVSize == 32
1445 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1446 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1447 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1448 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1449 llvm::Type *TypeParams[] = {
1450 getIdentTyPointerTy(), // loc
1451 CGM.Int32Ty, // tid
1452 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1453 PtrTy, // p_lower
1454 PtrTy, // p_upper
1455 PtrTy // p_stride
1456 };
1457 llvm::FunctionType *FnTy =
1458 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1459 return CGM.CreateRuntimeFunction(FnTy, Name);
1460}
1461
Alexey Bataev97720002014-11-11 04:05:39 +00001462llvm::Constant *
1463CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001464 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1465 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001466 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001467 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001468 Twine(CGM.getMangledName(VD)) + ".cache.");
1469}
1470
John McCall7f416cc2015-09-08 08:05:57 +00001471Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1472 const VarDecl *VD,
1473 Address VDAddr,
1474 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001475 if (CGM.getLangOpts().OpenMPUseTLS &&
1476 CGM.getContext().getTargetInfo().isTLSSupported())
1477 return VDAddr;
1478
John McCall7f416cc2015-09-08 08:05:57 +00001479 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001480 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001481 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1482 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001483 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1484 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001485 return Address(CGF.EmitRuntimeCall(
1486 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1487 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001488}
1489
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001490void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001491 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001492 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1493 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1494 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001495 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1496 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001497 OMPLoc);
1498 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1499 // to register constructor/destructor for variable.
1500 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001501 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1502 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001503 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001504 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001505 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001506}
1507
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001508llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001509 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001510 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001511 if (CGM.getLangOpts().OpenMPUseTLS &&
1512 CGM.getContext().getTargetInfo().isTLSSupported())
1513 return nullptr;
1514
Alexey Bataev97720002014-11-11 04:05:39 +00001515 VD = VD->getDefinition(CGM.getContext());
1516 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1517 ThreadPrivateWithDefinition.insert(VD);
1518 QualType ASTTy = VD->getType();
1519
1520 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1521 auto Init = VD->getAnyInitializer();
1522 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1523 // Generate function that re-emits the declaration's initializer into the
1524 // threadprivate copy of the variable VD
1525 CodeGenFunction CtorCGF(CGM);
1526 FunctionArgList Args;
1527 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1528 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1529 Args.push_back(&Dst);
1530
1531 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1532 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1533 /*isVariadic=*/false);
1534 auto FTy = CGM.getTypes().GetFunctionType(FI);
1535 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001536 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001537 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1538 Args, SourceLocation());
1539 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001540 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001541 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001542 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1543 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1544 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001545 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1546 /*IsInitializer=*/true);
1547 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001548 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001549 CGM.getContext().VoidPtrTy, Dst.getLocation());
1550 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1551 CtorCGF.FinishFunction();
1552 Ctor = Fn;
1553 }
1554 if (VD->getType().isDestructedType() != QualType::DK_none) {
1555 // Generate function that emits destructor call for the threadprivate copy
1556 // of the variable VD
1557 CodeGenFunction DtorCGF(CGM);
1558 FunctionArgList Args;
1559 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1560 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1561 Args.push_back(&Dst);
1562
1563 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1564 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1565 /*isVariadic=*/false);
1566 auto FTy = CGM.getTypes().GetFunctionType(FI);
1567 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001568 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001569 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1570 SourceLocation());
1571 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1572 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001573 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1574 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001575 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1576 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1577 DtorCGF.FinishFunction();
1578 Dtor = Fn;
1579 }
1580 // Do not emit init function if it is not required.
1581 if (!Ctor && !Dtor)
1582 return nullptr;
1583
1584 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1585 auto CopyCtorTy =
1586 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1587 /*isVarArg=*/false)->getPointerTo();
1588 // Copying constructor for the threadprivate variable.
1589 // Must be NULL - reserved by runtime, but currently it requires that this
1590 // parameter is always NULL. Otherwise it fires assertion.
1591 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1592 if (Ctor == nullptr) {
1593 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1594 /*isVarArg=*/false)->getPointerTo();
1595 Ctor = llvm::Constant::getNullValue(CtorTy);
1596 }
1597 if (Dtor == nullptr) {
1598 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1599 /*isVarArg=*/false)->getPointerTo();
1600 Dtor = llvm::Constant::getNullValue(DtorTy);
1601 }
1602 if (!CGF) {
1603 auto InitFunctionTy =
1604 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1605 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001606 InitFunctionTy, ".__omp_threadprivate_init_.",
1607 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001608 CodeGenFunction InitCGF(CGM);
1609 FunctionArgList ArgList;
1610 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1611 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1612 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001613 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001614 InitCGF.FinishFunction();
1615 return InitFunction;
1616 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001617 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001618 }
1619 return nullptr;
1620}
1621
Alexey Bataev1d677132015-04-22 13:57:31 +00001622/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1623/// function. Here is the logic:
1624/// if (Cond) {
1625/// ThenGen();
1626/// } else {
1627/// ElseGen();
1628/// }
1629static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1630 const RegionCodeGenTy &ThenGen,
1631 const RegionCodeGenTy &ElseGen) {
1632 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1633
1634 // If the condition constant folds and can be elided, try to avoid emitting
1635 // the condition and the dead arm of the if/else.
1636 bool CondConstant;
1637 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1638 CodeGenFunction::RunCleanupsScope Scope(CGF);
1639 if (CondConstant) {
1640 ThenGen(CGF);
1641 } else {
1642 ElseGen(CGF);
1643 }
1644 return;
1645 }
1646
1647 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1648 // emit the conditional branch.
1649 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1650 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1651 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1652 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1653
1654 // Emit the 'then' code.
1655 CGF.EmitBlock(ThenBlock);
1656 {
1657 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1658 ThenGen(CGF);
1659 }
1660 CGF.EmitBranch(ContBlock);
1661 // Emit the 'else' code if present.
1662 {
1663 // There is no need to emit line number for unconditional branch.
1664 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1665 CGF.EmitBlock(ElseBlock);
1666 }
1667 {
1668 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1669 ElseGen(CGF);
1670 }
1671 {
1672 // There is no need to emit line number for unconditional branch.
1673 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1674 CGF.EmitBranch(ContBlock);
1675 }
1676 // Emit the continuation block for code after the if.
1677 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001678}
1679
Alexey Bataev1d677132015-04-22 13:57:31 +00001680void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1681 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001682 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001683 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001684 if (!CGF.HaveInsertPoint())
1685 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001686 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001687 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1688 RTLoc](CodeGenFunction &CGF) {
1689 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1690 llvm::Value *Args[] = {
1691 RTLoc,
1692 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1693 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1694 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1695 RealArgs.append(std::begin(Args), std::end(Args));
1696 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1697
1698 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1699 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1700 };
1701 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1702 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001703 auto ThreadID = getThreadID(CGF, Loc);
1704 // Build calls:
1705 // __kmpc_serialized_parallel(&Loc, GTid);
1706 llvm::Value *Args[] = {RTLoc, ThreadID};
1707 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1708 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001709
Alexey Bataev1d677132015-04-22 13:57:31 +00001710 // OutlinedFn(&GTid, &zero, CapturedStruct);
1711 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001712 Address ZeroAddr =
1713 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1714 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001715 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001716 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1717 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1718 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1719 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001720 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001721
Alexey Bataev1d677132015-04-22 13:57:31 +00001722 // __kmpc_end_serialized_parallel(&Loc, GTid);
1723 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1724 CGF.EmitRuntimeCall(
1725 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1726 };
1727 if (IfCond) {
1728 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1729 } else {
1730 CodeGenFunction::RunCleanupsScope Scope(CGF);
1731 ThenGen(CGF);
1732 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001733}
1734
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001735// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001736// thread-ID variable (it is passed in a first argument of the outlined function
1737// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1738// regular serial code region, get thread ID by calling kmp_int32
1739// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1740// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001741Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1742 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001743 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001744 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001745 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001746 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001747
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001748 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001749 auto Int32Ty =
1750 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1751 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1752 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001753 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001754
1755 return ThreadIDTemp;
1756}
1757
Alexey Bataev97720002014-11-11 04:05:39 +00001758llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001759CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001760 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001761 SmallString<256> Buffer;
1762 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001763 Out << Name;
1764 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001765 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1766 if (Elem.second) {
1767 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001768 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001769 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001770 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001771
David Blaikie13156b62014-11-19 03:06:06 +00001772 return Elem.second = new llvm::GlobalVariable(
1773 CGM.getModule(), Ty, /*IsConstant*/ false,
1774 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1775 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001776}
1777
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001778llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001779 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001780 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001781}
1782
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001783namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001784template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001785 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001786 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001787
1788public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001789 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1790 : Callee(Callee) {
1791 assert(CleanupArgs.size() == N);
1792 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1793 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001794
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001795 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001796 if (!CGF.HaveInsertPoint())
1797 return;
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001798 CGF.EmitRuntimeCall(Callee, Args);
1799 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001800};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001801} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001802
1803void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1804 StringRef CriticalName,
1805 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001806 SourceLocation Loc, const Expr *Hint) {
1807 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001808 // CriticalOpGen();
1809 // __kmpc_end_critical(ident_t *, gtid, Lock);
1810 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001811 if (!CGF.HaveInsertPoint())
1812 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001813 CodeGenFunction::RunCleanupsScope Scope(CGF);
1814 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1815 getCriticalRegionLock(CriticalName)};
1816 if (Hint) {
1817 llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1818 std::end(Args));
1819 auto *HintVal = CGF.EmitScalarExpr(Hint);
1820 ArgsWithHint.push_back(
1821 CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1822 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1823 ArgsWithHint);
1824 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001825 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001826 // Build a call to __kmpc_end_critical
1827 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1828 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1829 llvm::makeArrayRef(Args));
1830 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001831}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001832
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001833static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001834 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001835 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001836 llvm::Value *CallBool = CGF.EmitScalarConversion(
1837 IfCond,
1838 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001839 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001840
1841 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1842 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1843 // Generate the branch (If-stmt)
1844 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1845 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001846 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001847 // Emit the rest of bblocks/branches
1848 CGF.EmitBranch(ContBlock);
1849 CGF.EmitBlock(ContBlock, true);
1850}
1851
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001852void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001853 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001854 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001855 if (!CGF.HaveInsertPoint())
1856 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001857 // if(__kmpc_master(ident_t *, gtid)) {
1858 // MasterOpGen();
1859 // __kmpc_end_master(ident_t *, gtid);
1860 // }
1861 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001862 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001863 auto *IsMaster =
1864 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001865 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1866 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001867 emitIfStmt(
1868 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1869 CodeGenFunction::RunCleanupsScope Scope(CGF);
1870 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1871 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1872 llvm::makeArrayRef(Args));
1873 MasterOpGen(CGF);
1874 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001875}
1876
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001877void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1878 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001879 if (!CGF.HaveInsertPoint())
1880 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001881 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1882 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001883 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001884 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001885 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001886}
1887
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001888void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1889 const RegionCodeGenTy &TaskgroupOpGen,
1890 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001891 if (!CGF.HaveInsertPoint())
1892 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001893 // __kmpc_taskgroup(ident_t *, gtid);
1894 // TaskgroupOpGen();
1895 // __kmpc_end_taskgroup(ident_t *, gtid);
1896 // Prepare arguments and build a call to __kmpc_taskgroup
1897 {
1898 CodeGenFunction::RunCleanupsScope Scope(CGF);
1899 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1900 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1901 // Build a call to __kmpc_end_taskgroup
1902 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1903 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1904 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001905 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001906 }
1907}
1908
John McCall7f416cc2015-09-08 08:05:57 +00001909/// Given an array of pointers to variables, project the address of a
1910/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001911static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1912 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001913 // Pull out the pointer to the variable.
1914 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001915 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001916 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1917
1918 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001919 Addr = CGF.Builder.CreateElementBitCast(
1920 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001921 return Addr;
1922}
1923
Alexey Bataeva63048e2015-03-23 06:18:07 +00001924static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001925 CodeGenModule &CGM, llvm::Type *ArgsType,
1926 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1927 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001928 auto &C = CGM.getContext();
1929 // void copy_func(void *LHSArg, void *RHSArg);
1930 FunctionArgList Args;
1931 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1932 C.VoidPtrTy);
1933 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1934 C.VoidPtrTy);
1935 Args.push_back(&LHSArg);
1936 Args.push_back(&RHSArg);
1937 FunctionType::ExtInfo EI;
1938 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1939 C.VoidTy, Args, EI, /*isVariadic=*/false);
1940 auto *Fn = llvm::Function::Create(
1941 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1942 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001943 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001944 CodeGenFunction CGF(CGM);
1945 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001946 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001947 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001948 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1949 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1950 ArgsType), CGF.getPointerAlign());
1951 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1952 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1953 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001954 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1955 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1956 // ...
1957 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001958 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001959 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1960 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1961
1962 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1963 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1964
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001965 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1966 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001967 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001968 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001969 CGF.FinishFunction();
1970 return Fn;
1971}
1972
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001973void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001974 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001975 SourceLocation Loc,
1976 ArrayRef<const Expr *> CopyprivateVars,
1977 ArrayRef<const Expr *> SrcExprs,
1978 ArrayRef<const Expr *> DstExprs,
1979 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001980 if (!CGF.HaveInsertPoint())
1981 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001982 assert(CopyprivateVars.size() == SrcExprs.size() &&
1983 CopyprivateVars.size() == DstExprs.size() &&
1984 CopyprivateVars.size() == AssignmentOps.size());
1985 auto &C = CGM.getContext();
1986 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001987 // if(__kmpc_single(ident_t *, gtid)) {
1988 // SingleOpGen();
1989 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001990 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001991 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001992 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1993 // <copy_func>, did_it);
1994
John McCall7f416cc2015-09-08 08:05:57 +00001995 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001996 if (!CopyprivateVars.empty()) {
1997 // int32 did_it = 0;
1998 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1999 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002000 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002001 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002002 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002003 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002004 auto *IsSingle =
2005 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00002006 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
2007 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002008 emitIfStmt(
2009 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
2010 CodeGenFunction::RunCleanupsScope Scope(CGF);
2011 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
2012 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
2013 llvm::makeArrayRef(Args));
2014 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002015 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002016 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00002017 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002018 }
2019 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00002020 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2021 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002022 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002023 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2024 auto CopyprivateArrayTy =
2025 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2026 /*IndexTypeQuals=*/0);
2027 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002028 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002029 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2030 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002031 Address Elem = CGF.Builder.CreateConstArrayGEP(
2032 CopyprivateList, I, CGF.getPointerSize());
2033 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002034 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002035 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2036 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002037 }
2038 // Build function that copies private values from single region to all other
2039 // threads in the corresponding parallel region.
2040 auto *CpyFn = emitCopyprivateCopyFunction(
2041 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002042 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002043 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002044 Address CL =
2045 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2046 CGF.VoidPtrTy);
2047 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002048 llvm::Value *Args[] = {
2049 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2050 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002051 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002052 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002053 CpyFn, // void (*) (void *, void *) <copy_func>
2054 DidItVal // i32 did_it
2055 };
2056 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2057 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002058}
2059
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002060void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2061 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002062 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002063 if (!CGF.HaveInsertPoint())
2064 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002065 // __kmpc_ordered(ident_t *, gtid);
2066 // OrderedOpGen();
2067 // __kmpc_end_ordered(ident_t *, gtid);
2068 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002069 CodeGenFunction::RunCleanupsScope Scope(CGF);
2070 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002071 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2072 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
2073 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00002074 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002075 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2076 llvm::makeArrayRef(Args));
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002077 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002078 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002079}
2080
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002081void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002082 OpenMPDirectiveKind Kind, bool EmitChecks,
2083 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002084 if (!CGF.HaveInsertPoint())
2085 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002086 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002087 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002088 unsigned Flags;
2089 if (Kind == OMPD_for)
2090 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2091 else if (Kind == OMPD_sections)
2092 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2093 else if (Kind == OMPD_single)
2094 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2095 else if (Kind == OMPD_barrier)
2096 Flags = OMP_IDENT_BARRIER_EXPL;
2097 else
2098 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002099 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2100 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002101 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2102 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002103 if (auto *OMPRegionInfo =
2104 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002105 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002106 auto *Result = CGF.EmitRuntimeCall(
2107 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002108 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002109 // if (__kmpc_cancel_barrier()) {
2110 // exit from construct;
2111 // }
2112 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2113 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2114 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2115 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2116 CGF.EmitBlock(ExitBB);
2117 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002118 auto CancelDestination =
2119 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002120 CGF.EmitBranchThroughCleanup(CancelDestination);
2121 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2122 }
2123 return;
2124 }
2125 }
2126 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002127}
2128
Alexander Musmanc6388682014-12-15 07:07:06 +00002129/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2130static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002131 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002132 switch (ScheduleKind) {
2133 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002134 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2135 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002136 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002137 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002138 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002139 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002140 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002141 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2142 case OMPC_SCHEDULE_auto:
2143 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002144 case OMPC_SCHEDULE_unknown:
2145 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002146 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002147 }
2148 llvm_unreachable("Unexpected runtime schedule");
2149}
2150
2151bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2152 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002153 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002154 return Schedule == OMP_sch_static;
2155}
2156
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002157bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002158 auto Schedule =
2159 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002160 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2161 return Schedule != OMP_sch_static;
2162}
2163
John McCall7f416cc2015-09-08 08:05:57 +00002164void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2165 SourceLocation Loc,
2166 OpenMPScheduleClauseKind ScheduleKind,
2167 unsigned IVSize, bool IVSigned,
2168 bool Ordered, llvm::Value *UB,
2169 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002170 if (!CGF.HaveInsertPoint())
2171 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002172 OpenMPSchedType Schedule =
2173 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002174 assert(Ordered ||
2175 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2176 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2177 // Call __kmpc_dispatch_init(
2178 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2179 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2180 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002181
John McCall7f416cc2015-09-08 08:05:57 +00002182 // If the Chunk was not specified in the clause - use default value 1.
2183 if (Chunk == nullptr)
2184 Chunk = CGF.Builder.getIntN(IVSize, 1);
2185 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002186 emitUpdateLocation(CGF, Loc),
2187 getThreadID(CGF, Loc),
2188 CGF.Builder.getInt32(Schedule), // Schedule type
2189 CGF.Builder.getIntN(IVSize, 0), // Lower
2190 UB, // Upper
2191 CGF.Builder.getIntN(IVSize, 1), // Stride
2192 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002193 };
2194 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2195}
2196
2197void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2198 SourceLocation Loc,
2199 OpenMPScheduleClauseKind ScheduleKind,
2200 unsigned IVSize, bool IVSigned,
2201 bool Ordered, Address IL, Address LB,
2202 Address UB, Address ST,
2203 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002204 if (!CGF.HaveInsertPoint())
2205 return;
John McCall7f416cc2015-09-08 08:05:57 +00002206 OpenMPSchedType Schedule =
2207 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
2208 assert(!Ordered);
2209 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2210 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked);
2211
2212 // Call __kmpc_for_static_init(
2213 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2214 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2215 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2216 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2217 if (Chunk == nullptr) {
2218 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
2219 "expected static non-chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00002220 // If the Chunk was not specified in the clause - use default value 1.
Alexander Musman92bdaab2015-03-12 13:37:50 +00002221 Chunk = CGF.Builder.getIntN(IVSize, 1);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002222 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002223 assert((Schedule == OMP_sch_static_chunked ||
2224 Schedule == OMP_ord_static_chunked) &&
2225 "expected static chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00002226 }
John McCall7f416cc2015-09-08 08:05:57 +00002227 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002228 emitUpdateLocation(CGF, Loc),
2229 getThreadID(CGF, Loc),
2230 CGF.Builder.getInt32(Schedule), // Schedule type
2231 IL.getPointer(), // &isLastIter
2232 LB.getPointer(), // &LB
2233 UB.getPointer(), // &UB
2234 ST.getPointer(), // &Stride
2235 CGF.Builder.getIntN(IVSize, 1), // Incr
2236 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002237 };
2238 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002239}
2240
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002241void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2242 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002243 if (!CGF.HaveInsertPoint())
2244 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002245 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002246 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002247 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2248 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002249}
2250
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002251void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2252 SourceLocation Loc,
2253 unsigned IVSize,
2254 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002255 if (!CGF.HaveInsertPoint())
2256 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002257 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002258 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002259 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2260}
2261
Alexander Musman92bdaab2015-03-12 13:37:50 +00002262llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2263 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002264 bool IVSigned, Address IL,
2265 Address LB, Address UB,
2266 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002267 // Call __kmpc_dispatch_next(
2268 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2269 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2270 // kmp_int[32|64] *p_stride);
2271 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002272 emitUpdateLocation(CGF, Loc),
2273 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002274 IL.getPointer(), // &isLastIter
2275 LB.getPointer(), // &Lower
2276 UB.getPointer(), // &Upper
2277 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002278 };
2279 llvm::Value *Call =
2280 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2281 return CGF.EmitScalarConversion(
2282 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002283 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002284}
2285
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002286void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2287 llvm::Value *NumThreads,
2288 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002289 if (!CGF.HaveInsertPoint())
2290 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002291 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2292 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002293 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002294 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002295 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2296 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002297}
2298
Alexey Bataev7f210c62015-06-18 13:40:03 +00002299void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2300 OpenMPProcBindClauseKind ProcBind,
2301 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002302 if (!CGF.HaveInsertPoint())
2303 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002304 // Constants for proc bind value accepted by the runtime.
2305 enum ProcBindTy {
2306 ProcBindFalse = 0,
2307 ProcBindTrue,
2308 ProcBindMaster,
2309 ProcBindClose,
2310 ProcBindSpread,
2311 ProcBindIntel,
2312 ProcBindDefault
2313 } RuntimeProcBind;
2314 switch (ProcBind) {
2315 case OMPC_PROC_BIND_master:
2316 RuntimeProcBind = ProcBindMaster;
2317 break;
2318 case OMPC_PROC_BIND_close:
2319 RuntimeProcBind = ProcBindClose;
2320 break;
2321 case OMPC_PROC_BIND_spread:
2322 RuntimeProcBind = ProcBindSpread;
2323 break;
2324 case OMPC_PROC_BIND_unknown:
2325 llvm_unreachable("Unsupported proc_bind value.");
2326 }
2327 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2328 llvm::Value *Args[] = {
2329 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2330 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2331 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2332}
2333
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002334void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2335 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002336 if (!CGF.HaveInsertPoint())
2337 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002338 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002339 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2340 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002341}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002342
Alexey Bataev62b63b12015-03-10 07:28:44 +00002343namespace {
2344/// \brief Indexes of fields for type kmp_task_t.
2345enum KmpTaskTFields {
2346 /// \brief List of shared variables.
2347 KmpTaskTShareds,
2348 /// \brief Task routine.
2349 KmpTaskTRoutine,
2350 /// \brief Partition id for the untied tasks.
2351 KmpTaskTPartId,
2352 /// \brief Function with call of destructors for private variables.
2353 KmpTaskTDestructors,
2354};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002355} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002356
Samuel Antaoee8fb302016-01-06 13:42:12 +00002357bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2358 // FIXME: Add other entries type when they become supported.
2359 return OffloadEntriesTargetRegion.empty();
2360}
2361
2362/// \brief Initialize target region entry.
2363void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2364 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2365 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002366 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002367 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2368 "only required for the device "
2369 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002370 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002371 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2372 ++OffloadingEntriesNum;
2373}
2374
2375void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2376 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2377 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002378 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002379 // If we are emitting code for a target, the entry is already initialized,
2380 // only has to be registered.
2381 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002382 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002383 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002384 auto &Entry =
2385 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002386 assert(Entry.isValid() && "Entry not initialized!");
2387 Entry.setAddress(Addr);
2388 Entry.setID(ID);
2389 return;
2390 } else {
2391 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002392 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002393 }
2394}
2395
2396bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002397 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2398 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002399 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2400 if (PerDevice == OffloadEntriesTargetRegion.end())
2401 return false;
2402 auto PerFile = PerDevice->second.find(FileID);
2403 if (PerFile == PerDevice->second.end())
2404 return false;
2405 auto PerParentName = PerFile->second.find(ParentName);
2406 if (PerParentName == PerFile->second.end())
2407 return false;
2408 auto PerLine = PerParentName->second.find(LineNum);
2409 if (PerLine == PerParentName->second.end())
2410 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002411 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002412 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002413 return false;
2414 return true;
2415}
2416
2417void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2418 const OffloadTargetRegionEntryInfoActTy &Action) {
2419 // Scan all target region entries and perform the provided action.
2420 for (auto &D : OffloadEntriesTargetRegion)
2421 for (auto &F : D.second)
2422 for (auto &P : F.second)
2423 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002424 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002425}
2426
2427/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2428/// \a Codegen. This is used to emit the two functions that register and
2429/// unregister the descriptor of the current compilation unit.
2430static llvm::Function *
2431createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2432 const RegionCodeGenTy &Codegen) {
2433 auto &C = CGM.getContext();
2434 FunctionArgList Args;
2435 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2436 /*Id=*/nullptr, C.VoidPtrTy);
2437 Args.push_back(&DummyPtr);
2438
2439 CodeGenFunction CGF(CGM);
2440 GlobalDecl();
2441 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2442 C.VoidTy, Args, FunctionType::ExtInfo(),
2443 /*isVariadic=*/false);
2444 auto FTy = CGM.getTypes().GetFunctionType(FI);
2445 auto *Fn =
2446 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2447 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2448 Codegen(CGF);
2449 CGF.FinishFunction();
2450 return Fn;
2451}
2452
2453llvm::Function *
2454CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2455
2456 // If we don't have entries or if we are emitting code for the device, we
2457 // don't need to do anything.
2458 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2459 return nullptr;
2460
2461 auto &M = CGM.getModule();
2462 auto &C = CGM.getContext();
2463
2464 // Get list of devices we care about
2465 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2466
2467 // We should be creating an offloading descriptor only if there are devices
2468 // specified.
2469 assert(!Devices.empty() && "No OpenMP offloading devices??");
2470
2471 // Create the external variables that will point to the begin and end of the
2472 // host entries section. These will be defined by the linker.
2473 auto *OffloadEntryTy =
2474 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2475 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2476 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002477 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002478 ".omp_offloading.entries_begin");
2479 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2480 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002481 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002482 ".omp_offloading.entries_end");
2483
2484 // Create all device images
2485 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2486 auto *DeviceImageTy = cast<llvm::StructType>(
2487 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2488
2489 for (unsigned i = 0; i < Devices.size(); ++i) {
2490 StringRef T = Devices[i].getTriple();
2491 auto *ImgBegin = new llvm::GlobalVariable(
2492 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002493 /*Initializer=*/nullptr,
2494 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002495 auto *ImgEnd = new llvm::GlobalVariable(
2496 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002497 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002498
2499 llvm::Constant *Dev =
2500 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2501 HostEntriesBegin, HostEntriesEnd, nullptr);
2502 DeviceImagesEntires.push_back(Dev);
2503 }
2504
2505 // Create device images global array.
2506 llvm::ArrayType *DeviceImagesInitTy =
2507 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2508 llvm::Constant *DeviceImagesInit =
2509 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2510
2511 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2512 M, DeviceImagesInitTy, /*isConstant=*/true,
2513 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2514 ".omp_offloading.device_images");
2515 DeviceImages->setUnnamedAddr(true);
2516
2517 // This is a Zero array to be used in the creation of the constant expressions
2518 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2519 llvm::Constant::getNullValue(CGM.Int32Ty)};
2520
2521 // Create the target region descriptor.
2522 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2523 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2524 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2525 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2526 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2527 Index),
2528 HostEntriesBegin, HostEntriesEnd, nullptr);
2529
2530 auto *Desc = new llvm::GlobalVariable(
2531 M, BinaryDescriptorTy, /*isConstant=*/true,
2532 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2533 ".omp_offloading.descriptor");
2534
2535 // Emit code to register or unregister the descriptor at execution
2536 // startup or closing, respectively.
2537
2538 // Create a variable to drive the registration and unregistration of the
2539 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2540 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2541 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2542 IdentInfo, C.CharTy);
2543
2544 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2545 CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2546 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2547 Desc);
2548 });
2549 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2550 CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2551 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2552 Desc);
2553 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2554 });
2555 return RegFn;
2556}
2557
Samuel Antao2de62b02016-02-13 23:35:10 +00002558void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2559 llvm::Constant *Addr, uint64_t Size) {
2560 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002561 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2562 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2563 llvm::LLVMContext &C = CGM.getModule().getContext();
2564 llvm::Module &M = CGM.getModule();
2565
2566 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002567 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002568
2569 // Create constant string with the name.
2570 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2571
2572 llvm::GlobalVariable *Str =
2573 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2574 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2575 ".omp_offloading.entry_name");
2576 Str->setUnnamedAddr(true);
2577 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2578
2579 // Create the entry struct.
2580 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2581 TgtOffloadEntryType, AddrPtr, StrPtr,
2582 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2583 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2584 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2585 EntryInit, ".omp_offloading.entry");
2586
2587 // The entry has to be created in the section the linker expects it to be.
2588 Entry->setSection(".omp_offloading.entries");
2589 // We can't have any padding between symbols, so we need to have 1-byte
2590 // alignment.
2591 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002592}
2593
2594void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2595 // Emit the offloading entries and metadata so that the device codegen side
2596 // can
2597 // easily figure out what to emit. The produced metadata looks like this:
2598 //
2599 // !omp_offload.info = !{!1, ...}
2600 //
2601 // Right now we only generate metadata for function that contain target
2602 // regions.
2603
2604 // If we do not have entries, we dont need to do anything.
2605 if (OffloadEntriesInfoManager.empty())
2606 return;
2607
2608 llvm::Module &M = CGM.getModule();
2609 llvm::LLVMContext &C = M.getContext();
2610 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2611 OrderedEntries(OffloadEntriesInfoManager.size());
2612
2613 // Create the offloading info metadata node.
2614 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2615
2616 // Auxiliar methods to create metadata values and strings.
2617 auto getMDInt = [&](unsigned v) {
2618 return llvm::ConstantAsMetadata::get(
2619 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2620 };
2621
2622 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2623
2624 // Create function that emits metadata for each target region entry;
2625 auto &&TargetRegionMetadataEmitter = [&](
2626 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002627 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2628 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2629 // Generate metadata for target regions. Each entry of this metadata
2630 // contains:
2631 // - Entry 0 -> Kind of this type of metadata (0).
2632 // - Entry 1 -> Device ID of the file where the entry was identified.
2633 // - Entry 2 -> File ID of the file where the entry was identified.
2634 // - Entry 3 -> Mangled name of the function where the entry was identified.
2635 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002636 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002637 // The first element of the metadata node is the kind.
2638 Ops.push_back(getMDInt(E.getKind()));
2639 Ops.push_back(getMDInt(DeviceID));
2640 Ops.push_back(getMDInt(FileID));
2641 Ops.push_back(getMDString(ParentName));
2642 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002643 Ops.push_back(getMDInt(E.getOrder()));
2644
2645 // Save this entry in the right position of the ordered entries array.
2646 OrderedEntries[E.getOrder()] = &E;
2647
2648 // Add metadata to the named metadata node.
2649 MD->addOperand(llvm::MDNode::get(C, Ops));
2650 };
2651
2652 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2653 TargetRegionMetadataEmitter);
2654
2655 for (auto *E : OrderedEntries) {
2656 assert(E && "All ordered entries must exist!");
2657 if (auto *CE =
2658 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2659 E)) {
2660 assert(CE->getID() && CE->getAddress() &&
2661 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002662 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002663 } else
2664 llvm_unreachable("Unsupported entry kind.");
2665 }
2666}
2667
2668/// \brief Loads all the offload entries information from the host IR
2669/// metadata.
2670void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2671 // If we are in target mode, load the metadata from the host IR. This code has
2672 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2673
2674 if (!CGM.getLangOpts().OpenMPIsDevice)
2675 return;
2676
2677 if (CGM.getLangOpts().OMPHostIRFile.empty())
2678 return;
2679
2680 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2681 if (Buf.getError())
2682 return;
2683
2684 llvm::LLVMContext C;
2685 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2686
2687 if (ME.getError())
2688 return;
2689
2690 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2691 if (!MD)
2692 return;
2693
2694 for (auto I : MD->operands()) {
2695 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2696
2697 auto getMDInt = [&](unsigned Idx) {
2698 llvm::ConstantAsMetadata *V =
2699 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2700 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2701 };
2702
2703 auto getMDString = [&](unsigned Idx) {
2704 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2705 return V->getString();
2706 };
2707
2708 switch (getMDInt(0)) {
2709 default:
2710 llvm_unreachable("Unexpected metadata!");
2711 break;
2712 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2713 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2714 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2715 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2716 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002717 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002718 break;
2719 }
2720 }
2721}
2722
Alexey Bataev62b63b12015-03-10 07:28:44 +00002723void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2724 if (!KmpRoutineEntryPtrTy) {
2725 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2726 auto &C = CGM.getContext();
2727 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2728 FunctionProtoType::ExtProtoInfo EPI;
2729 KmpRoutineEntryPtrQTy = C.getPointerType(
2730 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2731 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2732 }
2733}
2734
Alexey Bataevc71a4092015-09-11 10:29:41 +00002735static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2736 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002737 auto *Field = FieldDecl::Create(
2738 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2739 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2740 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2741 Field->setAccess(AS_public);
2742 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002743 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002744}
2745
Samuel Antaoee8fb302016-01-06 13:42:12 +00002746QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2747
2748 // Make sure the type of the entry is already created. This is the type we
2749 // have to create:
2750 // struct __tgt_offload_entry{
2751 // void *addr; // Pointer to the offload entry info.
2752 // // (function or global)
2753 // char *name; // Name of the function or global.
2754 // size_t size; // Size of the entry info (0 if it a function).
2755 // };
2756 if (TgtOffloadEntryQTy.isNull()) {
2757 ASTContext &C = CGM.getContext();
2758 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2759 RD->startDefinition();
2760 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2761 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2762 addFieldToRecordDecl(C, RD, C.getSizeType());
2763 RD->completeDefinition();
2764 TgtOffloadEntryQTy = C.getRecordType(RD);
2765 }
2766 return TgtOffloadEntryQTy;
2767}
2768
2769QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2770 // These are the types we need to build:
2771 // struct __tgt_device_image{
2772 // void *ImageStart; // Pointer to the target code start.
2773 // void *ImageEnd; // Pointer to the target code end.
2774 // // We also add the host entries to the device image, as it may be useful
2775 // // for the target runtime to have access to that information.
2776 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2777 // // the entries.
2778 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2779 // // entries (non inclusive).
2780 // };
2781 if (TgtDeviceImageQTy.isNull()) {
2782 ASTContext &C = CGM.getContext();
2783 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2784 RD->startDefinition();
2785 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2786 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2787 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2788 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2789 RD->completeDefinition();
2790 TgtDeviceImageQTy = C.getRecordType(RD);
2791 }
2792 return TgtDeviceImageQTy;
2793}
2794
2795QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2796 // struct __tgt_bin_desc{
2797 // int32_t NumDevices; // Number of devices supported.
2798 // __tgt_device_image *DeviceImages; // Arrays of device images
2799 // // (one per device).
2800 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2801 // // entries.
2802 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2803 // // entries (non inclusive).
2804 // };
2805 if (TgtBinaryDescriptorQTy.isNull()) {
2806 ASTContext &C = CGM.getContext();
2807 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2808 RD->startDefinition();
2809 addFieldToRecordDecl(
2810 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2811 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2812 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2813 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2814 RD->completeDefinition();
2815 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2816 }
2817 return TgtBinaryDescriptorQTy;
2818}
2819
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002820namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002821struct PrivateHelpersTy {
2822 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2823 const VarDecl *PrivateElemInit)
2824 : Original(Original), PrivateCopy(PrivateCopy),
2825 PrivateElemInit(PrivateElemInit) {}
2826 const VarDecl *Original;
2827 const VarDecl *PrivateCopy;
2828 const VarDecl *PrivateElemInit;
2829};
2830typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002831} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002832
Alexey Bataev9e034042015-05-05 04:05:12 +00002833static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002834createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002835 if (!Privates.empty()) {
2836 auto &C = CGM.getContext();
2837 // Build struct .kmp_privates_t. {
2838 // /* private vars */
2839 // };
2840 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2841 RD->startDefinition();
2842 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002843 auto *VD = Pair.second.Original;
2844 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002845 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002846 auto *FD = addFieldToRecordDecl(C, RD, Type);
2847 if (VD->hasAttrs()) {
2848 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2849 E(VD->getAttrs().end());
2850 I != E; ++I)
2851 FD->addAttr(*I);
2852 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002853 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002854 RD->completeDefinition();
2855 return RD;
2856 }
2857 return nullptr;
2858}
2859
Alexey Bataev9e034042015-05-05 04:05:12 +00002860static RecordDecl *
2861createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002862 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002863 auto &C = CGM.getContext();
2864 // Build struct kmp_task_t {
2865 // void * shareds;
2866 // kmp_routine_entry_t routine;
2867 // kmp_int32 part_id;
2868 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002869 // };
2870 auto *RD = C.buildImplicitRecord("kmp_task_t");
2871 RD->startDefinition();
2872 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2873 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2874 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2875 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002876 RD->completeDefinition();
2877 return RD;
2878}
2879
2880static RecordDecl *
2881createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002882 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002883 auto &C = CGM.getContext();
2884 // Build struct kmp_task_t_with_privates {
2885 // kmp_task_t task_data;
2886 // .kmp_privates_t. privates;
2887 // };
2888 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2889 RD->startDefinition();
2890 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002891 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2892 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2893 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002894 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002895 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002896}
2897
2898/// \brief Emit a proxy function which accepts kmp_task_t as the second
2899/// argument.
2900/// \code
2901/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002902/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2903/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002904/// return 0;
2905/// }
2906/// \endcode
2907static llvm::Value *
2908emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002909 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2910 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002911 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2912 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002913 auto &C = CGM.getContext();
2914 FunctionArgList Args;
2915 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2916 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002917 /*Id=*/nullptr,
2918 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002919 Args.push_back(&GtidArg);
2920 Args.push_back(&TaskTypeArg);
2921 FunctionType::ExtInfo Info;
2922 auto &TaskEntryFnInfo =
2923 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2924 /*isVariadic=*/false);
2925 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2926 auto *TaskEntry =
2927 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2928 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002929 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002930 CodeGenFunction CGF(CGM);
2931 CGF.disableDebugInfo();
2932 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2933
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002934 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2935 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002936 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002937 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002938 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2939 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2940 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002941 auto *KmpTaskTWithPrivatesQTyRD =
2942 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002943 LValue Base =
2944 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002945 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2946 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2947 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
2948 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
2949
2950 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
2951 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002952 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002953 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002954 CGF.ConvertTypeForMem(SharedsPtrTy));
2955
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002956 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
2957 llvm::Value *PrivatesParam;
2958 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
2959 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
2960 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002961 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002962 } else {
2963 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2964 }
2965
2966 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
2967 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002968 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2969 CGF.EmitStoreThroughLValue(
2970 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002971 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002972 CGF.FinishFunction();
2973 return TaskEntry;
2974}
2975
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002976static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2977 SourceLocation Loc,
2978 QualType KmpInt32Ty,
2979 QualType KmpTaskTWithPrivatesPtrQTy,
2980 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002981 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002982 FunctionArgList Args;
2983 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2984 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002985 /*Id=*/nullptr,
2986 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002987 Args.push_back(&GtidArg);
2988 Args.push_back(&TaskTypeArg);
2989 FunctionType::ExtInfo Info;
2990 auto &DestructorFnInfo =
2991 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2992 /*isVariadic=*/false);
2993 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2994 auto *DestructorFn =
2995 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2996 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002997 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
2998 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002999 CodeGenFunction CGF(CGM);
3000 CGF.disableDebugInfo();
3001 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3002 Args);
3003
Alexey Bataev31300ed2016-02-04 11:27:03 +00003004 LValue Base = CGF.EmitLoadOfPointerLValue(
3005 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3006 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003007 auto *KmpTaskTWithPrivatesQTyRD =
3008 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3009 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003010 Base = CGF.EmitLValueForField(Base, *FI);
3011 for (auto *Field :
3012 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3013 if (auto DtorKind = Field->getType().isDestructedType()) {
3014 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3015 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3016 }
3017 }
3018 CGF.FinishFunction();
3019 return DestructorFn;
3020}
3021
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003022/// \brief Emit a privates mapping function for correct handling of private and
3023/// firstprivate variables.
3024/// \code
3025/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3026/// **noalias priv1,..., <tyn> **noalias privn) {
3027/// *priv1 = &.privates.priv1;
3028/// ...;
3029/// *privn = &.privates.privn;
3030/// }
3031/// \endcode
3032static llvm::Value *
3033emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003034 ArrayRef<const Expr *> PrivateVars,
3035 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003036 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003037 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003038 auto &C = CGM.getContext();
3039 FunctionArgList Args;
3040 ImplicitParamDecl TaskPrivatesArg(
3041 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3042 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3043 Args.push_back(&TaskPrivatesArg);
3044 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3045 unsigned Counter = 1;
3046 for (auto *E: PrivateVars) {
3047 Args.push_back(ImplicitParamDecl::Create(
3048 C, /*DC=*/nullptr, Loc,
3049 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3050 .withConst()
3051 .withRestrict()));
3052 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3053 PrivateVarsPos[VD] = Counter;
3054 ++Counter;
3055 }
3056 for (auto *E : FirstprivateVars) {
3057 Args.push_back(ImplicitParamDecl::Create(
3058 C, /*DC=*/nullptr, Loc,
3059 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3060 .withConst()
3061 .withRestrict()));
3062 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3063 PrivateVarsPos[VD] = Counter;
3064 ++Counter;
3065 }
3066 FunctionType::ExtInfo Info;
3067 auto &TaskPrivatesMapFnInfo =
3068 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
3069 /*isVariadic=*/false);
3070 auto *TaskPrivatesMapTy =
3071 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3072 auto *TaskPrivatesMap = llvm::Function::Create(
3073 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3074 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003075 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3076 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003077 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003078 CodeGenFunction CGF(CGM);
3079 CGF.disableDebugInfo();
3080 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3081 TaskPrivatesMapFnInfo, Args);
3082
3083 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003084 LValue Base = CGF.EmitLoadOfPointerLValue(
3085 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3086 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003087 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3088 Counter = 0;
3089 for (auto *Field : PrivatesQTyRD->fields()) {
3090 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3091 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003092 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003093 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3094 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003095 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003096 ++Counter;
3097 }
3098 CGF.FinishFunction();
3099 return TaskPrivatesMap;
3100}
3101
Alexey Bataev9e034042015-05-05 04:05:12 +00003102static int array_pod_sort_comparator(const PrivateDataTy *P1,
3103 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003104 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3105}
3106
3107void CGOpenMPRuntime::emitTaskCall(
3108 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3109 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00003110 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003111 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3112 ArrayRef<const Expr *> PrivateCopies,
3113 ArrayRef<const Expr *> FirstprivateVars,
3114 ArrayRef<const Expr *> FirstprivateCopies,
3115 ArrayRef<const Expr *> FirstprivateInits,
3116 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003117 if (!CGF.HaveInsertPoint())
3118 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003119 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00003120 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003121 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003122 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003123 for (auto *E : PrivateVars) {
3124 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3125 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003126 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003127 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3128 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003129 ++I;
3130 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003131 I = FirstprivateCopies.begin();
3132 auto IElemInitRef = FirstprivateInits.begin();
3133 for (auto *E : FirstprivateVars) {
3134 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3135 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003136 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003137 PrivateHelpersTy(
3138 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3139 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003140 ++I;
3141 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003142 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003143 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3144 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003145 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3146 // Build type kmp_routine_entry_t (if not built yet).
3147 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003148 // Build type kmp_task_t (if not built yet).
3149 if (KmpTaskTQTy.isNull()) {
3150 KmpTaskTQTy = C.getRecordType(
3151 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
3152 }
3153 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003154 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003155 auto *KmpTaskTWithPrivatesQTyRD =
3156 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3157 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3158 QualType KmpTaskTWithPrivatesPtrQTy =
3159 C.getPointerType(KmpTaskTWithPrivatesQTy);
3160 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3161 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003162 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003163 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3164
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003165 // Emit initial values for private copies (if any).
3166 llvm::Value *TaskPrivatesMap = nullptr;
3167 auto *TaskPrivatesMapTy =
3168 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3169 3)
3170 ->getType();
3171 if (!Privates.empty()) {
3172 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3173 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3174 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3175 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3176 TaskPrivatesMap, TaskPrivatesMapTy);
3177 } else {
3178 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3179 cast<llvm::PointerType>(TaskPrivatesMapTy));
3180 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003181 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3182 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003183 auto *TaskEntry = emitProxyTaskFunction(
3184 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003185 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003186
3187 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3188 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3189 // kmp_routine_entry_t *task_entry);
3190 // Task flags. Format is taken from
3191 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3192 // description of kmp_tasking_flags struct.
3193 const unsigned TiedFlag = 0x1;
3194 const unsigned FinalFlag = 0x2;
3195 unsigned Flags = Tied ? TiedFlag : 0;
3196 auto *TaskFlags =
3197 Final.getPointer()
3198 ? CGF.Builder.CreateSelect(Final.getPointer(),
3199 CGF.Builder.getInt32(FinalFlag),
3200 CGF.Builder.getInt32(/*C=*/0))
3201 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3202 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003203 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003204 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3205 getThreadID(CGF, Loc), TaskFlags,
3206 KmpTaskTWithPrivatesTySize, SharedsSize,
3207 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3208 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003209 auto *NewTask = CGF.EmitRuntimeCall(
3210 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003211 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3212 NewTask, KmpTaskTWithPrivatesPtrTy);
3213 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3214 KmpTaskTWithPrivatesQTy);
3215 LValue TDBase =
3216 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003217 // Fill the data in the resulting kmp_task_t record.
3218 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003219 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003220 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003221 KmpTaskSharedsPtr =
3222 Address(CGF.EmitLoadOfScalar(
3223 CGF.EmitLValueForField(
3224 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3225 KmpTaskTShareds)),
3226 Loc),
3227 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003228 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003229 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003230 // Emit initial values for private copies (if any).
3231 bool NeedsCleanup = false;
3232 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003233 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3234 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003235 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003236 LValue SharedsBase;
3237 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003238 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003239 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3240 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3241 SharedsTy);
3242 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003243 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3244 cast<CapturedStmt>(*D.getAssociatedStmt()));
3245 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003246 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003247 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003248 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003249 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003250 if (auto *Elem = Pair.second.PrivateElemInit) {
3251 auto *OriginalVD = Pair.second.Original;
3252 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3253 auto SharedRefLValue =
3254 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003255 SharedRefLValue = CGF.MakeAddrLValue(
3256 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3257 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003258 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003259 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003260 // Initialize firstprivate array.
3261 if (!isa<CXXConstructExpr>(Init) ||
3262 CGF.isTrivialInitializer(Init)) {
3263 // Perform simple memcpy.
3264 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003265 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003266 } else {
3267 // Initialize firstprivate array using element-by-element
3268 // intialization.
3269 CGF.EmitOMPAggregateAssign(
3270 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003271 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003272 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003273 // Clean up any temporaries needed by the initialization.
3274 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003275 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003276 return SrcElement;
3277 });
3278 (void)InitScope.Privatize();
3279 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003280 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3281 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003282 CGF.EmitAnyExprToMem(Init, DestElement,
3283 Init->getType().getQualifiers(),
3284 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003285 });
3286 }
3287 } else {
3288 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003289 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003290 return SharedRefLValue.getAddress();
3291 });
3292 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003293 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003294 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3295 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003296 }
3297 } else {
3298 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3299 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003300 }
3301 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003302 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003303 }
3304 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003305 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003306 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003307 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3308 KmpTaskTWithPrivatesPtrQTy,
3309 KmpTaskTWithPrivatesQTy)
3310 : llvm::ConstantPointerNull::get(
3311 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3312 LValue Destructor = CGF.EmitLValueForField(
3313 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3314 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3315 DestructorFn, KmpRoutineEntryPtrTy),
3316 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003317
3318 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003319 Address DependenciesArray = Address::invalid();
3320 unsigned NumDependencies = Dependences.size();
3321 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003322 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003323 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003324 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3325 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003326 QualType FlagsTy =
3327 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003328 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3329 if (KmpDependInfoTy.isNull()) {
3330 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3331 KmpDependInfoRD->startDefinition();
3332 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3333 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3334 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3335 KmpDependInfoRD->completeDefinition();
3336 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3337 } else {
3338 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3339 }
John McCall7f416cc2015-09-08 08:05:57 +00003340 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003341 // Define type kmp_depend_info[<Dependences.size()>];
3342 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003343 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003344 ArrayType::Normal, /*IndexTypeQuals=*/0);
3345 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00003346 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
3347 for (unsigned i = 0; i < NumDependencies; ++i) {
3348 const Expr *E = Dependences[i].second;
3349 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003350 llvm::Value *Size;
3351 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003352 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3353 LValue UpAddrLVal =
3354 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3355 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003356 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003357 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003358 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003359 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3360 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003361 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003362 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003363 auto Base = CGF.MakeAddrLValue(
3364 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003365 KmpDependInfoTy);
3366 // deps[i].base_addr = &<Dependences[i].second>;
3367 auto BaseAddrLVal = CGF.EmitLValueForField(
3368 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003369 CGF.EmitStoreOfScalar(
3370 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3371 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003372 // deps[i].len = sizeof(<Dependences[i].second>);
3373 auto LenLVal = CGF.EmitLValueForField(
3374 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3375 CGF.EmitStoreOfScalar(Size, LenLVal);
3376 // deps[i].flags = <Dependences[i].first>;
3377 RTLDependenceKindTy DepKind;
3378 switch (Dependences[i].first) {
3379 case OMPC_DEPEND_in:
3380 DepKind = DepIn;
3381 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003382 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003383 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003384 case OMPC_DEPEND_inout:
3385 DepKind = DepInOut;
3386 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003387 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003388 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003389 case OMPC_DEPEND_unknown:
3390 llvm_unreachable("Unknown task dependence type");
3391 }
3392 auto FlagsLVal = CGF.EmitLValueForField(
3393 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3394 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3395 FlagsLVal);
3396 }
John McCall7f416cc2015-09-08 08:05:57 +00003397 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3398 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003399 CGF.VoidPtrTy);
3400 }
3401
Alexey Bataev62b63b12015-03-10 07:28:44 +00003402 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3403 // libcall.
3404 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3405 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003406 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3407 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3408 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3409 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003410 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003411 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003412 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3413 llvm::Value *DepTaskArgs[7];
3414 if (NumDependencies) {
3415 DepTaskArgs[0] = UpLoc;
3416 DepTaskArgs[1] = ThreadID;
3417 DepTaskArgs[2] = NewTask;
3418 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3419 DepTaskArgs[4] = DependenciesArray.getPointer();
3420 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3421 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3422 }
3423 auto &&ThenCodeGen = [this, NumDependencies,
3424 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3425 // TODO: add check for untied tasks.
3426 if (NumDependencies) {
3427 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3428 DepTaskArgs);
3429 } else {
3430 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3431 TaskArgs);
3432 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003433 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003434 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3435 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00003436
3437 llvm::Value *DepWaitTaskArgs[6];
3438 if (NumDependencies) {
3439 DepWaitTaskArgs[0] = UpLoc;
3440 DepWaitTaskArgs[1] = ThreadID;
3441 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3442 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3443 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3444 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3445 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003446 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00003447 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003448 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3449 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3450 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3451 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3452 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003453 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003454 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3455 DepWaitTaskArgs);
3456 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3457 // kmp_task_t *new_task);
3458 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3459 TaskArgs);
3460 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3461 // kmp_task_t *new_task);
3462 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3463 NormalAndEHCleanup,
3464 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3465 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00003466
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003467 // Call proxy_task_entry(gtid, new_task);
3468 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3469 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3470 };
John McCall7f416cc2015-09-08 08:05:57 +00003471
Alexey Bataev1d677132015-04-22 13:57:31 +00003472 if (IfCond) {
3473 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3474 } else {
3475 CodeGenFunction::RunCleanupsScope Scope(CGF);
3476 ThenCodeGen(CGF);
3477 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003478}
3479
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003480/// \brief Emit reduction operation for each element of array (required for
3481/// array sections) LHS op = RHS.
3482/// \param Type Type of array.
3483/// \param LHSVar Variable on the left side of the reduction operation
3484/// (references element of array in original variable).
3485/// \param RHSVar Variable on the right side of the reduction operation
3486/// (references element of array in original variable).
3487/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3488/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003489static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003490 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3491 const VarDecl *RHSVar,
3492 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3493 const Expr *, const Expr *)> &RedOpGen,
3494 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3495 const Expr *UpExpr = nullptr) {
3496 // Perform element-by-element initialization.
3497 QualType ElementTy;
3498 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3499 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3500
3501 // Drill down to the base element type on both arrays.
3502 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3503 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3504
3505 auto RHSBegin = RHSAddr.getPointer();
3506 auto LHSBegin = LHSAddr.getPointer();
3507 // Cast from pointer to array type to pointer to single element.
3508 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3509 // The basic structure here is a while-do loop.
3510 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3511 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3512 auto IsEmpty =
3513 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3514 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3515
3516 // Enter the loop body, making that address the current address.
3517 auto EntryBB = CGF.Builder.GetInsertBlock();
3518 CGF.EmitBlock(BodyBB);
3519
3520 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3521
3522 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3523 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3524 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3525 Address RHSElementCurrent =
3526 Address(RHSElementPHI,
3527 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3528
3529 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3530 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3531 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3532 Address LHSElementCurrent =
3533 Address(LHSElementPHI,
3534 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3535
3536 // Emit copy.
3537 CodeGenFunction::OMPPrivateScope Scope(CGF);
3538 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3539 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3540 Scope.Privatize();
3541 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3542 Scope.ForceCleanup();
3543
3544 // Shift the address forward by one element.
3545 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3546 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3547 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3548 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3549 // Check whether we've reached the end.
3550 auto Done =
3551 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3552 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3553 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3554 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3555
3556 // Done.
3557 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3558}
3559
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003560static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3561 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003562 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003563 ArrayRef<const Expr *> LHSExprs,
3564 ArrayRef<const Expr *> RHSExprs,
3565 ArrayRef<const Expr *> ReductionOps) {
3566 auto &C = CGM.getContext();
3567
3568 // void reduction_func(void *LHSArg, void *RHSArg);
3569 FunctionArgList Args;
3570 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3571 C.VoidPtrTy);
3572 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3573 C.VoidPtrTy);
3574 Args.push_back(&LHSArg);
3575 Args.push_back(&RHSArg);
3576 FunctionType::ExtInfo EI;
3577 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3578 C.VoidTy, Args, EI, /*isVariadic=*/false);
3579 auto *Fn = llvm::Function::Create(
3580 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3581 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003582 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003583 CodeGenFunction CGF(CGM);
3584 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3585
3586 // Dst = (void*[n])(LHSArg);
3587 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003588 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3589 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3590 ArgsType), CGF.getPointerAlign());
3591 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3592 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3593 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003594
3595 // ...
3596 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3597 // ...
3598 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003599 auto IPriv = Privates.begin();
3600 unsigned Idx = 0;
3601 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003602 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3603 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003604 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003605 });
3606 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3607 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003608 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003609 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003610 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003611 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003612 // Get array size and emit VLA type.
3613 ++Idx;
3614 Address Elem =
3615 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3616 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003617 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3618 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003619 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003620 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003621 CGF.EmitVariablyModifiedType(PrivTy);
3622 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003623 }
3624 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003625 IPriv = Privates.begin();
3626 auto ILHS = LHSExprs.begin();
3627 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003628 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003629 if ((*IPriv)->getType()->isArrayType()) {
3630 // Emit reduction for array section.
3631 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3632 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3633 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3634 [=](CodeGenFunction &CGF, const Expr *,
3635 const Expr *,
3636 const Expr *) { CGF.EmitIgnoredExpr(E); });
3637 } else
3638 // Emit reduction for array subscript or single variable.
3639 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003640 ++IPriv;
3641 ++ILHS;
3642 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003643 }
3644 Scope.ForceCleanup();
3645 CGF.FinishFunction();
3646 return Fn;
3647}
3648
3649void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003650 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003651 ArrayRef<const Expr *> LHSExprs,
3652 ArrayRef<const Expr *> RHSExprs,
3653 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003654 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003655 if (!CGF.HaveInsertPoint())
3656 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003657 // Next code should be emitted for reduction:
3658 //
3659 // static kmp_critical_name lock = { 0 };
3660 //
3661 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3662 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3663 // ...
3664 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3665 // *(Type<n>-1*)rhs[<n>-1]);
3666 // }
3667 //
3668 // ...
3669 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3670 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3671 // RedList, reduce_func, &<lock>)) {
3672 // case 1:
3673 // ...
3674 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3675 // ...
3676 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3677 // break;
3678 // case 2:
3679 // ...
3680 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3681 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003682 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003683 // break;
3684 // default:;
3685 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003686 //
3687 // if SimpleReduction is true, only the next code is generated:
3688 // ...
3689 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3690 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003691
3692 auto &C = CGM.getContext();
3693
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003694 if (SimpleReduction) {
3695 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003696 auto IPriv = Privates.begin();
3697 auto ILHS = LHSExprs.begin();
3698 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003699 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003700 if ((*IPriv)->getType()->isArrayType()) {
3701 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3702 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3703 EmitOMPAggregateReduction(
3704 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3705 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3706 const Expr *) { CGF.EmitIgnoredExpr(E); });
3707 } else
3708 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003709 ++IPriv;
3710 ++ILHS;
3711 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003712 }
3713 return;
3714 }
3715
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003716 // 1. Build a list of reduction variables.
3717 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003718 auto Size = RHSExprs.size();
3719 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003720 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003721 // Reserve place for array size.
3722 ++Size;
3723 }
3724 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003725 QualType ReductionArrayTy =
3726 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3727 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003728 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003729 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003730 auto IPriv = Privates.begin();
3731 unsigned Idx = 0;
3732 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003733 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003734 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003735 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003736 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003737 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3738 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003739 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003740 // Store array size.
3741 ++Idx;
3742 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3743 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003744 llvm::Value *Size = CGF.Builder.CreateIntCast(
3745 CGF.getVLASize(
3746 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3747 .first,
3748 CGF.SizeTy, /*isSigned=*/false);
3749 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3750 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003751 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003752 }
3753
3754 // 2. Emit reduce_func().
3755 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003756 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3757 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003758
3759 // 3. Create static kmp_critical_name lock = { 0 };
3760 auto *Lock = getCriticalRegionLock(".reduction");
3761
3762 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3763 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003764 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003765 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003766 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003767 auto *RL =
3768 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3769 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003770 llvm::Value *Args[] = {
3771 IdentTLoc, // ident_t *<loc>
3772 ThreadId, // i32 <gtid>
3773 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3774 ReductionArrayTySize, // size_type sizeof(RedList)
3775 RL, // void *RedList
3776 ReductionFn, // void (*) (void *, void *) <reduce_func>
3777 Lock // kmp_critical_name *&<lock>
3778 };
3779 auto Res = CGF.EmitRuntimeCall(
3780 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3781 : OMPRTL__kmpc_reduce),
3782 Args);
3783
3784 // 5. Build switch(res)
3785 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3786 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3787
3788 // 6. Build case 1:
3789 // ...
3790 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3791 // ...
3792 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3793 // break;
3794 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3795 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3796 CGF.EmitBlock(Case1BB);
3797
3798 {
3799 CodeGenFunction::RunCleanupsScope Scope(CGF);
3800 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3801 llvm::Value *EndArgs[] = {
3802 IdentTLoc, // ident_t *<loc>
3803 ThreadId, // i32 <gtid>
3804 Lock // kmp_critical_name *&<lock>
3805 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003806 CGF.EHStack
3807 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3808 NormalAndEHCleanup,
3809 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3810 : OMPRTL__kmpc_end_reduce),
3811 llvm::makeArrayRef(EndArgs));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003812 auto IPriv = Privates.begin();
3813 auto ILHS = LHSExprs.begin();
3814 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003815 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003816 if ((*IPriv)->getType()->isArrayType()) {
3817 // Emit reduction for array section.
3818 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3819 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3820 EmitOMPAggregateReduction(
3821 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3822 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3823 const Expr *) { CGF.EmitIgnoredExpr(E); });
3824 } else
3825 // Emit reduction for array subscript or single variable.
3826 CGF.EmitIgnoredExpr(E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003827 ++IPriv;
3828 ++ILHS;
3829 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003830 }
3831 }
3832
3833 CGF.EmitBranch(DefaultBB);
3834
3835 // 7. Build case 2:
3836 // ...
3837 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3838 // ...
3839 // break;
3840 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3841 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3842 CGF.EmitBlock(Case2BB);
3843
3844 {
3845 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00003846 if (!WithNowait) {
3847 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3848 llvm::Value *EndArgs[] = {
3849 IdentTLoc, // ident_t *<loc>
3850 ThreadId, // i32 <gtid>
3851 Lock // kmp_critical_name *&<lock>
3852 };
3853 CGF.EHStack
3854 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3855 NormalAndEHCleanup,
3856 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3857 llvm::makeArrayRef(EndArgs));
3858 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003859 auto ILHS = LHSExprs.begin();
3860 auto IRHS = RHSExprs.begin();
3861 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003862 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003863 const Expr *XExpr = nullptr;
3864 const Expr *EExpr = nullptr;
3865 const Expr *UpExpr = nullptr;
3866 BinaryOperatorKind BO = BO_Comma;
3867 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3868 if (BO->getOpcode() == BO_Assign) {
3869 XExpr = BO->getLHS();
3870 UpExpr = BO->getRHS();
3871 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003872 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003873 // Try to emit update expression as a simple atomic.
3874 auto *RHSExpr = UpExpr;
3875 if (RHSExpr) {
3876 // Analyze RHS part of the whole expression.
3877 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3878 RHSExpr->IgnoreParenImpCasts())) {
3879 // If this is a conditional operator, analyze its condition for
3880 // min/max reduction operator.
3881 RHSExpr = ACO->getCond();
3882 }
3883 if (auto *BORHS =
3884 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3885 EExpr = BORHS->getRHS();
3886 BO = BORHS->getOpcode();
3887 }
Alexey Bataev69a47792015-05-07 03:54:03 +00003888 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003889 if (XExpr) {
3890 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3891 auto &&AtomicRedGen = [this, BO, VD, IPriv,
3892 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3893 const Expr *EExpr, const Expr *UpExpr) {
3894 LValue X = CGF.EmitLValue(XExpr);
3895 RValue E;
3896 if (EExpr)
3897 E = CGF.EmitAnyExpr(EExpr);
3898 CGF.EmitOMPAtomicSimpleUpdateExpr(
3899 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
Alexey Bataev8524d152016-01-21 12:35:58 +00003900 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003901 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev8524d152016-01-21 12:35:58 +00003902 PrivateScope.addPrivate(
3903 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3904 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3905 CGF.emitOMPSimpleStore(
3906 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3907 VD->getType().getNonReferenceType(), Loc);
3908 return LHSTemp;
3909 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003910 (void)PrivateScope.Privatize();
3911 return CGF.EmitAnyExpr(UpExpr);
3912 });
3913 };
3914 if ((*IPriv)->getType()->isArrayType()) {
3915 // Emit atomic reduction for array section.
3916 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3917 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3918 AtomicRedGen, XExpr, EExpr, UpExpr);
3919 } else
3920 // Emit atomic reduction for array subscript or single variable.
3921 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3922 } else {
3923 // Emit as a critical region.
3924 auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3925 const Expr *, const Expr *) {
3926 emitCriticalRegion(
3927 CGF, ".atomic_reduction",
3928 [E](CodeGenFunction &CGF) { CGF.EmitIgnoredExpr(E); }, Loc);
3929 };
3930 if ((*IPriv)->getType()->isArrayType()) {
3931 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3932 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3933 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3934 CritRedGen);
3935 } else
3936 CritRedGen(CGF, nullptr, nullptr, nullptr);
3937 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003938 ++ILHS;
3939 ++IRHS;
3940 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003941 }
3942 }
3943
3944 CGF.EmitBranch(DefaultBB);
3945 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3946}
3947
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003948void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
3949 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003950 if (!CGF.HaveInsertPoint())
3951 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003952 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
3953 // global_tid);
3954 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3955 // Ignore return result until untied tasks are supported.
3956 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
3957}
3958
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003959void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003960 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003961 const RegionCodeGenTy &CodeGen,
3962 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003963 if (!CGF.HaveInsertPoint())
3964 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003965 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003966 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00003967}
3968
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003969namespace {
3970enum RTCancelKind {
3971 CancelNoreq = 0,
3972 CancelParallel = 1,
3973 CancelLoop = 2,
3974 CancelSections = 3,
3975 CancelTaskgroup = 4
3976};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003977} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003978
3979static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
3980 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00003981 if (CancelRegion == OMPD_parallel)
3982 CancelKind = CancelParallel;
3983 else if (CancelRegion == OMPD_for)
3984 CancelKind = CancelLoop;
3985 else if (CancelRegion == OMPD_sections)
3986 CancelKind = CancelSections;
3987 else {
3988 assert(CancelRegion == OMPD_taskgroup);
3989 CancelKind = CancelTaskgroup;
3990 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003991 return CancelKind;
3992}
3993
3994void CGOpenMPRuntime::emitCancellationPointCall(
3995 CodeGenFunction &CGF, SourceLocation Loc,
3996 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003997 if (!CGF.HaveInsertPoint())
3998 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003999 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4000 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004001 if (auto *OMPRegionInfo =
4002 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004003 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004004 llvm::Value *Args[] = {
4005 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4006 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004007 // Ignore return result until untied tasks are supported.
4008 auto *Result = CGF.EmitRuntimeCall(
4009 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4010 // if (__kmpc_cancellationpoint()) {
4011 // __kmpc_cancel_barrier();
4012 // exit from construct;
4013 // }
4014 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4015 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4016 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4017 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4018 CGF.EmitBlock(ExitBB);
4019 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004020 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004021 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004022 auto CancelDest =
4023 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004024 CGF.EmitBranchThroughCleanup(CancelDest);
4025 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4026 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004027 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004028}
4029
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004030void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004031 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004032 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004033 if (!CGF.HaveInsertPoint())
4034 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004035 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4036 // kmp_int32 cncl_kind);
4037 if (auto *OMPRegionInfo =
4038 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004039 auto &&ThenGen = [this, Loc, CancelRegion,
4040 OMPRegionInfo](CodeGenFunction &CGF) {
4041 llvm::Value *Args[] = {
4042 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4043 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4044 // Ignore return result until untied tasks are supported.
4045 auto *Result =
4046 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
4047 // if (__kmpc_cancel()) {
4048 // __kmpc_cancel_barrier();
4049 // exit from construct;
4050 // }
4051 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4052 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4053 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4054 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4055 CGF.EmitBlock(ExitBB);
4056 // __kmpc_cancel_barrier();
4057 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4058 // exit from construct;
4059 auto CancelDest =
4060 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4061 CGF.EmitBranchThroughCleanup(CancelDest);
4062 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4063 };
4064 if (IfCond)
4065 emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
4066 else
4067 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004068 }
4069}
Samuel Antaobed3c462015-10-02 16:14:20 +00004070
Samuel Antaoee8fb302016-01-06 13:42:12 +00004071/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004072/// consists of the file and device IDs as well as line number associated with
4073/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004074static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4075 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004076 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004077
4078 auto &SM = C.getSourceManager();
4079
4080 // The loc should be always valid and have a file ID (the user cannot use
4081 // #pragma directives in macros)
4082
4083 assert(Loc.isValid() && "Source location is expected to be always valid.");
4084 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4085
4086 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4087 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4088
4089 llvm::sys::fs::UniqueID ID;
4090 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4091 llvm_unreachable("Source file with target region no longer exists!");
4092
4093 DeviceID = ID.getDevice();
4094 FileID = ID.getFile();
4095 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004096}
4097
4098void CGOpenMPRuntime::emitTargetOutlinedFunction(
4099 const OMPExecutableDirective &D, StringRef ParentName,
4100 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4101 bool IsOffloadEntry) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004102 assert(!ParentName.empty() && "Invalid target region parent name!");
4103
Samuel Antaobed3c462015-10-02 16:14:20 +00004104 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4105
Samuel Antaoee8fb302016-01-06 13:42:12 +00004106 // Emit target region as a standalone region.
4107 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
4108 CGF.EmitStmt(CS.getCapturedStmt());
4109 };
4110
Samuel Antao2de62b02016-02-13 23:35:10 +00004111 // Create a unique name for the entry function using the source location
4112 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004113 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004114 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004115 //
4116 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004117 // mangled name of the function that encloses the target region and BB is the
4118 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004119
4120 unsigned DeviceID;
4121 unsigned FileID;
4122 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004123 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004124 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004125 SmallString<64> EntryFnName;
4126 {
4127 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004128 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4129 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004130 }
4131
Samuel Antaobed3c462015-10-02 16:14:20 +00004132 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004133 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004134 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004135
4136 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4137
4138 // If this target outline function is not an offload entry, we don't need to
4139 // register it.
4140 if (!IsOffloadEntry)
4141 return;
4142
4143 // The target region ID is used by the runtime library to identify the current
4144 // target region, so it only has to be unique and not necessarily point to
4145 // anything. It could be the pointer to the outlined function that implements
4146 // the target region, but we aren't using that so that the compiler doesn't
4147 // need to keep that, and could therefore inline the host function if proven
4148 // worthwhile during optimization. In the other hand, if emitting code for the
4149 // device, the ID has to be the function address so that it can retrieved from
4150 // the offloading entry and launched by the runtime library. We also mark the
4151 // outlined function to have external linkage in case we are emitting code for
4152 // the device, because these functions will be entry points to the device.
4153
4154 if (CGM.getLangOpts().OpenMPIsDevice) {
4155 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4156 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4157 } else
4158 OutlinedFnID = new llvm::GlobalVariable(
4159 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4160 llvm::GlobalValue::PrivateLinkage,
4161 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4162
4163 // Register the information for the entry associated with this target region.
4164 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004165 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004166}
4167
Samuel Antaob68e2db2016-03-03 16:20:23 +00004168/// \brief Emit the num_teams clause of an enclosed teams directive at the
4169/// target region scope. If there is no teams directive associated with the
4170/// target directive, or if there is no num_teams clause associated with the
4171/// enclosed teams directive, return nullptr.
4172static llvm::Value *
4173emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4174 CodeGenFunction &CGF,
4175 const OMPExecutableDirective &D) {
4176
4177 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4178 "teams directive expected to be "
4179 "emitted only for the host!");
4180
4181 // FIXME: For the moment we do not support combined directives with target and
4182 // teams, so we do not expect to get any num_teams clause in the provided
4183 // directive. Once we support that, this assertion can be replaced by the
4184 // actual emission of the clause expression.
4185 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4186 "Not expecting clause in directive.");
4187
4188 // If the current target region has a teams region enclosed, we need to get
4189 // the number of teams to pass to the runtime function call. This is done
4190 // by generating the expression in a inlined region. This is required because
4191 // the expression is captured in the enclosing target environment when the
4192 // teams directive is not combined with target.
4193
4194 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4195
4196 // FIXME: Accommodate other combined directives with teams when they become
4197 // available.
4198 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4199 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4200 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4201 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4202 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4203 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4204 /*IsSigned=*/true);
4205 }
4206
4207 // If we have an enclosed teams directive but no num_teams clause we use
4208 // the default value 0.
4209 return CGF.Builder.getInt32(0);
4210 }
4211
4212 // No teams associated with the directive.
4213 return nullptr;
4214}
4215
4216/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4217/// target region scope. If there is no teams directive associated with the
4218/// target directive, or if there is no thread_limit clause associated with the
4219/// enclosed teams directive, return nullptr.
4220static llvm::Value *
4221emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4222 CodeGenFunction &CGF,
4223 const OMPExecutableDirective &D) {
4224
4225 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4226 "teams directive expected to be "
4227 "emitted only for the host!");
4228
4229 // FIXME: For the moment we do not support combined directives with target and
4230 // teams, so we do not expect to get any thread_limit clause in the provided
4231 // directive. Once we support that, this assertion can be replaced by the
4232 // actual emission of the clause expression.
4233 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4234 "Not expecting clause in directive.");
4235
4236 // If the current target region has a teams region enclosed, we need to get
4237 // the thread limit to pass to the runtime function call. This is done
4238 // by generating the expression in a inlined region. This is required because
4239 // the expression is captured in the enclosing target environment when the
4240 // teams directive is not combined with target.
4241
4242 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4243
4244 // FIXME: Accommodate other combined directives with teams when they become
4245 // available.
4246 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4247 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4248 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4249 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4250 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4251 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4252 /*IsSigned=*/true);
4253 }
4254
4255 // If we have an enclosed teams directive but no thread_limit clause we use
4256 // the default value 0.
4257 return CGF.Builder.getInt32(0);
4258 }
4259
4260 // No teams associated with the directive.
4261 return nullptr;
4262}
4263
Samuel Antaobed3c462015-10-02 16:14:20 +00004264void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
4265 const OMPExecutableDirective &D,
4266 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004267 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00004268 const Expr *IfCond, const Expr *Device,
4269 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004270 if (!CGF.HaveInsertPoint())
4271 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00004272 /// \brief Values for bit flags used to specify the mapping type for
4273 /// offloading.
4274 enum OpenMPOffloadMappingFlags {
4275 /// \brief Allocate memory on the device and move data from host to device.
4276 OMP_MAP_TO = 0x01,
4277 /// \brief Allocate memory on the device and move data from device to host.
4278 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004279 /// \brief The element passed to the device is a pointer.
4280 OMP_MAP_PTR = 0x20,
4281 /// \brief Pass the element to the device by value.
4282 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00004283 };
4284
4285 enum OpenMPOffloadingReservedDeviceIDs {
4286 /// \brief Device ID if the device was not defined, runtime should get it
4287 /// from environment variables in the spec.
4288 OMP_DEVICEID_UNDEF = -1,
4289 };
4290
Samuel Antaoee8fb302016-01-06 13:42:12 +00004291 assert(OutlinedFn && "Invalid outlined function!");
4292
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004293 auto &Ctx = CGF.getContext();
4294
Samuel Antaobed3c462015-10-02 16:14:20 +00004295 // Fill up the arrays with the all the captured variables.
4296 SmallVector<llvm::Value *, 16> BasePointers;
4297 SmallVector<llvm::Value *, 16> Pointers;
4298 SmallVector<llvm::Value *, 16> Sizes;
4299 SmallVector<unsigned, 16> MapTypes;
4300
4301 bool hasVLACaptures = false;
4302
4303 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4304 auto RI = CS.getCapturedRecordDecl()->field_begin();
4305 // auto II = CS.capture_init_begin();
4306 auto CV = CapturedVars.begin();
4307 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
4308 CE = CS.capture_end();
4309 CI != CE; ++CI, ++RI, ++CV) {
4310 StringRef Name;
4311 QualType Ty;
4312 llvm::Value *BasePointer;
4313 llvm::Value *Pointer;
4314 llvm::Value *Size;
4315 unsigned MapType;
4316
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004317 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00004318 if (CI->capturesVariableArrayType()) {
4319 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00004320 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004321 // Copy to the device as an argument. No need to retrieve it.
4322 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00004323 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00004324 } else if (CI->capturesThis()) {
4325 BasePointer = Pointer = *CV;
4326 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004327 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004328 // Default map type.
4329 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004330 } else if (CI->capturesVariableByCopy()) {
4331 MapType = OMP_MAP_BYCOPY;
4332 if (!RI->getType()->isAnyPointerType()) {
4333 // If the field is not a pointer, we need to save the actual value and
4334 // load it as a void pointer.
4335 auto DstAddr = CGF.CreateMemTemp(
4336 Ctx.getUIntPtrType(),
4337 Twine(CI->getCapturedVar()->getName()) + ".casted");
4338 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
4339
4340 auto *SrcAddrVal = CGF.EmitScalarConversion(
4341 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
4342 Ctx.getPointerType(RI->getType()), SourceLocation());
4343 LValue SrcLV =
4344 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
4345
4346 // Store the value using the source type pointer.
4347 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
4348
4349 // Load the value using the destination type pointer.
4350 BasePointer = Pointer =
4351 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
4352 } else {
4353 MapType |= OMP_MAP_PTR;
4354 BasePointer = Pointer = *CV;
4355 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00004356 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004357 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004358 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00004359 BasePointer = Pointer = *CV;
4360
4361 const ReferenceType *PtrTy =
4362 cast<ReferenceType>(RI->getType().getTypePtr());
4363 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004364 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004365 // The default map type for a scalar/complex type is 'to' because by
4366 // default the value doesn't have to be retrieved. For an aggregate type,
4367 // the default is 'tofrom'.
4368 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
4369 : OMP_MAP_TO;
4370 if (ElementType->isAnyPointerType())
4371 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00004372 }
4373
4374 BasePointers.push_back(BasePointer);
4375 Pointers.push_back(Pointer);
4376 Sizes.push_back(Size);
4377 MapTypes.push_back(MapType);
4378 }
4379
4380 // Keep track on whether the host function has to be executed.
4381 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004382 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004383 auto OffloadError = CGF.MakeAddrLValue(
4384 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
4385 OffloadErrorQType);
4386 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
4387 OffloadError);
4388
4389 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004390 auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004391 hasVLACaptures, Device, OutlinedFnID, OffloadError,
Samuel Antaob68e2db2016-03-03 16:20:23 +00004392 OffloadErrorQType, &D](CodeGenFunction &CGF) {
Samuel Antaobed3c462015-10-02 16:14:20 +00004393 unsigned PointerNumVal = BasePointers.size();
4394 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
4395 llvm::Value *BasePointersArray;
4396 llvm::Value *PointersArray;
4397 llvm::Value *SizesArray;
4398 llvm::Value *MapTypesArray;
4399
4400 if (PointerNumVal) {
4401 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004402 QualType PointerArrayType = Ctx.getConstantArrayType(
4403 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004404 /*IndexTypeQuals=*/0);
4405
4406 BasePointersArray =
4407 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
4408 PointersArray =
4409 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
4410
4411 // If we don't have any VLA types, we can use a constant array for the map
4412 // sizes, otherwise we need to fill up the arrays as we do for the
4413 // pointers.
4414 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004415 QualType SizeArrayType = Ctx.getConstantArrayType(
4416 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004417 /*IndexTypeQuals=*/0);
4418 SizesArray =
4419 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
4420 } else {
4421 // We expect all the sizes to be constant, so we collect them to create
4422 // a constant array.
4423 SmallVector<llvm::Constant *, 16> ConstSizes;
4424 for (auto S : Sizes)
4425 ConstSizes.push_back(cast<llvm::Constant>(S));
4426
4427 auto *SizesArrayInit = llvm::ConstantArray::get(
4428 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
4429 auto *SizesArrayGbl = new llvm::GlobalVariable(
4430 CGM.getModule(), SizesArrayInit->getType(),
4431 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4432 SizesArrayInit, ".offload_sizes");
4433 SizesArrayGbl->setUnnamedAddr(true);
4434 SizesArray = SizesArrayGbl;
4435 }
4436
4437 // The map types are always constant so we don't need to generate code to
4438 // fill arrays. Instead, we create an array constant.
4439 llvm::Constant *MapTypesArrayInit =
4440 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
4441 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
4442 CGM.getModule(), MapTypesArrayInit->getType(),
4443 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4444 MapTypesArrayInit, ".offload_maptypes");
4445 MapTypesArrayGbl->setUnnamedAddr(true);
4446 MapTypesArray = MapTypesArrayGbl;
4447
4448 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004449 llvm::Value *BPVal = BasePointers[i];
4450 if (BPVal->getType()->isPointerTy())
4451 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
4452 else {
4453 assert(BPVal->getType()->isIntegerTy() &&
4454 "If not a pointer, the value type must be an integer.");
4455 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
4456 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004457 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
4458 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
4459 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004460 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4461 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004462
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004463 llvm::Value *PVal = Pointers[i];
4464 if (PVal->getType()->isPointerTy())
4465 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
4466 else {
4467 assert(PVal->getType()->isIntegerTy() &&
4468 "If not a pointer, the value type must be an integer.");
4469 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
4470 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004471 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4472 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4473 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004474 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4475 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004476
4477 if (hasVLACaptures) {
4478 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4479 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4480 /*Idx0=*/0,
4481 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004482 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004483 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4484 Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4485 SAddr);
4486 }
4487 }
4488
4489 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4490 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4491 /*Idx0=*/0, /*Idx1=*/0);
4492 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4493 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4494 /*Idx0=*/0,
4495 /*Idx1=*/0);
4496 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4497 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4498 /*Idx0=*/0, /*Idx1=*/0);
4499 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4500 llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4501 /*Idx0=*/0,
4502 /*Idx1=*/0);
4503
4504 } else {
4505 BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4506 PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4507 SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4508 MapTypesArray =
4509 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4510 }
4511
4512 // On top of the arrays that were filled up, the target offloading call
4513 // takes as arguments the device id as well as the host pointer. The host
4514 // pointer is used by the runtime library to identify the current target
4515 // region, so it only has to be unique and not necessarily point to
4516 // anything. It could be the pointer to the outlined function that
4517 // implements the target region, but we aren't using that so that the
4518 // compiler doesn't need to keep that, and could therefore inline the host
4519 // function if proven worthwhile during optimization.
4520
Samuel Antaoee8fb302016-01-06 13:42:12 +00004521 // From this point on, we need to have an ID of the target region defined.
4522 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004523
4524 // Emit device ID if any.
4525 llvm::Value *DeviceID;
4526 if (Device)
4527 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4528 CGM.Int32Ty, /*isSigned=*/true);
4529 else
4530 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4531
Samuel Antaob68e2db2016-03-03 16:20:23 +00004532 // Return value of the runtime offloading call.
4533 llvm::Value *Return;
4534
4535 auto *NumTeams = emitNumTeamsClauseForTargetDirective(*this, CGF, D);
4536 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(*this, CGF, D);
4537
4538 // If we have NumTeams defined this means that we have an enclosed teams
4539 // region. Therefore we also expect to have ThreadLimit defined. These two
4540 // values should be defined in the presence of a teams directive, regardless
4541 // of having any clauses associated. If the user is using teams but no
4542 // clauses, these two values will be the default that should be passed to
4543 // the runtime library - a 32-bit integer with the value zero.
4544 if (NumTeams) {
4545 assert(ThreadLimit && "Thread limit expression should be available along "
4546 "with number of teams.");
4547 llvm::Value *OffloadingArgs[] = {
4548 DeviceID, OutlinedFnID, PointerNum,
4549 BasePointersArray, PointersArray, SizesArray,
4550 MapTypesArray, NumTeams, ThreadLimit};
4551 Return = CGF.EmitRuntimeCall(
4552 createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
4553 } else {
4554 llvm::Value *OffloadingArgs[] = {
4555 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4556 PointersArray, SizesArray, MapTypesArray};
4557 Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4558 OffloadingArgs);
4559 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004560
4561 CGF.EmitStoreOfScalar(Return, OffloadError);
4562 };
4563
Samuel Antaoee8fb302016-01-06 13:42:12 +00004564 // Notify that the host version must be executed.
4565 auto &&ElseGen = [this, OffloadError,
4566 OffloadErrorQType](CodeGenFunction &CGF) {
4567 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4568 OffloadError);
4569 };
4570
4571 // If we have a target function ID it means that we need to support
4572 // offloading, otherwise, just execute on the host. We need to execute on host
4573 // regardless of the conditional in the if clause if, e.g., the user do not
4574 // specify target triples.
4575 if (OutlinedFnID) {
4576 if (IfCond) {
4577 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4578 } else {
4579 CodeGenFunction::RunCleanupsScope Scope(CGF);
4580 ThenGen(CGF);
4581 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004582 } else {
4583 CodeGenFunction::RunCleanupsScope Scope(CGF);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004584 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004585 }
4586
4587 // Check the error code and execute the host version if required.
4588 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4589 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4590 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4591 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4592 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4593
4594 CGF.EmitBlock(OffloadFailedBlock);
4595 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4596 CGF.EmitBranch(OffloadContBlock);
4597
4598 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004599}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004600
4601void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4602 StringRef ParentName) {
4603 if (!S)
4604 return;
4605
4606 // If we find a OMP target directive, codegen the outline function and
4607 // register the result.
4608 // FIXME: Add other directives with target when they become supported.
4609 bool isTargetDirective = isa<OMPTargetDirective>(S);
4610
4611 if (isTargetDirective) {
4612 auto *E = cast<OMPExecutableDirective>(S);
4613 unsigned DeviceID;
4614 unsigned FileID;
4615 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004616 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004617 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004618
4619 // Is this a target region that should not be emitted as an entry point? If
4620 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00004621 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4622 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004623 return;
4624
4625 llvm::Function *Fn;
4626 llvm::Constant *Addr;
4627 emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4628 /*isOffloadEntry=*/true);
4629 assert(Fn && Addr && "Target region emission failed.");
4630 return;
4631 }
4632
4633 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4634 if (!E->getAssociatedStmt())
4635 return;
4636
4637 scanForTargetRegionsFunctions(
4638 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4639 ParentName);
4640 return;
4641 }
4642
4643 // If this is a lambda function, look into its body.
4644 if (auto *L = dyn_cast<LambdaExpr>(S))
4645 S = L->getBody();
4646
4647 // Keep looking for target regions recursively.
4648 for (auto *II : S->children())
4649 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004650}
4651
4652bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4653 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4654
4655 // If emitting code for the host, we do not process FD here. Instead we do
4656 // the normal code generation.
4657 if (!CGM.getLangOpts().OpenMPIsDevice)
4658 return false;
4659
4660 // Try to detect target regions in the function.
4661 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4662
4663 // We should not emit any function othen that the ones created during the
4664 // scanning. Therefore, we signal that this function is completely dealt
4665 // with.
4666 return true;
4667}
4668
4669bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4670 if (!CGM.getLangOpts().OpenMPIsDevice)
4671 return false;
4672
4673 // Check if there are Ctors/Dtors in this declaration and look for target
4674 // regions in it. We use the complete variant to produce the kernel name
4675 // mangling.
4676 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4677 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4678 for (auto *Ctor : RD->ctors()) {
4679 StringRef ParentName =
4680 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4681 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4682 }
4683 auto *Dtor = RD->getDestructor();
4684 if (Dtor) {
4685 StringRef ParentName =
4686 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4687 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4688 }
4689 }
4690
4691 // If we are in target mode we do not emit any global (declare target is not
4692 // implemented yet). Therefore we signal that GD was processed in this case.
4693 return true;
4694}
4695
4696bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4697 auto *VD = GD.getDecl();
4698 if (isa<FunctionDecl>(VD))
4699 return emitTargetFunctions(GD);
4700
4701 return emitTargetGlobalVariable(GD);
4702}
4703
4704llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4705 // If we have offloading in the current module, we need to emit the entries
4706 // now and register the offloading descriptor.
4707 createOffloadEntriesAndInfoMetadata();
4708
4709 // Create and register the offloading binary descriptors. This is the main
4710 // entity that captures all the information about offloading in the current
4711 // compilation unit.
4712 return createOffloadingBinaryDescriptorRegistration();
4713}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004714
4715void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
4716 const OMPExecutableDirective &D,
4717 SourceLocation Loc,
4718 llvm::Value *OutlinedFn,
4719 ArrayRef<llvm::Value *> CapturedVars) {
4720 if (!CGF.HaveInsertPoint())
4721 return;
4722
4723 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4724 CodeGenFunction::RunCleanupsScope Scope(CGF);
4725
4726 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
4727 llvm::Value *Args[] = {
4728 RTLoc,
4729 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
4730 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
4731 llvm::SmallVector<llvm::Value *, 16> RealArgs;
4732 RealArgs.append(std::begin(Args), std::end(Args));
4733 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
4734
4735 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
4736 CGF.EmitRuntimeCall(RTLFn, RealArgs);
4737}
4738
4739void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
4740 llvm::Value *NumTeams,
4741 llvm::Value *ThreadLimit,
4742 SourceLocation Loc) {
4743 if (!CGF.HaveInsertPoint())
4744 return;
4745
4746 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4747
4748 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
4749 llvm::Value *PushNumTeamsArgs[] = {
4750 RTLoc, getThreadID(CGF, Loc), NumTeams, ThreadLimit};
4751 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
4752 PushNumTeamsArgs);
4753}