blob: 810a2db3a5be30198f3749abaa16e27b8d5c024f [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,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000428 /// \brief dist_schedule types
429 OMP_dist_sch_static_chunked = 91,
430 OMP_dist_sch_static = 92,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000431};
432
433enum OpenMPRTLFunction {
434 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
435 /// kmpc_micro microtask, ...);
436 OMPRTL__kmpc_fork_call,
437 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
438 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
439 OMPRTL__kmpc_threadprivate_cached,
440 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
441 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
442 OMPRTL__kmpc_threadprivate_register,
443 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
444 OMPRTL__kmpc_global_thread_num,
445 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
446 // kmp_critical_name *crit);
447 OMPRTL__kmpc_critical,
448 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
449 // global_tid, kmp_critical_name *crit, uintptr_t hint);
450 OMPRTL__kmpc_critical_with_hint,
451 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
452 // kmp_critical_name *crit);
453 OMPRTL__kmpc_end_critical,
454 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
455 // global_tid);
456 OMPRTL__kmpc_cancel_barrier,
457 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
458 OMPRTL__kmpc_barrier,
459 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
460 OMPRTL__kmpc_for_static_fini,
461 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
462 // global_tid);
463 OMPRTL__kmpc_serialized_parallel,
464 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
465 // global_tid);
466 OMPRTL__kmpc_end_serialized_parallel,
467 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
468 // kmp_int32 num_threads);
469 OMPRTL__kmpc_push_num_threads,
470 // Call to void __kmpc_flush(ident_t *loc);
471 OMPRTL__kmpc_flush,
472 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
473 OMPRTL__kmpc_master,
474 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
475 OMPRTL__kmpc_end_master,
476 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
477 // int end_part);
478 OMPRTL__kmpc_omp_taskyield,
479 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
480 OMPRTL__kmpc_single,
481 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
482 OMPRTL__kmpc_end_single,
483 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
484 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
485 // kmp_routine_entry_t *task_entry);
486 OMPRTL__kmpc_omp_task_alloc,
487 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
488 // new_task);
489 OMPRTL__kmpc_omp_task,
490 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
491 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
492 // kmp_int32 didit);
493 OMPRTL__kmpc_copyprivate,
494 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
495 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
496 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
497 OMPRTL__kmpc_reduce,
498 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
499 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
500 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
501 // *lck);
502 OMPRTL__kmpc_reduce_nowait,
503 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
504 // kmp_critical_name *lck);
505 OMPRTL__kmpc_end_reduce,
506 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
507 // kmp_critical_name *lck);
508 OMPRTL__kmpc_end_reduce_nowait,
509 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
510 // kmp_task_t * new_task);
511 OMPRTL__kmpc_omp_task_begin_if0,
512 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
513 // kmp_task_t * new_task);
514 OMPRTL__kmpc_omp_task_complete_if0,
515 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
516 OMPRTL__kmpc_ordered,
517 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
518 OMPRTL__kmpc_end_ordered,
519 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
520 // global_tid);
521 OMPRTL__kmpc_omp_taskwait,
522 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
523 OMPRTL__kmpc_taskgroup,
524 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
525 OMPRTL__kmpc_end_taskgroup,
526 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
527 // int proc_bind);
528 OMPRTL__kmpc_push_proc_bind,
529 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
530 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
531 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
532 OMPRTL__kmpc_omp_task_with_deps,
533 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
534 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
535 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
536 OMPRTL__kmpc_omp_wait_deps,
537 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
538 // global_tid, kmp_int32 cncl_kind);
539 OMPRTL__kmpc_cancellationpoint,
540 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
541 // kmp_int32 cncl_kind);
542 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000543 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
544 // kmp_int32 num_teams, kmp_int32 thread_limit);
545 OMPRTL__kmpc_push_num_teams,
546 /// \brief Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc,
547 /// kmpc_micro microtask, ...);
548 OMPRTL__kmpc_fork_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000549
550 //
551 // Offloading related calls
552 //
553 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
554 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
555 // *arg_types);
556 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000557 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
558 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
559 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
560 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000561 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
562 OMPRTL__tgt_register_lib,
563 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
564 OMPRTL__tgt_unregister_lib,
565};
566
Hans Wennborg7eb54642015-09-10 17:07:54 +0000567} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000568
569LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000570 return CGF.EmitLoadOfPointerLValue(
571 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
572 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000573}
574
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000575void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000576 if (!CGF.HaveInsertPoint())
577 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000578 // 1.2.2 OpenMP Language Terminology
579 // Structured block - An executable statement with a single entry at the
580 // top and a single exit at the bottom.
581 // The point of exit cannot be a branch out of the structured block.
582 // longjmp() and throw() must not violate the entry/exit criteria.
583 CGF.EHStack.pushTerminate();
584 {
585 CodeGenFunction::RunCleanupsScope Scope(CGF);
586 CodeGen(CGF);
587 }
588 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000589}
590
Alexey Bataev62b63b12015-03-10 07:28:44 +0000591LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
592 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000593 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
594 getThreadIDVariable()->getType(),
595 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000596}
597
Alexey Bataev9959db52014-05-06 10:08:46 +0000598CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000599 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000600 IdentTy = llvm::StructType::create(
601 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
602 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000603 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000604 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000605 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
606 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000607 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000608 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000609
610 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000611}
612
Alexey Bataev91797552015-03-18 04:13:55 +0000613void CGOpenMPRuntime::clear() {
614 InternalVars.clear();
615}
616
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000617static llvm::Function *
618emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
619 const Expr *CombinerInitializer, const VarDecl *In,
620 const VarDecl *Out, bool IsCombiner) {
621 // void .omp_combiner.(Ty *in, Ty *out);
622 auto &C = CGM.getContext();
623 QualType PtrTy = C.getPointerType(Ty).withRestrict();
624 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000625 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
626 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000627 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
628 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000629 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000630 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000631 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000632 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000633 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
634 auto *Fn = llvm::Function::Create(
635 FnTy, llvm::GlobalValue::InternalLinkage,
636 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
637 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000638 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000639 CodeGenFunction CGF(CGM);
640 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
641 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
642 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
643 CodeGenFunction::OMPPrivateScope Scope(CGF);
644 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
645 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
646 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
647 .getAddress();
648 });
649 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
650 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
651 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
652 .getAddress();
653 });
654 (void)Scope.Privatize();
655 CGF.EmitIgnoredExpr(CombinerInitializer);
656 Scope.ForceCleanup();
657 CGF.FinishFunction();
658 return Fn;
659}
660
661void CGOpenMPRuntime::emitUserDefinedReduction(
662 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
663 if (UDRMap.count(D) > 0)
664 return;
665 auto &C = CGM.getContext();
666 if (!In || !Out) {
667 In = &C.Idents.get("omp_in");
668 Out = &C.Idents.get("omp_out");
669 }
670 llvm::Function *Combiner = emitCombinerOrInitializer(
671 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
672 cast<VarDecl>(D->lookup(Out).front()),
673 /*IsCombiner=*/true);
674 llvm::Function *Initializer = nullptr;
675 if (auto *Init = D->getInitializer()) {
676 if (!Priv || !Orig) {
677 Priv = &C.Idents.get("omp_priv");
678 Orig = &C.Idents.get("omp_orig");
679 }
680 Initializer = emitCombinerOrInitializer(
681 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
682 cast<VarDecl>(D->lookup(Priv).front()),
683 /*IsCombiner=*/false);
684 }
685 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
686 if (CGF) {
687 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
688 Decls.second.push_back(D);
689 }
690}
691
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000692std::pair<llvm::Function *, llvm::Function *>
693CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
694 auto I = UDRMap.find(D);
695 if (I != UDRMap.end())
696 return I->second;
697 emitUserDefinedReduction(/*CGF=*/nullptr, D);
698 return UDRMap.lookup(D);
699}
700
John McCall7f416cc2015-09-08 08:05:57 +0000701// Layout information for ident_t.
702static CharUnits getIdentAlign(CodeGenModule &CGM) {
703 return CGM.getPointerAlign();
704}
705static CharUnits getIdentSize(CodeGenModule &CGM) {
706 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
707 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
708}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000709static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000710 // All the fields except the last are i32, so this works beautifully.
711 return unsigned(Field) * CharUnits::fromQuantity(4);
712}
713static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000714 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000715 const llvm::Twine &Name = "") {
716 auto Offset = getOffsetOfIdentField(Field);
717 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
718}
719
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000720llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000721 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
722 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000723 assert(ThreadIDVar->getType()->isPointerType() &&
724 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000725 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
726 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000727 bool HasCancel = false;
728 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
729 HasCancel = OPD->hasCancel();
730 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
731 HasCancel = OPSD->hasCancel();
732 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
733 HasCancel = OPFD->hasCancel();
734 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
735 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000736 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000737 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000738}
739
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000740llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
741 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
742 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000743 assert(!ThreadIDVar->getType()->isPointerType() &&
744 "thread id variable must be of type kmp_int32 for tasks");
745 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
746 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000747 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000748 InnermostKind,
749 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000750 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000751 return CGF.GenerateCapturedStmtFunction(*CS);
752}
753
Alexey Bataev50b3c952016-02-19 10:38:26 +0000754Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000755 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000756 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000757 if (!Entry) {
758 if (!DefaultOpenMPPSource) {
759 // Initialize default location for psource field of ident_t structure of
760 // all ident_t objects. Format is ";file;function;line;column;;".
761 // Taken from
762 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
763 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000764 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000765 DefaultOpenMPPSource =
766 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
767 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000768 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
769 CGM.getModule(), IdentTy, /*isConstant*/ true,
770 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000771 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000772 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000773
774 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000775 llvm::Constant *Values[] = {Zero,
776 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
777 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000778 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
779 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000780 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000781 }
John McCall7f416cc2015-09-08 08:05:57 +0000782 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000783}
784
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000785llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
786 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000787 unsigned Flags) {
788 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000789 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000790 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000791 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000792 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000793
794 assert(CGF.CurFn && "No function in current CodeGenFunction.");
795
John McCall7f416cc2015-09-08 08:05:57 +0000796 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000797 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
798 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000799 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
800
Alexander Musmanc6388682014-12-15 07:07:06 +0000801 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
802 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000803 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000804 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000805 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
806 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000807 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000808 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000809 LocValue = AI;
810
811 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
812 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000813 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000814 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000815 }
816
817 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000818 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000819
Alexey Bataevf002aca2014-05-30 05:48:40 +0000820 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
821 if (OMPDebugLoc == nullptr) {
822 SmallString<128> Buffer2;
823 llvm::raw_svector_ostream OS2(Buffer2);
824 // Build debug location
825 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
826 OS2 << ";" << PLoc.getFilename() << ";";
827 if (const FunctionDecl *FD =
828 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
829 OS2 << FD->getQualifiedNameAsString();
830 }
831 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
832 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
833 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000834 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000835 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000836 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
837
John McCall7f416cc2015-09-08 08:05:57 +0000838 // Our callers always pass this to a runtime function, so for
839 // convenience, go ahead and return a naked pointer.
840 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000841}
842
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000843llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
844 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000845 assert(CGF.CurFn && "No function in current CodeGenFunction.");
846
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000847 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000848 // Check whether we've already cached a load of the thread id in this
849 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000850 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000851 if (I != OpenMPLocThreadIDMap.end()) {
852 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000853 if (ThreadID != nullptr)
854 return ThreadID;
855 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000856 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000857 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000858 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000859 // Check if this an outlined function with thread id passed as argument.
860 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000861 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
862 // If value loaded in entry block, cache it and use it everywhere in
863 // function.
864 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
865 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
866 Elem.second.ThreadID = ThreadID;
867 }
868 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000869 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000870 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000871
872 // This is not an outlined function region - need to call __kmpc_int32
873 // kmpc_global_thread_num(ident_t *loc).
874 // Generate thread id value and cache this value for use across the
875 // function.
876 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
877 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
878 ThreadID =
879 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
880 emitUpdateLocation(CGF, Loc));
881 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
882 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000883 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000884}
885
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000886void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000887 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000888 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
889 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000890 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
891 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
892 UDRMap.erase(D);
893 }
894 FunctionUDRMap.erase(CGF.CurFn);
895 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000896}
897
898llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
899 return llvm::PointerType::getUnqual(IdentTy);
900}
901
902llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
903 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
904}
905
906llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +0000907CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000908 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +0000909 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000910 case OMPRTL__kmpc_fork_call: {
911 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
912 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000913 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
914 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000915 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000916 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000917 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
918 break;
919 }
920 case OMPRTL__kmpc_global_thread_num: {
921 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000922 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000923 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000924 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000925 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
926 break;
927 }
Alexey Bataev97720002014-11-11 04:05:39 +0000928 case OMPRTL__kmpc_threadprivate_cached: {
929 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
930 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
931 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
932 CGM.VoidPtrTy, CGM.SizeTy,
933 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
934 llvm::FunctionType *FnTy =
935 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
936 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
937 break;
938 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000939 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000940 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
941 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000942 llvm::Type *TypeParams[] = {
943 getIdentTyPointerTy(), CGM.Int32Ty,
944 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
945 llvm::FunctionType *FnTy =
946 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
947 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
948 break;
949 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000950 case OMPRTL__kmpc_critical_with_hint: {
951 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
952 // kmp_critical_name *crit, uintptr_t hint);
953 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
954 llvm::PointerType::getUnqual(KmpCriticalNameTy),
955 CGM.IntPtrTy};
956 llvm::FunctionType *FnTy =
957 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
958 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
959 break;
960 }
Alexey Bataev97720002014-11-11 04:05:39 +0000961 case OMPRTL__kmpc_threadprivate_register: {
962 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
963 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
964 // typedef void *(*kmpc_ctor)(void *);
965 auto KmpcCtorTy =
966 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
967 /*isVarArg*/ false)->getPointerTo();
968 // typedef void *(*kmpc_cctor)(void *, void *);
969 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
970 auto KmpcCopyCtorTy =
971 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
972 /*isVarArg*/ false)->getPointerTo();
973 // typedef void (*kmpc_dtor)(void *);
974 auto KmpcDtorTy =
975 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
976 ->getPointerTo();
977 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
978 KmpcCopyCtorTy, KmpcDtorTy};
979 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
980 /*isVarArg*/ false);
981 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
982 break;
983 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000984 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000985 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
986 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000987 llvm::Type *TypeParams[] = {
988 getIdentTyPointerTy(), CGM.Int32Ty,
989 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
990 llvm::FunctionType *FnTy =
991 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
992 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
993 break;
994 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000995 case OMPRTL__kmpc_cancel_barrier: {
996 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
997 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000998 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
999 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001000 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1001 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001002 break;
1003 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001004 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001005 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001006 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1007 llvm::FunctionType *FnTy =
1008 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1009 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1010 break;
1011 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001012 case OMPRTL__kmpc_for_static_fini: {
1013 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1014 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1015 llvm::FunctionType *FnTy =
1016 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1017 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1018 break;
1019 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001020 case OMPRTL__kmpc_push_num_threads: {
1021 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1022 // kmp_int32 num_threads)
1023 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1024 CGM.Int32Ty};
1025 llvm::FunctionType *FnTy =
1026 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1027 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1028 break;
1029 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001030 case OMPRTL__kmpc_serialized_parallel: {
1031 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1032 // global_tid);
1033 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1034 llvm::FunctionType *FnTy =
1035 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1036 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1037 break;
1038 }
1039 case OMPRTL__kmpc_end_serialized_parallel: {
1040 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1041 // global_tid);
1042 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1043 llvm::FunctionType *FnTy =
1044 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1045 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1046 break;
1047 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001048 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001049 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001050 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1051 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001052 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001053 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1054 break;
1055 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001056 case OMPRTL__kmpc_master: {
1057 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1058 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1059 llvm::FunctionType *FnTy =
1060 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1061 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1062 break;
1063 }
1064 case OMPRTL__kmpc_end_master: {
1065 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1066 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1067 llvm::FunctionType *FnTy =
1068 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1069 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1070 break;
1071 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001072 case OMPRTL__kmpc_omp_taskyield: {
1073 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1074 // int end_part);
1075 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1076 llvm::FunctionType *FnTy =
1077 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1078 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1079 break;
1080 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001081 case OMPRTL__kmpc_single: {
1082 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1083 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1084 llvm::FunctionType *FnTy =
1085 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1086 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1087 break;
1088 }
1089 case OMPRTL__kmpc_end_single: {
1090 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1091 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1092 llvm::FunctionType *FnTy =
1093 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1094 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1095 break;
1096 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001097 case OMPRTL__kmpc_omp_task_alloc: {
1098 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1099 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1100 // kmp_routine_entry_t *task_entry);
1101 assert(KmpRoutineEntryPtrTy != nullptr &&
1102 "Type kmp_routine_entry_t must be created.");
1103 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1104 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1105 // Return void * and then cast to particular kmp_task_t type.
1106 llvm::FunctionType *FnTy =
1107 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1108 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1109 break;
1110 }
1111 case OMPRTL__kmpc_omp_task: {
1112 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1113 // *new_task);
1114 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1115 CGM.VoidPtrTy};
1116 llvm::FunctionType *FnTy =
1117 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1118 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1119 break;
1120 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001121 case OMPRTL__kmpc_copyprivate: {
1122 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001123 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001124 // kmp_int32 didit);
1125 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1126 auto *CpyFnTy =
1127 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001128 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001129 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1130 CGM.Int32Ty};
1131 llvm::FunctionType *FnTy =
1132 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1133 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1134 break;
1135 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001136 case OMPRTL__kmpc_reduce: {
1137 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1138 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1139 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1140 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1141 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1142 /*isVarArg=*/false);
1143 llvm::Type *TypeParams[] = {
1144 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1145 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1146 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1147 llvm::FunctionType *FnTy =
1148 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1149 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1150 break;
1151 }
1152 case OMPRTL__kmpc_reduce_nowait: {
1153 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1154 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1155 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1156 // *lck);
1157 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1158 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1159 /*isVarArg=*/false);
1160 llvm::Type *TypeParams[] = {
1161 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1162 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1163 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1164 llvm::FunctionType *FnTy =
1165 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1166 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1167 break;
1168 }
1169 case OMPRTL__kmpc_end_reduce: {
1170 // Build void __kmpc_end_reduce(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 = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1178 break;
1179 }
1180 case OMPRTL__kmpc_end_reduce_nowait: {
1181 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1182 // kmp_critical_name *lck);
1183 llvm::Type *TypeParams[] = {
1184 getIdentTyPointerTy(), CGM.Int32Ty,
1185 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1188 RTLFn =
1189 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1190 break;
1191 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001192 case OMPRTL__kmpc_omp_task_begin_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 =
1200 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1201 break;
1202 }
1203 case OMPRTL__kmpc_omp_task_complete_if0: {
1204 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1205 // *new_task);
1206 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1207 CGM.VoidPtrTy};
1208 llvm::FunctionType *FnTy =
1209 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1210 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1211 /*Name=*/"__kmpc_omp_task_complete_if0");
1212 break;
1213 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001214 case OMPRTL__kmpc_ordered: {
1215 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1216 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1217 llvm::FunctionType *FnTy =
1218 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1219 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1220 break;
1221 }
1222 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001223 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001224 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1225 llvm::FunctionType *FnTy =
1226 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1227 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1228 break;
1229 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001230 case OMPRTL__kmpc_omp_taskwait: {
1231 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1232 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1233 llvm::FunctionType *FnTy =
1234 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1235 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1236 break;
1237 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001238 case OMPRTL__kmpc_taskgroup: {
1239 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1240 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1241 llvm::FunctionType *FnTy =
1242 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1243 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1244 break;
1245 }
1246 case OMPRTL__kmpc_end_taskgroup: {
1247 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1248 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1249 llvm::FunctionType *FnTy =
1250 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1251 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1252 break;
1253 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001254 case OMPRTL__kmpc_push_proc_bind: {
1255 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1256 // int proc_bind)
1257 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1258 llvm::FunctionType *FnTy =
1259 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1260 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1261 break;
1262 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001263 case OMPRTL__kmpc_omp_task_with_deps: {
1264 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1265 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1266 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1267 llvm::Type *TypeParams[] = {
1268 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1269 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1270 llvm::FunctionType *FnTy =
1271 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1272 RTLFn =
1273 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1274 break;
1275 }
1276 case OMPRTL__kmpc_omp_wait_deps: {
1277 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1278 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1279 // kmp_depend_info_t *noalias_dep_list);
1280 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1281 CGM.Int32Ty, CGM.VoidPtrTy,
1282 CGM.Int32Ty, CGM.VoidPtrTy};
1283 llvm::FunctionType *FnTy =
1284 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1285 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1286 break;
1287 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001288 case OMPRTL__kmpc_cancellationpoint: {
1289 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1290 // global_tid, kmp_int32 cncl_kind)
1291 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1292 llvm::FunctionType *FnTy =
1293 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1294 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1295 break;
1296 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001297 case OMPRTL__kmpc_cancel: {
1298 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1299 // kmp_int32 cncl_kind)
1300 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1301 llvm::FunctionType *FnTy =
1302 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1303 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1304 break;
1305 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001306 case OMPRTL__kmpc_push_num_teams: {
1307 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1308 // kmp_int32 num_teams, kmp_int32 num_threads)
1309 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1310 CGM.Int32Ty};
1311 llvm::FunctionType *FnTy =
1312 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1313 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1314 break;
1315 }
1316 case OMPRTL__kmpc_fork_teams: {
1317 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1318 // microtask, ...);
1319 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1320 getKmpc_MicroPointerTy()};
1321 llvm::FunctionType *FnTy =
1322 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1323 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1324 break;
1325 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001326 case OMPRTL__tgt_target: {
1327 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1328 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1329 // *arg_types);
1330 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1331 CGM.VoidPtrTy,
1332 CGM.Int32Ty,
1333 CGM.VoidPtrPtrTy,
1334 CGM.VoidPtrPtrTy,
1335 CGM.SizeTy->getPointerTo(),
1336 CGM.Int32Ty->getPointerTo()};
1337 llvm::FunctionType *FnTy =
1338 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1339 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1340 break;
1341 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001342 case OMPRTL__tgt_target_teams: {
1343 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1344 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1345 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1346 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1347 CGM.VoidPtrTy,
1348 CGM.Int32Ty,
1349 CGM.VoidPtrPtrTy,
1350 CGM.VoidPtrPtrTy,
1351 CGM.SizeTy->getPointerTo(),
1352 CGM.Int32Ty->getPointerTo(),
1353 CGM.Int32Ty,
1354 CGM.Int32Ty};
1355 llvm::FunctionType *FnTy =
1356 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1357 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1358 break;
1359 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001360 case OMPRTL__tgt_register_lib: {
1361 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1362 QualType ParamTy =
1363 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1364 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1365 llvm::FunctionType *FnTy =
1366 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1367 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1368 break;
1369 }
1370 case OMPRTL__tgt_unregister_lib: {
1371 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1372 QualType ParamTy =
1373 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1374 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1375 llvm::FunctionType *FnTy =
1376 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1377 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1378 break;
1379 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001380 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001381 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001382 return RTLFn;
1383}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001384
Alexander Musman21212e42015-03-13 10:38:23 +00001385llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1386 bool IVSigned) {
1387 assert((IVSize == 32 || IVSize == 64) &&
1388 "IV size is not compatible with the omp runtime");
1389 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1390 : "__kmpc_for_static_init_4u")
1391 : (IVSigned ? "__kmpc_for_static_init_8"
1392 : "__kmpc_for_static_init_8u");
1393 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1394 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1395 llvm::Type *TypeParams[] = {
1396 getIdentTyPointerTy(), // loc
1397 CGM.Int32Ty, // tid
1398 CGM.Int32Ty, // schedtype
1399 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1400 PtrTy, // p_lower
1401 PtrTy, // p_upper
1402 PtrTy, // p_stride
1403 ITy, // incr
1404 ITy // chunk
1405 };
1406 llvm::FunctionType *FnTy =
1407 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1408 return CGM.CreateRuntimeFunction(FnTy, Name);
1409}
1410
Alexander Musman92bdaab2015-03-12 13:37:50 +00001411llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1412 bool IVSigned) {
1413 assert((IVSize == 32 || IVSize == 64) &&
1414 "IV size is not compatible with the omp runtime");
1415 auto Name =
1416 IVSize == 32
1417 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1418 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1419 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1420 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1421 CGM.Int32Ty, // tid
1422 CGM.Int32Ty, // schedtype
1423 ITy, // lower
1424 ITy, // upper
1425 ITy, // stride
1426 ITy // chunk
1427 };
1428 llvm::FunctionType *FnTy =
1429 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1430 return CGM.CreateRuntimeFunction(FnTy, Name);
1431}
1432
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001433llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1434 bool IVSigned) {
1435 assert((IVSize == 32 || IVSize == 64) &&
1436 "IV size is not compatible with the omp runtime");
1437 auto Name =
1438 IVSize == 32
1439 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1440 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1441 llvm::Type *TypeParams[] = {
1442 getIdentTyPointerTy(), // loc
1443 CGM.Int32Ty, // tid
1444 };
1445 llvm::FunctionType *FnTy =
1446 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1447 return CGM.CreateRuntimeFunction(FnTy, Name);
1448}
1449
Alexander Musman92bdaab2015-03-12 13:37:50 +00001450llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1451 bool IVSigned) {
1452 assert((IVSize == 32 || IVSize == 64) &&
1453 "IV size is not compatible with the omp runtime");
1454 auto Name =
1455 IVSize == 32
1456 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1457 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1458 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1459 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1460 llvm::Type *TypeParams[] = {
1461 getIdentTyPointerTy(), // loc
1462 CGM.Int32Ty, // tid
1463 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1464 PtrTy, // p_lower
1465 PtrTy, // p_upper
1466 PtrTy // p_stride
1467 };
1468 llvm::FunctionType *FnTy =
1469 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1470 return CGM.CreateRuntimeFunction(FnTy, Name);
1471}
1472
Alexey Bataev97720002014-11-11 04:05:39 +00001473llvm::Constant *
1474CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001475 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1476 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001477 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001478 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001479 Twine(CGM.getMangledName(VD)) + ".cache.");
1480}
1481
John McCall7f416cc2015-09-08 08:05:57 +00001482Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1483 const VarDecl *VD,
1484 Address VDAddr,
1485 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001486 if (CGM.getLangOpts().OpenMPUseTLS &&
1487 CGM.getContext().getTargetInfo().isTLSSupported())
1488 return VDAddr;
1489
John McCall7f416cc2015-09-08 08:05:57 +00001490 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001491 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001492 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1493 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001494 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1495 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001496 return Address(CGF.EmitRuntimeCall(
1497 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1498 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001499}
1500
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001501void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001502 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001503 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1504 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1505 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001506 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1507 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001508 OMPLoc);
1509 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1510 // to register constructor/destructor for variable.
1511 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001512 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1513 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001514 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001515 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001516 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001517}
1518
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001519llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001520 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001521 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001522 if (CGM.getLangOpts().OpenMPUseTLS &&
1523 CGM.getContext().getTargetInfo().isTLSSupported())
1524 return nullptr;
1525
Alexey Bataev97720002014-11-11 04:05:39 +00001526 VD = VD->getDefinition(CGM.getContext());
1527 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1528 ThreadPrivateWithDefinition.insert(VD);
1529 QualType ASTTy = VD->getType();
1530
1531 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1532 auto Init = VD->getAnyInitializer();
1533 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1534 // Generate function that re-emits the declaration's initializer into the
1535 // threadprivate copy of the variable VD
1536 CodeGenFunction CtorCGF(CGM);
1537 FunctionArgList Args;
1538 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1539 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1540 Args.push_back(&Dst);
1541
John McCallc56a8b32016-03-11 04:30:31 +00001542 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1543 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001544 auto FTy = CGM.getTypes().GetFunctionType(FI);
1545 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001546 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001547 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1548 Args, SourceLocation());
1549 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001550 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001551 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001552 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1553 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1554 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001555 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1556 /*IsInitializer=*/true);
1557 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001558 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001559 CGM.getContext().VoidPtrTy, Dst.getLocation());
1560 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1561 CtorCGF.FinishFunction();
1562 Ctor = Fn;
1563 }
1564 if (VD->getType().isDestructedType() != QualType::DK_none) {
1565 // Generate function that emits destructor call for the threadprivate copy
1566 // of the variable VD
1567 CodeGenFunction DtorCGF(CGM);
1568 FunctionArgList Args;
1569 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1570 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1571 Args.push_back(&Dst);
1572
John McCallc56a8b32016-03-11 04:30:31 +00001573 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1574 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001575 auto FTy = CGM.getTypes().GetFunctionType(FI);
1576 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001577 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001578 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1579 SourceLocation());
1580 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1581 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001582 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1583 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001584 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1585 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1586 DtorCGF.FinishFunction();
1587 Dtor = Fn;
1588 }
1589 // Do not emit init function if it is not required.
1590 if (!Ctor && !Dtor)
1591 return nullptr;
1592
1593 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1594 auto CopyCtorTy =
1595 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1596 /*isVarArg=*/false)->getPointerTo();
1597 // Copying constructor for the threadprivate variable.
1598 // Must be NULL - reserved by runtime, but currently it requires that this
1599 // parameter is always NULL. Otherwise it fires assertion.
1600 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1601 if (Ctor == nullptr) {
1602 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1603 /*isVarArg=*/false)->getPointerTo();
1604 Ctor = llvm::Constant::getNullValue(CtorTy);
1605 }
1606 if (Dtor == nullptr) {
1607 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1608 /*isVarArg=*/false)->getPointerTo();
1609 Dtor = llvm::Constant::getNullValue(DtorTy);
1610 }
1611 if (!CGF) {
1612 auto InitFunctionTy =
1613 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1614 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001615 InitFunctionTy, ".__omp_threadprivate_init_.",
1616 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001617 CodeGenFunction InitCGF(CGM);
1618 FunctionArgList ArgList;
1619 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1620 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1621 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001622 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001623 InitCGF.FinishFunction();
1624 return InitFunction;
1625 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001626 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001627 }
1628 return nullptr;
1629}
1630
Alexey Bataev1d677132015-04-22 13:57:31 +00001631/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1632/// function. Here is the logic:
1633/// if (Cond) {
1634/// ThenGen();
1635/// } else {
1636/// ElseGen();
1637/// }
1638static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1639 const RegionCodeGenTy &ThenGen,
1640 const RegionCodeGenTy &ElseGen) {
1641 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1642
1643 // If the condition constant folds and can be elided, try to avoid emitting
1644 // the condition and the dead arm of the if/else.
1645 bool CondConstant;
1646 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1647 CodeGenFunction::RunCleanupsScope Scope(CGF);
1648 if (CondConstant) {
1649 ThenGen(CGF);
1650 } else {
1651 ElseGen(CGF);
1652 }
1653 return;
1654 }
1655
1656 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1657 // emit the conditional branch.
1658 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1659 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1660 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1661 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1662
1663 // Emit the 'then' code.
1664 CGF.EmitBlock(ThenBlock);
1665 {
1666 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1667 ThenGen(CGF);
1668 }
1669 CGF.EmitBranch(ContBlock);
1670 // Emit the 'else' code if present.
1671 {
1672 // There is no need to emit line number for unconditional branch.
1673 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1674 CGF.EmitBlock(ElseBlock);
1675 }
1676 {
1677 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1678 ElseGen(CGF);
1679 }
1680 {
1681 // There is no need to emit line number for unconditional branch.
1682 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1683 CGF.EmitBranch(ContBlock);
1684 }
1685 // Emit the continuation block for code after the if.
1686 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001687}
1688
Alexey Bataev1d677132015-04-22 13:57:31 +00001689void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1690 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001691 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001692 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001693 if (!CGF.HaveInsertPoint())
1694 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001695 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001696 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1697 RTLoc](CodeGenFunction &CGF) {
1698 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1699 llvm::Value *Args[] = {
1700 RTLoc,
1701 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1702 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1703 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1704 RealArgs.append(std::begin(Args), std::end(Args));
1705 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1706
1707 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1708 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1709 };
1710 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1711 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001712 auto ThreadID = getThreadID(CGF, Loc);
1713 // Build calls:
1714 // __kmpc_serialized_parallel(&Loc, GTid);
1715 llvm::Value *Args[] = {RTLoc, ThreadID};
1716 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1717 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001718
Alexey Bataev1d677132015-04-22 13:57:31 +00001719 // OutlinedFn(&GTid, &zero, CapturedStruct);
1720 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001721 Address ZeroAddr =
1722 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1723 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001724 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001725 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1726 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1727 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1728 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001729 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001730
Alexey Bataev1d677132015-04-22 13:57:31 +00001731 // __kmpc_end_serialized_parallel(&Loc, GTid);
1732 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1733 CGF.EmitRuntimeCall(
1734 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1735 };
1736 if (IfCond) {
1737 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1738 } else {
1739 CodeGenFunction::RunCleanupsScope Scope(CGF);
1740 ThenGen(CGF);
1741 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001742}
1743
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001744// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001745// thread-ID variable (it is passed in a first argument of the outlined function
1746// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1747// regular serial code region, get thread ID by calling kmp_int32
1748// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1749// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001750Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1751 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001752 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001753 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001754 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001755 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001756
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001757 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001758 auto Int32Ty =
1759 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1760 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1761 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001762 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001763
1764 return ThreadIDTemp;
1765}
1766
Alexey Bataev97720002014-11-11 04:05:39 +00001767llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001768CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001769 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001770 SmallString<256> Buffer;
1771 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001772 Out << Name;
1773 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001774 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1775 if (Elem.second) {
1776 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001777 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001778 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001779 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001780
David Blaikie13156b62014-11-19 03:06:06 +00001781 return Elem.second = new llvm::GlobalVariable(
1782 CGM.getModule(), Ty, /*IsConstant*/ false,
1783 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1784 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001785}
1786
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001787llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001788 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001789 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001790}
1791
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001792namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001793template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001794 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001795 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001796
1797public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001798 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1799 : Callee(Callee) {
1800 assert(CleanupArgs.size() == N);
1801 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1802 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001803
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001804 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001805 if (!CGF.HaveInsertPoint())
1806 return;
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001807 CGF.EmitRuntimeCall(Callee, Args);
1808 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001809};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001810} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001811
1812void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1813 StringRef CriticalName,
1814 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001815 SourceLocation Loc, const Expr *Hint) {
1816 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001817 // CriticalOpGen();
1818 // __kmpc_end_critical(ident_t *, gtid, Lock);
1819 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001820 if (!CGF.HaveInsertPoint())
1821 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001822 CodeGenFunction::RunCleanupsScope Scope(CGF);
1823 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1824 getCriticalRegionLock(CriticalName)};
1825 if (Hint) {
1826 llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1827 std::end(Args));
1828 auto *HintVal = CGF.EmitScalarExpr(Hint);
1829 ArgsWithHint.push_back(
1830 CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1831 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1832 ArgsWithHint);
1833 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001834 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001835 // Build a call to __kmpc_end_critical
1836 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1837 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1838 llvm::makeArrayRef(Args));
1839 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001840}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001841
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001842static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001843 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001844 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001845 llvm::Value *CallBool = CGF.EmitScalarConversion(
1846 IfCond,
1847 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001848 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001849
1850 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1851 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1852 // Generate the branch (If-stmt)
1853 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1854 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001855 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001856 // Emit the rest of bblocks/branches
1857 CGF.EmitBranch(ContBlock);
1858 CGF.EmitBlock(ContBlock, true);
1859}
1860
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001861void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001862 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001863 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001864 if (!CGF.HaveInsertPoint())
1865 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001866 // if(__kmpc_master(ident_t *, gtid)) {
1867 // MasterOpGen();
1868 // __kmpc_end_master(ident_t *, gtid);
1869 // }
1870 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001871 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001872 auto *IsMaster =
1873 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001874 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1875 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001876 emitIfStmt(
1877 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1878 CodeGenFunction::RunCleanupsScope Scope(CGF);
1879 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1880 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1881 llvm::makeArrayRef(Args));
1882 MasterOpGen(CGF);
1883 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001884}
1885
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001886void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1887 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001888 if (!CGF.HaveInsertPoint())
1889 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001890 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1891 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001892 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001893 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001894 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001895}
1896
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001897void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1898 const RegionCodeGenTy &TaskgroupOpGen,
1899 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001900 if (!CGF.HaveInsertPoint())
1901 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001902 // __kmpc_taskgroup(ident_t *, gtid);
1903 // TaskgroupOpGen();
1904 // __kmpc_end_taskgroup(ident_t *, gtid);
1905 // Prepare arguments and build a call to __kmpc_taskgroup
1906 {
1907 CodeGenFunction::RunCleanupsScope Scope(CGF);
1908 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1909 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1910 // Build a call to __kmpc_end_taskgroup
1911 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1912 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1913 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001914 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001915 }
1916}
1917
John McCall7f416cc2015-09-08 08:05:57 +00001918/// Given an array of pointers to variables, project the address of a
1919/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001920static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1921 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001922 // Pull out the pointer to the variable.
1923 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001924 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001925 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1926
1927 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001928 Addr = CGF.Builder.CreateElementBitCast(
1929 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001930 return Addr;
1931}
1932
Alexey Bataeva63048e2015-03-23 06:18:07 +00001933static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001934 CodeGenModule &CGM, llvm::Type *ArgsType,
1935 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1936 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001937 auto &C = CGM.getContext();
1938 // void copy_func(void *LHSArg, void *RHSArg);
1939 FunctionArgList Args;
1940 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1941 C.VoidPtrTy);
1942 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1943 C.VoidPtrTy);
1944 Args.push_back(&LHSArg);
1945 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00001946 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001947 auto *Fn = llvm::Function::Create(
1948 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1949 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001950 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001951 CodeGenFunction CGF(CGM);
1952 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001953 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001954 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001955 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1956 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1957 ArgsType), CGF.getPointerAlign());
1958 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1959 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1960 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001961 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1962 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1963 // ...
1964 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001965 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001966 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1967 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1968
1969 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1970 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1971
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001972 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1973 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001974 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001975 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001976 CGF.FinishFunction();
1977 return Fn;
1978}
1979
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001980void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001981 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001982 SourceLocation Loc,
1983 ArrayRef<const Expr *> CopyprivateVars,
1984 ArrayRef<const Expr *> SrcExprs,
1985 ArrayRef<const Expr *> DstExprs,
1986 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001987 if (!CGF.HaveInsertPoint())
1988 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001989 assert(CopyprivateVars.size() == SrcExprs.size() &&
1990 CopyprivateVars.size() == DstExprs.size() &&
1991 CopyprivateVars.size() == AssignmentOps.size());
1992 auto &C = CGM.getContext();
1993 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001994 // if(__kmpc_single(ident_t *, gtid)) {
1995 // SingleOpGen();
1996 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001997 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001998 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001999 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2000 // <copy_func>, did_it);
2001
John McCall7f416cc2015-09-08 08:05:57 +00002002 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002003 if (!CopyprivateVars.empty()) {
2004 // int32 did_it = 0;
2005 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2006 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002007 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002008 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002009 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002010 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002011 auto *IsSingle =
2012 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00002013 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
2014 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002015 emitIfStmt(
2016 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
2017 CodeGenFunction::RunCleanupsScope Scope(CGF);
2018 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
2019 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
2020 llvm::makeArrayRef(Args));
2021 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002022 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002023 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00002024 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002025 }
2026 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00002027 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2028 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002029 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002030 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2031 auto CopyprivateArrayTy =
2032 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2033 /*IndexTypeQuals=*/0);
2034 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002035 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002036 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2037 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002038 Address Elem = CGF.Builder.CreateConstArrayGEP(
2039 CopyprivateList, I, CGF.getPointerSize());
2040 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002041 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002042 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2043 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002044 }
2045 // Build function that copies private values from single region to all other
2046 // threads in the corresponding parallel region.
2047 auto *CpyFn = emitCopyprivateCopyFunction(
2048 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002049 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002050 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002051 Address CL =
2052 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2053 CGF.VoidPtrTy);
2054 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002055 llvm::Value *Args[] = {
2056 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2057 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002058 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002059 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002060 CpyFn, // void (*) (void *, void *) <copy_func>
2061 DidItVal // i32 did_it
2062 };
2063 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2064 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002065}
2066
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002067void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2068 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002069 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002070 if (!CGF.HaveInsertPoint())
2071 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002072 // __kmpc_ordered(ident_t *, gtid);
2073 // OrderedOpGen();
2074 // __kmpc_end_ordered(ident_t *, gtid);
2075 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002076 CodeGenFunction::RunCleanupsScope Scope(CGF);
2077 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002078 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2079 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
2080 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00002081 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002082 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2083 llvm::makeArrayRef(Args));
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002084 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002085 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002086}
2087
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002088void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002089 OpenMPDirectiveKind Kind, bool EmitChecks,
2090 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002091 if (!CGF.HaveInsertPoint())
2092 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002093 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002094 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002095 unsigned Flags;
2096 if (Kind == OMPD_for)
2097 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2098 else if (Kind == OMPD_sections)
2099 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2100 else if (Kind == OMPD_single)
2101 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2102 else if (Kind == OMPD_barrier)
2103 Flags = OMP_IDENT_BARRIER_EXPL;
2104 else
2105 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002106 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2107 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002108 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2109 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002110 if (auto *OMPRegionInfo =
2111 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002112 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002113 auto *Result = CGF.EmitRuntimeCall(
2114 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002115 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002116 // if (__kmpc_cancel_barrier()) {
2117 // exit from construct;
2118 // }
2119 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2120 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2121 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2122 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2123 CGF.EmitBlock(ExitBB);
2124 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002125 auto CancelDestination =
2126 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002127 CGF.EmitBranchThroughCleanup(CancelDestination);
2128 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2129 }
2130 return;
2131 }
2132 }
2133 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002134}
2135
Alexander Musmanc6388682014-12-15 07:07:06 +00002136/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2137static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002138 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002139 switch (ScheduleKind) {
2140 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002141 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2142 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002143 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002144 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002145 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002146 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002147 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002148 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2149 case OMPC_SCHEDULE_auto:
2150 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002151 case OMPC_SCHEDULE_unknown:
2152 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002153 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002154 }
2155 llvm_unreachable("Unexpected runtime schedule");
2156}
2157
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002158/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2159static OpenMPSchedType
2160getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2161 // only static is allowed for dist_schedule
2162 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2163}
2164
Alexander Musmanc6388682014-12-15 07:07:06 +00002165bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2166 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002167 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002168 return Schedule == OMP_sch_static;
2169}
2170
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002171bool CGOpenMPRuntime::isStaticNonchunked(
2172 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2173 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2174 return Schedule == OMP_dist_sch_static;
2175}
2176
2177
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002178bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002179 auto Schedule =
2180 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002181 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2182 return Schedule != OMP_sch_static;
2183}
2184
John McCall7f416cc2015-09-08 08:05:57 +00002185void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2186 SourceLocation Loc,
2187 OpenMPScheduleClauseKind ScheduleKind,
2188 unsigned IVSize, bool IVSigned,
2189 bool Ordered, llvm::Value *UB,
2190 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002191 if (!CGF.HaveInsertPoint())
2192 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002193 OpenMPSchedType Schedule =
2194 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002195 assert(Ordered ||
2196 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2197 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2198 // Call __kmpc_dispatch_init(
2199 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2200 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2201 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002202
John McCall7f416cc2015-09-08 08:05:57 +00002203 // If the Chunk was not specified in the clause - use default value 1.
2204 if (Chunk == nullptr)
2205 Chunk = CGF.Builder.getIntN(IVSize, 1);
2206 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002207 emitUpdateLocation(CGF, Loc),
2208 getThreadID(CGF, Loc),
2209 CGF.Builder.getInt32(Schedule), // Schedule type
2210 CGF.Builder.getIntN(IVSize, 0), // Lower
2211 UB, // Upper
2212 CGF.Builder.getIntN(IVSize, 1), // Stride
2213 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002214 };
2215 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2216}
2217
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002218static void emitForStaticInitCall(CodeGenFunction &CGF,
2219 SourceLocation Loc,
2220 llvm::Value * UpdateLocation,
2221 llvm::Value * ThreadId,
2222 llvm::Constant * ForStaticInitFunction,
2223 OpenMPSchedType Schedule,
2224 unsigned IVSize, bool IVSigned, bool Ordered,
2225 Address IL, Address LB, Address UB,
2226 Address ST, llvm::Value *Chunk) {
2227 if (!CGF.HaveInsertPoint())
2228 return;
2229
2230 assert(!Ordered);
2231 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2232 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2233 Schedule == OMP_dist_sch_static ||
2234 Schedule == OMP_dist_sch_static_chunked);
2235
2236 // Call __kmpc_for_static_init(
2237 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2238 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2239 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2240 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2241 if (Chunk == nullptr) {
2242 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2243 Schedule == OMP_dist_sch_static) &&
2244 "expected static non-chunked schedule");
2245 // If the Chunk was not specified in the clause - use default value 1.
2246 Chunk = CGF.Builder.getIntN(IVSize, 1);
2247 } else {
2248 assert((Schedule == OMP_sch_static_chunked ||
2249 Schedule == OMP_ord_static_chunked ||
2250 Schedule == OMP_dist_sch_static_chunked) &&
2251 "expected static chunked schedule");
2252 }
2253 llvm::Value *Args[] = {
2254 UpdateLocation,
2255 ThreadId,
2256 CGF.Builder.getInt32(Schedule), // Schedule type
2257 IL.getPointer(), // &isLastIter
2258 LB.getPointer(), // &LB
2259 UB.getPointer(), // &UB
2260 ST.getPointer(), // &Stride
2261 CGF.Builder.getIntN(IVSize, 1), // Incr
2262 Chunk // Chunk
2263 };
2264 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2265}
2266
John McCall7f416cc2015-09-08 08:05:57 +00002267void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2268 SourceLocation Loc,
2269 OpenMPScheduleClauseKind ScheduleKind,
2270 unsigned IVSize, bool IVSigned,
2271 bool Ordered, Address IL, Address LB,
2272 Address UB, Address ST,
2273 llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002274 OpenMPSchedType ScheduleNum = getRuntimeSchedule(ScheduleKind, Chunk != nullptr,
2275 Ordered);
2276 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2277 auto *ThreadId = getThreadID(CGF, Loc);
2278 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2279 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2280 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
2281}
John McCall7f416cc2015-09-08 08:05:57 +00002282
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002283void CGOpenMPRuntime::emitDistributeStaticInit(CodeGenFunction &CGF,
2284 SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind,
2285 unsigned IVSize, bool IVSigned,
2286 bool Ordered, Address IL, Address LB,
2287 Address UB, Address ST,
2288 llvm::Value *Chunk) {
2289 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2290 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2291 auto *ThreadId = getThreadID(CGF, Loc);
2292 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2293 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2294 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002295}
2296
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002297void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2298 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002299 if (!CGF.HaveInsertPoint())
2300 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002301 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002302 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002303 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2304 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002305}
2306
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002307void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2308 SourceLocation Loc,
2309 unsigned IVSize,
2310 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002311 if (!CGF.HaveInsertPoint())
2312 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002313 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002314 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002315 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2316}
2317
Alexander Musman92bdaab2015-03-12 13:37:50 +00002318llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2319 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002320 bool IVSigned, Address IL,
2321 Address LB, Address UB,
2322 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002323 // Call __kmpc_dispatch_next(
2324 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2325 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2326 // kmp_int[32|64] *p_stride);
2327 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002328 emitUpdateLocation(CGF, Loc),
2329 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002330 IL.getPointer(), // &isLastIter
2331 LB.getPointer(), // &Lower
2332 UB.getPointer(), // &Upper
2333 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002334 };
2335 llvm::Value *Call =
2336 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2337 return CGF.EmitScalarConversion(
2338 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002339 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002340}
2341
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002342void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2343 llvm::Value *NumThreads,
2344 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002345 if (!CGF.HaveInsertPoint())
2346 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002347 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2348 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002349 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002350 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002351 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2352 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002353}
2354
Alexey Bataev7f210c62015-06-18 13:40:03 +00002355void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2356 OpenMPProcBindClauseKind ProcBind,
2357 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002358 if (!CGF.HaveInsertPoint())
2359 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002360 // Constants for proc bind value accepted by the runtime.
2361 enum ProcBindTy {
2362 ProcBindFalse = 0,
2363 ProcBindTrue,
2364 ProcBindMaster,
2365 ProcBindClose,
2366 ProcBindSpread,
2367 ProcBindIntel,
2368 ProcBindDefault
2369 } RuntimeProcBind;
2370 switch (ProcBind) {
2371 case OMPC_PROC_BIND_master:
2372 RuntimeProcBind = ProcBindMaster;
2373 break;
2374 case OMPC_PROC_BIND_close:
2375 RuntimeProcBind = ProcBindClose;
2376 break;
2377 case OMPC_PROC_BIND_spread:
2378 RuntimeProcBind = ProcBindSpread;
2379 break;
2380 case OMPC_PROC_BIND_unknown:
2381 llvm_unreachable("Unsupported proc_bind value.");
2382 }
2383 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2384 llvm::Value *Args[] = {
2385 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2386 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2387 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2388}
2389
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002390void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2391 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002392 if (!CGF.HaveInsertPoint())
2393 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002394 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002395 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2396 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002397}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002398
Alexey Bataev62b63b12015-03-10 07:28:44 +00002399namespace {
2400/// \brief Indexes of fields for type kmp_task_t.
2401enum KmpTaskTFields {
2402 /// \brief List of shared variables.
2403 KmpTaskTShareds,
2404 /// \brief Task routine.
2405 KmpTaskTRoutine,
2406 /// \brief Partition id for the untied tasks.
2407 KmpTaskTPartId,
2408 /// \brief Function with call of destructors for private variables.
2409 KmpTaskTDestructors,
2410};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002411} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002412
Samuel Antaoee8fb302016-01-06 13:42:12 +00002413bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2414 // FIXME: Add other entries type when they become supported.
2415 return OffloadEntriesTargetRegion.empty();
2416}
2417
2418/// \brief Initialize target region entry.
2419void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2420 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2421 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002422 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002423 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2424 "only required for the device "
2425 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002426 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002427 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2428 ++OffloadingEntriesNum;
2429}
2430
2431void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2432 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2433 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002434 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002435 // If we are emitting code for a target, the entry is already initialized,
2436 // only has to be registered.
2437 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002438 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002439 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002440 auto &Entry =
2441 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002442 assert(Entry.isValid() && "Entry not initialized!");
2443 Entry.setAddress(Addr);
2444 Entry.setID(ID);
2445 return;
2446 } else {
2447 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002448 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002449 }
2450}
2451
2452bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002453 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2454 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002455 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2456 if (PerDevice == OffloadEntriesTargetRegion.end())
2457 return false;
2458 auto PerFile = PerDevice->second.find(FileID);
2459 if (PerFile == PerDevice->second.end())
2460 return false;
2461 auto PerParentName = PerFile->second.find(ParentName);
2462 if (PerParentName == PerFile->second.end())
2463 return false;
2464 auto PerLine = PerParentName->second.find(LineNum);
2465 if (PerLine == PerParentName->second.end())
2466 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002467 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002468 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002469 return false;
2470 return true;
2471}
2472
2473void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2474 const OffloadTargetRegionEntryInfoActTy &Action) {
2475 // Scan all target region entries and perform the provided action.
2476 for (auto &D : OffloadEntriesTargetRegion)
2477 for (auto &F : D.second)
2478 for (auto &P : F.second)
2479 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002480 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002481}
2482
2483/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2484/// \a Codegen. This is used to emit the two functions that register and
2485/// unregister the descriptor of the current compilation unit.
2486static llvm::Function *
2487createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2488 const RegionCodeGenTy &Codegen) {
2489 auto &C = CGM.getContext();
2490 FunctionArgList Args;
2491 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2492 /*Id=*/nullptr, C.VoidPtrTy);
2493 Args.push_back(&DummyPtr);
2494
2495 CodeGenFunction CGF(CGM);
2496 GlobalDecl();
John McCallc56a8b32016-03-11 04:30:31 +00002497 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002498 auto FTy = CGM.getTypes().GetFunctionType(FI);
2499 auto *Fn =
2500 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2501 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2502 Codegen(CGF);
2503 CGF.FinishFunction();
2504 return Fn;
2505}
2506
2507llvm::Function *
2508CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2509
2510 // If we don't have entries or if we are emitting code for the device, we
2511 // don't need to do anything.
2512 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2513 return nullptr;
2514
2515 auto &M = CGM.getModule();
2516 auto &C = CGM.getContext();
2517
2518 // Get list of devices we care about
2519 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2520
2521 // We should be creating an offloading descriptor only if there are devices
2522 // specified.
2523 assert(!Devices.empty() && "No OpenMP offloading devices??");
2524
2525 // Create the external variables that will point to the begin and end of the
2526 // host entries section. These will be defined by the linker.
2527 auto *OffloadEntryTy =
2528 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2529 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2530 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002531 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002532 ".omp_offloading.entries_begin");
2533 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2534 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002535 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002536 ".omp_offloading.entries_end");
2537
2538 // Create all device images
2539 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2540 auto *DeviceImageTy = cast<llvm::StructType>(
2541 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2542
2543 for (unsigned i = 0; i < Devices.size(); ++i) {
2544 StringRef T = Devices[i].getTriple();
2545 auto *ImgBegin = new llvm::GlobalVariable(
2546 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002547 /*Initializer=*/nullptr,
2548 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002549 auto *ImgEnd = new llvm::GlobalVariable(
2550 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002551 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002552
2553 llvm::Constant *Dev =
2554 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2555 HostEntriesBegin, HostEntriesEnd, nullptr);
2556 DeviceImagesEntires.push_back(Dev);
2557 }
2558
2559 // Create device images global array.
2560 llvm::ArrayType *DeviceImagesInitTy =
2561 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2562 llvm::Constant *DeviceImagesInit =
2563 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2564
2565 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2566 M, DeviceImagesInitTy, /*isConstant=*/true,
2567 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2568 ".omp_offloading.device_images");
2569 DeviceImages->setUnnamedAddr(true);
2570
2571 // This is a Zero array to be used in the creation of the constant expressions
2572 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2573 llvm::Constant::getNullValue(CGM.Int32Ty)};
2574
2575 // Create the target region descriptor.
2576 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2577 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2578 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2579 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2580 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2581 Index),
2582 HostEntriesBegin, HostEntriesEnd, nullptr);
2583
2584 auto *Desc = new llvm::GlobalVariable(
2585 M, BinaryDescriptorTy, /*isConstant=*/true,
2586 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2587 ".omp_offloading.descriptor");
2588
2589 // Emit code to register or unregister the descriptor at execution
2590 // startup or closing, respectively.
2591
2592 // Create a variable to drive the registration and unregistration of the
2593 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2594 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2595 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2596 IdentInfo, C.CharTy);
2597
2598 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2599 CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2600 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2601 Desc);
2602 });
2603 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2604 CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2605 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2606 Desc);
2607 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2608 });
2609 return RegFn;
2610}
2611
Samuel Antao2de62b02016-02-13 23:35:10 +00002612void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2613 llvm::Constant *Addr, uint64_t Size) {
2614 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002615 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2616 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2617 llvm::LLVMContext &C = CGM.getModule().getContext();
2618 llvm::Module &M = CGM.getModule();
2619
2620 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002621 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002622
2623 // Create constant string with the name.
2624 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2625
2626 llvm::GlobalVariable *Str =
2627 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2628 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2629 ".omp_offloading.entry_name");
2630 Str->setUnnamedAddr(true);
2631 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2632
2633 // Create the entry struct.
2634 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2635 TgtOffloadEntryType, AddrPtr, StrPtr,
2636 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2637 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2638 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2639 EntryInit, ".omp_offloading.entry");
2640
2641 // The entry has to be created in the section the linker expects it to be.
2642 Entry->setSection(".omp_offloading.entries");
2643 // We can't have any padding between symbols, so we need to have 1-byte
2644 // alignment.
2645 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002646}
2647
2648void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2649 // Emit the offloading entries and metadata so that the device codegen side
2650 // can
2651 // easily figure out what to emit. The produced metadata looks like this:
2652 //
2653 // !omp_offload.info = !{!1, ...}
2654 //
2655 // Right now we only generate metadata for function that contain target
2656 // regions.
2657
2658 // If we do not have entries, we dont need to do anything.
2659 if (OffloadEntriesInfoManager.empty())
2660 return;
2661
2662 llvm::Module &M = CGM.getModule();
2663 llvm::LLVMContext &C = M.getContext();
2664 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2665 OrderedEntries(OffloadEntriesInfoManager.size());
2666
2667 // Create the offloading info metadata node.
2668 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2669
2670 // Auxiliar methods to create metadata values and strings.
2671 auto getMDInt = [&](unsigned v) {
2672 return llvm::ConstantAsMetadata::get(
2673 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2674 };
2675
2676 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2677
2678 // Create function that emits metadata for each target region entry;
2679 auto &&TargetRegionMetadataEmitter = [&](
2680 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002681 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2682 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2683 // Generate metadata for target regions. Each entry of this metadata
2684 // contains:
2685 // - Entry 0 -> Kind of this type of metadata (0).
2686 // - Entry 1 -> Device ID of the file where the entry was identified.
2687 // - Entry 2 -> File ID of the file where the entry was identified.
2688 // - Entry 3 -> Mangled name of the function where the entry was identified.
2689 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002690 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002691 // The first element of the metadata node is the kind.
2692 Ops.push_back(getMDInt(E.getKind()));
2693 Ops.push_back(getMDInt(DeviceID));
2694 Ops.push_back(getMDInt(FileID));
2695 Ops.push_back(getMDString(ParentName));
2696 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002697 Ops.push_back(getMDInt(E.getOrder()));
2698
2699 // Save this entry in the right position of the ordered entries array.
2700 OrderedEntries[E.getOrder()] = &E;
2701
2702 // Add metadata to the named metadata node.
2703 MD->addOperand(llvm::MDNode::get(C, Ops));
2704 };
2705
2706 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2707 TargetRegionMetadataEmitter);
2708
2709 for (auto *E : OrderedEntries) {
2710 assert(E && "All ordered entries must exist!");
2711 if (auto *CE =
2712 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2713 E)) {
2714 assert(CE->getID() && CE->getAddress() &&
2715 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002716 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002717 } else
2718 llvm_unreachable("Unsupported entry kind.");
2719 }
2720}
2721
2722/// \brief Loads all the offload entries information from the host IR
2723/// metadata.
2724void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2725 // If we are in target mode, load the metadata from the host IR. This code has
2726 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2727
2728 if (!CGM.getLangOpts().OpenMPIsDevice)
2729 return;
2730
2731 if (CGM.getLangOpts().OMPHostIRFile.empty())
2732 return;
2733
2734 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2735 if (Buf.getError())
2736 return;
2737
2738 llvm::LLVMContext C;
2739 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2740
2741 if (ME.getError())
2742 return;
2743
2744 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2745 if (!MD)
2746 return;
2747
2748 for (auto I : MD->operands()) {
2749 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2750
2751 auto getMDInt = [&](unsigned Idx) {
2752 llvm::ConstantAsMetadata *V =
2753 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2754 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2755 };
2756
2757 auto getMDString = [&](unsigned Idx) {
2758 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2759 return V->getString();
2760 };
2761
2762 switch (getMDInt(0)) {
2763 default:
2764 llvm_unreachable("Unexpected metadata!");
2765 break;
2766 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2767 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2768 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2769 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2770 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002771 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002772 break;
2773 }
2774 }
2775}
2776
Alexey Bataev62b63b12015-03-10 07:28:44 +00002777void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2778 if (!KmpRoutineEntryPtrTy) {
2779 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2780 auto &C = CGM.getContext();
2781 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2782 FunctionProtoType::ExtProtoInfo EPI;
2783 KmpRoutineEntryPtrQTy = C.getPointerType(
2784 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2785 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2786 }
2787}
2788
Alexey Bataevc71a4092015-09-11 10:29:41 +00002789static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2790 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002791 auto *Field = FieldDecl::Create(
2792 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2793 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2794 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2795 Field->setAccess(AS_public);
2796 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002797 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002798}
2799
Samuel Antaoee8fb302016-01-06 13:42:12 +00002800QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2801
2802 // Make sure the type of the entry is already created. This is the type we
2803 // have to create:
2804 // struct __tgt_offload_entry{
2805 // void *addr; // Pointer to the offload entry info.
2806 // // (function or global)
2807 // char *name; // Name of the function or global.
2808 // size_t size; // Size of the entry info (0 if it a function).
2809 // };
2810 if (TgtOffloadEntryQTy.isNull()) {
2811 ASTContext &C = CGM.getContext();
2812 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2813 RD->startDefinition();
2814 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2815 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2816 addFieldToRecordDecl(C, RD, C.getSizeType());
2817 RD->completeDefinition();
2818 TgtOffloadEntryQTy = C.getRecordType(RD);
2819 }
2820 return TgtOffloadEntryQTy;
2821}
2822
2823QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2824 // These are the types we need to build:
2825 // struct __tgt_device_image{
2826 // void *ImageStart; // Pointer to the target code start.
2827 // void *ImageEnd; // Pointer to the target code end.
2828 // // We also add the host entries to the device image, as it may be useful
2829 // // for the target runtime to have access to that information.
2830 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2831 // // the entries.
2832 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2833 // // entries (non inclusive).
2834 // };
2835 if (TgtDeviceImageQTy.isNull()) {
2836 ASTContext &C = CGM.getContext();
2837 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2838 RD->startDefinition();
2839 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2840 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2841 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2842 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2843 RD->completeDefinition();
2844 TgtDeviceImageQTy = C.getRecordType(RD);
2845 }
2846 return TgtDeviceImageQTy;
2847}
2848
2849QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2850 // struct __tgt_bin_desc{
2851 // int32_t NumDevices; // Number of devices supported.
2852 // __tgt_device_image *DeviceImages; // Arrays of device images
2853 // // (one per device).
2854 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2855 // // entries.
2856 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2857 // // entries (non inclusive).
2858 // };
2859 if (TgtBinaryDescriptorQTy.isNull()) {
2860 ASTContext &C = CGM.getContext();
2861 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2862 RD->startDefinition();
2863 addFieldToRecordDecl(
2864 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2865 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2866 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2867 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2868 RD->completeDefinition();
2869 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2870 }
2871 return TgtBinaryDescriptorQTy;
2872}
2873
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002874namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002875struct PrivateHelpersTy {
2876 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2877 const VarDecl *PrivateElemInit)
2878 : Original(Original), PrivateCopy(PrivateCopy),
2879 PrivateElemInit(PrivateElemInit) {}
2880 const VarDecl *Original;
2881 const VarDecl *PrivateCopy;
2882 const VarDecl *PrivateElemInit;
2883};
2884typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002885} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002886
Alexey Bataev9e034042015-05-05 04:05:12 +00002887static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002888createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002889 if (!Privates.empty()) {
2890 auto &C = CGM.getContext();
2891 // Build struct .kmp_privates_t. {
2892 // /* private vars */
2893 // };
2894 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2895 RD->startDefinition();
2896 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002897 auto *VD = Pair.second.Original;
2898 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002899 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002900 auto *FD = addFieldToRecordDecl(C, RD, Type);
2901 if (VD->hasAttrs()) {
2902 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2903 E(VD->getAttrs().end());
2904 I != E; ++I)
2905 FD->addAttr(*I);
2906 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002907 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002908 RD->completeDefinition();
2909 return RD;
2910 }
2911 return nullptr;
2912}
2913
Alexey Bataev9e034042015-05-05 04:05:12 +00002914static RecordDecl *
2915createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002916 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002917 auto &C = CGM.getContext();
2918 // Build struct kmp_task_t {
2919 // void * shareds;
2920 // kmp_routine_entry_t routine;
2921 // kmp_int32 part_id;
2922 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002923 // };
2924 auto *RD = C.buildImplicitRecord("kmp_task_t");
2925 RD->startDefinition();
2926 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2927 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2928 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2929 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002930 RD->completeDefinition();
2931 return RD;
2932}
2933
2934static RecordDecl *
2935createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002936 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002937 auto &C = CGM.getContext();
2938 // Build struct kmp_task_t_with_privates {
2939 // kmp_task_t task_data;
2940 // .kmp_privates_t. privates;
2941 // };
2942 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2943 RD->startDefinition();
2944 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002945 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2946 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2947 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002948 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002949 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002950}
2951
2952/// \brief Emit a proxy function which accepts kmp_task_t as the second
2953/// argument.
2954/// \code
2955/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002956/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2957/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002958/// return 0;
2959/// }
2960/// \endcode
2961static llvm::Value *
2962emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002963 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2964 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002965 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2966 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002967 auto &C = CGM.getContext();
2968 FunctionArgList Args;
2969 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2970 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002971 /*Id=*/nullptr,
2972 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002973 Args.push_back(&GtidArg);
2974 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002975 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00002976 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002977 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2978 auto *TaskEntry =
2979 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2980 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002981 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002982 CodeGenFunction CGF(CGM);
2983 CGF.disableDebugInfo();
2984 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2985
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002986 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2987 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002988 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002989 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002990 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2991 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2992 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002993 auto *KmpTaskTWithPrivatesQTyRD =
2994 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002995 LValue Base =
2996 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002997 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2998 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2999 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3000 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
3001
3002 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3003 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003004 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003005 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003006 CGF.ConvertTypeForMem(SharedsPtrTy));
3007
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003008 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3009 llvm::Value *PrivatesParam;
3010 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3011 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3012 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003013 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003014 } else {
3015 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3016 }
3017
3018 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
3019 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003020 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3021 CGF.EmitStoreThroughLValue(
3022 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003023 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003024 CGF.FinishFunction();
3025 return TaskEntry;
3026}
3027
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003028static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3029 SourceLocation Loc,
3030 QualType KmpInt32Ty,
3031 QualType KmpTaskTWithPrivatesPtrQTy,
3032 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003033 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003034 FunctionArgList Args;
3035 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3036 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003037 /*Id=*/nullptr,
3038 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003039 Args.push_back(&GtidArg);
3040 Args.push_back(&TaskTypeArg);
3041 FunctionType::ExtInfo Info;
3042 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003043 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003044 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3045 auto *DestructorFn =
3046 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3047 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003048 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3049 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003050 CodeGenFunction CGF(CGM);
3051 CGF.disableDebugInfo();
3052 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3053 Args);
3054
Alexey Bataev31300ed2016-02-04 11:27:03 +00003055 LValue Base = CGF.EmitLoadOfPointerLValue(
3056 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3057 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003058 auto *KmpTaskTWithPrivatesQTyRD =
3059 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3060 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003061 Base = CGF.EmitLValueForField(Base, *FI);
3062 for (auto *Field :
3063 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3064 if (auto DtorKind = Field->getType().isDestructedType()) {
3065 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3066 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3067 }
3068 }
3069 CGF.FinishFunction();
3070 return DestructorFn;
3071}
3072
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003073/// \brief Emit a privates mapping function for correct handling of private and
3074/// firstprivate variables.
3075/// \code
3076/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3077/// **noalias priv1,..., <tyn> **noalias privn) {
3078/// *priv1 = &.privates.priv1;
3079/// ...;
3080/// *privn = &.privates.privn;
3081/// }
3082/// \endcode
3083static llvm::Value *
3084emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003085 ArrayRef<const Expr *> PrivateVars,
3086 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003087 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003088 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003089 auto &C = CGM.getContext();
3090 FunctionArgList Args;
3091 ImplicitParamDecl TaskPrivatesArg(
3092 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3093 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3094 Args.push_back(&TaskPrivatesArg);
3095 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3096 unsigned Counter = 1;
3097 for (auto *E: PrivateVars) {
3098 Args.push_back(ImplicitParamDecl::Create(
3099 C, /*DC=*/nullptr, Loc,
3100 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3101 .withConst()
3102 .withRestrict()));
3103 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3104 PrivateVarsPos[VD] = Counter;
3105 ++Counter;
3106 }
3107 for (auto *E : FirstprivateVars) {
3108 Args.push_back(ImplicitParamDecl::Create(
3109 C, /*DC=*/nullptr, Loc,
3110 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3111 .withConst()
3112 .withRestrict()));
3113 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3114 PrivateVarsPos[VD] = Counter;
3115 ++Counter;
3116 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003117 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003118 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003119 auto *TaskPrivatesMapTy =
3120 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3121 auto *TaskPrivatesMap = llvm::Function::Create(
3122 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3123 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003124 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3125 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003126 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003127 CodeGenFunction CGF(CGM);
3128 CGF.disableDebugInfo();
3129 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3130 TaskPrivatesMapFnInfo, Args);
3131
3132 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003133 LValue Base = CGF.EmitLoadOfPointerLValue(
3134 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3135 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003136 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3137 Counter = 0;
3138 for (auto *Field : PrivatesQTyRD->fields()) {
3139 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3140 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003141 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003142 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3143 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003144 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003145 ++Counter;
3146 }
3147 CGF.FinishFunction();
3148 return TaskPrivatesMap;
3149}
3150
Alexey Bataev9e034042015-05-05 04:05:12 +00003151static int array_pod_sort_comparator(const PrivateDataTy *P1,
3152 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003153 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3154}
3155
3156void CGOpenMPRuntime::emitTaskCall(
3157 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3158 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00003159 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003160 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3161 ArrayRef<const Expr *> PrivateCopies,
3162 ArrayRef<const Expr *> FirstprivateVars,
3163 ArrayRef<const Expr *> FirstprivateCopies,
3164 ArrayRef<const Expr *> FirstprivateInits,
3165 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003166 if (!CGF.HaveInsertPoint())
3167 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003168 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00003169 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003170 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003171 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003172 for (auto *E : PrivateVars) {
3173 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3174 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003175 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003176 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3177 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003178 ++I;
3179 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003180 I = FirstprivateCopies.begin();
3181 auto IElemInitRef = FirstprivateInits.begin();
3182 for (auto *E : FirstprivateVars) {
3183 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3184 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003185 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003186 PrivateHelpersTy(
3187 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3188 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003189 ++I;
3190 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003191 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003192 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3193 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003194 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3195 // Build type kmp_routine_entry_t (if not built yet).
3196 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003197 // Build type kmp_task_t (if not built yet).
3198 if (KmpTaskTQTy.isNull()) {
3199 KmpTaskTQTy = C.getRecordType(
3200 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
3201 }
3202 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003203 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003204 auto *KmpTaskTWithPrivatesQTyRD =
3205 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3206 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3207 QualType KmpTaskTWithPrivatesPtrQTy =
3208 C.getPointerType(KmpTaskTWithPrivatesQTy);
3209 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3210 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003211 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003212 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3213
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003214 // Emit initial values for private copies (if any).
3215 llvm::Value *TaskPrivatesMap = nullptr;
3216 auto *TaskPrivatesMapTy =
3217 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3218 3)
3219 ->getType();
3220 if (!Privates.empty()) {
3221 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3222 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3223 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3224 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3225 TaskPrivatesMap, TaskPrivatesMapTy);
3226 } else {
3227 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3228 cast<llvm::PointerType>(TaskPrivatesMapTy));
3229 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003230 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3231 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003232 auto *TaskEntry = emitProxyTaskFunction(
3233 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003234 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003235
3236 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3237 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3238 // kmp_routine_entry_t *task_entry);
3239 // Task flags. Format is taken from
3240 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3241 // description of kmp_tasking_flags struct.
3242 const unsigned TiedFlag = 0x1;
3243 const unsigned FinalFlag = 0x2;
3244 unsigned Flags = Tied ? TiedFlag : 0;
3245 auto *TaskFlags =
3246 Final.getPointer()
3247 ? CGF.Builder.CreateSelect(Final.getPointer(),
3248 CGF.Builder.getInt32(FinalFlag),
3249 CGF.Builder.getInt32(/*C=*/0))
3250 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3251 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003252 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003253 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3254 getThreadID(CGF, Loc), TaskFlags,
3255 KmpTaskTWithPrivatesTySize, SharedsSize,
3256 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3257 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003258 auto *NewTask = CGF.EmitRuntimeCall(
3259 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003260 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3261 NewTask, KmpTaskTWithPrivatesPtrTy);
3262 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3263 KmpTaskTWithPrivatesQTy);
3264 LValue TDBase =
3265 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003266 // Fill the data in the resulting kmp_task_t record.
3267 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003268 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003269 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003270 KmpTaskSharedsPtr =
3271 Address(CGF.EmitLoadOfScalar(
3272 CGF.EmitLValueForField(
3273 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3274 KmpTaskTShareds)),
3275 Loc),
3276 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003277 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003278 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003279 // Emit initial values for private copies (if any).
3280 bool NeedsCleanup = false;
3281 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003282 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3283 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003284 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003285 LValue SharedsBase;
3286 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003287 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003288 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3289 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3290 SharedsTy);
3291 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003292 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3293 cast<CapturedStmt>(*D.getAssociatedStmt()));
3294 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003295 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003296 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003297 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003298 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003299 if (auto *Elem = Pair.second.PrivateElemInit) {
3300 auto *OriginalVD = Pair.second.Original;
3301 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3302 auto SharedRefLValue =
3303 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003304 SharedRefLValue = CGF.MakeAddrLValue(
3305 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3306 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003307 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003308 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003309 // Initialize firstprivate array.
3310 if (!isa<CXXConstructExpr>(Init) ||
3311 CGF.isTrivialInitializer(Init)) {
3312 // Perform simple memcpy.
3313 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003314 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003315 } else {
3316 // Initialize firstprivate array using element-by-element
3317 // intialization.
3318 CGF.EmitOMPAggregateAssign(
3319 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003320 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003321 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003322 // Clean up any temporaries needed by the initialization.
3323 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003324 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003325 return SrcElement;
3326 });
3327 (void)InitScope.Privatize();
3328 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003329 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3330 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003331 CGF.EmitAnyExprToMem(Init, DestElement,
3332 Init->getType().getQualifiers(),
3333 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003334 });
3335 }
3336 } else {
3337 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003338 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003339 return SharedRefLValue.getAddress();
3340 });
3341 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003342 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003343 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3344 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003345 }
3346 } else {
3347 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3348 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003349 }
3350 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003351 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003352 }
3353 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003354 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003355 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003356 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3357 KmpTaskTWithPrivatesPtrQTy,
3358 KmpTaskTWithPrivatesQTy)
3359 : llvm::ConstantPointerNull::get(
3360 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3361 LValue Destructor = CGF.EmitLValueForField(
3362 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3363 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3364 DestructorFn, KmpRoutineEntryPtrTy),
3365 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003366
3367 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003368 Address DependenciesArray = Address::invalid();
3369 unsigned NumDependencies = Dependences.size();
3370 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003371 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003372 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003373 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3374 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003375 QualType FlagsTy =
3376 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003377 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3378 if (KmpDependInfoTy.isNull()) {
3379 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3380 KmpDependInfoRD->startDefinition();
3381 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3382 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3383 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3384 KmpDependInfoRD->completeDefinition();
3385 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3386 } else {
3387 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3388 }
John McCall7f416cc2015-09-08 08:05:57 +00003389 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003390 // Define type kmp_depend_info[<Dependences.size()>];
3391 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003392 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003393 ArrayType::Normal, /*IndexTypeQuals=*/0);
3394 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00003395 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
3396 for (unsigned i = 0; i < NumDependencies; ++i) {
3397 const Expr *E = Dependences[i].second;
3398 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003399 llvm::Value *Size;
3400 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003401 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3402 LValue UpAddrLVal =
3403 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3404 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003405 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003406 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003407 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003408 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3409 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003410 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003411 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003412 auto Base = CGF.MakeAddrLValue(
3413 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003414 KmpDependInfoTy);
3415 // deps[i].base_addr = &<Dependences[i].second>;
3416 auto BaseAddrLVal = CGF.EmitLValueForField(
3417 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003418 CGF.EmitStoreOfScalar(
3419 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3420 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003421 // deps[i].len = sizeof(<Dependences[i].second>);
3422 auto LenLVal = CGF.EmitLValueForField(
3423 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3424 CGF.EmitStoreOfScalar(Size, LenLVal);
3425 // deps[i].flags = <Dependences[i].first>;
3426 RTLDependenceKindTy DepKind;
3427 switch (Dependences[i].first) {
3428 case OMPC_DEPEND_in:
3429 DepKind = DepIn;
3430 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003431 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003432 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003433 case OMPC_DEPEND_inout:
3434 DepKind = DepInOut;
3435 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003436 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003437 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003438 case OMPC_DEPEND_unknown:
3439 llvm_unreachable("Unknown task dependence type");
3440 }
3441 auto FlagsLVal = CGF.EmitLValueForField(
3442 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3443 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3444 FlagsLVal);
3445 }
John McCall7f416cc2015-09-08 08:05:57 +00003446 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3447 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003448 CGF.VoidPtrTy);
3449 }
3450
Alexey Bataev62b63b12015-03-10 07:28:44 +00003451 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3452 // libcall.
3453 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3454 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003455 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3456 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3457 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3458 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003459 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003460 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003461 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3462 llvm::Value *DepTaskArgs[7];
3463 if (NumDependencies) {
3464 DepTaskArgs[0] = UpLoc;
3465 DepTaskArgs[1] = ThreadID;
3466 DepTaskArgs[2] = NewTask;
3467 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3468 DepTaskArgs[4] = DependenciesArray.getPointer();
3469 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3470 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3471 }
3472 auto &&ThenCodeGen = [this, NumDependencies,
3473 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3474 // TODO: add check for untied tasks.
3475 if (NumDependencies) {
3476 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3477 DepTaskArgs);
3478 } else {
3479 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3480 TaskArgs);
3481 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003482 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003483 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3484 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00003485
3486 llvm::Value *DepWaitTaskArgs[6];
3487 if (NumDependencies) {
3488 DepWaitTaskArgs[0] = UpLoc;
3489 DepWaitTaskArgs[1] = ThreadID;
3490 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3491 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3492 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3493 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3494 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003495 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00003496 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003497 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3498 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3499 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3500 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3501 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003502 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003503 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3504 DepWaitTaskArgs);
3505 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3506 // kmp_task_t *new_task);
3507 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3508 TaskArgs);
3509 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3510 // kmp_task_t *new_task);
3511 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3512 NormalAndEHCleanup,
3513 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3514 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00003515
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003516 // Call proxy_task_entry(gtid, new_task);
3517 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3518 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3519 };
John McCall7f416cc2015-09-08 08:05:57 +00003520
Alexey Bataev1d677132015-04-22 13:57:31 +00003521 if (IfCond) {
3522 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3523 } else {
3524 CodeGenFunction::RunCleanupsScope Scope(CGF);
3525 ThenCodeGen(CGF);
3526 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003527}
3528
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003529/// \brief Emit reduction operation for each element of array (required for
3530/// array sections) LHS op = RHS.
3531/// \param Type Type of array.
3532/// \param LHSVar Variable on the left side of the reduction operation
3533/// (references element of array in original variable).
3534/// \param RHSVar Variable on the right side of the reduction operation
3535/// (references element of array in original variable).
3536/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3537/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003538static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003539 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3540 const VarDecl *RHSVar,
3541 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3542 const Expr *, const Expr *)> &RedOpGen,
3543 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3544 const Expr *UpExpr = nullptr) {
3545 // Perform element-by-element initialization.
3546 QualType ElementTy;
3547 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3548 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3549
3550 // Drill down to the base element type on both arrays.
3551 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3552 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3553
3554 auto RHSBegin = RHSAddr.getPointer();
3555 auto LHSBegin = LHSAddr.getPointer();
3556 // Cast from pointer to array type to pointer to single element.
3557 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3558 // The basic structure here is a while-do loop.
3559 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3560 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3561 auto IsEmpty =
3562 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3563 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3564
3565 // Enter the loop body, making that address the current address.
3566 auto EntryBB = CGF.Builder.GetInsertBlock();
3567 CGF.EmitBlock(BodyBB);
3568
3569 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3570
3571 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3572 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3573 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3574 Address RHSElementCurrent =
3575 Address(RHSElementPHI,
3576 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3577
3578 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3579 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3580 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3581 Address LHSElementCurrent =
3582 Address(LHSElementPHI,
3583 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3584
3585 // Emit copy.
3586 CodeGenFunction::OMPPrivateScope Scope(CGF);
3587 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3588 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3589 Scope.Privatize();
3590 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3591 Scope.ForceCleanup();
3592
3593 // Shift the address forward by one element.
3594 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3595 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3596 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3597 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3598 // Check whether we've reached the end.
3599 auto Done =
3600 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3601 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3602 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3603 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3604
3605 // Done.
3606 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3607}
3608
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003609/// Emit reduction combiner. If the combiner is a simple expression emit it as
3610/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
3611/// UDR combiner function.
3612static void emitReductionCombiner(CodeGenFunction &CGF,
3613 const Expr *ReductionOp) {
3614 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
3615 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
3616 if (auto *DRE =
3617 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
3618 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
3619 std::pair<llvm::Function *, llvm::Function *> Reduction =
3620 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
3621 RValue Func = RValue::get(Reduction.first);
3622 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
3623 CGF.EmitIgnoredExpr(ReductionOp);
3624 return;
3625 }
3626 CGF.EmitIgnoredExpr(ReductionOp);
3627}
3628
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003629static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3630 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003631 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003632 ArrayRef<const Expr *> LHSExprs,
3633 ArrayRef<const Expr *> RHSExprs,
3634 ArrayRef<const Expr *> ReductionOps) {
3635 auto &C = CGM.getContext();
3636
3637 // void reduction_func(void *LHSArg, void *RHSArg);
3638 FunctionArgList Args;
3639 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3640 C.VoidPtrTy);
3641 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3642 C.VoidPtrTy);
3643 Args.push_back(&LHSArg);
3644 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00003645 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003646 auto *Fn = llvm::Function::Create(
3647 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3648 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003649 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003650 CodeGenFunction CGF(CGM);
3651 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3652
3653 // Dst = (void*[n])(LHSArg);
3654 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003655 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3656 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3657 ArgsType), CGF.getPointerAlign());
3658 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3659 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3660 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003661
3662 // ...
3663 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3664 // ...
3665 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003666 auto IPriv = Privates.begin();
3667 unsigned Idx = 0;
3668 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003669 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3670 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003671 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003672 });
3673 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3674 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003675 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003676 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003677 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003678 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003679 // Get array size and emit VLA type.
3680 ++Idx;
3681 Address Elem =
3682 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3683 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003684 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3685 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003686 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003687 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003688 CGF.EmitVariablyModifiedType(PrivTy);
3689 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003690 }
3691 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003692 IPriv = Privates.begin();
3693 auto ILHS = LHSExprs.begin();
3694 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003695 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003696 if ((*IPriv)->getType()->isArrayType()) {
3697 // Emit reduction for array section.
3698 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3699 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003700 EmitOMPAggregateReduction(
3701 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3702 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
3703 emitReductionCombiner(CGF, E);
3704 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003705 } else
3706 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003707 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003708 ++IPriv;
3709 ++ILHS;
3710 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003711 }
3712 Scope.ForceCleanup();
3713 CGF.FinishFunction();
3714 return Fn;
3715}
3716
3717void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003718 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003719 ArrayRef<const Expr *> LHSExprs,
3720 ArrayRef<const Expr *> RHSExprs,
3721 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003722 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003723 if (!CGF.HaveInsertPoint())
3724 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003725 // Next code should be emitted for reduction:
3726 //
3727 // static kmp_critical_name lock = { 0 };
3728 //
3729 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3730 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3731 // ...
3732 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3733 // *(Type<n>-1*)rhs[<n>-1]);
3734 // }
3735 //
3736 // ...
3737 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3738 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3739 // RedList, reduce_func, &<lock>)) {
3740 // case 1:
3741 // ...
3742 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3743 // ...
3744 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3745 // break;
3746 // case 2:
3747 // ...
3748 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3749 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003750 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003751 // break;
3752 // default:;
3753 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003754 //
3755 // if SimpleReduction is true, only the next code is generated:
3756 // ...
3757 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3758 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003759
3760 auto &C = CGM.getContext();
3761
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003762 if (SimpleReduction) {
3763 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003764 auto IPriv = Privates.begin();
3765 auto ILHS = LHSExprs.begin();
3766 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003767 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003768 if ((*IPriv)->getType()->isArrayType()) {
3769 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3770 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3771 EmitOMPAggregateReduction(
3772 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3773 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003774 const Expr *) { emitReductionCombiner(CGF, E); });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003775 } else
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003776 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003777 ++IPriv;
3778 ++ILHS;
3779 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003780 }
3781 return;
3782 }
3783
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003784 // 1. Build a list of reduction variables.
3785 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003786 auto Size = RHSExprs.size();
3787 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003788 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003789 // Reserve place for array size.
3790 ++Size;
3791 }
3792 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003793 QualType ReductionArrayTy =
3794 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3795 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003796 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003797 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003798 auto IPriv = Privates.begin();
3799 unsigned Idx = 0;
3800 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003801 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003802 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003803 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003804 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003805 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3806 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003807 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003808 // Store array size.
3809 ++Idx;
3810 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3811 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003812 llvm::Value *Size = CGF.Builder.CreateIntCast(
3813 CGF.getVLASize(
3814 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3815 .first,
3816 CGF.SizeTy, /*isSigned=*/false);
3817 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3818 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003819 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003820 }
3821
3822 // 2. Emit reduce_func().
3823 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003824 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3825 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003826
3827 // 3. Create static kmp_critical_name lock = { 0 };
3828 auto *Lock = getCriticalRegionLock(".reduction");
3829
3830 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3831 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003832 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003833 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003834 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003835 auto *RL =
3836 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3837 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003838 llvm::Value *Args[] = {
3839 IdentTLoc, // ident_t *<loc>
3840 ThreadId, // i32 <gtid>
3841 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3842 ReductionArrayTySize, // size_type sizeof(RedList)
3843 RL, // void *RedList
3844 ReductionFn, // void (*) (void *, void *) <reduce_func>
3845 Lock // kmp_critical_name *&<lock>
3846 };
3847 auto Res = CGF.EmitRuntimeCall(
3848 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3849 : OMPRTL__kmpc_reduce),
3850 Args);
3851
3852 // 5. Build switch(res)
3853 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3854 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3855
3856 // 6. Build case 1:
3857 // ...
3858 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3859 // ...
3860 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3861 // break;
3862 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3863 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3864 CGF.EmitBlock(Case1BB);
3865
3866 {
3867 CodeGenFunction::RunCleanupsScope Scope(CGF);
3868 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3869 llvm::Value *EndArgs[] = {
3870 IdentTLoc, // ident_t *<loc>
3871 ThreadId, // i32 <gtid>
3872 Lock // kmp_critical_name *&<lock>
3873 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003874 CGF.EHStack
3875 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3876 NormalAndEHCleanup,
3877 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3878 : OMPRTL__kmpc_end_reduce),
3879 llvm::makeArrayRef(EndArgs));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003880 auto IPriv = Privates.begin();
3881 auto ILHS = LHSExprs.begin();
3882 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003883 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003884 if ((*IPriv)->getType()->isArrayType()) {
3885 // Emit reduction for array section.
3886 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3887 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3888 EmitOMPAggregateReduction(
3889 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3890 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003891 const Expr *) { emitReductionCombiner(CGF, E); });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003892 } else
3893 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003894 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003895 ++IPriv;
3896 ++ILHS;
3897 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003898 }
3899 }
3900
3901 CGF.EmitBranch(DefaultBB);
3902
3903 // 7. Build case 2:
3904 // ...
3905 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3906 // ...
3907 // break;
3908 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3909 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3910 CGF.EmitBlock(Case2BB);
3911
3912 {
3913 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00003914 if (!WithNowait) {
3915 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3916 llvm::Value *EndArgs[] = {
3917 IdentTLoc, // ident_t *<loc>
3918 ThreadId, // i32 <gtid>
3919 Lock // kmp_critical_name *&<lock>
3920 };
3921 CGF.EHStack
3922 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3923 NormalAndEHCleanup,
3924 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3925 llvm::makeArrayRef(EndArgs));
3926 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003927 auto ILHS = LHSExprs.begin();
3928 auto IRHS = RHSExprs.begin();
3929 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003930 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003931 const Expr *XExpr = nullptr;
3932 const Expr *EExpr = nullptr;
3933 const Expr *UpExpr = nullptr;
3934 BinaryOperatorKind BO = BO_Comma;
3935 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3936 if (BO->getOpcode() == BO_Assign) {
3937 XExpr = BO->getLHS();
3938 UpExpr = BO->getRHS();
3939 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003940 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003941 // Try to emit update expression as a simple atomic.
3942 auto *RHSExpr = UpExpr;
3943 if (RHSExpr) {
3944 // Analyze RHS part of the whole expression.
3945 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3946 RHSExpr->IgnoreParenImpCasts())) {
3947 // If this is a conditional operator, analyze its condition for
3948 // min/max reduction operator.
3949 RHSExpr = ACO->getCond();
3950 }
3951 if (auto *BORHS =
3952 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3953 EExpr = BORHS->getRHS();
3954 BO = BORHS->getOpcode();
3955 }
Alexey Bataev69a47792015-05-07 03:54:03 +00003956 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003957 if (XExpr) {
3958 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3959 auto &&AtomicRedGen = [this, BO, VD, IPriv,
3960 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3961 const Expr *EExpr, const Expr *UpExpr) {
3962 LValue X = CGF.EmitLValue(XExpr);
3963 RValue E;
3964 if (EExpr)
3965 E = CGF.EmitAnyExpr(EExpr);
3966 CGF.EmitOMPAtomicSimpleUpdateExpr(
3967 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
Alexey Bataev8524d152016-01-21 12:35:58 +00003968 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003969 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev8524d152016-01-21 12:35:58 +00003970 PrivateScope.addPrivate(
3971 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3972 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3973 CGF.emitOMPSimpleStore(
3974 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3975 VD->getType().getNonReferenceType(), Loc);
3976 return LHSTemp;
3977 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003978 (void)PrivateScope.Privatize();
3979 return CGF.EmitAnyExpr(UpExpr);
3980 });
3981 };
3982 if ((*IPriv)->getType()->isArrayType()) {
3983 // Emit atomic reduction for array section.
3984 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3985 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3986 AtomicRedGen, XExpr, EExpr, UpExpr);
3987 } else
3988 // Emit atomic reduction for array subscript or single variable.
3989 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3990 } else {
3991 // Emit as a critical region.
3992 auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3993 const Expr *, const Expr *) {
3994 emitCriticalRegion(
3995 CGF, ".atomic_reduction",
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003996 [=](CodeGenFunction &CGF) { emitReductionCombiner(CGF, E); },
3997 Loc);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003998 };
3999 if ((*IPriv)->getType()->isArrayType()) {
4000 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4001 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4002 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4003 CritRedGen);
4004 } else
4005 CritRedGen(CGF, nullptr, nullptr, nullptr);
4006 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004007 ++ILHS;
4008 ++IRHS;
4009 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004010 }
4011 }
4012
4013 CGF.EmitBranch(DefaultBB);
4014 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4015}
4016
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004017void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4018 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004019 if (!CGF.HaveInsertPoint())
4020 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004021 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4022 // global_tid);
4023 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4024 // Ignore return result until untied tasks are supported.
4025 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
4026}
4027
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004028void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004029 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004030 const RegionCodeGenTy &CodeGen,
4031 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004032 if (!CGF.HaveInsertPoint())
4033 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004034 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004035 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004036}
4037
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004038namespace {
4039enum RTCancelKind {
4040 CancelNoreq = 0,
4041 CancelParallel = 1,
4042 CancelLoop = 2,
4043 CancelSections = 3,
4044 CancelTaskgroup = 4
4045};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004046} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004047
4048static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4049 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004050 if (CancelRegion == OMPD_parallel)
4051 CancelKind = CancelParallel;
4052 else if (CancelRegion == OMPD_for)
4053 CancelKind = CancelLoop;
4054 else if (CancelRegion == OMPD_sections)
4055 CancelKind = CancelSections;
4056 else {
4057 assert(CancelRegion == OMPD_taskgroup);
4058 CancelKind = CancelTaskgroup;
4059 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004060 return CancelKind;
4061}
4062
4063void CGOpenMPRuntime::emitCancellationPointCall(
4064 CodeGenFunction &CGF, SourceLocation Loc,
4065 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004066 if (!CGF.HaveInsertPoint())
4067 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004068 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4069 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004070 if (auto *OMPRegionInfo =
4071 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004072 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004073 llvm::Value *Args[] = {
4074 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4075 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004076 // Ignore return result until untied tasks are supported.
4077 auto *Result = CGF.EmitRuntimeCall(
4078 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4079 // if (__kmpc_cancellationpoint()) {
4080 // __kmpc_cancel_barrier();
4081 // exit from construct;
4082 // }
4083 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4084 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4085 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4086 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4087 CGF.EmitBlock(ExitBB);
4088 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004089 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004090 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004091 auto CancelDest =
4092 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004093 CGF.EmitBranchThroughCleanup(CancelDest);
4094 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4095 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004096 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004097}
4098
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004099void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004100 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004101 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004102 if (!CGF.HaveInsertPoint())
4103 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004104 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4105 // kmp_int32 cncl_kind);
4106 if (auto *OMPRegionInfo =
4107 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004108 auto &&ThenGen = [this, Loc, CancelRegion,
4109 OMPRegionInfo](CodeGenFunction &CGF) {
4110 llvm::Value *Args[] = {
4111 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4112 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4113 // Ignore return result until untied tasks are supported.
4114 auto *Result =
4115 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
4116 // if (__kmpc_cancel()) {
4117 // __kmpc_cancel_barrier();
4118 // exit from construct;
4119 // }
4120 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4121 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4122 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4123 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4124 CGF.EmitBlock(ExitBB);
4125 // __kmpc_cancel_barrier();
4126 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4127 // exit from construct;
4128 auto CancelDest =
4129 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4130 CGF.EmitBranchThroughCleanup(CancelDest);
4131 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4132 };
4133 if (IfCond)
4134 emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
4135 else
4136 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004137 }
4138}
Samuel Antaobed3c462015-10-02 16:14:20 +00004139
Samuel Antaoee8fb302016-01-06 13:42:12 +00004140/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004141/// consists of the file and device IDs as well as line number associated with
4142/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004143static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4144 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004145 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004146
4147 auto &SM = C.getSourceManager();
4148
4149 // The loc should be always valid and have a file ID (the user cannot use
4150 // #pragma directives in macros)
4151
4152 assert(Loc.isValid() && "Source location is expected to be always valid.");
4153 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4154
4155 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4156 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4157
4158 llvm::sys::fs::UniqueID ID;
4159 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4160 llvm_unreachable("Source file with target region no longer exists!");
4161
4162 DeviceID = ID.getDevice();
4163 FileID = ID.getFile();
4164 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004165}
4166
4167void CGOpenMPRuntime::emitTargetOutlinedFunction(
4168 const OMPExecutableDirective &D, StringRef ParentName,
4169 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4170 bool IsOffloadEntry) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004171 assert(!ParentName.empty() && "Invalid target region parent name!");
4172
Samuel Antaobed3c462015-10-02 16:14:20 +00004173 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4174
Samuel Antaoee8fb302016-01-06 13:42:12 +00004175 // Emit target region as a standalone region.
Carlo Bertollia03acfa2016-03-16 19:04:22 +00004176 auto &&CodeGen = [&CS, &D](CodeGenFunction &CGF) {
4177 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00004178 (void)CGF.EmitOMPFirstprivateClause(D, PrivateScope);
Carlo Bertollia03acfa2016-03-16 19:04:22 +00004179 CGF.EmitOMPPrivateClause(D, PrivateScope);
4180 (void)PrivateScope.Privatize();
4181
Samuel Antaoee8fb302016-01-06 13:42:12 +00004182 CGF.EmitStmt(CS.getCapturedStmt());
4183 };
4184
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004185 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4186 IsOffloadEntry, CodeGen);
4187}
4188
4189void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4190 const OMPExecutableDirective &D, StringRef ParentName,
4191 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4192 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004193 // Create a unique name for the entry function using the source location
4194 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004195 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004196 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004197 //
4198 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004199 // mangled name of the function that encloses the target region and BB is the
4200 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004201
4202 unsigned DeviceID;
4203 unsigned FileID;
4204 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004205 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004206 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004207 SmallString<64> EntryFnName;
4208 {
4209 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004210 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4211 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004212 }
4213
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004214 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4215
Samuel Antaobed3c462015-10-02 16:14:20 +00004216 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004217 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004218 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004219
4220 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4221
4222 // If this target outline function is not an offload entry, we don't need to
4223 // register it.
4224 if (!IsOffloadEntry)
4225 return;
4226
4227 // The target region ID is used by the runtime library to identify the current
4228 // target region, so it only has to be unique and not necessarily point to
4229 // anything. It could be the pointer to the outlined function that implements
4230 // the target region, but we aren't using that so that the compiler doesn't
4231 // need to keep that, and could therefore inline the host function if proven
4232 // worthwhile during optimization. In the other hand, if emitting code for the
4233 // device, the ID has to be the function address so that it can retrieved from
4234 // the offloading entry and launched by the runtime library. We also mark the
4235 // outlined function to have external linkage in case we are emitting code for
4236 // the device, because these functions will be entry points to the device.
4237
4238 if (CGM.getLangOpts().OpenMPIsDevice) {
4239 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4240 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4241 } else
4242 OutlinedFnID = new llvm::GlobalVariable(
4243 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4244 llvm::GlobalValue::PrivateLinkage,
4245 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4246
4247 // Register the information for the entry associated with this target region.
4248 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004249 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004250}
4251
Samuel Antaob68e2db2016-03-03 16:20:23 +00004252/// \brief Emit the num_teams clause of an enclosed teams directive at the
4253/// target region scope. If there is no teams directive associated with the
4254/// target directive, or if there is no num_teams clause associated with the
4255/// enclosed teams directive, return nullptr.
4256static llvm::Value *
4257emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4258 CodeGenFunction &CGF,
4259 const OMPExecutableDirective &D) {
4260
4261 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4262 "teams directive expected to be "
4263 "emitted only for the host!");
4264
4265 // FIXME: For the moment we do not support combined directives with target and
4266 // teams, so we do not expect to get any num_teams clause in the provided
4267 // directive. Once we support that, this assertion can be replaced by the
4268 // actual emission of the clause expression.
4269 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4270 "Not expecting clause in directive.");
4271
4272 // If the current target region has a teams region enclosed, we need to get
4273 // the number of teams to pass to the runtime function call. This is done
4274 // by generating the expression in a inlined region. This is required because
4275 // the expression is captured in the enclosing target environment when the
4276 // teams directive is not combined with target.
4277
4278 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4279
4280 // FIXME: Accommodate other combined directives with teams when they become
4281 // available.
4282 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4283 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4284 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4285 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4286 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4287 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4288 /*IsSigned=*/true);
4289 }
4290
4291 // If we have an enclosed teams directive but no num_teams clause we use
4292 // the default value 0.
4293 return CGF.Builder.getInt32(0);
4294 }
4295
4296 // No teams associated with the directive.
4297 return nullptr;
4298}
4299
4300/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4301/// target region scope. If there is no teams directive associated with the
4302/// target directive, or if there is no thread_limit clause associated with the
4303/// enclosed teams directive, return nullptr.
4304static llvm::Value *
4305emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4306 CodeGenFunction &CGF,
4307 const OMPExecutableDirective &D) {
4308
4309 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4310 "teams directive expected to be "
4311 "emitted only for the host!");
4312
4313 // FIXME: For the moment we do not support combined directives with target and
4314 // teams, so we do not expect to get any thread_limit clause in the provided
4315 // directive. Once we support that, this assertion can be replaced by the
4316 // actual emission of the clause expression.
4317 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4318 "Not expecting clause in directive.");
4319
4320 // If the current target region has a teams region enclosed, we need to get
4321 // the thread limit to pass to the runtime function call. This is done
4322 // by generating the expression in a inlined region. This is required because
4323 // the expression is captured in the enclosing target environment when the
4324 // teams directive is not combined with target.
4325
4326 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4327
4328 // FIXME: Accommodate other combined directives with teams when they become
4329 // available.
4330 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4331 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4332 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4333 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4334 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4335 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4336 /*IsSigned=*/true);
4337 }
4338
4339 // If we have an enclosed teams directive but no thread_limit clause we use
4340 // the default value 0.
4341 return CGF.Builder.getInt32(0);
4342 }
4343
4344 // No teams associated with the directive.
4345 return nullptr;
4346}
4347
Samuel Antaobed3c462015-10-02 16:14:20 +00004348void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
4349 const OMPExecutableDirective &D,
4350 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004351 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00004352 const Expr *IfCond, const Expr *Device,
4353 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004354 if (!CGF.HaveInsertPoint())
4355 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00004356 /// \brief Values for bit flags used to specify the mapping type for
4357 /// offloading.
4358 enum OpenMPOffloadMappingFlags {
4359 /// \brief Allocate memory on the device and move data from host to device.
4360 OMP_MAP_TO = 0x01,
4361 /// \brief Allocate memory on the device and move data from device to host.
4362 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004363 /// \brief The element passed to the device is a pointer.
4364 OMP_MAP_PTR = 0x20,
4365 /// \brief Pass the element to the device by value.
4366 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00004367 };
4368
4369 enum OpenMPOffloadingReservedDeviceIDs {
4370 /// \brief Device ID if the device was not defined, runtime should get it
4371 /// from environment variables in the spec.
4372 OMP_DEVICEID_UNDEF = -1,
4373 };
4374
Samuel Antaoee8fb302016-01-06 13:42:12 +00004375 assert(OutlinedFn && "Invalid outlined function!");
4376
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004377 auto &Ctx = CGF.getContext();
4378
Samuel Antaobed3c462015-10-02 16:14:20 +00004379 // Fill up the arrays with the all the captured variables.
4380 SmallVector<llvm::Value *, 16> BasePointers;
4381 SmallVector<llvm::Value *, 16> Pointers;
4382 SmallVector<llvm::Value *, 16> Sizes;
4383 SmallVector<unsigned, 16> MapTypes;
4384
4385 bool hasVLACaptures = false;
4386
4387 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4388 auto RI = CS.getCapturedRecordDecl()->field_begin();
4389 // auto II = CS.capture_init_begin();
4390 auto CV = CapturedVars.begin();
4391 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
4392 CE = CS.capture_end();
4393 CI != CE; ++CI, ++RI, ++CV) {
4394 StringRef Name;
4395 QualType Ty;
4396 llvm::Value *BasePointer;
4397 llvm::Value *Pointer;
4398 llvm::Value *Size;
4399 unsigned MapType;
4400
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004401 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00004402 if (CI->capturesVariableArrayType()) {
4403 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00004404 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004405 // Copy to the device as an argument. No need to retrieve it.
4406 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00004407 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00004408 } else if (CI->capturesThis()) {
4409 BasePointer = Pointer = *CV;
4410 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004411 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004412 // Default map type.
4413 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004414 } else if (CI->capturesVariableByCopy()) {
4415 MapType = OMP_MAP_BYCOPY;
4416 if (!RI->getType()->isAnyPointerType()) {
4417 // If the field is not a pointer, we need to save the actual value and
4418 // load it as a void pointer.
4419 auto DstAddr = CGF.CreateMemTemp(
4420 Ctx.getUIntPtrType(),
4421 Twine(CI->getCapturedVar()->getName()) + ".casted");
4422 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
4423
4424 auto *SrcAddrVal = CGF.EmitScalarConversion(
4425 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
4426 Ctx.getPointerType(RI->getType()), SourceLocation());
4427 LValue SrcLV =
4428 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
4429
4430 // Store the value using the source type pointer.
4431 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
4432
4433 // Load the value using the destination type pointer.
4434 BasePointer = Pointer =
4435 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
4436 } else {
4437 MapType |= OMP_MAP_PTR;
4438 BasePointer = Pointer = *CV;
4439 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00004440 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00004441 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004442 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00004443 BasePointer = Pointer = *CV;
4444
4445 const ReferenceType *PtrTy =
4446 cast<ReferenceType>(RI->getType().getTypePtr());
4447 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004448 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004449 // The default map type for a scalar/complex type is 'to' because by
4450 // default the value doesn't have to be retrieved. For an aggregate type,
4451 // the default is 'tofrom'.
4452 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
4453 : OMP_MAP_TO;
4454 if (ElementType->isAnyPointerType())
4455 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00004456 }
4457
4458 BasePointers.push_back(BasePointer);
4459 Pointers.push_back(Pointer);
4460 Sizes.push_back(Size);
4461 MapTypes.push_back(MapType);
4462 }
4463
4464 // Keep track on whether the host function has to be executed.
4465 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004466 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004467 auto OffloadError = CGF.MakeAddrLValue(
4468 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
4469 OffloadErrorQType);
4470 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
4471 OffloadError);
4472
4473 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004474 auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antaoee8fb302016-01-06 13:42:12 +00004475 hasVLACaptures, Device, OutlinedFnID, OffloadError,
Samuel Antaob68e2db2016-03-03 16:20:23 +00004476 OffloadErrorQType, &D](CodeGenFunction &CGF) {
Samuel Antaobed3c462015-10-02 16:14:20 +00004477 unsigned PointerNumVal = BasePointers.size();
4478 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
4479 llvm::Value *BasePointersArray;
4480 llvm::Value *PointersArray;
4481 llvm::Value *SizesArray;
4482 llvm::Value *MapTypesArray;
4483
4484 if (PointerNumVal) {
4485 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004486 QualType PointerArrayType = Ctx.getConstantArrayType(
4487 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004488 /*IndexTypeQuals=*/0);
4489
4490 BasePointersArray =
4491 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
4492 PointersArray =
4493 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
4494
4495 // If we don't have any VLA types, we can use a constant array for the map
4496 // sizes, otherwise we need to fill up the arrays as we do for the
4497 // pointers.
4498 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004499 QualType SizeArrayType = Ctx.getConstantArrayType(
4500 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00004501 /*IndexTypeQuals=*/0);
4502 SizesArray =
4503 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
4504 } else {
4505 // We expect all the sizes to be constant, so we collect them to create
4506 // a constant array.
4507 SmallVector<llvm::Constant *, 16> ConstSizes;
4508 for (auto S : Sizes)
4509 ConstSizes.push_back(cast<llvm::Constant>(S));
4510
4511 auto *SizesArrayInit = llvm::ConstantArray::get(
4512 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
4513 auto *SizesArrayGbl = new llvm::GlobalVariable(
4514 CGM.getModule(), SizesArrayInit->getType(),
4515 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4516 SizesArrayInit, ".offload_sizes");
4517 SizesArrayGbl->setUnnamedAddr(true);
4518 SizesArray = SizesArrayGbl;
4519 }
4520
4521 // The map types are always constant so we don't need to generate code to
4522 // fill arrays. Instead, we create an array constant.
4523 llvm::Constant *MapTypesArrayInit =
4524 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
4525 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
4526 CGM.getModule(), MapTypesArrayInit->getType(),
4527 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4528 MapTypesArrayInit, ".offload_maptypes");
4529 MapTypesArrayGbl->setUnnamedAddr(true);
4530 MapTypesArray = MapTypesArrayGbl;
4531
4532 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004533 llvm::Value *BPVal = BasePointers[i];
4534 if (BPVal->getType()->isPointerTy())
4535 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
4536 else {
4537 assert(BPVal->getType()->isIntegerTy() &&
4538 "If not a pointer, the value type must be an integer.");
4539 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
4540 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004541 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
4542 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
4543 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004544 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4545 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004546
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004547 llvm::Value *PVal = Pointers[i];
4548 if (PVal->getType()->isPointerTy())
4549 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
4550 else {
4551 assert(PVal->getType()->isIntegerTy() &&
4552 "If not a pointer, the value type must be an integer.");
4553 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
4554 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004555 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4556 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4557 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004558 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4559 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004560
4561 if (hasVLACaptures) {
4562 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4563 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4564 /*Idx0=*/0,
4565 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004566 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004567 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4568 Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4569 SAddr);
4570 }
4571 }
4572
4573 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4574 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4575 /*Idx0=*/0, /*Idx1=*/0);
4576 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4577 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4578 /*Idx0=*/0,
4579 /*Idx1=*/0);
4580 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4581 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4582 /*Idx0=*/0, /*Idx1=*/0);
4583 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4584 llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4585 /*Idx0=*/0,
4586 /*Idx1=*/0);
4587
4588 } else {
4589 BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4590 PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4591 SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4592 MapTypesArray =
4593 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4594 }
4595
4596 // On top of the arrays that were filled up, the target offloading call
4597 // takes as arguments the device id as well as the host pointer. The host
4598 // pointer is used by the runtime library to identify the current target
4599 // region, so it only has to be unique and not necessarily point to
4600 // anything. It could be the pointer to the outlined function that
4601 // implements the target region, but we aren't using that so that the
4602 // compiler doesn't need to keep that, and could therefore inline the host
4603 // function if proven worthwhile during optimization.
4604
Samuel Antaoee8fb302016-01-06 13:42:12 +00004605 // From this point on, we need to have an ID of the target region defined.
4606 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004607
4608 // Emit device ID if any.
4609 llvm::Value *DeviceID;
4610 if (Device)
4611 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4612 CGM.Int32Ty, /*isSigned=*/true);
4613 else
4614 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4615
Samuel Antaob68e2db2016-03-03 16:20:23 +00004616 // Return value of the runtime offloading call.
4617 llvm::Value *Return;
4618
4619 auto *NumTeams = emitNumTeamsClauseForTargetDirective(*this, CGF, D);
4620 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(*this, CGF, D);
4621
4622 // If we have NumTeams defined this means that we have an enclosed teams
4623 // region. Therefore we also expect to have ThreadLimit defined. These two
4624 // values should be defined in the presence of a teams directive, regardless
4625 // of having any clauses associated. If the user is using teams but no
4626 // clauses, these two values will be the default that should be passed to
4627 // the runtime library - a 32-bit integer with the value zero.
4628 if (NumTeams) {
4629 assert(ThreadLimit && "Thread limit expression should be available along "
4630 "with number of teams.");
4631 llvm::Value *OffloadingArgs[] = {
4632 DeviceID, OutlinedFnID, PointerNum,
4633 BasePointersArray, PointersArray, SizesArray,
4634 MapTypesArray, NumTeams, ThreadLimit};
4635 Return = CGF.EmitRuntimeCall(
4636 createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
4637 } else {
4638 llvm::Value *OffloadingArgs[] = {
4639 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4640 PointersArray, SizesArray, MapTypesArray};
4641 Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4642 OffloadingArgs);
4643 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004644
4645 CGF.EmitStoreOfScalar(Return, OffloadError);
4646 };
4647
Samuel Antaoee8fb302016-01-06 13:42:12 +00004648 // Notify that the host version must be executed.
4649 auto &&ElseGen = [this, OffloadError,
4650 OffloadErrorQType](CodeGenFunction &CGF) {
4651 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4652 OffloadError);
4653 };
4654
4655 // If we have a target function ID it means that we need to support
4656 // offloading, otherwise, just execute on the host. We need to execute on host
4657 // regardless of the conditional in the if clause if, e.g., the user do not
4658 // specify target triples.
4659 if (OutlinedFnID) {
4660 if (IfCond) {
4661 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4662 } else {
4663 CodeGenFunction::RunCleanupsScope Scope(CGF);
4664 ThenGen(CGF);
4665 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004666 } else {
4667 CodeGenFunction::RunCleanupsScope Scope(CGF);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004668 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004669 }
4670
4671 // Check the error code and execute the host version if required.
4672 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4673 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4674 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4675 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4676 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4677
4678 CGF.EmitBlock(OffloadFailedBlock);
4679 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4680 CGF.EmitBranch(OffloadContBlock);
4681
4682 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00004683}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004684
4685void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4686 StringRef ParentName) {
4687 if (!S)
4688 return;
4689
4690 // If we find a OMP target directive, codegen the outline function and
4691 // register the result.
4692 // FIXME: Add other directives with target when they become supported.
4693 bool isTargetDirective = isa<OMPTargetDirective>(S);
4694
4695 if (isTargetDirective) {
4696 auto *E = cast<OMPExecutableDirective>(S);
4697 unsigned DeviceID;
4698 unsigned FileID;
4699 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004700 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004701 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004702
4703 // Is this a target region that should not be emitted as an entry point? If
4704 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00004705 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4706 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004707 return;
4708
4709 llvm::Function *Fn;
4710 llvm::Constant *Addr;
4711 emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4712 /*isOffloadEntry=*/true);
4713 assert(Fn && Addr && "Target region emission failed.");
4714 return;
4715 }
4716
4717 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4718 if (!E->getAssociatedStmt())
4719 return;
4720
4721 scanForTargetRegionsFunctions(
4722 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4723 ParentName);
4724 return;
4725 }
4726
4727 // If this is a lambda function, look into its body.
4728 if (auto *L = dyn_cast<LambdaExpr>(S))
4729 S = L->getBody();
4730
4731 // Keep looking for target regions recursively.
4732 for (auto *II : S->children())
4733 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004734}
4735
4736bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4737 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4738
4739 // If emitting code for the host, we do not process FD here. Instead we do
4740 // the normal code generation.
4741 if (!CGM.getLangOpts().OpenMPIsDevice)
4742 return false;
4743
4744 // Try to detect target regions in the function.
4745 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4746
4747 // We should not emit any function othen that the ones created during the
4748 // scanning. Therefore, we signal that this function is completely dealt
4749 // with.
4750 return true;
4751}
4752
4753bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4754 if (!CGM.getLangOpts().OpenMPIsDevice)
4755 return false;
4756
4757 // Check if there are Ctors/Dtors in this declaration and look for target
4758 // regions in it. We use the complete variant to produce the kernel name
4759 // mangling.
4760 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4761 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4762 for (auto *Ctor : RD->ctors()) {
4763 StringRef ParentName =
4764 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4765 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4766 }
4767 auto *Dtor = RD->getDestructor();
4768 if (Dtor) {
4769 StringRef ParentName =
4770 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4771 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4772 }
4773 }
4774
4775 // If we are in target mode we do not emit any global (declare target is not
4776 // implemented yet). Therefore we signal that GD was processed in this case.
4777 return true;
4778}
4779
4780bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4781 auto *VD = GD.getDecl();
4782 if (isa<FunctionDecl>(VD))
4783 return emitTargetFunctions(GD);
4784
4785 return emitTargetGlobalVariable(GD);
4786}
4787
4788llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4789 // If we have offloading in the current module, we need to emit the entries
4790 // now and register the offloading descriptor.
4791 createOffloadEntriesAndInfoMetadata();
4792
4793 // Create and register the offloading binary descriptors. This is the main
4794 // entity that captures all the information about offloading in the current
4795 // compilation unit.
4796 return createOffloadingBinaryDescriptorRegistration();
4797}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004798
4799void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
4800 const OMPExecutableDirective &D,
4801 SourceLocation Loc,
4802 llvm::Value *OutlinedFn,
4803 ArrayRef<llvm::Value *> CapturedVars) {
4804 if (!CGF.HaveInsertPoint())
4805 return;
4806
4807 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4808 CodeGenFunction::RunCleanupsScope Scope(CGF);
4809
4810 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
4811 llvm::Value *Args[] = {
4812 RTLoc,
4813 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
4814 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
4815 llvm::SmallVector<llvm::Value *, 16> RealArgs;
4816 RealArgs.append(std::begin(Args), std::end(Args));
4817 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
4818
4819 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
4820 CGF.EmitRuntimeCall(RTLFn, RealArgs);
4821}
4822
4823void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
4824 llvm::Value *NumTeams,
4825 llvm::Value *ThreadLimit,
4826 SourceLocation Loc) {
4827 if (!CGF.HaveInsertPoint())
4828 return;
4829
4830 auto *RTLoc = emitUpdateLocation(CGF, Loc);
4831
4832 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
4833 llvm::Value *PushNumTeamsArgs[] = {
4834 RTLoc, getThreadID(CGF, Loc), NumTeams, ThreadLimit};
4835 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
4836 PushNumTeamsArgs);
4837}