blob: 004008b693c9018bfe46b6cbba1876005ce4f33b [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"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
Alexey Bataev48591dd2016-04-20 04:01:36 +0000151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
195 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Alexey Bataev311a9282017-10-12 13:51:32 +0000268 /// \brief Get an LValue for the current ThreadID variable.
269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct");
273 }
274
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000275 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000276 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 llvm_unreachable("No helper name for inlined OpenMP construct");
280 }
281
Alexey Bataev48591dd2016-04-20 04:01:36 +0000282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
Alexey Bataev48591dd2016-04-20 04:01:36 +0000294 ~CGOpenMPInlinedRegionInfo() override = default;
295
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000296private:
297 /// \brief CodeGen info about outer OpenMP region.
298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000300};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000301
Samuel Antaobed3c462015-10-02 16:14:20 +0000302/// \brief API for captured statement code generation in OpenMP target
303/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 /// \brief This is unused for target regions because each starts executing
316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
319 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000320 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000326
327private:
328 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000329};
330
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000332 llvm_unreachable("No codegen for expressions");
333}
334/// \brief API for generation of expressions captured in a innermost OpenMP
335/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
346 for (auto &C : CS.captures()) {
347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
354 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000357 C.getLocation());
Samuel Antaob68e2db2016-03-03 16:20:23 +0000358 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
359 return CGF.EmitLValue(&DRE).getAddress();
360 });
361 }
362 (void)PrivScope.Privatize();
363 }
364
365 /// \brief Lookup the captured field decl for a variable.
366 const FieldDecl *lookup(const VarDecl *VD) const override {
367 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
368 return FD;
369 return nullptr;
370 }
371
372 /// \brief Emit the captured statement body.
373 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
374 llvm_unreachable("No body for expressions");
375 }
376
377 /// \brief Get a variable or parameter for storing global thread id
378 /// inside OpenMP construct.
379 const VarDecl *getThreadIDVariable() const override {
380 llvm_unreachable("No thread id for expressions");
381 }
382
383 /// \brief Get the name of the capture helper.
384 StringRef getHelperName() const override {
385 llvm_unreachable("No helper name for expressions");
386 }
387
388 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
389
390private:
391 /// Private scope to capture global variables.
392 CodeGenFunction::OMPPrivateScope PrivScope;
393};
394
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000395/// \brief RAII for emitting code of OpenMP constructs.
396class InlinedOpenMPRegionRAII {
397 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000398 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
399 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000400 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401
402public:
403 /// \brief Constructs region for combined constructs.
404 /// \param CodeGen Code generation sequence for combined directives. Includes
405 /// a list of functions used for code generation of implicitly inlined
406 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000407 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000408 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 : CGF(CGF) {
410 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000411 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
412 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
415 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000416 BlockInfo = CGF.BlockInfo;
417 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000419
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000420 ~InlinedOpenMPRegionRAII() {
421 // Restore original CapturedStmtInfo only if we're done with code emission.
422 auto *OldCSI =
423 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
424 delete CGF.CapturedStmtInfo;
425 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000426 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
427 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000428 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000429 }
430};
431
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432/// \brief Values for bit flags used in the ident_t to describe the fields.
433/// All enumeric elements are named and described in accordance with the code
434/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000435enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000436 /// \brief Use trampoline for internal microtask.
437 OMP_IDENT_IMD = 0x01,
438 /// \brief Use c-style ident structure.
439 OMP_IDENT_KMPC = 0x02,
440 /// \brief Atomic reduction option for kmpc_reduce.
441 OMP_ATOMIC_REDUCE = 0x10,
442 /// \brief Explicit 'barrier' directive.
443 OMP_IDENT_BARRIER_EXPL = 0x20,
444 /// \brief Implicit barrier in code.
445 OMP_IDENT_BARRIER_IMPL = 0x40,
446 /// \brief Implicit barrier in 'for' directive.
447 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
448 /// \brief Implicit barrier in 'sections' directive.
449 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
450 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000451 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
452 /// Call of __kmp_for_static_init for static loop.
453 OMP_IDENT_WORK_LOOP = 0x200,
454 /// Call of __kmp_for_static_init for sections.
455 OMP_IDENT_WORK_SECTIONS = 0x400,
456 /// Call of __kmp_for_static_init for distribute.
457 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
458 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000459};
460
461/// \brief Describes ident structure that describes a source location.
462/// All descriptions are taken from
463/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
464/// Original structure:
465/// typedef struct ident {
466/// kmp_int32 reserved_1; /**< might be used in Fortran;
467/// see above */
468/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
469/// KMP_IDENT_KMPC identifies this union
470/// member */
471/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
472/// see above */
473///#if USE_ITT_BUILD
474/// /* but currently used for storing
475/// region-specific ITT */
476/// /* contextual information. */
477///#endif /* USE_ITT_BUILD */
478/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
479/// C++ */
480/// char const *psource; /**< String describing the source location.
481/// The string is composed of semi-colon separated
482// fields which describe the source file,
483/// the function and a pair of line numbers that
484/// delimit the construct.
485/// */
486/// } ident_t;
487enum IdentFieldIndex {
488 /// \brief might be used in Fortran
489 IdentField_Reserved_1,
490 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
491 IdentField_Flags,
492 /// \brief Not really used in Fortran any more
493 IdentField_Reserved_2,
494 /// \brief Source[4] in Fortran, do not use for C++
495 IdentField_Reserved_3,
496 /// \brief String describing the source location. The string is composed of
497 /// semi-colon separated fields which describe the source file, the function
498 /// and a pair of line numbers that delimit the construct.
499 IdentField_PSource
500};
501
502/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
503/// the enum sched_type in kmp.h).
504enum OpenMPSchedType {
505 /// \brief Lower bound for default (unordered) versions.
506 OMP_sch_lower = 32,
507 OMP_sch_static_chunked = 33,
508 OMP_sch_static = 34,
509 OMP_sch_dynamic_chunked = 35,
510 OMP_sch_guided_chunked = 36,
511 OMP_sch_runtime = 37,
512 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000513 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000514 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000515 /// \brief Lower bound for 'ordered' versions.
516 OMP_ord_lower = 64,
517 OMP_ord_static_chunked = 65,
518 OMP_ord_static = 66,
519 OMP_ord_dynamic_chunked = 67,
520 OMP_ord_guided_chunked = 68,
521 OMP_ord_runtime = 69,
522 OMP_ord_auto = 70,
523 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000524 /// \brief dist_schedule types
525 OMP_dist_sch_static_chunked = 91,
526 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000527 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
528 /// Set if the monotonic schedule modifier was present.
529 OMP_sch_modifier_monotonic = (1 << 29),
530 /// Set if the nonmonotonic schedule modifier was present.
531 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000532};
533
534enum OpenMPRTLFunction {
535 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
536 /// kmpc_micro microtask, ...);
537 OMPRTL__kmpc_fork_call,
538 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
539 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
540 OMPRTL__kmpc_threadprivate_cached,
541 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
542 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
543 OMPRTL__kmpc_threadprivate_register,
544 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
545 OMPRTL__kmpc_global_thread_num,
546 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
547 // kmp_critical_name *crit);
548 OMPRTL__kmpc_critical,
549 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
550 // global_tid, kmp_critical_name *crit, uintptr_t hint);
551 OMPRTL__kmpc_critical_with_hint,
552 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
553 // kmp_critical_name *crit);
554 OMPRTL__kmpc_end_critical,
555 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
556 // global_tid);
557 OMPRTL__kmpc_cancel_barrier,
558 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
559 OMPRTL__kmpc_barrier,
560 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
561 OMPRTL__kmpc_for_static_fini,
562 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
563 // global_tid);
564 OMPRTL__kmpc_serialized_parallel,
565 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
566 // global_tid);
567 OMPRTL__kmpc_end_serialized_parallel,
568 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
569 // kmp_int32 num_threads);
570 OMPRTL__kmpc_push_num_threads,
571 // Call to void __kmpc_flush(ident_t *loc);
572 OMPRTL__kmpc_flush,
573 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
574 OMPRTL__kmpc_master,
575 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
576 OMPRTL__kmpc_end_master,
577 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
578 // int end_part);
579 OMPRTL__kmpc_omp_taskyield,
580 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
581 OMPRTL__kmpc_single,
582 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
583 OMPRTL__kmpc_end_single,
584 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
585 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
586 // kmp_routine_entry_t *task_entry);
587 OMPRTL__kmpc_omp_task_alloc,
588 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
589 // new_task);
590 OMPRTL__kmpc_omp_task,
591 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
592 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
593 // kmp_int32 didit);
594 OMPRTL__kmpc_copyprivate,
595 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
596 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
597 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
598 OMPRTL__kmpc_reduce,
599 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
600 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
601 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
602 // *lck);
603 OMPRTL__kmpc_reduce_nowait,
604 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
605 // kmp_critical_name *lck);
606 OMPRTL__kmpc_end_reduce,
607 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
608 // kmp_critical_name *lck);
609 OMPRTL__kmpc_end_reduce_nowait,
610 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
611 // kmp_task_t * new_task);
612 OMPRTL__kmpc_omp_task_begin_if0,
613 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
614 // kmp_task_t * new_task);
615 OMPRTL__kmpc_omp_task_complete_if0,
616 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
617 OMPRTL__kmpc_ordered,
618 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
619 OMPRTL__kmpc_end_ordered,
620 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
621 // global_tid);
622 OMPRTL__kmpc_omp_taskwait,
623 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
624 OMPRTL__kmpc_taskgroup,
625 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
626 OMPRTL__kmpc_end_taskgroup,
627 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
628 // int proc_bind);
629 OMPRTL__kmpc_push_proc_bind,
630 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
632 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_task_with_deps,
634 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
635 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
636 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
637 OMPRTL__kmpc_omp_wait_deps,
638 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
639 // global_tid, kmp_int32 cncl_kind);
640 OMPRTL__kmpc_cancellationpoint,
641 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
642 // kmp_int32 cncl_kind);
643 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000644 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
645 // kmp_int32 num_teams, kmp_int32 thread_limit);
646 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000647 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
648 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000649 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000650 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
651 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
652 // sched, kmp_uint64 grainsize, void *task_dup);
653 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000654 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
655 // num_dims, struct kmp_dim *dims);
656 OMPRTL__kmpc_doacross_init,
657 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
658 OMPRTL__kmpc_doacross_fini,
659 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
660 // *vec);
661 OMPRTL__kmpc_doacross_post,
662 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
663 // *vec);
664 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000665 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
666 // *data);
667 OMPRTL__kmpc_task_reduction_init,
668 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
669 // *d);
670 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671
672 //
673 // Offloading related calls
674 //
George Rokos63bc9d62017-11-21 18:25:12 +0000675 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
676 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000677 // *arg_types);
678 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000679 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
680 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
681 // *arg_types);
682 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000683 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
684 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
685 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000686 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000687 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
688 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
689 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
690 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000691 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
692 OMPRTL__tgt_register_lib,
693 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
694 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000695 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
696 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000697 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000698 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
699 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
700 // *arg_types);
701 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000702 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
703 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000704 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000705 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
706 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
707 // *arg_types);
708 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000709 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
710 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000711 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000712 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
713 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
714 // *arg_types);
715 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000716};
717
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000718/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
719/// region.
720class CleanupTy final : public EHScopeStack::Cleanup {
721 PrePostActionTy *Action;
722
723public:
724 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
725 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
726 if (!CGF.HaveInsertPoint())
727 return;
728 Action->Exit(CGF);
729 }
730};
731
Hans Wennborg7eb54642015-09-10 17:07:54 +0000732} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000733
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000734void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
735 CodeGenFunction::RunCleanupsScope Scope(CGF);
736 if (PrePostAction) {
737 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
738 Callback(CodeGen, CGF, *PrePostAction);
739 } else {
740 PrePostActionTy Action;
741 Callback(CodeGen, CGF, Action);
742 }
743}
744
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000745/// Check if the combiner is a call to UDR combiner and if it is so return the
746/// UDR decl used for reduction.
747static const OMPDeclareReductionDecl *
748getReductionInit(const Expr *ReductionOp) {
749 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
750 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
751 if (auto *DRE =
752 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
753 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
754 return DRD;
755 return nullptr;
756}
757
758static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
759 const OMPDeclareReductionDecl *DRD,
760 const Expr *InitOp,
761 Address Private, Address Original,
762 QualType Ty) {
763 if (DRD->getInitializer()) {
764 std::pair<llvm::Function *, llvm::Function *> Reduction =
765 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
766 auto *CE = cast<CallExpr>(InitOp);
767 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
768 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
769 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
770 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
771 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
772 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
773 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
774 [=]() -> Address { return Private; });
775 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
776 [=]() -> Address { return Original; });
777 (void)PrivateScope.Privatize();
778 RValue Func = RValue::get(Reduction.second);
779 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
780 CGF.EmitIgnoredExpr(InitOp);
781 } else {
782 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
783 auto *GV = new llvm::GlobalVariable(
784 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
785 llvm::GlobalValue::PrivateLinkage, Init, ".init");
786 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
787 RValue InitRVal;
788 switch (CGF.getEvaluationKind(Ty)) {
789 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000790 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000791 break;
792 case TEK_Complex:
793 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Aggregate:
797 InitRVal = RValue::getAggregate(LV.getAddress());
798 break;
799 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000800 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000801 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
802 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
803 /*IsInitializer=*/false);
804 }
805}
806
807/// \brief Emit initialization of arrays of complex types.
808/// \param DestAddr Address of the array.
809/// \param Type Type of array.
810/// \param Init Initial expression of array.
811/// \param SrcAddr Address of the original array.
812static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000813 QualType Type, bool EmitDeclareReductionInit,
814 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000815 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000816 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000817 // Perform element-by-element initialization.
818 QualType ElementTy;
819
820 // Drill down to the base element type on both arrays.
821 auto ArrayTy = Type->getAsArrayTypeUnsafe();
822 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
823 DestAddr =
824 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
825 if (DRD)
826 SrcAddr =
827 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
828
829 llvm::Value *SrcBegin = nullptr;
830 if (DRD)
831 SrcBegin = SrcAddr.getPointer();
832 auto DestBegin = DestAddr.getPointer();
833 // Cast from pointer to array type to pointer to single element.
834 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
835 // The basic structure here is a while-do loop.
836 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
837 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
838 auto IsEmpty =
839 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
840 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
841
842 // Enter the loop body, making that address the current address.
843 auto EntryBB = CGF.Builder.GetInsertBlock();
844 CGF.EmitBlock(BodyBB);
845
846 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
847
848 llvm::PHINode *SrcElementPHI = nullptr;
849 Address SrcElementCurrent = Address::invalid();
850 if (DRD) {
851 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
852 "omp.arraycpy.srcElementPast");
853 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
854 SrcElementCurrent =
855 Address(SrcElementPHI,
856 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
857 }
858 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
859 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
860 DestElementPHI->addIncoming(DestBegin, EntryBB);
861 Address DestElementCurrent =
862 Address(DestElementPHI,
863 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
864
865 // Emit copy.
866 {
867 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000868 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000869 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
870 SrcElementCurrent, ElementTy);
871 } else
872 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
873 /*IsInitializer=*/false);
874 }
875
876 if (DRD) {
877 // Shift the address forward by one element.
878 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
879 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
880 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
881 }
882
883 // Shift the address forward by one element.
884 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
885 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
886 // Check whether we've reached the end.
887 auto Done =
888 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
889 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
890 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
891
892 // Done.
893 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
894}
895
Alexey Bataev92327c52018-03-26 16:40:55 +0000896static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
897isDeclareTargetDeclaration(const ValueDecl *VD) {
898 for (const auto *D : VD->redecls()) {
899 if (!D->hasAttrs())
900 continue;
901 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
902 return Attr->getMapType();
903 }
904 return llvm::None;
905}
906
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000907LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000908 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000909}
910
911LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
912 const Expr *E) {
913 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
914 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
915 return LValue();
916}
917
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000918void ReductionCodeGen::emitAggregateInitialization(
919 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
920 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921 // Emit VarDecl with copy init for arrays.
922 // Get the address of the original variable captured in current
923 // captured region.
924 auto *PrivateVD =
925 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000926 bool EmitDeclareReductionInit =
927 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000928 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000929 EmitDeclareReductionInit,
930 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
931 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000932 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933}
934
935ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
936 ArrayRef<const Expr *> Privates,
937 ArrayRef<const Expr *> ReductionOps) {
938 ClausesData.reserve(Shareds.size());
939 SharedAddresses.reserve(Shareds.size());
940 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000941 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 auto IPriv = Privates.begin();
943 auto IRed = ReductionOps.begin();
944 for (const auto *Ref : Shareds) {
945 ClausesData.emplace_back(Ref, *IPriv, *IRed);
946 std::advance(IPriv, 1);
947 std::advance(IRed, 1);
948 }
949}
950
951void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
952 assert(SharedAddresses.size() == N &&
953 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000954 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
955 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
956 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957}
958
959void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
960 auto *PrivateVD =
961 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
962 QualType PrivateType = PrivateVD->getType();
963 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000964 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000965 Sizes.emplace_back(
966 CGF.getTypeSize(
967 SharedAddresses[N].first.getType().getNonReferenceType()),
968 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969 return;
970 }
971 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000972 llvm::Value *SizeInChars;
973 llvm::Type *ElemType =
974 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
975 ->getElementType();
976 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000977 if (AsArraySection) {
978 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
979 SharedAddresses[N].first.getPointer());
980 Size = CGF.Builder.CreateNUWAdd(
981 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000982 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000984 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000985 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000986 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000987 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000988 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000989 CodeGenFunction::OpaqueValueMapping OpaqueMap(
990 CGF,
991 cast<OpaqueValueExpr>(
992 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
993 RValue::get(Size));
994 CGF.EmitVariablyModifiedType(PrivateType);
995}
996
997void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
998 llvm::Value *Size) {
999 auto *PrivateVD =
1000 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1001 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001002 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001003 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001004 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001005 "items.");
1006 return;
1007 }
1008 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1009 CGF,
1010 cast<OpaqueValueExpr>(
1011 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1012 RValue::get(Size));
1013 CGF.EmitVariablyModifiedType(PrivateType);
1014}
1015
1016void ReductionCodeGen::emitInitialization(
1017 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1018 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1019 assert(SharedAddresses.size() > N && "No variable was generated");
1020 auto *PrivateVD =
1021 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1022 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1023 QualType PrivateType = PrivateVD->getType();
1024 PrivateAddr = CGF.Builder.CreateElementBitCast(
1025 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1026 QualType SharedType = SharedAddresses[N].first.getType();
1027 SharedLVal = CGF.MakeAddrLValue(
1028 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1029 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001030 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001031 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001032 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001033 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001034 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1035 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1036 PrivateAddr, SharedLVal.getAddress(),
1037 SharedLVal.getType());
1038 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1039 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1040 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1041 PrivateVD->getType().getQualifiers(),
1042 /*IsInitializer=*/false);
1043 }
1044}
1045
1046bool ReductionCodeGen::needCleanups(unsigned N) {
1047 auto *PrivateVD =
1048 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1049 QualType PrivateType = PrivateVD->getType();
1050 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1051 return DTorKind != QualType::DK_none;
1052}
1053
1054void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1055 Address PrivateAddr) {
1056 auto *PrivateVD =
1057 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1058 QualType PrivateType = PrivateVD->getType();
1059 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1060 if (needCleanups(N)) {
1061 PrivateAddr = CGF.Builder.CreateElementBitCast(
1062 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1063 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1064 }
1065}
1066
1067static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1068 LValue BaseLV) {
1069 BaseTy = BaseTy.getNonReferenceType();
1070 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1071 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1072 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1073 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1074 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001075 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1076 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001077 }
1078 BaseTy = BaseTy->getPointeeType();
1079 }
1080 return CGF.MakeAddrLValue(
1081 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1082 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001083 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001084 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001085}
1086
1087static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1088 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1089 llvm::Value *Addr) {
1090 Address Tmp = Address::invalid();
1091 Address TopTmp = Address::invalid();
1092 Address MostTopTmp = Address::invalid();
1093 BaseTy = BaseTy.getNonReferenceType();
1094 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1095 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1096 Tmp = CGF.CreateMemTemp(BaseTy);
1097 if (TopTmp.isValid())
1098 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1099 else
1100 MostTopTmp = Tmp;
1101 TopTmp = Tmp;
1102 BaseTy = BaseTy->getPointeeType();
1103 }
1104 llvm::Type *Ty = BaseLVType;
1105 if (Tmp.isValid())
1106 Ty = Tmp.getElementType();
1107 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1108 if (Tmp.isValid()) {
1109 CGF.Builder.CreateStore(Addr, Tmp);
1110 return MostTopTmp;
1111 }
1112 return Address(Addr, BaseLVAlignment);
1113}
1114
Alexey Bataev1c44e152018-03-06 18:59:43 +00001115static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 const VarDecl *OrigVD = nullptr;
Alexey Bataev1c44e152018-03-06 18:59:43 +00001117 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001118 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1119 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1120 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1121 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1122 Base = TempASE->getBase()->IgnoreParenImpCasts();
1123 DE = cast<DeclRefExpr>(Base);
1124 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataev1c44e152018-03-06 18:59:43 +00001125 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001126 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1127 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1128 Base = TempASE->getBase()->IgnoreParenImpCasts();
1129 DE = cast<DeclRefExpr>(Base);
1130 OrigVD = cast<VarDecl>(DE->getDecl());
1131 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001132 return OrigVD;
1133}
1134
1135Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1136 Address PrivateAddr) {
1137 const DeclRefExpr *DE;
1138 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001139 BaseDecls.emplace_back(OrigVD);
1140 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1141 LValue BaseLValue =
1142 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1143 OriginalBaseLValue);
1144 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1145 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001146 llvm::Value *PrivatePointer =
1147 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1148 PrivateAddr.getPointer(),
1149 SharedAddresses[N].first.getAddress().getType());
1150 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001151 return castToBase(CGF, OrigVD->getType(),
1152 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001153 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001154 OriginalBaseLValue.getAlignment(), Ptr);
1155 }
1156 BaseDecls.emplace_back(
1157 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1158 return PrivateAddr;
1159}
1160
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001161bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1162 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1163 return DRD && DRD->getInitializer();
1164}
1165
Alexey Bataev18095712014-10-10 12:19:54 +00001166LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001167 return CGF.EmitLoadOfPointerLValue(
1168 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1169 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001170}
1171
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001172void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001173 if (!CGF.HaveInsertPoint())
1174 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001175 // 1.2.2 OpenMP Language Terminology
1176 // Structured block - An executable statement with a single entry at the
1177 // top and a single exit at the bottom.
1178 // The point of exit cannot be a branch out of the structured block.
1179 // longjmp() and throw() must not violate the entry/exit criteria.
1180 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001181 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001182 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001183}
1184
Alexey Bataev62b63b12015-03-10 07:28:44 +00001185LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1186 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001187 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1188 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001189 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001190}
1191
Alexey Bataev9959db52014-05-06 10:08:46 +00001192CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001193 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001194 IdentTy = llvm::StructType::create(
1195 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1196 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001197 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001198 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001199
1200 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001201}
1202
Alexey Bataev91797552015-03-18 04:13:55 +00001203void CGOpenMPRuntime::clear() {
1204 InternalVars.clear();
1205}
1206
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001207static llvm::Function *
1208emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1209 const Expr *CombinerInitializer, const VarDecl *In,
1210 const VarDecl *Out, bool IsCombiner) {
1211 // void .omp_combiner.(Ty *in, Ty *out);
1212 auto &C = CGM.getContext();
1213 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1214 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001215 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001216 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001217 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001218 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001219 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001220 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001221 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001222 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001223 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1224 auto *Fn = llvm::Function::Create(
1225 FnTy, llvm::GlobalValue::InternalLinkage,
1226 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001227 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001228 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001229 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001230 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001231 CodeGenFunction CGF(CGM);
1232 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1233 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001234 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1235 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001236 CodeGenFunction::OMPPrivateScope Scope(CGF);
1237 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1238 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1239 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1240 .getAddress();
1241 });
1242 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1243 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1244 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1245 .getAddress();
1246 });
1247 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001248 if (!IsCombiner && Out->hasInit() &&
1249 !CGF.isTrivialInitializer(Out->getInit())) {
1250 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1251 Out->getType().getQualifiers(),
1252 /*IsInitializer=*/true);
1253 }
1254 if (CombinerInitializer)
1255 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001256 Scope.ForceCleanup();
1257 CGF.FinishFunction();
1258 return Fn;
1259}
1260
1261void CGOpenMPRuntime::emitUserDefinedReduction(
1262 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1263 if (UDRMap.count(D) > 0)
1264 return;
1265 auto &C = CGM.getContext();
1266 if (!In || !Out) {
1267 In = &C.Idents.get("omp_in");
1268 Out = &C.Idents.get("omp_out");
1269 }
1270 llvm::Function *Combiner = emitCombinerOrInitializer(
1271 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1272 cast<VarDecl>(D->lookup(Out).front()),
1273 /*IsCombiner=*/true);
1274 llvm::Function *Initializer = nullptr;
1275 if (auto *Init = D->getInitializer()) {
1276 if (!Priv || !Orig) {
1277 Priv = &C.Idents.get("omp_priv");
1278 Orig = &C.Idents.get("omp_orig");
1279 }
1280 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001281 CGM, D->getType(),
1282 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1283 : nullptr,
1284 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001285 cast<VarDecl>(D->lookup(Priv).front()),
1286 /*IsCombiner=*/false);
1287 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001288 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001289 if (CGF) {
1290 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1291 Decls.second.push_back(D);
1292 }
1293}
1294
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001295std::pair<llvm::Function *, llvm::Function *>
1296CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1297 auto I = UDRMap.find(D);
1298 if (I != UDRMap.end())
1299 return I->second;
1300 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1301 return UDRMap.lookup(D);
1302}
1303
John McCall7f416cc2015-09-08 08:05:57 +00001304// Layout information for ident_t.
1305static CharUnits getIdentAlign(CodeGenModule &CGM) {
1306 return CGM.getPointerAlign();
1307}
1308static CharUnits getIdentSize(CodeGenModule &CGM) {
1309 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1310 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1311}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001312static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001313 // All the fields except the last are i32, so this works beautifully.
1314 return unsigned(Field) * CharUnits::fromQuantity(4);
1315}
1316static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001317 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001318 const llvm::Twine &Name = "") {
1319 auto Offset = getOffsetOfIdentField(Field);
1320 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1321}
1322
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001323static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1324 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1325 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1326 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001327 assert(ThreadIDVar->getType()->isPointerType() &&
1328 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001329 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001330 bool HasCancel = false;
1331 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1332 HasCancel = OPD->hasCancel();
1333 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1334 HasCancel = OPSD->hasCancel();
1335 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1336 HasCancel = OPFD->hasCancel();
Alexey Bataev2139ed62017-11-16 18:20:21 +00001337 else if (auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1338 HasCancel = OPFD->hasCancel();
Alexey Bataev10a54312017-11-27 16:54:08 +00001339 else if (auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1340 HasCancel = OPFD->hasCancel();
1341 else if (auto *OPFD = dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1342 HasCancel = OPFD->hasCancel();
1343 else if (auto *OPFD =
1344 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1345 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001346 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001347 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001348 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001349 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001350}
1351
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001352llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1353 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1354 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1355 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1356 return emitParallelOrTeamsOutlinedFunction(
1357 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1358}
1359
1360llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1361 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1362 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1363 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1364 return emitParallelOrTeamsOutlinedFunction(
1365 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1366}
1367
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001368llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1369 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001370 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1371 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1372 bool Tied, unsigned &NumberOfParts) {
1373 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1374 PrePostActionTy &) {
1375 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1376 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1377 llvm::Value *TaskArgs[] = {
1378 UpLoc, ThreadID,
1379 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1380 TaskTVar->getType()->castAs<PointerType>())
1381 .getPointer()};
1382 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1383 };
1384 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1385 UntiedCodeGen);
1386 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001387 assert(!ThreadIDVar->getType()->isPointerType() &&
1388 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001389 const OpenMPDirectiveKind Region =
1390 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1391 : OMPD_task;
1392 auto *CS = D.getCapturedStmt(Region);
Alexey Bataev7292c292016-04-25 12:22:29 +00001393 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001394 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001395 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1396 InnermostKind,
1397 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001398 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001399 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1400 if (!Tied)
1401 NumberOfParts = Action.getNumberOfParts();
1402 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001403}
1404
Alexey Bataev50b3c952016-02-19 10:38:26 +00001405Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001406 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001407 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001408 if (!Entry) {
1409 if (!DefaultOpenMPPSource) {
1410 // Initialize default location for psource field of ident_t structure of
1411 // all ident_t objects. Format is ";file;function;line;column;;".
1412 // Taken from
1413 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1414 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001415 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001416 DefaultOpenMPPSource =
1417 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1418 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001419
John McCall23c9dc62016-11-28 22:18:27 +00001420 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001421 auto fields = builder.beginStruct(IdentTy);
1422 fields.addInt(CGM.Int32Ty, 0);
1423 fields.addInt(CGM.Int32Ty, Flags);
1424 fields.addInt(CGM.Int32Ty, 0);
1425 fields.addInt(CGM.Int32Ty, 0);
1426 fields.add(DefaultOpenMPPSource);
1427 auto DefaultOpenMPLocation =
1428 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1429 llvm::GlobalValue::PrivateLinkage);
1430 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1431
John McCall7f416cc2015-09-08 08:05:57 +00001432 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001433 }
John McCall7f416cc2015-09-08 08:05:57 +00001434 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001435}
1436
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001437llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1438 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001439 unsigned Flags) {
1440 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001441 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001442 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001443 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001444 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001445
1446 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1447
John McCall7f416cc2015-09-08 08:05:57 +00001448 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001449 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1450 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001451 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1452
Alexander Musmanc6388682014-12-15 07:07:06 +00001453 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1454 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001455 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001456 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001457 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1458 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001459 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001460 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001461 LocValue = AI;
1462
1463 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1464 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001465 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001466 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001467 }
1468
1469 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001470 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001471
Alexey Bataevf002aca2014-05-30 05:48:40 +00001472 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1473 if (OMPDebugLoc == nullptr) {
1474 SmallString<128> Buffer2;
1475 llvm::raw_svector_ostream OS2(Buffer2);
1476 // Build debug location
1477 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1478 OS2 << ";" << PLoc.getFilename() << ";";
1479 if (const FunctionDecl *FD =
1480 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1481 OS2 << FD->getQualifiedNameAsString();
1482 }
1483 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1484 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1485 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001487 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001488 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1489
John McCall7f416cc2015-09-08 08:05:57 +00001490 // Our callers always pass this to a runtime function, so for
1491 // convenience, go ahead and return a naked pointer.
1492 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001493}
1494
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001495llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1496 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001497 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1498
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001499 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001500 // Check whether we've already cached a load of the thread id in this
1501 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001502 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001503 if (I != OpenMPLocThreadIDMap.end()) {
1504 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001505 if (ThreadID != nullptr)
1506 return ThreadID;
1507 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001508 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001509 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1510 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001511 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001512 if (auto *OMPRegionInfo =
1513 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1514 if (OMPRegionInfo->getThreadIDVariable()) {
1515 // Check if this an outlined function with thread id passed as argument.
1516 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001517 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001518 // If value loaded in entry block, cache it and use it everywhere in
1519 // function.
1520 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1521 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1522 Elem.second.ThreadID = ThreadID;
1523 }
1524 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001525 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001526 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001527 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001528
1529 // This is not an outlined function region - need to call __kmpc_int32
1530 // kmpc_global_thread_num(ident_t *loc).
1531 // Generate thread id value and cache this value for use across the
1532 // function.
1533 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1534 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001535 auto *Call = CGF.Builder.CreateCall(
1536 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1537 emitUpdateLocation(CGF, Loc));
1538 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001539 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001540 Elem.second.ThreadID = Call;
1541 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001542}
1543
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001544void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001545 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001546 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1547 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001548 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1549 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1550 UDRMap.erase(D);
1551 }
1552 FunctionUDRMap.erase(CGF.CurFn);
1553 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001554}
1555
1556llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001557 if (!IdentTy) {
1558 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001559 return llvm::PointerType::getUnqual(IdentTy);
1560}
1561
1562llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001563 if (!Kmpc_MicroTy) {
1564 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1565 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1566 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1567 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1568 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001569 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1570}
1571
1572llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001573CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001574 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001575 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001576 case OMPRTL__kmpc_fork_call: {
1577 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1578 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1580 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001581 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001582 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001583 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1584 break;
1585 }
1586 case OMPRTL__kmpc_global_thread_num: {
1587 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001588 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001589 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001590 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1592 break;
1593 }
Alexey Bataev97720002014-11-11 04:05:39 +00001594 case OMPRTL__kmpc_threadprivate_cached: {
1595 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1596 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1597 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1598 CGM.VoidPtrTy, CGM.SizeTy,
1599 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1600 llvm::FunctionType *FnTy =
1601 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1602 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1603 break;
1604 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001605 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001606 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1607 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001608 llvm::Type *TypeParams[] = {
1609 getIdentTyPointerTy(), CGM.Int32Ty,
1610 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1611 llvm::FunctionType *FnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1613 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1614 break;
1615 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001616 case OMPRTL__kmpc_critical_with_hint: {
1617 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1618 // kmp_critical_name *crit, uintptr_t hint);
1619 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1620 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1621 CGM.IntPtrTy};
1622 llvm::FunctionType *FnTy =
1623 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1625 break;
1626 }
Alexey Bataev97720002014-11-11 04:05:39 +00001627 case OMPRTL__kmpc_threadprivate_register: {
1628 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1629 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1630 // typedef void *(*kmpc_ctor)(void *);
1631 auto KmpcCtorTy =
1632 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1633 /*isVarArg*/ false)->getPointerTo();
1634 // typedef void *(*kmpc_cctor)(void *, void *);
1635 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1636 auto KmpcCopyCtorTy =
1637 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1638 /*isVarArg*/ false)->getPointerTo();
1639 // typedef void (*kmpc_dtor)(void *);
1640 auto KmpcDtorTy =
1641 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1642 ->getPointerTo();
1643 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1644 KmpcCopyCtorTy, KmpcDtorTy};
1645 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1646 /*isVarArg*/ false);
1647 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1648 break;
1649 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001650 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001651 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1652 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001653 llvm::Type *TypeParams[] = {
1654 getIdentTyPointerTy(), CGM.Int32Ty,
1655 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1656 llvm::FunctionType *FnTy =
1657 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1658 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1659 break;
1660 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001661 case OMPRTL__kmpc_cancel_barrier: {
1662 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1663 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001664 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1665 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001666 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1667 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001668 break;
1669 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001670 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001671 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1673 llvm::FunctionType *FnTy =
1674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1676 break;
1677 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001678 case OMPRTL__kmpc_for_static_fini: {
1679 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1680 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1681 llvm::FunctionType *FnTy =
1682 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1683 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1684 break;
1685 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001686 case OMPRTL__kmpc_push_num_threads: {
1687 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1688 // kmp_int32 num_threads)
1689 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1690 CGM.Int32Ty};
1691 llvm::FunctionType *FnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1694 break;
1695 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001696 case OMPRTL__kmpc_serialized_parallel: {
1697 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1698 // global_tid);
1699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1700 llvm::FunctionType *FnTy =
1701 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1702 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1703 break;
1704 }
1705 case OMPRTL__kmpc_end_serialized_parallel: {
1706 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1707 // global_tid);
1708 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1709 llvm::FunctionType *FnTy =
1710 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1712 break;
1713 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001714 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001715 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001716 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1717 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001718 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001719 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1720 break;
1721 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001722 case OMPRTL__kmpc_master: {
1723 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1724 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1725 llvm::FunctionType *FnTy =
1726 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1727 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1728 break;
1729 }
1730 case OMPRTL__kmpc_end_master: {
1731 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1732 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1733 llvm::FunctionType *FnTy =
1734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1735 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1736 break;
1737 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001738 case OMPRTL__kmpc_omp_taskyield: {
1739 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1740 // int end_part);
1741 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1742 llvm::FunctionType *FnTy =
1743 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1745 break;
1746 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001747 case OMPRTL__kmpc_single: {
1748 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1749 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1750 llvm::FunctionType *FnTy =
1751 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1753 break;
1754 }
1755 case OMPRTL__kmpc_end_single: {
1756 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1757 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1758 llvm::FunctionType *FnTy =
1759 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1760 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1761 break;
1762 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001763 case OMPRTL__kmpc_omp_task_alloc: {
1764 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1765 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1766 // kmp_routine_entry_t *task_entry);
1767 assert(KmpRoutineEntryPtrTy != nullptr &&
1768 "Type kmp_routine_entry_t must be created.");
1769 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1770 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1771 // Return void * and then cast to particular kmp_task_t type.
1772 llvm::FunctionType *FnTy =
1773 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1775 break;
1776 }
1777 case OMPRTL__kmpc_omp_task: {
1778 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1779 // *new_task);
1780 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1781 CGM.VoidPtrTy};
1782 llvm::FunctionType *FnTy =
1783 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1785 break;
1786 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001787 case OMPRTL__kmpc_copyprivate: {
1788 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001789 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001790 // kmp_int32 didit);
1791 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1792 auto *CpyFnTy =
1793 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001794 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001795 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1796 CGM.Int32Ty};
1797 llvm::FunctionType *FnTy =
1798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1799 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1800 break;
1801 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001802 case OMPRTL__kmpc_reduce: {
1803 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1804 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1805 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1806 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1807 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1808 /*isVarArg=*/false);
1809 llvm::Type *TypeParams[] = {
1810 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1811 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1812 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1813 llvm::FunctionType *FnTy =
1814 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1815 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1816 break;
1817 }
1818 case OMPRTL__kmpc_reduce_nowait: {
1819 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1820 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1821 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1822 // *lck);
1823 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1824 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1825 /*isVarArg=*/false);
1826 llvm::Type *TypeParams[] = {
1827 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1828 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1829 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1830 llvm::FunctionType *FnTy =
1831 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1832 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1833 break;
1834 }
1835 case OMPRTL__kmpc_end_reduce: {
1836 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1837 // kmp_critical_name *lck);
1838 llvm::Type *TypeParams[] = {
1839 getIdentTyPointerTy(), CGM.Int32Ty,
1840 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1841 llvm::FunctionType *FnTy =
1842 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1843 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1844 break;
1845 }
1846 case OMPRTL__kmpc_end_reduce_nowait: {
1847 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1848 // kmp_critical_name *lck);
1849 llvm::Type *TypeParams[] = {
1850 getIdentTyPointerTy(), CGM.Int32Ty,
1851 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1852 llvm::FunctionType *FnTy =
1853 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1854 RTLFn =
1855 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1856 break;
1857 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001858 case OMPRTL__kmpc_omp_task_begin_if0: {
1859 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1860 // *new_task);
1861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1862 CGM.VoidPtrTy};
1863 llvm::FunctionType *FnTy =
1864 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1865 RTLFn =
1866 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1867 break;
1868 }
1869 case OMPRTL__kmpc_omp_task_complete_if0: {
1870 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1871 // *new_task);
1872 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1873 CGM.VoidPtrTy};
1874 llvm::FunctionType *FnTy =
1875 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1876 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1877 /*Name=*/"__kmpc_omp_task_complete_if0");
1878 break;
1879 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001880 case OMPRTL__kmpc_ordered: {
1881 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1882 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1883 llvm::FunctionType *FnTy =
1884 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1885 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1886 break;
1887 }
1888 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001889 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001890 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1891 llvm::FunctionType *FnTy =
1892 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1894 break;
1895 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001896 case OMPRTL__kmpc_omp_taskwait: {
1897 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1898 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1899 llvm::FunctionType *FnTy =
1900 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1901 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1902 break;
1903 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001904 case OMPRTL__kmpc_taskgroup: {
1905 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1907 llvm::FunctionType *FnTy =
1908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1910 break;
1911 }
1912 case OMPRTL__kmpc_end_taskgroup: {
1913 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1914 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1915 llvm::FunctionType *FnTy =
1916 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1917 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1918 break;
1919 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001920 case OMPRTL__kmpc_push_proc_bind: {
1921 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1922 // int proc_bind)
1923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1924 llvm::FunctionType *FnTy =
1925 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1926 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1927 break;
1928 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001929 case OMPRTL__kmpc_omp_task_with_deps: {
1930 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1931 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1932 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1933 llvm::Type *TypeParams[] = {
1934 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1935 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1936 llvm::FunctionType *FnTy =
1937 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1938 RTLFn =
1939 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1940 break;
1941 }
1942 case OMPRTL__kmpc_omp_wait_deps: {
1943 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1944 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1945 // kmp_depend_info_t *noalias_dep_list);
1946 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1947 CGM.Int32Ty, CGM.VoidPtrTy,
1948 CGM.Int32Ty, CGM.VoidPtrTy};
1949 llvm::FunctionType *FnTy =
1950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1952 break;
1953 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001954 case OMPRTL__kmpc_cancellationpoint: {
1955 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1956 // global_tid, kmp_int32 cncl_kind)
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1958 llvm::FunctionType *FnTy =
1959 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1960 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1961 break;
1962 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001963 case OMPRTL__kmpc_cancel: {
1964 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1965 // kmp_int32 cncl_kind)
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1967 llvm::FunctionType *FnTy =
1968 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1970 break;
1971 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001972 case OMPRTL__kmpc_push_num_teams: {
1973 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1974 // kmp_int32 num_teams, kmp_int32 num_threads)
1975 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1976 CGM.Int32Ty};
1977 llvm::FunctionType *FnTy =
1978 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1979 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1980 break;
1981 }
1982 case OMPRTL__kmpc_fork_teams: {
1983 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1984 // microtask, ...);
1985 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1986 getKmpc_MicroPointerTy()};
1987 llvm::FunctionType *FnTy =
1988 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1989 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1990 break;
1991 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001992 case OMPRTL__kmpc_taskloop: {
1993 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1994 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1995 // sched, kmp_uint64 grainsize, void *task_dup);
1996 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1997 CGM.IntTy,
1998 CGM.VoidPtrTy,
1999 CGM.IntTy,
2000 CGM.Int64Ty->getPointerTo(),
2001 CGM.Int64Ty->getPointerTo(),
2002 CGM.Int64Ty,
2003 CGM.IntTy,
2004 CGM.IntTy,
2005 CGM.Int64Ty,
2006 CGM.VoidPtrTy};
2007 llvm::FunctionType *FnTy =
2008 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2009 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2010 break;
2011 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002012 case OMPRTL__kmpc_doacross_init: {
2013 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2014 // num_dims, struct kmp_dim *dims);
2015 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2016 CGM.Int32Ty,
2017 CGM.Int32Ty,
2018 CGM.VoidPtrTy};
2019 llvm::FunctionType *FnTy =
2020 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2021 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2022 break;
2023 }
2024 case OMPRTL__kmpc_doacross_fini: {
2025 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2026 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2027 llvm::FunctionType *FnTy =
2028 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2029 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2030 break;
2031 }
2032 case OMPRTL__kmpc_doacross_post: {
2033 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2034 // *vec);
2035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2036 CGM.Int64Ty->getPointerTo()};
2037 llvm::FunctionType *FnTy =
2038 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2039 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2040 break;
2041 }
2042 case OMPRTL__kmpc_doacross_wait: {
2043 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2044 // *vec);
2045 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2046 CGM.Int64Ty->getPointerTo()};
2047 llvm::FunctionType *FnTy =
2048 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2049 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2050 break;
2051 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002052 case OMPRTL__kmpc_task_reduction_init: {
2053 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2054 // *data);
2055 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2056 llvm::FunctionType *FnTy =
2057 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2058 RTLFn =
2059 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2060 break;
2061 }
2062 case OMPRTL__kmpc_task_reduction_get_th_data: {
2063 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2064 // *d);
2065 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2066 llvm::FunctionType *FnTy =
2067 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2068 RTLFn = CGM.CreateRuntimeFunction(
2069 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2070 break;
2071 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002072 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002073 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2074 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002075 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002076 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002077 CGM.VoidPtrTy,
2078 CGM.Int32Ty,
2079 CGM.VoidPtrPtrTy,
2080 CGM.VoidPtrPtrTy,
2081 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002082 CGM.Int64Ty->getPointerTo()};
Samuel Antaobed3c462015-10-02 16:14:20 +00002083 llvm::FunctionType *FnTy =
2084 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2085 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2086 break;
2087 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002088 case OMPRTL__tgt_target_nowait: {
2089 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2090 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2091 // int64_t *arg_types);
2092 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2093 CGM.VoidPtrTy,
2094 CGM.Int32Ty,
2095 CGM.VoidPtrPtrTy,
2096 CGM.VoidPtrPtrTy,
2097 CGM.SizeTy->getPointerTo(),
2098 CGM.Int64Ty->getPointerTo()};
2099 llvm::FunctionType *FnTy =
2100 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2101 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2102 break;
2103 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002104 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002105 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002106 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002107 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2108 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002109 CGM.VoidPtrTy,
2110 CGM.Int32Ty,
2111 CGM.VoidPtrPtrTy,
2112 CGM.VoidPtrPtrTy,
2113 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002114 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002115 CGM.Int32Ty,
2116 CGM.Int32Ty};
2117 llvm::FunctionType *FnTy =
2118 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2119 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2120 break;
2121 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002122 case OMPRTL__tgt_target_teams_nowait: {
2123 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2124 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2125 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2126 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2127 CGM.VoidPtrTy,
2128 CGM.Int32Ty,
2129 CGM.VoidPtrPtrTy,
2130 CGM.VoidPtrPtrTy,
2131 CGM.SizeTy->getPointerTo(),
2132 CGM.Int64Ty->getPointerTo(),
2133 CGM.Int32Ty,
2134 CGM.Int32Ty};
2135 llvm::FunctionType *FnTy =
2136 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2137 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2138 break;
2139 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002140 case OMPRTL__tgt_register_lib: {
2141 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2142 QualType ParamTy =
2143 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2144 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2145 llvm::FunctionType *FnTy =
2146 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2147 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2148 break;
2149 }
2150 case OMPRTL__tgt_unregister_lib: {
2151 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2152 QualType ParamTy =
2153 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2154 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2155 llvm::FunctionType *FnTy =
2156 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2157 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2158 break;
2159 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002160 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002161 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2162 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2163 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002164 CGM.Int32Ty,
2165 CGM.VoidPtrPtrTy,
2166 CGM.VoidPtrPtrTy,
2167 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002168 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002169 llvm::FunctionType *FnTy =
2170 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2171 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2172 break;
2173 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002174 case OMPRTL__tgt_target_data_begin_nowait: {
2175 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2176 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2177 // *arg_types);
2178 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2179 CGM.Int32Ty,
2180 CGM.VoidPtrPtrTy,
2181 CGM.VoidPtrPtrTy,
2182 CGM.SizeTy->getPointerTo(),
2183 CGM.Int64Ty->getPointerTo()};
2184 auto *FnTy =
2185 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2186 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2187 break;
2188 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002189 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002190 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2191 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2192 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002193 CGM.Int32Ty,
2194 CGM.VoidPtrPtrTy,
2195 CGM.VoidPtrPtrTy,
2196 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002197 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002198 llvm::FunctionType *FnTy =
2199 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2200 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2201 break;
2202 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002203 case OMPRTL__tgt_target_data_end_nowait: {
2204 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2205 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2206 // *arg_types);
2207 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2208 CGM.Int32Ty,
2209 CGM.VoidPtrPtrTy,
2210 CGM.VoidPtrPtrTy,
2211 CGM.SizeTy->getPointerTo(),
2212 CGM.Int64Ty->getPointerTo()};
2213 auto *FnTy =
2214 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2215 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2216 break;
2217 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002218 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002219 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2220 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2221 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002222 CGM.Int32Ty,
2223 CGM.VoidPtrPtrTy,
2224 CGM.VoidPtrPtrTy,
2225 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002226 CGM.Int64Ty->getPointerTo()};
Samuel Antao8d2d7302016-05-26 18:30:22 +00002227 llvm::FunctionType *FnTy =
2228 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2229 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2230 break;
2231 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002232 case OMPRTL__tgt_target_data_update_nowait: {
2233 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2234 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2235 // *arg_types);
2236 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2237 CGM.Int32Ty,
2238 CGM.VoidPtrPtrTy,
2239 CGM.VoidPtrPtrTy,
2240 CGM.SizeTy->getPointerTo(),
2241 CGM.Int64Ty->getPointerTo()};
2242 auto *FnTy =
2243 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2244 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2245 break;
2246 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002247 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002248 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002249 return RTLFn;
2250}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002251
Alexander Musman21212e42015-03-13 10:38:23 +00002252llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2253 bool IVSigned) {
2254 assert((IVSize == 32 || IVSize == 64) &&
2255 "IV size is not compatible with the omp runtime");
2256 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2257 : "__kmpc_for_static_init_4u")
2258 : (IVSigned ? "__kmpc_for_static_init_8"
2259 : "__kmpc_for_static_init_8u");
2260 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2261 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2262 llvm::Type *TypeParams[] = {
2263 getIdentTyPointerTy(), // loc
2264 CGM.Int32Ty, // tid
2265 CGM.Int32Ty, // schedtype
2266 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2267 PtrTy, // p_lower
2268 PtrTy, // p_upper
2269 PtrTy, // p_stride
2270 ITy, // incr
2271 ITy // chunk
2272 };
2273 llvm::FunctionType *FnTy =
2274 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2275 return CGM.CreateRuntimeFunction(FnTy, Name);
2276}
2277
Alexander Musman92bdaab2015-03-12 13:37:50 +00002278llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2279 bool IVSigned) {
2280 assert((IVSize == 32 || IVSize == 64) &&
2281 "IV size is not compatible with the omp runtime");
2282 auto Name =
2283 IVSize == 32
2284 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2285 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2286 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2287 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2288 CGM.Int32Ty, // tid
2289 CGM.Int32Ty, // schedtype
2290 ITy, // lower
2291 ITy, // upper
2292 ITy, // stride
2293 ITy // chunk
2294 };
2295 llvm::FunctionType *FnTy =
2296 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2297 return CGM.CreateRuntimeFunction(FnTy, Name);
2298}
2299
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002300llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2301 bool IVSigned) {
2302 assert((IVSize == 32 || IVSize == 64) &&
2303 "IV size is not compatible with the omp runtime");
2304 auto Name =
2305 IVSize == 32
2306 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2307 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2308 llvm::Type *TypeParams[] = {
2309 getIdentTyPointerTy(), // loc
2310 CGM.Int32Ty, // tid
2311 };
2312 llvm::FunctionType *FnTy =
2313 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2314 return CGM.CreateRuntimeFunction(FnTy, Name);
2315}
2316
Alexander Musman92bdaab2015-03-12 13:37:50 +00002317llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2318 bool IVSigned) {
2319 assert((IVSize == 32 || IVSize == 64) &&
2320 "IV size is not compatible with the omp runtime");
2321 auto Name =
2322 IVSize == 32
2323 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2324 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2325 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2326 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2327 llvm::Type *TypeParams[] = {
2328 getIdentTyPointerTy(), // loc
2329 CGM.Int32Ty, // tid
2330 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2331 PtrTy, // p_lower
2332 PtrTy, // p_upper
2333 PtrTy // p_stride
2334 };
2335 llvm::FunctionType *FnTy =
2336 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2337 return CGM.CreateRuntimeFunction(FnTy, Name);
2338}
2339
Alexey Bataev03f270c2018-03-30 18:31:07 +00002340Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2341 if (CGM.getLangOpts().OpenMPSimd)
2342 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002343 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2344 isDeclareTargetDeclaration(VD);
2345 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2346 SmallString<64> PtrName;
2347 {
2348 llvm::raw_svector_ostream OS(PtrName);
2349 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2350 }
2351 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2352 if (!Ptr) {
2353 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2354 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2355 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002356 if (!CGM.getLangOpts().OpenMPIsDevice) {
2357 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2358 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2359 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2360 }
2361 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2362 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002363 }
2364 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2365 }
2366 return Address::invalid();
2367}
2368
Alexey Bataev97720002014-11-11 04:05:39 +00002369llvm::Constant *
2370CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002371 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2372 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002373 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002374 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002375 Twine(CGM.getMangledName(VD)) + ".cache.");
2376}
2377
John McCall7f416cc2015-09-08 08:05:57 +00002378Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2379 const VarDecl *VD,
2380 Address VDAddr,
2381 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002382 if (CGM.getLangOpts().OpenMPUseTLS &&
2383 CGM.getContext().getTargetInfo().isTLSSupported())
2384 return VDAddr;
2385
John McCall7f416cc2015-09-08 08:05:57 +00002386 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002387 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002388 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2389 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002390 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2391 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002392 return Address(CGF.EmitRuntimeCall(
2393 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2394 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002395}
2396
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002397void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002398 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002399 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2400 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2401 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002402 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2403 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002404 OMPLoc);
2405 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2406 // to register constructor/destructor for variable.
2407 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002408 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2409 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002410 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002411 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002412 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002413}
2414
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002415llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002416 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002417 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002418 if (CGM.getLangOpts().OpenMPUseTLS &&
2419 CGM.getContext().getTargetInfo().isTLSSupported())
2420 return nullptr;
2421
Alexey Bataev97720002014-11-11 04:05:39 +00002422 VD = VD->getDefinition(CGM.getContext());
2423 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2424 ThreadPrivateWithDefinition.insert(VD);
2425 QualType ASTTy = VD->getType();
2426
2427 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2428 auto Init = VD->getAnyInitializer();
2429 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2430 // Generate function that re-emits the declaration's initializer into the
2431 // threadprivate copy of the variable VD
2432 CodeGenFunction CtorCGF(CGM);
2433 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002434 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2435 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002436 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002437 Args.push_back(&Dst);
2438
John McCallc56a8b32016-03-11 04:30:31 +00002439 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2440 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002441 auto FTy = CGM.getTypes().GetFunctionType(FI);
2442 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002443 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002444 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002445 Args, Loc, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002446 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002447 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002448 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002449 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002450 Arg = CtorCGF.Builder.CreateElementBitCast(
2451 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002452 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2453 /*IsInitializer=*/true);
2454 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002455 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002456 CGM.getContext().VoidPtrTy, Dst.getLocation());
2457 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2458 CtorCGF.FinishFunction();
2459 Ctor = Fn;
2460 }
2461 if (VD->getType().isDestructedType() != QualType::DK_none) {
2462 // Generate function that emits destructor call for the threadprivate copy
2463 // of the variable VD
2464 CodeGenFunction DtorCGF(CGM);
2465 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002466 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2467 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002468 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002469 Args.push_back(&Dst);
2470
John McCallc56a8b32016-03-11 04:30:31 +00002471 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2472 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002473 auto FTy = CGM.getTypes().GetFunctionType(FI);
2474 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002475 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002476 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002477 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002478 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002479 // Create a scope with an artificial location for the body of this function.
2480 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002481 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2482 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002483 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2484 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002485 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2486 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2487 DtorCGF.FinishFunction();
2488 Dtor = Fn;
2489 }
2490 // Do not emit init function if it is not required.
2491 if (!Ctor && !Dtor)
2492 return nullptr;
2493
2494 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2495 auto CopyCtorTy =
2496 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2497 /*isVarArg=*/false)->getPointerTo();
2498 // Copying constructor for the threadprivate variable.
2499 // Must be NULL - reserved by runtime, but currently it requires that this
2500 // parameter is always NULL. Otherwise it fires assertion.
2501 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2502 if (Ctor == nullptr) {
2503 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2504 /*isVarArg=*/false)->getPointerTo();
2505 Ctor = llvm::Constant::getNullValue(CtorTy);
2506 }
2507 if (Dtor == nullptr) {
2508 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2509 /*isVarArg=*/false)->getPointerTo();
2510 Dtor = llvm::Constant::getNullValue(DtorTy);
2511 }
2512 if (!CGF) {
2513 auto InitFunctionTy =
2514 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2515 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002516 InitFunctionTy, ".__omp_threadprivate_init_.",
2517 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002518 CodeGenFunction InitCGF(CGM);
2519 FunctionArgList ArgList;
2520 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2521 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002522 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002523 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002524 InitCGF.FinishFunction();
2525 return InitFunction;
2526 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002527 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002528 }
2529 return nullptr;
2530}
2531
Alexey Bataev34f8a702018-03-28 14:28:54 +00002532/// \brief Obtain information that uniquely identifies a target entry. This
2533/// consists of the file and device IDs as well as line number associated with
2534/// the relevant entry source location.
2535static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2536 unsigned &DeviceID, unsigned &FileID,
2537 unsigned &LineNum) {
2538
2539 auto &SM = C.getSourceManager();
2540
2541 // The loc should be always valid and have a file ID (the user cannot use
2542 // #pragma directives in macros)
2543
2544 assert(Loc.isValid() && "Source location is expected to be always valid.");
2545 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
2546
2547 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2548 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2549
2550 llvm::sys::fs::UniqueID ID;
2551 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2552 llvm_unreachable("Source file with target region no longer exists!");
2553
2554 DeviceID = ID.getDevice();
2555 FileID = ID.getFile();
2556 LineNum = PLoc.getLine();
2557}
2558
2559bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2560 llvm::GlobalVariable *Addr,
2561 bool PerformInit) {
2562 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2563 isDeclareTargetDeclaration(VD);
2564 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2565 return false;
2566 VD = VD->getDefinition(CGM.getContext());
2567 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2568 return CGM.getLangOpts().OpenMPIsDevice;
2569
2570 QualType ASTTy = VD->getType();
2571
2572 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2573 // Produce the unique prefix to identify the new target regions. We use
2574 // the source location of the variable declaration which we know to not
2575 // conflict with any target region.
2576 unsigned DeviceID;
2577 unsigned FileID;
2578 unsigned Line;
2579 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2580 SmallString<128> Buffer, Out;
2581 {
2582 llvm::raw_svector_ostream OS(Buffer);
2583 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2584 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2585 }
2586
2587 const Expr *Init = VD->getAnyInitializer();
2588 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2589 llvm::Constant *Ctor;
2590 llvm::Constant *ID;
2591 if (CGM.getLangOpts().OpenMPIsDevice) {
2592 // Generate function that re-emits the declaration's initializer into
2593 // the threadprivate copy of the variable VD
2594 CodeGenFunction CtorCGF(CGM);
2595
2596 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2597 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2598 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2599 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2600 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2601 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2602 FunctionArgList(), Loc, Loc);
2603 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2604 CtorCGF.EmitAnyExprToMem(Init,
2605 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2606 Init->getType().getQualifiers(),
2607 /*IsInitializer=*/true);
2608 CtorCGF.FinishFunction();
2609 Ctor = Fn;
2610 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2611 } else {
2612 Ctor = new llvm::GlobalVariable(
2613 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2614 llvm::GlobalValue::PrivateLinkage,
2615 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2616 ID = Ctor;
2617 }
2618
2619 // Register the information for the entry associated with the constructor.
2620 Out.clear();
2621 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2622 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002623 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002624 }
2625 if (VD->getType().isDestructedType() != QualType::DK_none) {
2626 llvm::Constant *Dtor;
2627 llvm::Constant *ID;
2628 if (CGM.getLangOpts().OpenMPIsDevice) {
2629 // Generate function that emits destructor call for the threadprivate
2630 // copy of the variable VD
2631 CodeGenFunction DtorCGF(CGM);
2632
2633 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2634 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2635 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2636 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2637 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2638 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2639 FunctionArgList(), Loc, Loc);
2640 // Create a scope with an artificial location for the body of this
2641 // function.
2642 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2643 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2644 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2645 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2646 DtorCGF.FinishFunction();
2647 Dtor = Fn;
2648 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2649 } else {
2650 Dtor = new llvm::GlobalVariable(
2651 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2652 llvm::GlobalValue::PrivateLinkage,
2653 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2654 ID = Dtor;
2655 }
2656 // Register the information for the entry associated with the destructor.
2657 Out.clear();
2658 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2659 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002660 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002661 }
2662 return CGM.getLangOpts().OpenMPIsDevice;
2663}
2664
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002665Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2666 QualType VarType,
2667 StringRef Name) {
2668 llvm::Twine VarName(Name, ".artificial.");
2669 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2670 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2671 llvm::Value *Args[] = {
2672 emitUpdateLocation(CGF, SourceLocation()),
2673 getThreadID(CGF, SourceLocation()),
2674 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2675 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2676 /*IsSigned=*/false),
2677 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2678 return Address(
2679 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2680 CGF.EmitRuntimeCall(
2681 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2682 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2683 CGM.getPointerAlign());
2684}
2685
Alexey Bataev1d677132015-04-22 13:57:31 +00002686/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2687/// function. Here is the logic:
2688/// if (Cond) {
2689/// ThenGen();
2690/// } else {
2691/// ElseGen();
2692/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002693void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2694 const RegionCodeGenTy &ThenGen,
2695 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002696 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2697
2698 // If the condition constant folds and can be elided, try to avoid emitting
2699 // the condition and the dead arm of the if/else.
2700 bool CondConstant;
2701 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002702 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002703 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002704 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002705 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002706 return;
2707 }
2708
2709 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2710 // emit the conditional branch.
2711 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2712 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2713 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2714 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2715
2716 // Emit the 'then' code.
2717 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002718 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002719 CGF.EmitBranch(ContBlock);
2720 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002721 // There is no need to emit line number for unconditional branch.
2722 (void)ApplyDebugLocation::CreateEmpty(CGF);
2723 CGF.EmitBlock(ElseBlock);
2724 ElseGen(CGF);
2725 // There is no need to emit line number for unconditional branch.
2726 (void)ApplyDebugLocation::CreateEmpty(CGF);
2727 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002728 // Emit the continuation block for code after the if.
2729 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002730}
2731
Alexey Bataev1d677132015-04-22 13:57:31 +00002732void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2733 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002734 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002735 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002736 if (!CGF.HaveInsertPoint())
2737 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002738 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002739 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2740 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002741 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002742 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002743 llvm::Value *Args[] = {
2744 RTLoc,
2745 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002746 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002747 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2748 RealArgs.append(std::begin(Args), std::end(Args));
2749 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2750
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002751 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002752 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2753 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002754 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2755 PrePostActionTy &) {
2756 auto &RT = CGF.CGM.getOpenMPRuntime();
2757 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002758 // Build calls:
2759 // __kmpc_serialized_parallel(&Loc, GTid);
2760 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002761 CGF.EmitRuntimeCall(
2762 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002763
Alexey Bataev1d677132015-04-22 13:57:31 +00002764 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002765 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002766 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002767 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2768 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002769 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002770 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2771 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2772 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2773 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002774 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002775
Alexey Bataev1d677132015-04-22 13:57:31 +00002776 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002777 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002778 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002779 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2780 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002781 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002782 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002783 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002784 else {
2785 RegionCodeGenTy ThenRCG(ThenGen);
2786 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002787 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002788}
2789
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002790// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002791// thread-ID variable (it is passed in a first argument of the outlined function
2792// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2793// regular serial code region, get thread ID by calling kmp_int32
2794// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2795// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002796Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2797 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002798 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002799 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002800 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002801 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002802
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002803 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002804 auto Int32Ty =
2805 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2806 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2807 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002808 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002809
2810 return ThreadIDTemp;
2811}
2812
Alexey Bataev97720002014-11-11 04:05:39 +00002813llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002814CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002815 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002816 SmallString<256> Buffer;
2817 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002818 Out << Name;
2819 auto RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002820 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002821 if (Elem.second) {
2822 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002823 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002824 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002825 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002826
David Blaikie13156b62014-11-19 03:06:06 +00002827 return Elem.second = new llvm::GlobalVariable(
2828 CGM.getModule(), Ty, /*IsConstant*/ false,
2829 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2830 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002831}
2832
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002833llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002834 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002835 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002836}
2837
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002838namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002839/// Common pre(post)-action for different OpenMP constructs.
2840class CommonActionTy final : public PrePostActionTy {
2841 llvm::Value *EnterCallee;
2842 ArrayRef<llvm::Value *> EnterArgs;
2843 llvm::Value *ExitCallee;
2844 ArrayRef<llvm::Value *> ExitArgs;
2845 bool Conditional;
2846 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002847
2848public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002849 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2850 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2851 bool Conditional = false)
2852 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2853 ExitArgs(ExitArgs), Conditional(Conditional) {}
2854 void Enter(CodeGenFunction &CGF) override {
2855 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2856 if (Conditional) {
2857 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2858 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2859 ContBlock = CGF.createBasicBlock("omp_if.end");
2860 // Generate the branch (If-stmt)
2861 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2862 CGF.EmitBlock(ThenBlock);
2863 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002864 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002865 void Done(CodeGenFunction &CGF) {
2866 // Emit the rest of blocks/branches
2867 CGF.EmitBranch(ContBlock);
2868 CGF.EmitBlock(ContBlock, true);
2869 }
2870 void Exit(CodeGenFunction &CGF) override {
2871 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002872 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002873};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002874} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002875
2876void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2877 StringRef CriticalName,
2878 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002879 SourceLocation Loc, const Expr *Hint) {
2880 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002881 // CriticalOpGen();
2882 // __kmpc_end_critical(ident_t *, gtid, Lock);
2883 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002884 if (!CGF.HaveInsertPoint())
2885 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002886 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2887 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002888 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2889 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002890 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002891 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2892 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2893 }
2894 CommonActionTy Action(
2895 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2896 : OMPRTL__kmpc_critical),
2897 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2898 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002899 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002900}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002901
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002902void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002903 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002904 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002905 if (!CGF.HaveInsertPoint())
2906 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002907 // if(__kmpc_master(ident_t *, gtid)) {
2908 // MasterOpGen();
2909 // __kmpc_end_master(ident_t *, gtid);
2910 // }
2911 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002912 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002913 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2914 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2915 /*Conditional=*/true);
2916 MasterOpGen.setAction(Action);
2917 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2918 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002919}
2920
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002921void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2922 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002923 if (!CGF.HaveInsertPoint())
2924 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002925 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2926 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002927 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002928 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002929 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002930 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2931 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002932}
2933
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002934void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2935 const RegionCodeGenTy &TaskgroupOpGen,
2936 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002937 if (!CGF.HaveInsertPoint())
2938 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002939 // __kmpc_taskgroup(ident_t *, gtid);
2940 // TaskgroupOpGen();
2941 // __kmpc_end_taskgroup(ident_t *, gtid);
2942 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002943 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2944 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2945 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2946 Args);
2947 TaskgroupOpGen.setAction(Action);
2948 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002949}
2950
John McCall7f416cc2015-09-08 08:05:57 +00002951/// Given an array of pointers to variables, project the address of a
2952/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002953static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2954 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002955 // Pull out the pointer to the variable.
2956 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002957 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002958 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2959
2960 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002961 Addr = CGF.Builder.CreateElementBitCast(
2962 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002963 return Addr;
2964}
2965
Alexey Bataeva63048e2015-03-23 06:18:07 +00002966static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002967 CodeGenModule &CGM, llvm::Type *ArgsType,
2968 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002969 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2970 SourceLocation Loc) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002971 auto &C = CGM.getContext();
2972 // void copy_func(void *LHSArg, void *RHSArg);
2973 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002974 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2975 ImplicitParamDecl::Other);
2976 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2977 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002978 Args.push_back(&LHSArg);
2979 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002980 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002981 auto *Fn = llvm::Function::Create(
2982 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2983 ".omp.copyprivate.copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002984 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002985 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002986 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002987 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002988 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002989 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002990 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2991 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2992 ArgsType), CGF.getPointerAlign());
2993 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2994 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2995 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002996 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2997 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2998 // ...
2999 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003000 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003001 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
3002 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3003
3004 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
3005 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3006
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003007 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
3008 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003009 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003010 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003011 CGF.FinishFunction();
3012 return Fn;
3013}
3014
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003015void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003016 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003017 SourceLocation Loc,
3018 ArrayRef<const Expr *> CopyprivateVars,
3019 ArrayRef<const Expr *> SrcExprs,
3020 ArrayRef<const Expr *> DstExprs,
3021 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003022 if (!CGF.HaveInsertPoint())
3023 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003024 assert(CopyprivateVars.size() == SrcExprs.size() &&
3025 CopyprivateVars.size() == DstExprs.size() &&
3026 CopyprivateVars.size() == AssignmentOps.size());
3027 auto &C = CGM.getContext();
3028 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003029 // if(__kmpc_single(ident_t *, gtid)) {
3030 // SingleOpGen();
3031 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003032 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003033 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003034 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3035 // <copy_func>, did_it);
3036
John McCall7f416cc2015-09-08 08:05:57 +00003037 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003038 if (!CopyprivateVars.empty()) {
3039 // int32 did_it = 0;
3040 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3041 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003042 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003043 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003044 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003045 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003046 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3047 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3048 /*Conditional=*/true);
3049 SingleOpGen.setAction(Action);
3050 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3051 if (DidIt.isValid()) {
3052 // did_it = 1;
3053 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3054 }
3055 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003056 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3057 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003058 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003059 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
3060 auto CopyprivateArrayTy =
3061 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3062 /*IndexTypeQuals=*/0);
3063 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003064 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003065 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3066 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003067 Address Elem = CGF.Builder.CreateConstArrayGEP(
3068 CopyprivateList, I, CGF.getPointerSize());
3069 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003070 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003071 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3072 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003073 }
3074 // Build function that copies private values from single region to all other
3075 // threads in the corresponding parallel region.
3076 auto *CpyFn = emitCopyprivateCopyFunction(
3077 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003078 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003079 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003080 Address CL =
3081 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3082 CGF.VoidPtrTy);
3083 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003084 llvm::Value *Args[] = {
3085 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3086 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003087 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003088 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003089 CpyFn, // void (*) (void *, void *) <copy_func>
3090 DidItVal // i32 did_it
3091 };
3092 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3093 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003094}
3095
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003096void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3097 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003098 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003099 if (!CGF.HaveInsertPoint())
3100 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003101 // __kmpc_ordered(ident_t *, gtid);
3102 // OrderedOpGen();
3103 // __kmpc_end_ordered(ident_t *, gtid);
3104 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003105 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003106 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003107 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3108 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3109 Args);
3110 OrderedOpGen.setAction(Action);
3111 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3112 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003113 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003114 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003115}
3116
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003117void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003118 OpenMPDirectiveKind Kind, bool EmitChecks,
3119 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003120 if (!CGF.HaveInsertPoint())
3121 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003122 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003123 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003124 unsigned Flags;
3125 if (Kind == OMPD_for)
3126 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3127 else if (Kind == OMPD_sections)
3128 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3129 else if (Kind == OMPD_single)
3130 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3131 else if (Kind == OMPD_barrier)
3132 Flags = OMP_IDENT_BARRIER_EXPL;
3133 else
3134 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003135 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3136 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003137 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3138 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003139 if (auto *OMPRegionInfo =
3140 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003141 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003142 auto *Result = CGF.EmitRuntimeCall(
3143 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003144 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003145 // if (__kmpc_cancel_barrier()) {
3146 // exit from construct;
3147 // }
3148 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3149 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3150 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3151 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3152 CGF.EmitBlock(ExitBB);
3153 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003154 auto CancelDestination =
3155 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003156 CGF.EmitBranchThroughCleanup(CancelDestination);
3157 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3158 }
3159 return;
3160 }
3161 }
3162 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003163}
3164
Alexander Musmanc6388682014-12-15 07:07:06 +00003165/// \brief Map the OpenMP loop schedule to the runtime enumeration.
3166static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003167 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003168 switch (ScheduleKind) {
3169 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003170 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3171 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003172 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003173 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003174 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003175 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003176 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003177 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3178 case OMPC_SCHEDULE_auto:
3179 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003180 case OMPC_SCHEDULE_unknown:
3181 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003182 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003183 }
3184 llvm_unreachable("Unexpected runtime schedule");
3185}
3186
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003187/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3188static OpenMPSchedType
3189getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3190 // only static is allowed for dist_schedule
3191 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3192}
3193
Alexander Musmanc6388682014-12-15 07:07:06 +00003194bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3195 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003196 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003197 return Schedule == OMP_sch_static;
3198}
3199
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003200bool CGOpenMPRuntime::isStaticNonchunked(
3201 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3202 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3203 return Schedule == OMP_dist_sch_static;
3204}
3205
3206
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003207bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003208 auto Schedule =
3209 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003210 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3211 return Schedule != OMP_sch_static;
3212}
3213
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003214static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3215 OpenMPScheduleClauseModifier M1,
3216 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003217 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003218 switch (M1) {
3219 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003220 Modifier = OMP_sch_modifier_monotonic;
3221 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003222 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003223 Modifier = OMP_sch_modifier_nonmonotonic;
3224 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003225 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003226 if (Schedule == OMP_sch_static_chunked)
3227 Schedule = OMP_sch_static_balanced_chunked;
3228 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003229 case OMPC_SCHEDULE_MODIFIER_last:
3230 case OMPC_SCHEDULE_MODIFIER_unknown:
3231 break;
3232 }
3233 switch (M2) {
3234 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003235 Modifier = OMP_sch_modifier_monotonic;
3236 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003237 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003238 Modifier = OMP_sch_modifier_nonmonotonic;
3239 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003240 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003241 if (Schedule == OMP_sch_static_chunked)
3242 Schedule = OMP_sch_static_balanced_chunked;
3243 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003244 case OMPC_SCHEDULE_MODIFIER_last:
3245 case OMPC_SCHEDULE_MODIFIER_unknown:
3246 break;
3247 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003248 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003249}
3250
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003251void CGOpenMPRuntime::emitForDispatchInit(
3252 CodeGenFunction &CGF, SourceLocation Loc,
3253 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3254 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003255 if (!CGF.HaveInsertPoint())
3256 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003257 OpenMPSchedType Schedule = getRuntimeSchedule(
3258 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003259 assert(Ordered ||
3260 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003261 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3262 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003263 // Call __kmpc_dispatch_init(
3264 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3265 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3266 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003267
John McCall7f416cc2015-09-08 08:05:57 +00003268 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003269 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3270 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003271 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003272 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3273 CGF.Builder.getInt32(addMonoNonMonoModifier(
3274 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003275 DispatchValues.LB, // Lower
3276 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003277 CGF.Builder.getIntN(IVSize, 1), // Stride
3278 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003279 };
3280 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3281}
3282
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003283static void emitForStaticInitCall(
3284 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3285 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3286 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003287 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003288 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003289 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003290
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003291 assert(!Values.Ordered);
3292 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3293 Schedule == OMP_sch_static_balanced_chunked ||
3294 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3295 Schedule == OMP_dist_sch_static ||
3296 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003297
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003298 // Call __kmpc_for_static_init(
3299 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3300 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3301 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3302 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3303 llvm::Value *Chunk = Values.Chunk;
3304 if (Chunk == nullptr) {
3305 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3306 Schedule == OMP_dist_sch_static) &&
3307 "expected static non-chunked schedule");
3308 // If the Chunk was not specified in the clause - use default value 1.
3309 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3310 } else {
3311 assert((Schedule == OMP_sch_static_chunked ||
3312 Schedule == OMP_sch_static_balanced_chunked ||
3313 Schedule == OMP_ord_static_chunked ||
3314 Schedule == OMP_dist_sch_static_chunked) &&
3315 "expected static chunked schedule");
3316 }
3317 llvm::Value *Args[] = {
3318 UpdateLocation,
3319 ThreadId,
3320 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3321 M2)), // Schedule type
3322 Values.IL.getPointer(), // &isLastIter
3323 Values.LB.getPointer(), // &LB
3324 Values.UB.getPointer(), // &UB
3325 Values.ST.getPointer(), // &Stride
3326 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3327 Chunk // Chunk
3328 };
3329 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003330}
3331
John McCall7f416cc2015-09-08 08:05:57 +00003332void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3333 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003334 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003335 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003336 const StaticRTInput &Values) {
3337 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3338 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3339 assert(isOpenMPWorksharingDirective(DKind) &&
3340 "Expected loop-based or sections-based directive.");
3341 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3342 isOpenMPLoopDirective(DKind)
3343 ? OMP_IDENT_WORK_LOOP
3344 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003345 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003346 auto *StaticInitFunction =
3347 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003348 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003349 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003350}
John McCall7f416cc2015-09-08 08:05:57 +00003351
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003352void CGOpenMPRuntime::emitDistributeStaticInit(
3353 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003354 OpenMPDistScheduleClauseKind SchedKind,
3355 const CGOpenMPRuntime::StaticRTInput &Values) {
3356 OpenMPSchedType ScheduleNum =
3357 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3358 auto *UpdatedLocation =
3359 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003360 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003361 auto *StaticInitFunction =
3362 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003363 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3364 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003365 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003366}
3367
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003368void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003369 SourceLocation Loc,
3370 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003371 if (!CGF.HaveInsertPoint())
3372 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003373 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003374 llvm::Value *Args[] = {
3375 emitUpdateLocation(CGF, Loc,
3376 isOpenMPDistributeDirective(DKind)
3377 ? OMP_IDENT_WORK_DISTRIBUTE
3378 : isOpenMPLoopDirective(DKind)
3379 ? OMP_IDENT_WORK_LOOP
3380 : OMP_IDENT_WORK_SECTIONS),
3381 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003382 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3383 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003384}
3385
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003386void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3387 SourceLocation Loc,
3388 unsigned IVSize,
3389 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003390 if (!CGF.HaveInsertPoint())
3391 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003392 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003393 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003394 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3395}
3396
Alexander Musman92bdaab2015-03-12 13:37:50 +00003397llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3398 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003399 bool IVSigned, Address IL,
3400 Address LB, Address UB,
3401 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003402 // Call __kmpc_dispatch_next(
3403 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3404 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3405 // kmp_int[32|64] *p_stride);
3406 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003407 emitUpdateLocation(CGF, Loc),
3408 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003409 IL.getPointer(), // &isLastIter
3410 LB.getPointer(), // &Lower
3411 UB.getPointer(), // &Upper
3412 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003413 };
3414 llvm::Value *Call =
3415 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3416 return CGF.EmitScalarConversion(
3417 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003418 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003419}
3420
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003421void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3422 llvm::Value *NumThreads,
3423 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003424 if (!CGF.HaveInsertPoint())
3425 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003426 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3427 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003428 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003429 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003430 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3431 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003432}
3433
Alexey Bataev7f210c62015-06-18 13:40:03 +00003434void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3435 OpenMPProcBindClauseKind ProcBind,
3436 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003437 if (!CGF.HaveInsertPoint())
3438 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003439 // Constants for proc bind value accepted by the runtime.
3440 enum ProcBindTy {
3441 ProcBindFalse = 0,
3442 ProcBindTrue,
3443 ProcBindMaster,
3444 ProcBindClose,
3445 ProcBindSpread,
3446 ProcBindIntel,
3447 ProcBindDefault
3448 } RuntimeProcBind;
3449 switch (ProcBind) {
3450 case OMPC_PROC_BIND_master:
3451 RuntimeProcBind = ProcBindMaster;
3452 break;
3453 case OMPC_PROC_BIND_close:
3454 RuntimeProcBind = ProcBindClose;
3455 break;
3456 case OMPC_PROC_BIND_spread:
3457 RuntimeProcBind = ProcBindSpread;
3458 break;
3459 case OMPC_PROC_BIND_unknown:
3460 llvm_unreachable("Unsupported proc_bind value.");
3461 }
3462 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3463 llvm::Value *Args[] = {
3464 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3465 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3466 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3467}
3468
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003469void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3470 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003471 if (!CGF.HaveInsertPoint())
3472 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003473 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003474 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3475 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003476}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003477
Alexey Bataev62b63b12015-03-10 07:28:44 +00003478namespace {
3479/// \brief Indexes of fields for type kmp_task_t.
3480enum KmpTaskTFields {
3481 /// \brief List of shared variables.
3482 KmpTaskTShareds,
3483 /// \brief Task routine.
3484 KmpTaskTRoutine,
3485 /// \brief Partition id for the untied tasks.
3486 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003487 /// Function with call of destructors for private variables.
3488 Data1,
3489 /// Task priority.
3490 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003491 /// (Taskloops only) Lower bound.
3492 KmpTaskTLowerBound,
3493 /// (Taskloops only) Upper bound.
3494 KmpTaskTUpperBound,
3495 /// (Taskloops only) Stride.
3496 KmpTaskTStride,
3497 /// (Taskloops only) Is last iteration flag.
3498 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003499 /// (Taskloops only) Reduction data.
3500 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003501};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003502} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003503
Samuel Antaoee8fb302016-01-06 13:42:12 +00003504bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003505 return OffloadEntriesTargetRegion.empty() &&
3506 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003507}
3508
3509/// \brief Initialize target region entry.
3510void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3511 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3512 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003513 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003514 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3515 "only required for the device "
3516 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003517 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003518 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003519 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003520 ++OffloadingEntriesNum;
3521}
3522
3523void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3524 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3525 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003526 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003527 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003528 // If we are emitting code for a target, the entry is already initialized,
3529 // only has to be registered.
3530 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003531 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003532 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003533 auto &Entry =
3534 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003535 assert(Entry.isValid() && "Entry not initialized!");
3536 Entry.setAddress(Addr);
3537 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003538 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003539 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003540 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003541 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003542 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003543 }
3544}
3545
3546bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003547 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3548 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003549 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3550 if (PerDevice == OffloadEntriesTargetRegion.end())
3551 return false;
3552 auto PerFile = PerDevice->second.find(FileID);
3553 if (PerFile == PerDevice->second.end())
3554 return false;
3555 auto PerParentName = PerFile->second.find(ParentName);
3556 if (PerParentName == PerFile->second.end())
3557 return false;
3558 auto PerLine = PerParentName->second.find(LineNum);
3559 if (PerLine == PerParentName->second.end())
3560 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003561 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003562 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003563 return false;
3564 return true;
3565}
3566
3567void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3568 const OffloadTargetRegionEntryInfoActTy &Action) {
3569 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003570 for (const auto &D : OffloadEntriesTargetRegion)
3571 for (const auto &F : D.second)
3572 for (const auto &P : F.second)
3573 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003574 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003575}
3576
Alexey Bataev03f270c2018-03-30 18:31:07 +00003577void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3578 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3579 OMPTargetGlobalVarEntryKind Flags,
3580 unsigned Order) {
3581 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3582 "only required for the device "
3583 "code generation.");
3584 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3585 ++OffloadingEntriesNum;
3586}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003587
Alexey Bataev03f270c2018-03-30 18:31:07 +00003588void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3589 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3590 CharUnits VarSize,
3591 OMPTargetGlobalVarEntryKind Flags,
3592 llvm::GlobalValue::LinkageTypes Linkage) {
3593 if (CGM.getLangOpts().OpenMPIsDevice) {
3594 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3595 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3596 "Entry not initialized!");
3597 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3598 "Resetting with the new address.");
3599 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3600 return;
3601 Entry.setAddress(Addr);
3602 Entry.setVarSize(VarSize);
3603 Entry.setLinkage(Linkage);
3604 } else {
3605 if (hasDeviceGlobalVarEntryInfo(VarName))
3606 return;
3607 OffloadEntriesDeviceGlobalVar.try_emplace(
3608 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3609 ++OffloadingEntriesNum;
3610 }
3611}
3612
3613void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3614 actOnDeviceGlobalVarEntriesInfo(
3615 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3616 // Scan all target region entries and perform the provided action.
3617 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3618 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003619}
3620
3621llvm::Function *
3622CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003623 // If we don't have entries or if we are emitting code for the device, we
3624 // don't need to do anything.
3625 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3626 return nullptr;
3627
3628 auto &M = CGM.getModule();
3629 auto &C = CGM.getContext();
3630
3631 // Get list of devices we care about
3632 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3633
3634 // We should be creating an offloading descriptor only if there are devices
3635 // specified.
3636 assert(!Devices.empty() && "No OpenMP offloading devices??");
3637
3638 // Create the external variables that will point to the begin and end of the
3639 // host entries section. These will be defined by the linker.
3640 auto *OffloadEntryTy =
3641 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3642 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3643 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003644 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003645 ".omp_offloading.entries_begin");
3646 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3647 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003648 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003649 ".omp_offloading.entries_end");
3650
3651 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003652 auto *DeviceImageTy = cast<llvm::StructType>(
3653 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003654 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003655 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003656
Alexey Bataev03f270c2018-03-30 18:31:07 +00003657 for (llvm::Triple Device : Devices) {
3658 StringRef T = Device.getTriple();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003659 auto *ImgBegin = new llvm::GlobalVariable(
3660 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003661 /*Initializer=*/nullptr,
3662 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003663 auto *ImgEnd = new llvm::GlobalVariable(
3664 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003665 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003666
John McCall6c9f1fdb2016-11-19 08:17:24 +00003667 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3668 Dev.add(ImgBegin);
3669 Dev.add(ImgEnd);
3670 Dev.add(HostEntriesBegin);
3671 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003672 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003673 }
3674
3675 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003676 llvm::GlobalVariable *DeviceImages =
3677 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3678 CGM.getPointerAlign(),
3679 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003680 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003681
3682 // This is a Zero array to be used in the creation of the constant expressions
3683 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3684 llvm::Constant::getNullValue(CGM.Int32Ty)};
3685
3686 // Create the target region descriptor.
3687 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3688 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003689 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003690 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3691 DescInit.addInt(CGM.Int32Ty, Devices.size());
3692 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3693 DeviceImages,
3694 Index));
3695 DescInit.add(HostEntriesBegin);
3696 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003697
John McCall6c9f1fdb2016-11-19 08:17:24 +00003698 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3699 CGM.getPointerAlign(),
3700 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003701
3702 // Emit code to register or unregister the descriptor at execution
3703 // startup or closing, respectively.
3704
Alexey Bataev03f270c2018-03-30 18:31:07 +00003705 llvm::Function *UnRegFn;
3706 {
3707 FunctionArgList Args;
3708 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3709 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003710
Alexey Bataev03f270c2018-03-30 18:31:07 +00003711 CodeGenFunction CGF(CGM);
3712 // Disable debug info for global (de-)initializer because they are not part
3713 // of some particular construct.
3714 CGF.disableDebugInfo();
3715 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3716 auto FTy = CGM.getTypes().GetFunctionType(FI);
3717 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(
3718 FTy, ".omp_offloading.descriptor_unreg", FI);
3719 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3720 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3721 Desc);
3722 CGF.FinishFunction();
3723 }
3724 llvm::Function *RegFn;
3725 {
3726 CodeGenFunction CGF(CGM);
3727 // Disable debug info for global (de-)initializer because they are not part
3728 // of some particular construct.
3729 CGF.disableDebugInfo();
3730 auto &FI = CGM.getTypes().arrangeNullaryFunction();
3731 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3732 RegFn = CGM.CreateGlobalInitOrDestructFunction(
3733 FTy, ".omp_offloading.descriptor_reg", FI);
3734 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3735 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3736 // Create a variable to drive the registration and unregistration of the
3737 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3738 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3739 SourceLocation(), nullptr, C.CharTy,
3740 ImplicitParamDecl::Other);
3741 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3742 CGF.FinishFunction();
3743 }
George Rokos29d0f002017-05-27 03:03:13 +00003744 if (CGM.supportsCOMDAT()) {
3745 // It is sufficient to call registration function only once, so create a
3746 // COMDAT group for registration/unregistration functions and associated
3747 // data. That would reduce startup time and code size. Registration
3748 // function serves as a COMDAT group key.
3749 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3750 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3751 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3752 RegFn->setComdat(ComdatKey);
3753 UnRegFn->setComdat(ComdatKey);
3754 DeviceImages->setComdat(ComdatKey);
3755 Desc->setComdat(ComdatKey);
3756 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003757 return RegFn;
3758}
3759
Alexey Bataev03f270c2018-03-30 18:31:07 +00003760void CGOpenMPRuntime::createOffloadEntry(
3761 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3762 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003763 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003764 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3765 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3766 llvm::LLVMContext &C = CGM.getModule().getContext();
3767 llvm::Module &M = CGM.getModule();
3768
3769 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003770 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003771
3772 // Create constant string with the name.
3773 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3774
3775 llvm::GlobalVariable *Str =
3776 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3777 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3778 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003779 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003780 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3781
John McCall6c9f1fdb2016-11-19 08:17:24 +00003782 // We can't have any padding between symbols, so we need to have 1-byte
3783 // alignment.
3784 auto Align = CharUnits::fromQuantity(1);
3785
Samuel Antaoee8fb302016-01-06 13:42:12 +00003786 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003787 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003788 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3789 EntryInit.add(AddrPtr);
3790 EntryInit.add(StrPtr);
3791 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003792 EntryInit.addInt(CGM.Int32Ty, Flags);
3793 EntryInit.addInt(CGM.Int32Ty, 0);
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00003794 llvm::GlobalVariable *Entry = EntryInit.finishAndCreateGlobal(
Alexey Bataev03f270c2018-03-30 18:31:07 +00003795 Twine(".omp_offloading.entry.", Name), Align,
3796 /*Constant=*/true, Linkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003797
3798 // The entry has to be created in the section the linker expects it to be.
3799 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003800}
3801
3802void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3803 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003804 // can easily figure out what to emit. The produced metadata looks like
3805 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003806 //
3807 // !omp_offload.info = !{!1, ...}
3808 //
3809 // Right now we only generate metadata for function that contain target
3810 // regions.
3811
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003812 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003813 if (OffloadEntriesInfoManager.empty())
3814 return;
3815
3816 llvm::Module &M = CGM.getModule();
3817 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003818 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003819 OrderedEntries(OffloadEntriesInfoManager.size());
3820
Simon Pilgrim2c518802017-03-30 14:13:19 +00003821 // Auxiliary methods to create metadata values and strings.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003822 auto &&GetMDInt = [&C](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003823 return llvm::ConstantAsMetadata::get(
Alexey Bataev34f8a702018-03-28 14:28:54 +00003824 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003825 };
3826
Alexey Bataev03f270c2018-03-30 18:31:07 +00003827 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3828
3829 // Create the offloading info metadata node.
3830 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003831
3832 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003833 auto &&TargetRegionMetadataEmitter =
3834 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3835 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3836 unsigned Line,
3837 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3838 // Generate metadata for target regions. Each entry of this metadata
3839 // contains:
3840 // - Entry 0 -> Kind of this type of metadata (0).
3841 // - Entry 1 -> Device ID of the file where the entry was identified.
3842 // - Entry 2 -> File ID of the file where the entry was identified.
3843 // - Entry 3 -> Mangled name of the function where the entry was
3844 // identified.
3845 // - Entry 4 -> Line in the file where the entry was identified.
3846 // - Entry 5 -> Order the entry was created.
3847 // The first element of the metadata node is the kind.
3848 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3849 GetMDInt(FileID), GetMDString(ParentName),
3850 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003851
Alexey Bataev03f270c2018-03-30 18:31:07 +00003852 // Save this entry in the right position of the ordered entries array.
3853 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003854
Alexey Bataev03f270c2018-03-30 18:31:07 +00003855 // Add metadata to the named metadata node.
3856 MD->addOperand(llvm::MDNode::get(C, Ops));
3857 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003858
3859 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3860 TargetRegionMetadataEmitter);
3861
Alexey Bataev03f270c2018-03-30 18:31:07 +00003862 // Create function that emits metadata for each device global variable entry;
3863 auto &&DeviceGlobalVarMetadataEmitter =
3864 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3865 MD](StringRef MangledName,
3866 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3867 &E) {
3868 // Generate metadata for global variables. Each entry of this metadata
3869 // contains:
3870 // - Entry 0 -> Kind of this type of metadata (1).
3871 // - Entry 1 -> Mangled name of the variable.
3872 // - Entry 2 -> Declare target kind.
3873 // - Entry 3 -> Order the entry was created.
3874 // The first element of the metadata node is the kind.
3875 llvm::Metadata *Ops[] = {
3876 GetMDInt(E.getKind()), GetMDString(MangledName),
3877 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3878
3879 // Save this entry in the right position of the ordered entries array.
3880 OrderedEntries[E.getOrder()] = &E;
3881
3882 // Add metadata to the named metadata node.
3883 MD->addOperand(llvm::MDNode::get(C, Ops));
3884 };
3885
3886 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3887 DeviceGlobalVarMetadataEmitter);
3888
3889 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003890 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003891 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003892 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3893 E)) {
3894 assert(CE->getID() && CE->getAddress() &&
3895 "Entry ID and Addr are invalid!");
Alexey Bataev34f8a702018-03-28 14:28:54 +00003896 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003897 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3898 } else if (const auto *CE =
3899 dyn_cast<OffloadEntriesInfoManagerTy::
3900 OffloadEntryInfoDeviceGlobalVar>(E)) {
3901 assert(CE->getAddress() && "Entry Addr is invalid!");
3902 createOffloadEntry(CE->getAddress(), CE->getAddress(),
3903 CE->getVarSize().getQuantity(), CE->getFlags(),
3904 CE->getLinkage());
3905 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003906 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003907 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003908 }
3909}
3910
3911/// \brief Loads all the offload entries information from the host IR
3912/// metadata.
3913void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3914 // If we are in target mode, load the metadata from the host IR. This code has
3915 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3916
3917 if (!CGM.getLangOpts().OpenMPIsDevice)
3918 return;
3919
3920 if (CGM.getLangOpts().OMPHostIRFile.empty())
3921 return;
3922
3923 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3924 if (Buf.getError())
3925 return;
3926
3927 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003928 auto ME = expectedToErrorOrAndEmitErrors(
3929 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003930
3931 if (ME.getError())
3932 return;
3933
3934 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3935 if (!MD)
3936 return;
3937
George Burgess IV00f70bd2018-03-01 05:43:23 +00003938 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003939 auto GetMDInt = [MN](unsigned Idx) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003940 llvm::ConstantAsMetadata *V =
3941 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3942 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3943 };
3944
Alexey Bataev03f270c2018-03-30 18:31:07 +00003945 auto GetMDString = [MN](unsigned Idx) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003946 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3947 return V->getString();
3948 };
3949
Alexey Bataev03f270c2018-03-30 18:31:07 +00003950 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003951 default:
3952 llvm_unreachable("Unexpected metadata!");
3953 break;
3954 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00003955 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003956 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00003957 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
3958 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
3959 /*Order=*/GetMDInt(5));
3960 break;
3961 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3962 OffloadingEntryInfoDeviceGlobalVar:
3963 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
3964 /*MangledName=*/GetMDString(1),
3965 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
3966 /*Flags=*/GetMDInt(2)),
3967 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003968 break;
3969 }
3970 }
3971}
3972
Alexey Bataev62b63b12015-03-10 07:28:44 +00003973void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3974 if (!KmpRoutineEntryPtrTy) {
3975 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3976 auto &C = CGM.getContext();
3977 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3978 FunctionProtoType::ExtProtoInfo EPI;
3979 KmpRoutineEntryPtrQTy = C.getPointerType(
3980 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3981 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3982 }
3983}
3984
Alexey Bataevc71a4092015-09-11 10:29:41 +00003985static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3986 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003987 auto *Field = FieldDecl::Create(
3988 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3989 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3990 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3991 Field->setAccess(AS_public);
3992 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003993 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003994}
3995
Samuel Antaoee8fb302016-01-06 13:42:12 +00003996QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3997
3998 // Make sure the type of the entry is already created. This is the type we
3999 // have to create:
4000 // struct __tgt_offload_entry{
4001 // void *addr; // Pointer to the offload entry info.
4002 // // (function or global)
4003 // char *name; // Name of the function or global.
4004 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004005 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4006 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004007 // };
4008 if (TgtOffloadEntryQTy.isNull()) {
4009 ASTContext &C = CGM.getContext();
4010 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
4011 RD->startDefinition();
4012 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4013 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4014 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004015 addFieldToRecordDecl(
4016 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4017 addFieldToRecordDecl(
4018 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004019 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004020 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004021 TgtOffloadEntryQTy = C.getRecordType(RD);
4022 }
4023 return TgtOffloadEntryQTy;
4024}
4025
4026QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4027 // These are the types we need to build:
4028 // struct __tgt_device_image{
4029 // void *ImageStart; // Pointer to the target code start.
4030 // void *ImageEnd; // Pointer to the target code end.
4031 // // We also add the host entries to the device image, as it may be useful
4032 // // for the target runtime to have access to that information.
4033 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4034 // // the entries.
4035 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4036 // // entries (non inclusive).
4037 // };
4038 if (TgtDeviceImageQTy.isNull()) {
4039 ASTContext &C = CGM.getContext();
4040 auto *RD = C.buildImplicitRecord("__tgt_device_image");
4041 RD->startDefinition();
4042 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4043 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4044 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4045 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4046 RD->completeDefinition();
4047 TgtDeviceImageQTy = C.getRecordType(RD);
4048 }
4049 return TgtDeviceImageQTy;
4050}
4051
4052QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4053 // struct __tgt_bin_desc{
4054 // int32_t NumDevices; // Number of devices supported.
4055 // __tgt_device_image *DeviceImages; // Arrays of device images
4056 // // (one per device).
4057 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4058 // // entries.
4059 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4060 // // entries (non inclusive).
4061 // };
4062 if (TgtBinaryDescriptorQTy.isNull()) {
4063 ASTContext &C = CGM.getContext();
4064 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
4065 RD->startDefinition();
4066 addFieldToRecordDecl(
4067 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4068 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4069 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4070 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4071 RD->completeDefinition();
4072 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4073 }
4074 return TgtBinaryDescriptorQTy;
4075}
4076
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004077namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004078struct PrivateHelpersTy {
4079 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4080 const VarDecl *PrivateElemInit)
4081 : Original(Original), PrivateCopy(PrivateCopy),
4082 PrivateElemInit(PrivateElemInit) {}
4083 const VarDecl *Original;
4084 const VarDecl *PrivateCopy;
4085 const VarDecl *PrivateElemInit;
4086};
4087typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004088} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004089
Alexey Bataev9e034042015-05-05 04:05:12 +00004090static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004091createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004092 if (!Privates.empty()) {
4093 auto &C = CGM.getContext();
4094 // Build struct .kmp_privates_t. {
4095 // /* private vars */
4096 // };
4097 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
4098 RD->startDefinition();
4099 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00004100 auto *VD = Pair.second.Original;
4101 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00004102 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00004103 auto *FD = addFieldToRecordDecl(C, RD, Type);
4104 if (VD->hasAttrs()) {
4105 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4106 E(VD->getAttrs().end());
4107 I != E; ++I)
4108 FD->addAttr(*I);
4109 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004110 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004111 RD->completeDefinition();
4112 return RD;
4113 }
4114 return nullptr;
4115}
4116
Alexey Bataev9e034042015-05-05 04:05:12 +00004117static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004118createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4119 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004120 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00004121 auto &C = CGM.getContext();
4122 // Build struct kmp_task_t {
4123 // void * shareds;
4124 // kmp_routine_entry_t routine;
4125 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004126 // kmp_cmplrdata_t data1;
4127 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004128 // For taskloops additional fields:
4129 // kmp_uint64 lb;
4130 // kmp_uint64 ub;
4131 // kmp_int64 st;
4132 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004133 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004134 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00004135 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
4136 UD->startDefinition();
4137 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4138 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4139 UD->completeDefinition();
4140 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004141 auto *RD = C.buildImplicitRecord("kmp_task_t");
4142 RD->startDefinition();
4143 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4144 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4145 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004146 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4147 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004148 if (isOpenMPTaskLoopDirective(Kind)) {
4149 QualType KmpUInt64Ty =
4150 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4151 QualType KmpInt64Ty =
4152 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4153 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4154 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4155 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4156 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004157 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004158 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004159 RD->completeDefinition();
4160 return RD;
4161}
4162
4163static RecordDecl *
4164createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004165 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004166 auto &C = CGM.getContext();
4167 // Build struct kmp_task_t_with_privates {
4168 // kmp_task_t task_data;
4169 // .kmp_privates_t. privates;
4170 // };
4171 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
4172 RD->startDefinition();
4173 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004174 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
4175 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
4176 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004177 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004178 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004179}
4180
4181/// \brief Emit a proxy function which accepts kmp_task_t as the second
4182/// argument.
4183/// \code
4184/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004185/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004186/// For taskloops:
4187/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004188/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004189/// return 0;
4190/// }
4191/// \endcode
4192static llvm::Value *
4193emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004194 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4195 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004196 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004197 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4198 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00004199 auto &C = CGM.getContext();
4200 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004201 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4202 ImplicitParamDecl::Other);
4203 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4204 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4205 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004206 Args.push_back(&GtidArg);
4207 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004208 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004209 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004210 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
4211 auto *TaskEntry =
4212 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
4213 ".omp_task_entry.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004214 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004215 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004216 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004217 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4218 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004219
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004220 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004221 // tt,
4222 // For taskloops:
4223 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4224 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004225 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004226 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004227 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4228 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4229 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004230 auto *KmpTaskTWithPrivatesQTyRD =
4231 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004232 LValue Base =
4233 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004234 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4235 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4236 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004237 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004238
4239 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
4240 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004241 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004242 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004243 CGF.ConvertTypeForMem(SharedsPtrTy));
4244
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004245 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4246 llvm::Value *PrivatesParam;
4247 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
4248 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
4249 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004250 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004251 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004252 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004253
Alexey Bataev7292c292016-04-25 12:22:29 +00004254 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4255 TaskPrivatesMap,
4256 CGF.Builder
4257 .CreatePointerBitCastOrAddrSpaceCast(
4258 TDBase.getAddress(), CGF.VoidPtrTy)
4259 .getPointer()};
4260 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4261 std::end(CommonArgs));
4262 if (isOpenMPTaskLoopDirective(Kind)) {
4263 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
4264 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004265 auto *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004266 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4267 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004268 auto *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004269 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4270 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004271 auto *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004272 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4273 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004274 auto *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004275 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4276 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004277 auto *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004278 CallArgs.push_back(LBParam);
4279 CallArgs.push_back(UBParam);
4280 CallArgs.push_back(StParam);
4281 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004282 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004283 }
4284 CallArgs.push_back(SharedsParam);
4285
Alexey Bataev3c595a62017-08-14 15:01:03 +00004286 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4287 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004288 CGF.EmitStoreThroughLValue(
4289 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00004290 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004291 CGF.FinishFunction();
4292 return TaskEntry;
4293}
4294
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004295static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4296 SourceLocation Loc,
4297 QualType KmpInt32Ty,
4298 QualType KmpTaskTWithPrivatesPtrQTy,
4299 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00004300 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004301 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004302 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4303 ImplicitParamDecl::Other);
4304 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4305 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4306 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004307 Args.push_back(&GtidArg);
4308 Args.push_back(&TaskTypeArg);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004309 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004310 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004311 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
4312 auto *DestructorFn =
4313 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4314 ".omp_task_destructor.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004315 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004316 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004317 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004318 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004319 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004320 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004321
Alexey Bataev31300ed2016-02-04 11:27:03 +00004322 LValue Base = CGF.EmitLoadOfPointerLValue(
4323 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4324 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004325 auto *KmpTaskTWithPrivatesQTyRD =
4326 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4327 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004328 Base = CGF.EmitLValueForField(Base, *FI);
4329 for (auto *Field :
4330 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4331 if (auto DtorKind = Field->getType().isDestructedType()) {
4332 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
4333 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4334 }
4335 }
4336 CGF.FinishFunction();
4337 return DestructorFn;
4338}
4339
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004340/// \brief Emit a privates mapping function for correct handling of private and
4341/// firstprivate variables.
4342/// \code
4343/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4344/// **noalias priv1,..., <tyn> **noalias privn) {
4345/// *priv1 = &.privates.priv1;
4346/// ...;
4347/// *privn = &.privates.privn;
4348/// }
4349/// \endcode
4350static llvm::Value *
4351emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004352 ArrayRef<const Expr *> PrivateVars,
4353 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004354 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004355 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004356 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004357 auto &C = CGM.getContext();
4358 FunctionArgList Args;
4359 ImplicitParamDecl TaskPrivatesArg(
4360 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004361 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4362 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004363 Args.push_back(&TaskPrivatesArg);
4364 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4365 unsigned Counter = 1;
4366 for (auto *E: PrivateVars) {
4367 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004368 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4369 C.getPointerType(C.getPointerType(E->getType()))
4370 .withConst()
4371 .withRestrict(),
4372 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004373 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4374 PrivateVarsPos[VD] = Counter;
4375 ++Counter;
4376 }
4377 for (auto *E : FirstprivateVars) {
4378 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004379 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4380 C.getPointerType(C.getPointerType(E->getType()))
4381 .withConst()
4382 .withRestrict(),
4383 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004384 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4385 PrivateVarsPos[VD] = Counter;
4386 ++Counter;
4387 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004388 for (auto *E: LastprivateVars) {
4389 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004390 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4391 C.getPointerType(C.getPointerType(E->getType()))
4392 .withConst()
4393 .withRestrict(),
4394 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004395 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4396 PrivateVarsPos[VD] = Counter;
4397 ++Counter;
4398 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004399 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004400 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004401 auto *TaskPrivatesMapTy =
4402 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4403 auto *TaskPrivatesMap = llvm::Function::Create(
4404 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4405 ".omp_task_privates_map.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004406 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004407 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004408 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004409 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004410 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004411 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004412 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004413 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004414
4415 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004416 LValue Base = CGF.EmitLoadOfPointerLValue(
4417 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4418 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004419 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4420 Counter = 0;
4421 for (auto *Field : PrivatesQTyRD->fields()) {
4422 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4423 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004424 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004425 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4426 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004427 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004428 ++Counter;
4429 }
4430 CGF.FinishFunction();
4431 return TaskPrivatesMap;
4432}
4433
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004434static bool stable_sort_comparator(const PrivateDataTy P1,
4435 const PrivateDataTy P2) {
4436 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004437}
4438
Alexey Bataevf93095a2016-05-05 08:46:22 +00004439/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004440static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004441 const OMPExecutableDirective &D,
4442 Address KmpTaskSharedsPtr, LValue TDBase,
4443 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4444 QualType SharedsTy, QualType SharedsPtrTy,
4445 const OMPTaskDataTy &Data,
4446 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4447 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004448 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4449 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004450 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4451 ? OMPD_taskloop
4452 : OMPD_task;
4453 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4454 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004455 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004456 bool IsTargetTask =
4457 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4458 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4459 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4460 // PointersArray and SizesArray. The original variables for these arrays are
4461 // not captured and we get their addresses explicitly.
4462 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004463 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004464 SrcBase = CGF.MakeAddrLValue(
4465 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4466 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4467 SharedsTy);
4468 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004469 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4470 for (auto &&Pair : Privates) {
4471 auto *VD = Pair.second.PrivateCopy;
4472 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004473 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4474 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004475 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004476 if (auto *Elem = Pair.second.PrivateElemInit) {
4477 auto *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004478 // Check if the variable is the target-based BasePointersArray,
4479 // PointersArray or SizesArray.
4480 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004481 QualType Type = OriginalVD->getType();
Alexey Bataev8451efa2018-01-15 19:06:12 +00004482 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4483 if (IsTargetTask && !SharedField) {
4484 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4485 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4486 cast<CapturedDecl>(OriginalVD->getDeclContext())
4487 ->getNumParams() == 0 &&
4488 isa<TranslationUnitDecl>(
4489 cast<CapturedDecl>(OriginalVD->getDeclContext())
4490 ->getDeclContext()) &&
4491 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004492 SharedRefLValue =
4493 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4494 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004495 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4496 SharedRefLValue = CGF.MakeAddrLValue(
4497 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4498 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4499 SharedRefLValue.getTBAAInfo());
4500 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004501 if (Type->isArrayType()) {
4502 // Initialize firstprivate array.
4503 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4504 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004505 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004506 } else {
4507 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004508 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004509 CGF.EmitOMPAggregateAssign(
4510 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4511 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4512 Address SrcElement) {
4513 // Clean up any temporaries needed by the initialization.
4514 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4515 InitScope.addPrivate(
4516 Elem, [SrcElement]() -> Address { return SrcElement; });
4517 (void)InitScope.Privatize();
4518 // Emit initialization for single element.
4519 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4520 CGF, &CapturesInfo);
4521 CGF.EmitAnyExprToMem(Init, DestElement,
4522 Init->getType().getQualifiers(),
4523 /*IsInitializer=*/false);
4524 });
4525 }
4526 } else {
4527 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4528 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4529 return SharedRefLValue.getAddress();
4530 });
4531 (void)InitScope.Privatize();
4532 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4533 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4534 /*capturedByInit=*/false);
4535 }
4536 } else
4537 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4538 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004539 ++FI;
4540 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004541}
4542
4543/// Check if duplication function is required for taskloops.
4544static bool checkInitIsRequired(CodeGenFunction &CGF,
4545 ArrayRef<PrivateDataTy> Privates) {
4546 bool InitRequired = false;
4547 for (auto &&Pair : Privates) {
4548 auto *VD = Pair.second.PrivateCopy;
4549 auto *Init = VD->getAnyInitializer();
4550 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4551 !CGF.isTrivialInitializer(Init));
4552 }
4553 return InitRequired;
4554}
4555
4556
4557/// Emit task_dup function (for initialization of
4558/// private/firstprivate/lastprivate vars and last_iter flag)
4559/// \code
4560/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4561/// lastpriv) {
4562/// // setup lastprivate flag
4563/// task_dst->last = lastpriv;
4564/// // could be constructor calls here...
4565/// }
4566/// \endcode
4567static llvm::Value *
4568emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4569 const OMPExecutableDirective &D,
4570 QualType KmpTaskTWithPrivatesPtrQTy,
4571 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4572 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4573 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4574 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4575 auto &C = CGM.getContext();
4576 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004577 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4578 KmpTaskTWithPrivatesPtrQTy,
4579 ImplicitParamDecl::Other);
4580 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4581 KmpTaskTWithPrivatesPtrQTy,
4582 ImplicitParamDecl::Other);
4583 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4584 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004585 Args.push_back(&DstArg);
4586 Args.push_back(&SrcArg);
4587 Args.push_back(&LastprivArg);
4588 auto &TaskDupFnInfo =
4589 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4590 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4591 auto *TaskDup =
4592 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4593 ".omp_task_dup.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004594 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004595 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004596 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004597 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4598 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004599
4600 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4601 CGF.GetAddrOfLocalVar(&DstArg),
4602 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4603 // task_dst->liter = lastpriv;
4604 if (WithLastIter) {
4605 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4606 LValue Base = CGF.EmitLValueForField(
4607 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4608 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4609 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4610 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4611 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4612 }
4613
4614 // Emit initial values for private copies (if any).
4615 assert(!Privates.empty());
4616 Address KmpTaskSharedsPtr = Address::invalid();
4617 if (!Data.FirstprivateVars.empty()) {
4618 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4619 CGF.GetAddrOfLocalVar(&SrcArg),
4620 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4621 LValue Base = CGF.EmitLValueForField(
4622 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4623 KmpTaskSharedsPtr = Address(
4624 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4625 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4626 KmpTaskTShareds)),
4627 Loc),
4628 CGF.getNaturalTypeAlignment(SharedsTy));
4629 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004630 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4631 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004632 CGF.FinishFunction();
4633 return TaskDup;
4634}
4635
Alexey Bataev8a831592016-05-10 10:36:51 +00004636/// Checks if destructor function is required to be generated.
4637/// \return true if cleanups are required, false otherwise.
4638static bool
4639checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4640 bool NeedsCleanup = false;
4641 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4642 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4643 for (auto *FD : PrivateRD->fields()) {
4644 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4645 if (NeedsCleanup)
4646 break;
4647 }
4648 return NeedsCleanup;
4649}
4650
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004651CGOpenMPRuntime::TaskResultTy
4652CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4653 const OMPExecutableDirective &D,
4654 llvm::Value *TaskFunction, QualType SharedsTy,
4655 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004656 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004657 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004658 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004659 auto I = Data.PrivateCopies.begin();
4660 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004661 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004662 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004663 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004664 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004665 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004666 ++I;
4667 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004668 I = Data.FirstprivateCopies.begin();
4669 auto IElemInitRef = Data.FirstprivateInits.begin();
4670 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004671 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004672 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004673 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004674 PrivateHelpersTy(
4675 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004676 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004677 ++I;
4678 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004679 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004680 I = Data.LastprivateCopies.begin();
4681 for (auto *E : Data.LastprivateVars) {
4682 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004683 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004684 C.getDeclAlign(VD),
4685 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004686 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004687 ++I;
4688 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004689 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004690 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4691 // Build type kmp_routine_entry_t (if not built yet).
4692 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004693 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004694 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4695 if (SavedKmpTaskloopTQTy.isNull()) {
4696 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4697 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4698 }
4699 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004700 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004701 assert((D.getDirectiveKind() == OMPD_task ||
4702 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4703 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4704 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004705 if (SavedKmpTaskTQTy.isNull()) {
4706 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4707 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4708 }
4709 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004710 }
4711 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004712 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004713 auto *KmpTaskTWithPrivatesQTyRD =
4714 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4715 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4716 QualType KmpTaskTWithPrivatesPtrQTy =
4717 C.getPointerType(KmpTaskTWithPrivatesQTy);
4718 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4719 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004720 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004721 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4722
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004723 // Emit initial values for private copies (if any).
4724 llvm::Value *TaskPrivatesMap = nullptr;
4725 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004726 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004727 if (!Privates.empty()) {
4728 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004729 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4730 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4731 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004732 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4733 TaskPrivatesMap, TaskPrivatesMapTy);
4734 } else {
4735 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4736 cast<llvm::PointerType>(TaskPrivatesMapTy));
4737 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004738 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4739 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004740 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004741 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4742 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4743 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004744
4745 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4746 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4747 // kmp_routine_entry_t *task_entry);
4748 // Task flags. Format is taken from
4749 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4750 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004751 enum {
4752 TiedFlag = 0x1,
4753 FinalFlag = 0x2,
4754 DestructorsFlag = 0x8,
4755 PriorityFlag = 0x20
4756 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004757 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004758 bool NeedsCleanup = false;
4759 if (!Privates.empty()) {
4760 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4761 if (NeedsCleanup)
4762 Flags = Flags | DestructorsFlag;
4763 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004764 if (Data.Priority.getInt())
4765 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004766 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004767 Data.Final.getPointer()
4768 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004769 CGF.Builder.getInt32(FinalFlag),
4770 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004771 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004772 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004773 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004774 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4775 getThreadID(CGF, Loc), TaskFlags,
4776 KmpTaskTWithPrivatesTySize, SharedsSize,
4777 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4778 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004779 auto *NewTask = CGF.EmitRuntimeCall(
4780 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004781 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4782 NewTask, KmpTaskTWithPrivatesPtrTy);
4783 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4784 KmpTaskTWithPrivatesQTy);
4785 LValue TDBase =
4786 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004787 // Fill the data in the resulting kmp_task_t record.
4788 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004789 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004790 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004791 KmpTaskSharedsPtr =
4792 Address(CGF.EmitLoadOfScalar(
4793 CGF.EmitLValueForField(
4794 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4795 KmpTaskTShareds)),
4796 Loc),
4797 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004798 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4799 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004800 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004801 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004802 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004803 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004804 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004805 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4806 SharedsTy, SharedsPtrTy, Data, Privates,
4807 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004808 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4809 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4810 Result.TaskDupFn = emitTaskDupFunction(
4811 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4812 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4813 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004814 }
4815 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004816 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4817 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004818 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004819 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4820 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4821 if (NeedsCleanup) {
4822 llvm::Value *DestructorFn = emitDestructorsFunction(
4823 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4824 KmpTaskTWithPrivatesQTy);
4825 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4826 LValue DestructorsLV = CGF.EmitLValueForField(
4827 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4828 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4829 DestructorFn, KmpRoutineEntryPtrTy),
4830 DestructorsLV);
4831 }
4832 // Set priority.
4833 if (Data.Priority.getInt()) {
4834 LValue Data2LV = CGF.EmitLValueForField(
4835 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4836 LValue PriorityLV = CGF.EmitLValueForField(
4837 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4838 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4839 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004840 Result.NewTask = NewTask;
4841 Result.TaskEntry = TaskEntry;
4842 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4843 Result.TDBase = TDBase;
4844 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4845 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004846}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004847
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004848void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4849 const OMPExecutableDirective &D,
4850 llvm::Value *TaskFunction,
4851 QualType SharedsTy, Address Shareds,
4852 const Expr *IfCond,
4853 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004854 if (!CGF.HaveInsertPoint())
4855 return;
4856
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004857 TaskResultTy Result =
4858 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4859 llvm::Value *NewTask = Result.NewTask;
4860 llvm::Value *TaskEntry = Result.TaskEntry;
4861 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4862 LValue TDBase = Result.TDBase;
4863 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004864 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004865 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004866 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004867 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004868 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004869 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004870 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004871 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4872 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004873 QualType FlagsTy =
4874 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004875 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4876 if (KmpDependInfoTy.isNull()) {
4877 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4878 KmpDependInfoRD->startDefinition();
4879 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4880 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4881 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4882 KmpDependInfoRD->completeDefinition();
4883 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004884 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004885 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004886 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004887 // Define type kmp_depend_info[<Dependences.size()>];
4888 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004889 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004890 ArrayType::Normal, /*IndexTypeQuals=*/0);
4891 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004892 DependenciesArray =
4893 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004894 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004895 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004896 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004897 llvm::Value *Size;
4898 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004899 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4900 LValue UpAddrLVal =
4901 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4902 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004903 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004904 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004905 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004906 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4907 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004908 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004909 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004910 auto Base = CGF.MakeAddrLValue(
4911 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004912 KmpDependInfoTy);
4913 // deps[i].base_addr = &<Dependences[i].second>;
4914 auto BaseAddrLVal = CGF.EmitLValueForField(
4915 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004916 CGF.EmitStoreOfScalar(
4917 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4918 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004919 // deps[i].len = sizeof(<Dependences[i].second>);
4920 auto LenLVal = CGF.EmitLValueForField(
4921 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4922 CGF.EmitStoreOfScalar(Size, LenLVal);
4923 // deps[i].flags = <Dependences[i].first>;
4924 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004925 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004926 case OMPC_DEPEND_in:
4927 DepKind = DepIn;
4928 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004929 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004930 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004931 case OMPC_DEPEND_inout:
4932 DepKind = DepInOut;
4933 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004934 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004935 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004936 case OMPC_DEPEND_unknown:
4937 llvm_unreachable("Unknown task dependence type");
4938 }
4939 auto FlagsLVal = CGF.EmitLValueForField(
4940 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4941 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4942 FlagsLVal);
4943 }
John McCall7f416cc2015-09-08 08:05:57 +00004944 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4945 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004946 CGF.VoidPtrTy);
4947 }
4948
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004949 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00004950 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004951 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4952 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4953 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4954 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004955 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004956 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004957 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4958 llvm::Value *DepTaskArgs[7];
4959 if (NumDependencies) {
4960 DepTaskArgs[0] = UpLoc;
4961 DepTaskArgs[1] = ThreadID;
4962 DepTaskArgs[2] = NewTask;
4963 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4964 DepTaskArgs[4] = DependenciesArray.getPointer();
4965 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4966 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4967 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004968 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4969 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004970 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004971 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004972 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4973 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4974 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4975 }
John McCall7f416cc2015-09-08 08:05:57 +00004976 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004977 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004978 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004979 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004980 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004981 TaskArgs);
4982 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004983 // Check if parent region is untied and build return for untied task;
4984 if (auto *Region =
4985 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4986 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004987 };
John McCall7f416cc2015-09-08 08:05:57 +00004988
4989 llvm::Value *DepWaitTaskArgs[6];
4990 if (NumDependencies) {
4991 DepWaitTaskArgs[0] = UpLoc;
4992 DepWaitTaskArgs[1] = ThreadID;
4993 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4994 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4995 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4996 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4997 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004998 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004999 NumDependencies, &DepWaitTaskArgs,
5000 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005001 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005002 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5003 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5004 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5005 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5006 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005007 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005008 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005009 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005010 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005011 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5012 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005013 Action.Enter(CGF);
5014 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005015 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005016 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005017 };
5018
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005019 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5020 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005021 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5022 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005023 RegionCodeGenTy RCG(CodeGen);
5024 CommonActionTy Action(
5025 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5026 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5027 RCG.setAction(Action);
5028 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005029 };
John McCall7f416cc2015-09-08 08:05:57 +00005030
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005031 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00005032 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005033 else {
5034 RegionCodeGenTy ThenRCG(ThenCodeGen);
5035 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005036 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005037}
5038
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005039void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5040 const OMPLoopDirective &D,
5041 llvm::Value *TaskFunction,
5042 QualType SharedsTy, Address Shareds,
5043 const Expr *IfCond,
5044 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005045 if (!CGF.HaveInsertPoint())
5046 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005047 TaskResultTy Result =
5048 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005049 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005050 // libcall.
5051 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5052 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5053 // sched, kmp_uint64 grainsize, void *task_dup);
5054 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5055 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5056 llvm::Value *IfVal;
5057 if (IfCond) {
5058 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5059 /*isSigned=*/true);
5060 } else
5061 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
5062
5063 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005064 Result.TDBase,
5065 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00005066 auto *LBVar =
5067 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5068 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5069 /*IsInitializer=*/true);
5070 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005071 Result.TDBase,
5072 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00005073 auto *UBVar =
5074 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5075 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5076 /*IsInitializer=*/true);
5077 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005078 Result.TDBase,
5079 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00005080 auto *StVar =
5081 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5082 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5083 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005084 // Store reductions address.
5085 LValue RedLVal = CGF.EmitLValueForField(
5086 Result.TDBase,
5087 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
5088 if (Data.Reductions)
5089 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
5090 else {
5091 CGF.EmitNullInitialization(RedLVal.getAddress(),
5092 CGF.getContext().VoidPtrTy);
5093 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005094 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005095 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005096 UpLoc,
5097 ThreadID,
5098 Result.NewTask,
5099 IfVal,
5100 LBLVal.getPointer(),
5101 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005102 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005103 llvm::ConstantInt::getNullValue(
5104 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005105 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005106 CGF.IntTy, Data.Schedule.getPointer()
5107 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005108 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005109 Data.Schedule.getPointer()
5110 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005111 /*isSigned=*/false)
5112 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005113 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5114 Result.TaskDupFn, CGF.VoidPtrTy)
5115 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005116 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5117}
5118
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005119/// \brief Emit reduction operation for each element of array (required for
5120/// array sections) LHS op = RHS.
5121/// \param Type Type of array.
5122/// \param LHSVar Variable on the left side of the reduction operation
5123/// (references element of array in original variable).
5124/// \param RHSVar Variable on the right side of the reduction operation
5125/// (references element of array in original variable).
5126/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5127/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005128static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005129 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5130 const VarDecl *RHSVar,
5131 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5132 const Expr *, const Expr *)> &RedOpGen,
5133 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5134 const Expr *UpExpr = nullptr) {
5135 // Perform element-by-element initialization.
5136 QualType ElementTy;
5137 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5138 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5139
5140 // Drill down to the base element type on both arrays.
5141 auto ArrayTy = Type->getAsArrayTypeUnsafe();
5142 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
5143
5144 auto RHSBegin = RHSAddr.getPointer();
5145 auto LHSBegin = LHSAddr.getPointer();
5146 // Cast from pointer to array type to pointer to single element.
5147 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
5148 // The basic structure here is a while-do loop.
5149 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5150 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5151 auto IsEmpty =
5152 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5153 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5154
5155 // Enter the loop body, making that address the current address.
5156 auto EntryBB = CGF.Builder.GetInsertBlock();
5157 CGF.EmitBlock(BodyBB);
5158
5159 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5160
5161 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5162 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5163 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5164 Address RHSElementCurrent =
5165 Address(RHSElementPHI,
5166 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5167
5168 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5169 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5170 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5171 Address LHSElementCurrent =
5172 Address(LHSElementPHI,
5173 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5174
5175 // Emit copy.
5176 CodeGenFunction::OMPPrivateScope Scope(CGF);
5177 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
5178 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
5179 Scope.Privatize();
5180 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5181 Scope.ForceCleanup();
5182
5183 // Shift the address forward by one element.
5184 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
5185 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
5186 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
5187 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5188 // Check whether we've reached the end.
5189 auto Done =
5190 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5191 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5192 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5193 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5194
5195 // Done.
5196 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5197}
5198
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005199/// Emit reduction combiner. If the combiner is a simple expression emit it as
5200/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5201/// UDR combiner function.
5202static void emitReductionCombiner(CodeGenFunction &CGF,
5203 const Expr *ReductionOp) {
5204 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
5205 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5206 if (auto *DRE =
5207 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
5208 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
5209 std::pair<llvm::Function *, llvm::Function *> Reduction =
5210 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5211 RValue Func = RValue::get(Reduction.first);
5212 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5213 CGF.EmitIgnoredExpr(ReductionOp);
5214 return;
5215 }
5216 CGF.EmitIgnoredExpr(ReductionOp);
5217}
5218
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005219llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005220 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5221 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5222 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005223 auto &C = CGM.getContext();
5224
5225 // void reduction_func(void *LHSArg, void *RHSArg);
5226 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005227 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5228 ImplicitParamDecl::Other);
5229 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5230 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005231 Args.push_back(&LHSArg);
5232 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00005233 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005234 auto *Fn = llvm::Function::Create(
5235 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
5236 ".omp.reduction.reduction_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005237 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005238 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005239 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005240 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005241
5242 // Dst = (void*[n])(LHSArg);
5243 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005244 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5245 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5246 ArgsType), CGF.getPointerAlign());
5247 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5248 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5249 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005250
5251 // ...
5252 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5253 // ...
5254 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005255 auto IPriv = Privates.begin();
5256 unsigned Idx = 0;
5257 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005258 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5259 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005260 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005261 });
5262 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5263 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005264 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005265 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005266 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005267 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005268 // Get array size and emit VLA type.
5269 ++Idx;
5270 Address Elem =
5271 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5272 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005273 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
5274 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005275 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005276 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005277 CGF.EmitVariablyModifiedType(PrivTy);
5278 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005279 }
5280 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005281 IPriv = Privates.begin();
5282 auto ILHS = LHSExprs.begin();
5283 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005284 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005285 if ((*IPriv)->getType()->isArrayType()) {
5286 // Emit reduction for array section.
5287 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5288 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005289 EmitOMPAggregateReduction(
5290 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5291 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5292 emitReductionCombiner(CGF, E);
5293 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005294 } else
5295 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005296 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00005297 ++IPriv;
5298 ++ILHS;
5299 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005300 }
5301 Scope.ForceCleanup();
5302 CGF.FinishFunction();
5303 return Fn;
5304}
5305
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005306void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5307 const Expr *ReductionOp,
5308 const Expr *PrivateRef,
5309 const DeclRefExpr *LHS,
5310 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005311 if (PrivateRef->getType()->isArrayType()) {
5312 // Emit reduction for array section.
5313 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5314 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5315 EmitOMPAggregateReduction(
5316 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5317 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5318 emitReductionCombiner(CGF, ReductionOp);
5319 });
5320 } else
5321 // Emit reduction for array subscript or single variable.
5322 emitReductionCombiner(CGF, ReductionOp);
5323}
5324
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005325void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005326 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005327 ArrayRef<const Expr *> LHSExprs,
5328 ArrayRef<const Expr *> RHSExprs,
5329 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005330 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005331 if (!CGF.HaveInsertPoint())
5332 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005333
5334 bool WithNowait = Options.WithNowait;
5335 bool SimpleReduction = Options.SimpleReduction;
5336
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005337 // Next code should be emitted for reduction:
5338 //
5339 // static kmp_critical_name lock = { 0 };
5340 //
5341 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5342 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5343 // ...
5344 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5345 // *(Type<n>-1*)rhs[<n>-1]);
5346 // }
5347 //
5348 // ...
5349 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5350 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5351 // RedList, reduce_func, &<lock>)) {
5352 // case 1:
5353 // ...
5354 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5355 // ...
5356 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5357 // break;
5358 // case 2:
5359 // ...
5360 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5361 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005362 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005363 // break;
5364 // default:;
5365 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005366 //
5367 // if SimpleReduction is true, only the next code is generated:
5368 // ...
5369 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5370 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005371
5372 auto &C = CGM.getContext();
5373
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005374 if (SimpleReduction) {
5375 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005376 auto IPriv = Privates.begin();
5377 auto ILHS = LHSExprs.begin();
5378 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005379 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005380 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5381 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005382 ++IPriv;
5383 ++ILHS;
5384 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005385 }
5386 return;
5387 }
5388
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005389 // 1. Build a list of reduction variables.
5390 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005391 auto Size = RHSExprs.size();
5392 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005393 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005394 // Reserve place for array size.
5395 ++Size;
5396 }
5397 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005398 QualType ReductionArrayTy =
5399 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5400 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005401 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005402 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005403 auto IPriv = Privates.begin();
5404 unsigned Idx = 0;
5405 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005406 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005407 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005408 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005409 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005410 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5411 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005412 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005413 // Store array size.
5414 ++Idx;
5415 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5416 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005417 llvm::Value *Size = CGF.Builder.CreateIntCast(
5418 CGF.getVLASize(
5419 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005420 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005421 CGF.SizeTy, /*isSigned=*/false);
5422 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5423 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005424 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005425 }
5426
5427 // 2. Emit reduce_func().
5428 auto *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005429 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5430 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005431
5432 // 3. Create static kmp_critical_name lock = { 0 };
5433 auto *Lock = getCriticalRegionLock(".reduction");
5434
5435 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5436 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005437 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005438 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005439 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005440 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5441 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005442 llvm::Value *Args[] = {
5443 IdentTLoc, // ident_t *<loc>
5444 ThreadId, // i32 <gtid>
5445 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5446 ReductionArrayTySize, // size_type sizeof(RedList)
5447 RL, // void *RedList
5448 ReductionFn, // void (*) (void *, void *) <reduce_func>
5449 Lock // kmp_critical_name *&<lock>
5450 };
5451 auto Res = CGF.EmitRuntimeCall(
5452 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5453 : OMPRTL__kmpc_reduce),
5454 Args);
5455
5456 // 5. Build switch(res)
5457 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5458 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5459
5460 // 6. Build case 1:
5461 // ...
5462 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5463 // ...
5464 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5465 // break;
5466 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5467 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5468 CGF.EmitBlock(Case1BB);
5469
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005470 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5471 llvm::Value *EndArgs[] = {
5472 IdentTLoc, // ident_t *<loc>
5473 ThreadId, // i32 <gtid>
5474 Lock // kmp_critical_name *&<lock>
5475 };
5476 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5477 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005478 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005479 auto IPriv = Privates.begin();
5480 auto ILHS = LHSExprs.begin();
5481 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005482 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005483 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5484 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005485 ++IPriv;
5486 ++ILHS;
5487 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005488 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005489 };
5490 RegionCodeGenTy RCG(CodeGen);
5491 CommonActionTy Action(
5492 nullptr, llvm::None,
5493 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5494 : OMPRTL__kmpc_end_reduce),
5495 EndArgs);
5496 RCG.setAction(Action);
5497 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005498
5499 CGF.EmitBranch(DefaultBB);
5500
5501 // 7. Build case 2:
5502 // ...
5503 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5504 // ...
5505 // break;
5506 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5507 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5508 CGF.EmitBlock(Case2BB);
5509
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005510 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5511 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005512 auto ILHS = LHSExprs.begin();
5513 auto IRHS = RHSExprs.begin();
5514 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005515 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005516 const Expr *XExpr = nullptr;
5517 const Expr *EExpr = nullptr;
5518 const Expr *UpExpr = nullptr;
5519 BinaryOperatorKind BO = BO_Comma;
5520 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5521 if (BO->getOpcode() == BO_Assign) {
5522 XExpr = BO->getLHS();
5523 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005524 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005525 }
5526 // Try to emit update expression as a simple atomic.
5527 auto *RHSExpr = UpExpr;
5528 if (RHSExpr) {
5529 // Analyze RHS part of the whole expression.
5530 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5531 RHSExpr->IgnoreParenImpCasts())) {
5532 // If this is a conditional operator, analyze its condition for
5533 // min/max reduction operator.
5534 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005535 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005536 if (auto *BORHS =
5537 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5538 EExpr = BORHS->getRHS();
5539 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005540 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005541 }
5542 if (XExpr) {
5543 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005544 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005545 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5546 const Expr *EExpr, const Expr *UpExpr) {
5547 LValue X = CGF.EmitLValue(XExpr);
5548 RValue E;
5549 if (EExpr)
5550 E = CGF.EmitAnyExpr(EExpr);
5551 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005552 X, E, BO, /*IsXLHSInRHSPart=*/true,
5553 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005554 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005555 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5556 PrivateScope.addPrivate(
5557 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5558 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5559 CGF.emitOMPSimpleStore(
5560 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5561 VD->getType().getNonReferenceType(), Loc);
5562 return LHSTemp;
5563 });
5564 (void)PrivateScope.Privatize();
5565 return CGF.EmitAnyExpr(UpExpr);
5566 });
5567 };
5568 if ((*IPriv)->getType()->isArrayType()) {
5569 // Emit atomic reduction for array section.
5570 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5571 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5572 AtomicRedGen, XExpr, EExpr, UpExpr);
5573 } else
5574 // Emit atomic reduction for array subscript or single variable.
5575 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5576 } else {
5577 // Emit as a critical region.
5578 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5579 const Expr *, const Expr *) {
5580 auto &RT = CGF.CGM.getOpenMPRuntime();
5581 RT.emitCriticalRegion(
5582 CGF, ".atomic_reduction",
5583 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5584 Action.Enter(CGF);
5585 emitReductionCombiner(CGF, E);
5586 },
5587 Loc);
5588 };
5589 if ((*IPriv)->getType()->isArrayType()) {
5590 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5591 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5592 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5593 CritRedGen);
5594 } else
5595 CritRedGen(CGF, nullptr, nullptr, nullptr);
5596 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005597 ++ILHS;
5598 ++IRHS;
5599 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005600 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005601 };
5602 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5603 if (!WithNowait) {
5604 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5605 llvm::Value *EndArgs[] = {
5606 IdentTLoc, // ident_t *<loc>
5607 ThreadId, // i32 <gtid>
5608 Lock // kmp_critical_name *&<lock>
5609 };
5610 CommonActionTy Action(nullptr, llvm::None,
5611 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5612 EndArgs);
5613 AtomicRCG.setAction(Action);
5614 AtomicRCG(CGF);
5615 } else
5616 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005617
5618 CGF.EmitBranch(DefaultBB);
5619 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5620}
5621
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005622/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005623/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5624static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5625 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005626 SmallString<256> Buffer;
5627 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005628 const clang::DeclRefExpr *DE;
5629 const VarDecl *D = ::getBaseDecl(Ref, DE);
5630 if (!D)
5631 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5632 D = D->getCanonicalDecl();
5633 Out << Prefix << "."
5634 << (D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D))
5635 << "_" << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005636 return Out.str();
5637}
5638
5639/// Emits reduction initializer function:
5640/// \code
5641/// void @.red_init(void* %arg) {
5642/// %0 = bitcast void* %arg to <type>*
5643/// store <type> <init>, <type>* %0
5644/// ret void
5645/// }
5646/// \endcode
5647static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5648 SourceLocation Loc,
5649 ReductionCodeGen &RCG, unsigned N) {
5650 auto &C = CGM.getContext();
5651 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005652 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5653 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005654 Args.emplace_back(&Param);
5655 auto &FnInfo =
5656 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5657 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5658 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5659 ".red_init.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005660 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005661 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005662 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005663 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005664 Address PrivateAddr = CGF.EmitLoadOfPointer(
5665 CGF.GetAddrOfLocalVar(&Param),
5666 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5667 llvm::Value *Size = nullptr;
5668 // If the size of the reduction item is non-constant, load it from global
5669 // threadprivate variable.
5670 if (RCG.getSizes(N).second) {
5671 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5672 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005673 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005674 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5675 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005676 }
5677 RCG.emitAggregateType(CGF, N, Size);
5678 LValue SharedLVal;
5679 // If initializer uses initializer from declare reduction construct, emit a
5680 // pointer to the address of the original reduction item (reuired by reduction
5681 // initializer)
5682 if (RCG.usesReductionInitializer(N)) {
5683 Address SharedAddr =
5684 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5685 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005686 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005687 SharedAddr = CGF.EmitLoadOfPointer(
5688 SharedAddr,
5689 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005690 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5691 } else {
5692 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5693 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5694 CGM.getContext().VoidPtrTy);
5695 }
5696 // Emit the initializer:
5697 // %0 = bitcast void* %arg to <type>*
5698 // store <type> <init>, <type>* %0
5699 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5700 [](CodeGenFunction &) { return false; });
5701 CGF.FinishFunction();
5702 return Fn;
5703}
5704
5705/// Emits reduction combiner function:
5706/// \code
5707/// void @.red_comb(void* %arg0, void* %arg1) {
5708/// %lhs = bitcast void* %arg0 to <type>*
5709/// %rhs = bitcast void* %arg1 to <type>*
5710/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5711/// store <type> %2, <type>* %lhs
5712/// ret void
5713/// }
5714/// \endcode
5715static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5716 SourceLocation Loc,
5717 ReductionCodeGen &RCG, unsigned N,
5718 const Expr *ReductionOp,
5719 const Expr *LHS, const Expr *RHS,
5720 const Expr *PrivateRef) {
5721 auto &C = CGM.getContext();
5722 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5723 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5724 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005725 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5726 C.VoidPtrTy, ImplicitParamDecl::Other);
5727 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5728 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005729 Args.emplace_back(&ParamInOut);
5730 Args.emplace_back(&ParamIn);
5731 auto &FnInfo =
5732 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5733 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5734 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5735 ".red_comb.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005736 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005737 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005738 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005739 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005740 llvm::Value *Size = nullptr;
5741 // If the size of the reduction item is non-constant, load it from global
5742 // threadprivate variable.
5743 if (RCG.getSizes(N).second) {
5744 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5745 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005746 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005747 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5748 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005749 }
5750 RCG.emitAggregateType(CGF, N, Size);
5751 // Remap lhs and rhs variables to the addresses of the function arguments.
5752 // %lhs = bitcast void* %arg0 to <type>*
5753 // %rhs = bitcast void* %arg1 to <type>*
5754 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5755 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5756 // Pull out the pointer to the variable.
5757 Address PtrAddr = CGF.EmitLoadOfPointer(
5758 CGF.GetAddrOfLocalVar(&ParamInOut),
5759 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5760 return CGF.Builder.CreateElementBitCast(
5761 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5762 });
5763 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5764 // Pull out the pointer to the variable.
5765 Address PtrAddr = CGF.EmitLoadOfPointer(
5766 CGF.GetAddrOfLocalVar(&ParamIn),
5767 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5768 return CGF.Builder.CreateElementBitCast(
5769 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5770 });
5771 PrivateScope.Privatize();
5772 // Emit the combiner body:
5773 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5774 // store <type> %2, <type>* %lhs
5775 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5776 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5777 cast<DeclRefExpr>(RHS));
5778 CGF.FinishFunction();
5779 return Fn;
5780}
5781
5782/// Emits reduction finalizer function:
5783/// \code
5784/// void @.red_fini(void* %arg) {
5785/// %0 = bitcast void* %arg to <type>*
5786/// <destroy>(<type>* %0)
5787/// ret void
5788/// }
5789/// \endcode
5790static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5791 SourceLocation Loc,
5792 ReductionCodeGen &RCG, unsigned N) {
5793 if (!RCG.needCleanups(N))
5794 return nullptr;
5795 auto &C = CGM.getContext();
5796 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005797 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5798 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005799 Args.emplace_back(&Param);
5800 auto &FnInfo =
5801 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5802 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5803 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5804 ".red_fini.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005805 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005806 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005807 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005808 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005809 Address PrivateAddr = CGF.EmitLoadOfPointer(
5810 CGF.GetAddrOfLocalVar(&Param),
5811 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5812 llvm::Value *Size = nullptr;
5813 // If the size of the reduction item is non-constant, load it from global
5814 // threadprivate variable.
5815 if (RCG.getSizes(N).second) {
5816 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5817 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005818 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005819 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5820 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005821 }
5822 RCG.emitAggregateType(CGF, N, Size);
5823 // Emit the finalizer body:
5824 // <destroy>(<type>* %0)
5825 RCG.emitCleanups(CGF, N, PrivateAddr);
5826 CGF.FinishFunction();
5827 return Fn;
5828}
5829
5830llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5831 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5832 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5833 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5834 return nullptr;
5835
5836 // Build typedef struct:
5837 // kmp_task_red_input {
5838 // void *reduce_shar; // shared reduction item
5839 // size_t reduce_size; // size of data item
5840 // void *reduce_init; // data initialization routine
5841 // void *reduce_fini; // data finalization routine
5842 // void *reduce_comb; // data combiner routine
5843 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5844 // } kmp_task_red_input_t;
5845 ASTContext &C = CGM.getContext();
5846 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5847 RD->startDefinition();
5848 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5849 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5850 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5851 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5852 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5853 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5854 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5855 RD->completeDefinition();
5856 QualType RDType = C.getRecordType(RD);
5857 unsigned Size = Data.ReductionVars.size();
5858 llvm::APInt ArraySize(/*numBits=*/64, Size);
5859 QualType ArrayRDType = C.getConstantArrayType(
5860 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5861 // kmp_task_red_input_t .rd_input.[Size];
5862 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5863 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5864 Data.ReductionOps);
5865 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5866 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5867 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5868 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5869 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5870 TaskRedInput.getPointer(), Idxs,
5871 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5872 ".rd_input.gep.");
5873 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5874 // ElemLVal.reduce_shar = &Shareds[Cnt];
5875 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5876 RCG.emitSharedLValue(CGF, Cnt);
5877 llvm::Value *CastedShared =
5878 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5879 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5880 RCG.emitAggregateType(CGF, Cnt);
5881 llvm::Value *SizeValInChars;
5882 llvm::Value *SizeVal;
5883 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5884 // We use delayed creation/initialization for VLAs, array sections and
5885 // custom reduction initializations. It is required because runtime does not
5886 // provide the way to pass the sizes of VLAs/array sections to
5887 // initializer/combiner/finalizer functions and does not pass the pointer to
5888 // original reduction item to the initializer. Instead threadprivate global
5889 // variables are used to store these values and use them in the functions.
5890 bool DelayedCreation = !!SizeVal;
5891 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5892 /*isSigned=*/false);
5893 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5894 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5895 // ElemLVal.reduce_init = init;
5896 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5897 llvm::Value *InitAddr =
5898 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5899 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5900 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5901 // ElemLVal.reduce_fini = fini;
5902 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5903 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5904 llvm::Value *FiniAddr = Fini
5905 ? CGF.EmitCastToVoidPtr(Fini)
5906 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5907 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5908 // ElemLVal.reduce_comb = comb;
5909 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5910 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5911 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5912 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5913 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5914 // ElemLVal.flags = 0;
5915 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5916 if (DelayedCreation) {
5917 CGF.EmitStoreOfScalar(
5918 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5919 FlagsLVal);
5920 } else
5921 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5922 }
5923 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5924 // *data);
5925 llvm::Value *Args[] = {
5926 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5927 /*isSigned=*/true),
5928 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5929 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5930 CGM.VoidPtrTy)};
5931 return CGF.EmitRuntimeCall(
5932 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5933}
5934
5935void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5936 SourceLocation Loc,
5937 ReductionCodeGen &RCG,
5938 unsigned N) {
5939 auto Sizes = RCG.getSizes(N);
5940 // Emit threadprivate global variable if the type is non-constant
5941 // (Sizes.second = nullptr).
5942 if (Sizes.second) {
5943 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5944 /*isSigned=*/false);
5945 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5946 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005947 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005948 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5949 }
5950 // Store address of the original reduction item if custom initializer is used.
5951 if (RCG.usesReductionInitializer(N)) {
5952 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5953 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005954 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005955 CGF.Builder.CreateStore(
5956 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5957 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5958 SharedAddr, /*IsVolatile=*/false);
5959 }
5960}
5961
5962Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5963 SourceLocation Loc,
5964 llvm::Value *ReductionsPtr,
5965 LValue SharedLVal) {
5966 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5967 // *d);
5968 llvm::Value *Args[] = {
5969 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5970 /*isSigned=*/true),
5971 ReductionsPtr,
5972 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5973 CGM.VoidPtrTy)};
5974 return Address(
5975 CGF.EmitRuntimeCall(
5976 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5977 SharedLVal.getAlignment());
5978}
5979
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005980void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5981 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005982 if (!CGF.HaveInsertPoint())
5983 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005984 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5985 // global_tid);
5986 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5987 // Ignore return result until untied tasks are supported.
5988 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005989 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5990 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005991}
5992
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005993void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005994 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005995 const RegionCodeGenTy &CodeGen,
5996 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005997 if (!CGF.HaveInsertPoint())
5998 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005999 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006000 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006001}
6002
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006003namespace {
6004enum RTCancelKind {
6005 CancelNoreq = 0,
6006 CancelParallel = 1,
6007 CancelLoop = 2,
6008 CancelSections = 3,
6009 CancelTaskgroup = 4
6010};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006011} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006012
6013static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6014 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006015 if (CancelRegion == OMPD_parallel)
6016 CancelKind = CancelParallel;
6017 else if (CancelRegion == OMPD_for)
6018 CancelKind = CancelLoop;
6019 else if (CancelRegion == OMPD_sections)
6020 CancelKind = CancelSections;
6021 else {
6022 assert(CancelRegion == OMPD_taskgroup);
6023 CancelKind = CancelTaskgroup;
6024 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006025 return CancelKind;
6026}
6027
6028void CGOpenMPRuntime::emitCancellationPointCall(
6029 CodeGenFunction &CGF, SourceLocation Loc,
6030 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006031 if (!CGF.HaveInsertPoint())
6032 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006033 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6034 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006035 if (auto *OMPRegionInfo =
6036 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006037 // For 'cancellation point taskgroup', the task region info may not have a
6038 // cancel. This may instead happen in another adjacent task.
6039 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006040 llvm::Value *Args[] = {
6041 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6042 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006043 // Ignore return result until untied tasks are supported.
6044 auto *Result = CGF.EmitRuntimeCall(
6045 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6046 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006047 // exit from construct;
6048 // }
6049 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
6050 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
6051 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
6052 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6053 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006054 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006055 auto CancelDest =
6056 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006057 CGF.EmitBranchThroughCleanup(CancelDest);
6058 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6059 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006060 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006061}
6062
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006063void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006064 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006065 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006066 if (!CGF.HaveInsertPoint())
6067 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006068 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6069 // kmp_int32 cncl_kind);
6070 if (auto *OMPRegionInfo =
6071 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006072 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6073 PrePostActionTy &) {
6074 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006075 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006076 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006077 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6078 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006079 auto *Result = CGF.EmitRuntimeCall(
6080 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006081 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006082 // exit from construct;
6083 // }
6084 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
6085 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
6086 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
6087 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6088 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006089 // exit from construct;
6090 auto CancelDest =
6091 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6092 CGF.EmitBranchThroughCleanup(CancelDest);
6093 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6094 };
6095 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006096 emitOMPIfClause(CGF, IfCond, ThenGen,
6097 [](CodeGenFunction &, PrePostActionTy &) {});
6098 else {
6099 RegionCodeGenTy ThenRCG(ThenGen);
6100 ThenRCG(CGF);
6101 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006102 }
6103}
Samuel Antaobed3c462015-10-02 16:14:20 +00006104
Samuel Antaoee8fb302016-01-06 13:42:12 +00006105void CGOpenMPRuntime::emitTargetOutlinedFunction(
6106 const OMPExecutableDirective &D, StringRef ParentName,
6107 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006108 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006109 assert(!ParentName.empty() && "Invalid target region parent name!");
6110
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006111 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6112 IsOffloadEntry, CodeGen);
6113}
6114
6115void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6116 const OMPExecutableDirective &D, StringRef ParentName,
6117 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6118 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006119 // Create a unique name for the entry function using the source location
6120 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006121 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006122 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006123 //
6124 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006125 // mangled name of the function that encloses the target region and BB is the
6126 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006127
6128 unsigned DeviceID;
6129 unsigned FileID;
6130 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006131 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006132 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006133 SmallString<64> EntryFnName;
6134 {
6135 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006136 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6137 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006138 }
6139
Alexey Bataev475a7442018-01-12 19:39:11 +00006140 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006141
Samuel Antaobed3c462015-10-02 16:14:20 +00006142 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006143 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006144 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006145
Samuel Antao6d004262016-06-16 18:39:34 +00006146 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006147
6148 // If this target outline function is not an offload entry, we don't need to
6149 // register it.
6150 if (!IsOffloadEntry)
6151 return;
6152
6153 // The target region ID is used by the runtime library to identify the current
6154 // target region, so it only has to be unique and not necessarily point to
6155 // anything. It could be the pointer to the outlined function that implements
6156 // the target region, but we aren't using that so that the compiler doesn't
6157 // need to keep that, and could therefore inline the host function if proven
6158 // worthwhile during optimization. In the other hand, if emitting code for the
6159 // device, the ID has to be the function address so that it can retrieved from
6160 // the offloading entry and launched by the runtime library. We also mark the
6161 // outlined function to have external linkage in case we are emitting code for
6162 // the device, because these functions will be entry points to the device.
6163
6164 if (CGM.getLangOpts().OpenMPIsDevice) {
6165 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
6166 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006167 OutlinedFn->setDSOLocal(false);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006168 } else
6169 OutlinedFnID = new llvm::GlobalVariable(
6170 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
6171 llvm::GlobalValue::PrivateLinkage,
6172 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
6173
6174 // Register the information for the entry associated with this target region.
6175 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006176 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006177 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006178}
6179
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006180/// discard all CompoundStmts intervening between two constructs
6181static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
6182 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
6183 Body = CS->body_front();
6184
6185 return Body;
6186}
6187
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006188/// Emit the number of teams for a target directive. Inspect the num_teams
6189/// clause associated with a teams construct combined or closely nested
6190/// with the target directive.
6191///
6192/// Emit a team of size one for directives such as 'target parallel' that
6193/// have no associated teams construct.
6194///
6195/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006196static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006197emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6198 CodeGenFunction &CGF,
6199 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006200
6201 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6202 "teams directive expected to be "
6203 "emitted only for the host!");
6204
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006205 auto &Bld = CGF.Builder;
6206
6207 // If the target directive is combined with a teams directive:
6208 // Return the value in the num_teams clause, if any.
6209 // Otherwise, return 0 to denote the runtime default.
6210 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6211 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6212 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
6213 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6214 /*IgnoreResultAssign*/ true);
6215 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6216 /*IsSigned=*/true);
6217 }
6218
6219 // The default value is 0.
6220 return Bld.getInt32(0);
6221 }
6222
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006223 // If the target directive is combined with a parallel directive but not a
6224 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006225 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6226 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006227
6228 // If the current target region has a teams region enclosed, we need to get
6229 // the number of teams to pass to the runtime function call. This is done
6230 // by generating the expression in a inlined region. This is required because
6231 // the expression is captured in the enclosing target environment when the
6232 // teams directive is not combined with target.
6233
Alexey Bataev475a7442018-01-12 19:39:11 +00006234 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006235
Alexey Bataev50a1c782017-12-01 21:31:08 +00006236 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006237 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006238 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6239 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
6240 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6241 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6242 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6243 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6244 /*IsSigned=*/true);
6245 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006246
Alexey Bataev50a1c782017-12-01 21:31:08 +00006247 // If we have an enclosed teams directive but no num_teams clause we use
6248 // the default value 0.
6249 return Bld.getInt32(0);
6250 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006251 }
6252
6253 // No teams associated with the directive.
6254 return nullptr;
6255}
6256
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006257/// Emit the number of threads for a target directive. Inspect the
6258/// thread_limit clause associated with a teams construct combined or closely
6259/// nested with the target directive.
6260///
6261/// Emit the num_threads clause for directives such as 'target parallel' that
6262/// have no associated teams construct.
6263///
6264/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006265static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006266emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6267 CodeGenFunction &CGF,
6268 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006269
6270 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6271 "teams directive expected to be "
6272 "emitted only for the host!");
6273
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006274 auto &Bld = CGF.Builder;
6275
6276 //
6277 // If the target directive is combined with a teams directive:
6278 // Return the value in the thread_limit clause, if any.
6279 //
6280 // If the target directive is combined with a parallel directive:
6281 // Return the value in the num_threads clause, if any.
6282 //
6283 // If both clauses are set, select the minimum of the two.
6284 //
6285 // If neither teams or parallel combined directives set the number of threads
6286 // in a team, return 0 to denote the runtime default.
6287 //
6288 // If this is not a teams directive return nullptr.
6289
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006290 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6291 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006292 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6293 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006294 llvm::Value *ThreadLimitVal = nullptr;
6295
6296 if (const auto *ThreadLimitClause =
6297 D.getSingleClause<OMPThreadLimitClause>()) {
6298 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6299 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6300 /*IgnoreResultAssign*/ true);
6301 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6302 /*IsSigned=*/true);
6303 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006304
6305 if (const auto *NumThreadsClause =
6306 D.getSingleClause<OMPNumThreadsClause>()) {
6307 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6308 llvm::Value *NumThreads =
6309 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6310 /*IgnoreResultAssign*/ true);
6311 NumThreadsVal =
6312 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6313 }
6314
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006315 // Select the lesser of thread_limit and num_threads.
6316 if (NumThreadsVal)
6317 ThreadLimitVal = ThreadLimitVal
6318 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6319 ThreadLimitVal),
6320 NumThreadsVal, ThreadLimitVal)
6321 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006322
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006323 // Set default value passed to the runtime if either teams or a target
6324 // parallel type directive is found but no clause is specified.
6325 if (!ThreadLimitVal)
6326 ThreadLimitVal = DefaultThreadLimitVal;
6327
6328 return ThreadLimitVal;
6329 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006330
Samuel Antaob68e2db2016-03-03 16:20:23 +00006331 // If the current target region has a teams region enclosed, we need to get
6332 // the thread limit to pass to the runtime function call. This is done
6333 // by generating the expression in a inlined region. This is required because
6334 // the expression is captured in the enclosing target environment when the
6335 // teams directive is not combined with target.
6336
Alexey Bataev475a7442018-01-12 19:39:11 +00006337 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006338
Alexey Bataev50a1c782017-12-01 21:31:08 +00006339 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006340 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006341 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6342 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
6343 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6344 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6345 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6346 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6347 /*IsSigned=*/true);
6348 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006349
Alexey Bataev50a1c782017-12-01 21:31:08 +00006350 // If we have an enclosed teams directive but no thread_limit clause we
6351 // use the default value 0.
6352 return CGF.Builder.getInt32(0);
6353 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006354 }
6355
6356 // No teams associated with the directive.
6357 return nullptr;
6358}
6359
Samuel Antao86ace552016-04-27 22:40:57 +00006360namespace {
6361// \brief Utility to handle information from clauses associated with a given
6362// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6363// It provides a convenient interface to obtain the information and generate
6364// code for that information.
6365class MappableExprsHandler {
6366public:
6367 /// \brief Values for bit flags used to specify the mapping type for
6368 /// offloading.
6369 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006370 /// \brief Allocate memory on the device and move data from host to device.
6371 OMP_MAP_TO = 0x01,
6372 /// \brief Allocate memory on the device and move data from device to host.
6373 OMP_MAP_FROM = 0x02,
6374 /// \brief Always perform the requested mapping action on the element, even
6375 /// if it was already mapped before.
6376 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006377 /// \brief Delete the element from the device environment, ignoring the
6378 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006379 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006380 /// \brief The element being mapped is a pointer-pointee pair; both the
6381 /// pointer and the pointee should be mapped.
6382 OMP_MAP_PTR_AND_OBJ = 0x10,
6383 /// \brief This flags signals that the base address of an entry should be
6384 /// passed to the target kernel as an argument.
6385 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006386 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006387 /// in the current position for the data being mapped. Used when we have the
6388 /// use_device_ptr clause.
6389 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006390 /// \brief This flag signals that the reference being passed is a pointer to
6391 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006392 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006393 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006394 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006395 /// Implicit map
6396 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006397 };
6398
Samuel Antaocc10b852016-07-28 14:23:26 +00006399 /// Class that associates information with a base pointer to be passed to the
6400 /// runtime library.
6401 class BasePointerInfo {
6402 /// The base pointer.
6403 llvm::Value *Ptr = nullptr;
6404 /// The base declaration that refers to this device pointer, or null if
6405 /// there is none.
6406 const ValueDecl *DevPtrDecl = nullptr;
6407
6408 public:
6409 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6410 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6411 llvm::Value *operator*() const { return Ptr; }
6412 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6413 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6414 };
6415
6416 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006417 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006418 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006419
6420private:
6421 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006422 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006423
6424 /// \brief Function the directive is being generated for.
6425 CodeGenFunction &CGF;
6426
Samuel Antaod486f842016-05-26 16:53:38 +00006427 /// \brief Set of all first private variables in the current directive.
6428 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006429 /// Set of all reduction variables in the current directive.
6430 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006431
Samuel Antao6890b092016-07-28 14:25:09 +00006432 /// Map between device pointer declarations and their expression components.
6433 /// The key value for declarations in 'this' is null.
6434 llvm::DenseMap<
6435 const ValueDecl *,
6436 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6437 DevPointersMap;
6438
Samuel Antao86ace552016-04-27 22:40:57 +00006439 llvm::Value *getExprTypeSize(const Expr *E) const {
6440 auto ExprTy = E->getType().getCanonicalType();
6441
6442 // Reference types are ignored for mapping purposes.
6443 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6444 ExprTy = RefTy->getPointeeType().getCanonicalType();
6445
6446 // Given that an array section is considered a built-in type, we need to
6447 // do the calculation based on the length of the section instead of relying
6448 // on CGF.getTypeSize(E->getType()).
6449 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6450 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6451 OAE->getBase()->IgnoreParenImpCasts())
6452 .getCanonicalType();
6453
6454 // If there is no length associated with the expression, that means we
6455 // are using the whole length of the base.
6456 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6457 return CGF.getTypeSize(BaseTy);
6458
6459 llvm::Value *ElemSize;
6460 if (auto *PTy = BaseTy->getAs<PointerType>())
6461 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6462 else {
6463 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6464 assert(ATy && "Expecting array type if not a pointer type.");
6465 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6466 }
6467
6468 // If we don't have a length at this point, that is because we have an
6469 // array section with a single element.
6470 if (!OAE->getLength())
6471 return ElemSize;
6472
6473 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6474 LengthVal =
6475 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6476 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6477 }
6478 return CGF.getTypeSize(ExprTy);
6479 }
6480
6481 /// \brief Return the corresponding bits for a given map clause modifier. Add
6482 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006483 /// map as the first one of a series of maps that relate to the same map
6484 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006485 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006486 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006487 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006488 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006489 switch (MapType) {
6490 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006491 case OMPC_MAP_release:
6492 // alloc and release is the default behavior in the runtime library, i.e.
6493 // if we don't pass any bits alloc/release that is what the runtime is
6494 // going to do. Therefore, we don't need to signal anything for these two
6495 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006496 break;
6497 case OMPC_MAP_to:
6498 Bits = OMP_MAP_TO;
6499 break;
6500 case OMPC_MAP_from:
6501 Bits = OMP_MAP_FROM;
6502 break;
6503 case OMPC_MAP_tofrom:
6504 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6505 break;
6506 case OMPC_MAP_delete:
6507 Bits = OMP_MAP_DELETE;
6508 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006509 default:
6510 llvm_unreachable("Unexpected map type!");
6511 break;
6512 }
6513 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006514 Bits |= OMP_MAP_PTR_AND_OBJ;
6515 if (AddIsTargetParamFlag)
6516 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006517 if (MapTypeModifier == OMPC_MAP_always)
6518 Bits |= OMP_MAP_ALWAYS;
6519 return Bits;
6520 }
6521
6522 /// \brief Return true if the provided expression is a final array section. A
6523 /// final array section, is one whose length can't be proved to be one.
6524 bool isFinalArraySectionExpression(const Expr *E) const {
6525 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6526
6527 // It is not an array section and therefore not a unity-size one.
6528 if (!OASE)
6529 return false;
6530
6531 // An array section with no colon always refer to a single element.
6532 if (OASE->getColonLoc().isInvalid())
6533 return false;
6534
6535 auto *Length = OASE->getLength();
6536
6537 // If we don't have a length we have to check if the array has size 1
6538 // for this dimension. Also, we should always expect a length if the
6539 // base type is pointer.
6540 if (!Length) {
6541 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6542 OASE->getBase()->IgnoreParenImpCasts())
6543 .getCanonicalType();
6544 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6545 return ATy->getSize().getSExtValue() != 1;
6546 // If we don't have a constant dimension length, we have to consider
6547 // the current section as having any size, so it is not necessarily
6548 // unitary. If it happen to be unity size, that's user fault.
6549 return true;
6550 }
6551
6552 // Check if the length evaluates to 1.
6553 llvm::APSInt ConstLength;
6554 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6555 return true; // Can have more that size 1.
6556
6557 return ConstLength.getSExtValue() != 1;
6558 }
6559
Alexey Bataev92327c52018-03-26 16:40:55 +00006560 /// \brief Return the adjusted map modifiers if the declaration a capture
6561 /// refers to appears in a first-private clause. This is expected to be used
6562 /// only with directives that start with 'target'.
6563 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6564 unsigned CurrentModifiers) {
6565 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6566
6567 // A first private variable captured by reference will use only the
6568 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6569 // declaration is known as first-private in this handler.
6570 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6571 return MappableExprsHandler::OMP_MAP_PRIVATE |
6572 MappableExprsHandler::OMP_MAP_TO;
6573 // Reduction variable will use only the 'private ptr' and 'map to_from'
6574 // flag.
6575 if (ReductionDecls.count(Cap.getCapturedVar())) {
6576 return MappableExprsHandler::OMP_MAP_TO |
6577 MappableExprsHandler::OMP_MAP_FROM;
6578 }
6579
6580 // We didn't modify anything.
6581 return CurrentModifiers;
6582 }
6583
6584public:
6585 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6586 : CurDir(Dir), CGF(CGF) {
6587 // Extract firstprivate clause information.
6588 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6589 for (const auto *D : C->varlists())
6590 FirstPrivateDecls.insert(
6591 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6592 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
6593 for (const auto *D : C->varlists()) {
6594 ReductionDecls.insert(
6595 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6596 }
6597 }
6598 // Extract device pointer clause information.
6599 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6600 for (auto L : C->component_lists())
6601 DevPointersMap[L.first].push_back(L.second);
6602 }
6603
Samuel Antao86ace552016-04-27 22:40:57 +00006604 /// \brief Generate the base pointers, section pointers, sizes and map type
6605 /// bits for the provided map type, map modifier, and expression components.
6606 /// \a IsFirstComponent should be set to true if the provided set of
6607 /// components is the first associated with a capture.
6608 void generateInfoForComponentList(
6609 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6610 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006611 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006612 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006613 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006614
6615 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006616 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006617 // base pointer, section pointer, size, flags
6618 // (to add to the ones that come from the map type and modifier).
6619 //
6620 // double d;
6621 // int i[100];
6622 // float *p;
6623 //
6624 // struct S1 {
6625 // int i;
6626 // float f[50];
6627 // }
6628 // struct S2 {
6629 // int i;
6630 // float f[50];
6631 // S1 s;
6632 // double *p;
6633 // struct S2 *ps;
6634 // }
6635 // S2 s;
6636 // S2 *ps;
6637 //
6638 // map(d)
6639 // &d, &d, sizeof(double), noflags
6640 //
6641 // map(i)
6642 // &i, &i, 100*sizeof(int), noflags
6643 //
6644 // map(i[1:23])
6645 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6646 //
6647 // map(p)
6648 // &p, &p, sizeof(float*), noflags
6649 //
6650 // map(p[1:24])
6651 // p, &p[1], 24*sizeof(float), noflags
6652 //
6653 // map(s)
6654 // &s, &s, sizeof(S2), noflags
6655 //
6656 // map(s.i)
6657 // &s, &(s.i), sizeof(int), noflags
6658 //
6659 // map(s.s.f)
6660 // &s, &(s.i.f), 50*sizeof(int), noflags
6661 //
6662 // map(s.p)
6663 // &s, &(s.p), sizeof(double*), noflags
6664 //
6665 // map(s.p[:22], s.a s.b)
6666 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006667 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006668 //
6669 // map(s.ps)
6670 // &s, &(s.ps), sizeof(S2*), noflags
6671 //
6672 // map(s.ps->s.i)
6673 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006674 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006675 //
6676 // map(s.ps->ps)
6677 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006678 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006679 //
6680 // map(s.ps->ps->ps)
6681 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006682 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6683 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006684 //
6685 // map(s.ps->ps->s.f[:22])
6686 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006687 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6688 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006689 //
6690 // map(ps)
6691 // &ps, &ps, sizeof(S2*), noflags
6692 //
6693 // map(ps->i)
6694 // ps, &(ps->i), sizeof(int), noflags
6695 //
6696 // map(ps->s.f)
6697 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6698 //
6699 // map(ps->p)
6700 // ps, &(ps->p), sizeof(double*), noflags
6701 //
6702 // map(ps->p[:22])
6703 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006704 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006705 //
6706 // map(ps->ps)
6707 // ps, &(ps->ps), sizeof(S2*), noflags
6708 //
6709 // map(ps->ps->s.i)
6710 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006711 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006712 //
6713 // map(ps->ps->ps)
6714 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006715 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006716 //
6717 // map(ps->ps->ps->ps)
6718 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006719 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6720 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006721 //
6722 // map(ps->ps->ps->s.f[:22])
6723 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006724 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6725 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006726
6727 // Track if the map information being generated is the first for a capture.
6728 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006729 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006730
6731 // Scan the components from the base to the complete expression.
6732 auto CI = Components.rbegin();
6733 auto CE = Components.rend();
6734 auto I = CI;
6735
6736 // Track if the map information being generated is the first for a list of
6737 // components.
6738 bool IsExpressionFirstInfo = true;
6739 llvm::Value *BP = nullptr;
6740
6741 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6742 // The base is the 'this' pointer. The content of the pointer is going
6743 // to be the base of the field being mapped.
6744 BP = CGF.EmitScalarExpr(ME->getBase());
6745 } else {
6746 // The base is the reference to the variable.
6747 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006748 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataev92327c52018-03-26 16:40:55 +00006749 if (const auto *VD =
6750 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6751 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
6752 isDeclareTargetDeclaration(VD)) {
6753 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
6754 "Declare target link is expected.");
6755 // Avoid warning in release build.
6756 (void)*Res;
6757 IsLink = true;
6758 BP = CGF.CGM.getOpenMPRuntime()
Alexey Bataev03f270c2018-03-30 18:31:07 +00006759 .getAddrOfDeclareTargetLink(VD)
Alexey Bataev92327c52018-03-26 16:40:55 +00006760 .getPointer();
6761 }
6762 }
Samuel Antao86ace552016-04-27 22:40:57 +00006763
6764 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006765 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006766 // reference. References are ignored for mapping purposes.
6767 QualType Ty =
6768 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6769 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6770 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006771 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006772 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006773 .getPointer();
6774
6775 // We do not need to generate individual map information for the
6776 // pointer, it can be associated with the combined storage.
6777 ++I;
6778 }
6779 }
6780
George Rokos63bc9d62017-11-21 18:25:12 +00006781 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006782 for (; I != CE; ++I) {
6783 auto Next = std::next(I);
6784
6785 // We need to generate the addresses and sizes if this is the last
6786 // component, if the component is a pointer or if it is an array section
6787 // whose length can't be proved to be one. If this is a pointer, it
6788 // becomes the base address for the following components.
6789
6790 // A final array section, is one whose length can't be proved to be one.
6791 bool IsFinalArraySection =
6792 isFinalArraySectionExpression(I->getAssociatedExpression());
6793
6794 // Get information on whether the element is a pointer. Have to do a
6795 // special treatment for array sections given that they are built-in
6796 // types.
6797 const auto *OASE =
6798 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6799 bool IsPointer =
6800 (OASE &&
6801 OMPArraySectionExpr::getBaseOriginalType(OASE)
6802 .getCanonicalType()
6803 ->isAnyPointerType()) ||
6804 I->getAssociatedExpression()->getType()->isAnyPointerType();
6805
6806 if (Next == CE || IsPointer || IsFinalArraySection) {
6807
6808 // If this is not the last component, we expect the pointer to be
6809 // associated with an array expression or member expression.
6810 assert((Next == CE ||
6811 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6812 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6813 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6814 "Unexpected expression");
6815
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006816 llvm::Value *LB =
6817 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006818 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6819
Samuel Antao03a3cec2016-07-27 22:52:16 +00006820 // If we have a member expression and the current component is a
6821 // reference, we have to map the reference too. Whenever we have a
6822 // reference, the section that reference refers to is going to be a
6823 // load instruction from the storage assigned to the reference.
6824 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6825 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6826 auto *LI = cast<llvm::LoadInst>(LB);
6827 auto *RefAddr = LI->getPointerOperand();
6828
6829 BasePointers.push_back(BP);
6830 Pointers.push_back(RefAddr);
6831 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006832 Types.push_back(DefaultFlags |
6833 getMapTypeBits(
6834 /*MapType*/ OMPC_MAP_alloc,
6835 /*MapTypeModifier=*/OMPC_MAP_unknown,
6836 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006837 IsExpressionFirstInfo = false;
6838 IsCaptureFirstInfo = false;
6839 // The reference will be the next base address.
6840 BP = RefAddr;
6841 }
6842
6843 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006844 Pointers.push_back(LB);
6845 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006846
Samuel Antao6782e942016-05-26 16:48:10 +00006847 // We need to add a pointer flag for each map that comes from the
6848 // same expression except for the first one. We also need to signal
6849 // this map is the first one that relates with the current capture
6850 // (there is a set of entries for each capture).
Alexey Bataev92327c52018-03-26 16:40:55 +00006851 Types.push_back(DefaultFlags |
6852 getMapTypeBits(MapType, MapTypeModifier,
6853 !IsExpressionFirstInfo || IsLink,
6854 IsCaptureFirstInfo && !IsLink));
Samuel Antao86ace552016-04-27 22:40:57 +00006855
6856 // If we have a final array section, we are done with this expression.
6857 if (IsFinalArraySection)
6858 break;
6859
6860 // The pointer becomes the base for the next element.
6861 if (Next != CE)
6862 BP = LB;
6863
6864 IsExpressionFirstInfo = false;
6865 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006866 }
6867 }
6868 }
6869
Samuel Antao86ace552016-04-27 22:40:57 +00006870 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006871 /// types for the extracted mappable expressions. Also, for each item that
6872 /// relates with a device pointer, a pair of the relevant declaration and
6873 /// index where it occurs is appended to the device pointers info array.
6874 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006875 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6876 MapFlagsArrayTy &Types) const {
6877 BasePointers.clear();
6878 Pointers.clear();
6879 Sizes.clear();
6880 Types.clear();
6881
6882 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006883 /// Kind that defines how a device pointer has to be returned.
6884 enum ReturnPointerKind {
6885 // Don't have to return any pointer.
6886 RPK_None,
6887 // Pointer is the base of the declaration.
6888 RPK_Base,
6889 // Pointer is a member of the base declaration - 'this'
6890 RPK_Member,
6891 // Pointer is a reference and a member of the base declaration - 'this'
6892 RPK_MemberReference,
6893 };
Samuel Antao86ace552016-04-27 22:40:57 +00006894 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006895 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6896 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6897 ReturnPointerKind ReturnDevicePointer = RPK_None;
6898 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006899
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006900 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006901 MapInfo(
6902 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6903 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006904 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006905 : Components(Components), MapType(MapType),
6906 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006907 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006908 };
6909
6910 // We have to process the component lists that relate with the same
6911 // declaration in a single chunk so that we can generate the map flags
6912 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006913 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006914
6915 // Helper function to fill the information map for the different supported
6916 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006917 auto &&InfoGen = [&Info](
6918 const ValueDecl *D,
6919 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6920 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006921 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006922 const ValueDecl *VD =
6923 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006924 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6925 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006926 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006927
Paul Robinson78fb1322016-08-01 22:12:46 +00006928 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006929 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006930 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006931 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006932 MapInfo::RPK_None, C->isImplicit());
6933 }
Paul Robinson15c84002016-07-29 20:46:16 +00006934 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006935 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006936 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006937 MapInfo::RPK_None, C->isImplicit());
6938 }
Paul Robinson15c84002016-07-29 20:46:16 +00006939 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006940 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006941 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006942 MapInfo::RPK_None, C->isImplicit());
6943 }
Samuel Antao86ace552016-04-27 22:40:57 +00006944
Samuel Antaocc10b852016-07-28 14:23:26 +00006945 // Look at the use_device_ptr clause information and mark the existing map
6946 // entries as such. If there is no map information for an entry in the
6947 // use_device_ptr list, we create one with map type 'alloc' and zero size
6948 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006949 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006950 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006951 for (auto L : C->component_lists()) {
6952 assert(!L.second.empty() && "Not expecting empty list of components!");
6953 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6954 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6955 auto *IE = L.second.back().getAssociatedExpression();
6956 // If the first component is a member expression, we have to look into
6957 // 'this', which maps to null in the map of map information. Otherwise
6958 // look directly for the information.
6959 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6960
6961 // We potentially have map information for this declaration already.
6962 // Look for the first set of components that refer to it.
6963 if (It != Info.end()) {
6964 auto CI = std::find_if(
6965 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6966 return MI.Components.back().getAssociatedDeclaration() == VD;
6967 });
6968 // If we found a map entry, signal that the pointer has to be returned
6969 // and move on to the next declaration.
6970 if (CI != It->second.end()) {
6971 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6972 ? (VD->getType()->isReferenceType()
6973 ? MapInfo::RPK_MemberReference
6974 : MapInfo::RPK_Member)
6975 : MapInfo::RPK_Base;
6976 continue;
6977 }
6978 }
6979
6980 // We didn't find any match in our map information - generate a zero
6981 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006982 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00006983 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
6984 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00006985 BasePointers.push_back({Ptr, VD});
6986 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006987 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00006988 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00006989 }
6990
Samuel Antao86ace552016-04-27 22:40:57 +00006991 for (auto &M : Info) {
6992 // We need to know when we generate information for the first component
6993 // associated with a capture, because the mapping flags depend on it.
6994 bool IsFirstComponentList = true;
6995 for (MapInfo &L : M.second) {
6996 assert(!L.Components.empty() &&
6997 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006998
6999 // Remember the current base pointer index.
7000 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007001 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007002 this->generateInfoForComponentList(
7003 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
7004 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007005
7006 // If this entry relates with a device pointer, set the relevant
7007 // declaration and add the 'return pointer' flag.
7008 if (IsFirstComponentList &&
7009 L.ReturnDevicePointer != MapInfo::RPK_None) {
7010 // If the pointer is not the base of the map, we need to skip the
7011 // base. If it is a reference in a member field, we also need to skip
7012 // the map of the reference.
7013 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
7014 ++CurrentBasePointersIdx;
7015 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
7016 ++CurrentBasePointersIdx;
7017 }
7018 assert(BasePointers.size() > CurrentBasePointersIdx &&
7019 "Unexpected number of mapped base pointers.");
7020
7021 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
7022 assert(RelevantVD &&
7023 "No relevant declaration related with device pointer??");
7024
7025 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00007026 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007027 }
Samuel Antao86ace552016-04-27 22:40:57 +00007028 IsFirstComponentList = false;
7029 }
7030 }
7031 }
7032
7033 /// \brief Generate the base pointers, section pointers, sizes and map types
7034 /// associated to a given capture.
7035 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007036 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007037 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007038 MapValuesArrayTy &Pointers,
7039 MapValuesArrayTy &Sizes,
7040 MapFlagsArrayTy &Types) const {
7041 assert(!Cap->capturesVariableArrayType() &&
7042 "Not expecting to generate map info for a variable array type!");
7043
7044 BasePointers.clear();
7045 Pointers.clear();
7046 Sizes.clear();
7047 Types.clear();
7048
Samuel Antao6890b092016-07-28 14:25:09 +00007049 // We need to know when we generating information for the first component
7050 // associated with a capture, because the mapping flags depend on it.
7051 bool IsFirstComponentList = true;
7052
Samuel Antao86ace552016-04-27 22:40:57 +00007053 const ValueDecl *VD =
7054 Cap->capturesThis()
7055 ? nullptr
George Burgess IV00f70bd2018-03-01 05:43:23 +00007056 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007057
Samuel Antao6890b092016-07-28 14:25:09 +00007058 // If this declaration appears in a is_device_ptr clause we just have to
7059 // pass the pointer by value. If it is a reference to a declaration, we just
7060 // pass its value, otherwise, if it is a member expression, we need to map
7061 // 'to' the field.
7062 if (!VD) {
7063 auto It = DevPointersMap.find(VD);
7064 if (It != DevPointersMap.end()) {
7065 for (auto L : It->second) {
7066 generateInfoForComponentList(
7067 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007068 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
7069 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00007070 IsFirstComponentList = false;
7071 }
7072 return;
7073 }
7074 } else if (DevPointersMap.count(VD)) {
7075 BasePointers.push_back({Arg, VD});
7076 Pointers.push_back(Arg);
7077 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007078 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007079 return;
7080 }
7081
Paul Robinson78fb1322016-08-01 22:12:46 +00007082 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00007083 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00007084 for (auto L : C->decl_component_lists(VD)) {
7085 assert(L.first == VD &&
7086 "We got information for the wrong declaration??");
7087 assert(!L.second.empty() &&
7088 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007089 generateInfoForComponentList(
7090 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7091 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007092 IsFirstComponentList = false;
7093 }
7094
7095 return;
7096 }
Samuel Antaod486f842016-05-26 16:53:38 +00007097
7098 /// \brief Generate the default map information for a given capture \a CI,
7099 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007100 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7101 const FieldDecl &RI, llvm::Value *CV,
7102 MapBaseValuesArrayTy &CurBasePointers,
7103 MapValuesArrayTy &CurPointers,
7104 MapValuesArrayTy &CurSizes,
7105 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00007106
7107 // Do the default mapping.
7108 if (CI.capturesThis()) {
7109 CurBasePointers.push_back(CV);
7110 CurPointers.push_back(CV);
7111 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
7112 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7113 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007114 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007115 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007116 CurBasePointers.push_back(CV);
7117 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007118 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007119 // We have to signal to the runtime captures passed by value that are
7120 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007121 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007122 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7123 } else {
7124 // Pointers are implicitly mapped with a zero size and no flags
7125 // (other than first map that is added for all implicit maps).
7126 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00007127 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7128 }
7129 } else {
7130 assert(CI.capturesVariable() && "Expected captured reference.");
7131 CurBasePointers.push_back(CV);
7132 CurPointers.push_back(CV);
7133
7134 const ReferenceType *PtrTy =
7135 cast<ReferenceType>(RI.getType().getTypePtr());
7136 QualType ElementType = PtrTy->getPointeeType();
7137 CurSizes.push_back(CGF.getTypeSize(ElementType));
7138 // The default map type for a scalar/complex type is 'to' because by
7139 // default the value doesn't have to be retrieved. For an aggregate
7140 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00007141 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
7142 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
7143 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00007144 }
George Rokos065755d2017-11-07 18:27:04 +00007145 // Every default map produces a single argument which is a target parameter.
7146 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00007147 }
Samuel Antao86ace552016-04-27 22:40:57 +00007148};
Samuel Antaodf158d52016-04-27 22:58:19 +00007149
7150enum OpenMPOffloadingReservedDeviceIDs {
7151 /// \brief Device ID if the device was not defined, runtime should get it
7152 /// from environment variables in the spec.
7153 OMP_DEVICEID_UNDEF = -1,
7154};
7155} // anonymous namespace
7156
7157/// \brief Emit the arrays used to pass the captures and map information to the
7158/// offloading runtime library. If there is no map or capture information,
7159/// return nullptr by reference.
7160static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007161emitOffloadingArrays(CodeGenFunction &CGF,
7162 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007163 MappableExprsHandler::MapValuesArrayTy &Pointers,
7164 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007165 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7166 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007167 auto &CGM = CGF.CGM;
7168 auto &Ctx = CGF.getContext();
7169
Samuel Antaocc10b852016-07-28 14:23:26 +00007170 // Reset the array information.
7171 Info.clearArrayInfo();
7172 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007173
Samuel Antaocc10b852016-07-28 14:23:26 +00007174 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007175 // Detect if we have any capture size requiring runtime evaluation of the
7176 // size so that a constant array could be eventually used.
7177 bool hasRuntimeEvaluationCaptureSize = false;
7178 for (auto *S : Sizes)
7179 if (!isa<llvm::Constant>(S)) {
7180 hasRuntimeEvaluationCaptureSize = true;
7181 break;
7182 }
7183
Samuel Antaocc10b852016-07-28 14:23:26 +00007184 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007185 QualType PointerArrayType =
7186 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7187 /*IndexTypeQuals=*/0);
7188
Samuel Antaocc10b852016-07-28 14:23:26 +00007189 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007190 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007191 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007192 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7193
7194 // If we don't have any VLA types or other types that require runtime
7195 // evaluation, we can use a constant array for the map sizes, otherwise we
7196 // need to fill up the arrays as we do for the pointers.
7197 if (hasRuntimeEvaluationCaptureSize) {
7198 QualType SizeArrayType = Ctx.getConstantArrayType(
7199 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7200 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007201 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007202 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7203 } else {
7204 // We expect all the sizes to be constant, so we collect them to create
7205 // a constant array.
7206 SmallVector<llvm::Constant *, 16> ConstSizes;
7207 for (auto S : Sizes)
7208 ConstSizes.push_back(cast<llvm::Constant>(S));
7209
7210 auto *SizesArrayInit = llvm::ConstantArray::get(
7211 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
7212 auto *SizesArrayGbl = new llvm::GlobalVariable(
7213 CGM.getModule(), SizesArrayInit->getType(),
7214 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7215 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007216 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007217 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007218 }
7219
7220 // The map types are always constant so we don't need to generate code to
7221 // fill arrays. Instead, we create an array constant.
7222 llvm::Constant *MapTypesArrayInit =
7223 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
7224 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7225 CGM.getModule(), MapTypesArrayInit->getType(),
7226 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7227 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007228 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007229 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007230
Samuel Antaocc10b852016-07-28 14:23:26 +00007231 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
7232 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00007233 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007234 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7235 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007236 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7237 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007238 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7239 CGF.Builder.CreateStore(BPVal, BPAddr);
7240
Samuel Antaocc10b852016-07-28 14:23:26 +00007241 if (Info.requiresDevicePointerInfo())
7242 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007243 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007244
Samuel Antaodf158d52016-04-27 22:58:19 +00007245 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00007246 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007247 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7248 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007249 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7250 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007251 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7252 CGF.Builder.CreateStore(PVal, PAddr);
7253
7254 if (hasRuntimeEvaluationCaptureSize) {
7255 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007256 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7257 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007258 /*Idx0=*/0,
7259 /*Idx1=*/i);
7260 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7261 CGF.Builder.CreateStore(
7262 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
7263 SAddr);
7264 }
7265 }
7266 }
7267}
7268/// \brief Emit the arguments to be passed to the runtime library based on the
7269/// arrays of pointers, sizes and map types.
7270static void emitOffloadingArraysArgument(
7271 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7272 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007273 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007274 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007275 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007276 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007277 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7278 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007279 /*Idx0=*/0, /*Idx1=*/0);
7280 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007281 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7282 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007283 /*Idx0=*/0,
7284 /*Idx1=*/0);
7285 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007286 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007287 /*Idx0=*/0, /*Idx1=*/0);
7288 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007289 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007290 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007291 /*Idx0=*/0,
7292 /*Idx1=*/0);
7293 } else {
7294 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7295 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7296 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7297 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007298 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007299 }
Samuel Antao86ace552016-04-27 22:40:57 +00007300}
7301
Samuel Antaobed3c462015-10-02 16:14:20 +00007302void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7303 const OMPExecutableDirective &D,
7304 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007305 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007306 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007307 if (!CGF.HaveInsertPoint())
7308 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007309
Samuel Antaoee8fb302016-01-06 13:42:12 +00007310 assert(OutlinedFn && "Invalid outlined function!");
7311
Alexey Bataev8451efa2018-01-15 19:06:12 +00007312 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7313 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007314 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007315 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7316 PrePostActionTy &) {
7317 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7318 };
7319 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007320
Alexey Bataev8451efa2018-01-15 19:06:12 +00007321 CodeGenFunction::OMPTargetDataInfo InputInfo;
7322 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007323 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007324 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7325 &MapTypesArray, &CS, RequiresOuterTask,
7326 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007327 // On top of the arrays that were filled up, the target offloading call
7328 // takes as arguments the device id as well as the host pointer. The host
7329 // pointer is used by the runtime library to identify the current target
7330 // region, so it only has to be unique and not necessarily point to
7331 // anything. It could be the pointer to the outlined function that
7332 // implements the target region, but we aren't using that so that the
7333 // compiler doesn't need to keep that, and could therefore inline the host
7334 // function if proven worthwhile during optimization.
7335
Samuel Antaoee8fb302016-01-06 13:42:12 +00007336 // From this point on, we need to have an ID of the target region defined.
7337 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007338
7339 // Emit device ID if any.
7340 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007341 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007342 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007343 CGF.Int64Ty, /*isSigned=*/true);
7344 } else {
7345 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7346 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007347
Samuel Antaodf158d52016-04-27 22:58:19 +00007348 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007349 llvm::Value *PointerNum =
7350 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007351
Samuel Antaob68e2db2016-03-03 16:20:23 +00007352 // Return value of the runtime offloading call.
7353 llvm::Value *Return;
7354
Alexey Bataev8451efa2018-01-15 19:06:12 +00007355 auto *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7356 auto *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007357
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007358 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007359 // The target region is an outlined function launched by the runtime
7360 // via calls __tgt_target() or __tgt_target_teams().
7361 //
7362 // __tgt_target() launches a target region with one team and one thread,
7363 // executing a serial region. This master thread may in turn launch
7364 // more threads within its team upon encountering a parallel region,
7365 // however, no additional teams can be launched on the device.
7366 //
7367 // __tgt_target_teams() launches a target region with one or more teams,
7368 // each with one or more threads. This call is required for target
7369 // constructs such as:
7370 // 'target teams'
7371 // 'target' / 'teams'
7372 // 'target teams distribute parallel for'
7373 // 'target parallel'
7374 // and so on.
7375 //
7376 // Note that on the host and CPU targets, the runtime implementation of
7377 // these calls simply call the outlined function without forking threads.
7378 // The outlined functions themselves have runtime calls to
7379 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7380 // the compiler in emitTeamsCall() and emitParallelCall().
7381 //
7382 // In contrast, on the NVPTX target, the implementation of
7383 // __tgt_target_teams() launches a GPU kernel with the requested number
7384 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007385 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007386 // If we have NumTeams defined this means that we have an enclosed teams
7387 // region. Therefore we also expect to have NumThreads defined. These two
7388 // values should be defined in the presence of a teams directive,
7389 // regardless of having any clauses associated. If the user is using teams
7390 // but no clauses, these two values will be the default that should be
7391 // passed to the runtime library - a 32-bit integer with the value zero.
7392 assert(NumThreads && "Thread limit expression should be available along "
7393 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007394 llvm::Value *OffloadingArgs[] = {DeviceID,
7395 OutlinedFnID,
7396 PointerNum,
7397 InputInfo.BasePointersArray.getPointer(),
7398 InputInfo.PointersArray.getPointer(),
7399 InputInfo.SizesArray.getPointer(),
7400 MapTypesArray,
7401 NumTeams,
7402 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007403 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007404 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7405 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007406 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007407 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007408 llvm::Value *OffloadingArgs[] = {DeviceID,
7409 OutlinedFnID,
7410 PointerNum,
7411 InputInfo.BasePointersArray.getPointer(),
7412 InputInfo.PointersArray.getPointer(),
7413 InputInfo.SizesArray.getPointer(),
7414 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007415 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007416 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7417 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007418 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007419 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007420
Alexey Bataev2a007e02017-10-02 14:20:58 +00007421 // Check the error code and execute the host version if required.
7422 llvm::BasicBlock *OffloadFailedBlock =
7423 CGF.createBasicBlock("omp_offload.failed");
7424 llvm::BasicBlock *OffloadContBlock =
7425 CGF.createBasicBlock("omp_offload.cont");
7426 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7427 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7428
7429 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007430 if (RequiresOuterTask) {
7431 CapturedVars.clear();
7432 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7433 }
7434 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007435 CGF.EmitBranch(OffloadContBlock);
7436
7437 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007438 };
7439
Samuel Antaoee8fb302016-01-06 13:42:12 +00007440 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007441 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7442 RequiresOuterTask](CodeGenFunction &CGF,
7443 PrePostActionTy &) {
7444 if (RequiresOuterTask) {
7445 CapturedVars.clear();
7446 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7447 }
7448 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7449 };
7450
7451 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7452 &CapturedVars, RequiresOuterTask,
7453 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7454 // Fill up the arrays with all the captured variables.
7455 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7456 MappableExprsHandler::MapValuesArrayTy Pointers;
7457 MappableExprsHandler::MapValuesArrayTy Sizes;
7458 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7459
7460 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7461 MappableExprsHandler::MapValuesArrayTy CurPointers;
7462 MappableExprsHandler::MapValuesArrayTy CurSizes;
7463 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7464
7465 // Get mappable expression information.
7466 MappableExprsHandler MEHandler(D, CGF);
7467
7468 auto RI = CS.getCapturedRecordDecl()->field_begin();
7469 auto CV = CapturedVars.begin();
7470 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7471 CE = CS.capture_end();
7472 CI != CE; ++CI, ++RI, ++CV) {
7473 CurBasePointers.clear();
7474 CurPointers.clear();
7475 CurSizes.clear();
7476 CurMapTypes.clear();
7477
7478 // VLA sizes are passed to the outlined region by copy and do not have map
7479 // information associated.
7480 if (CI->capturesVariableArrayType()) {
7481 CurBasePointers.push_back(*CV);
7482 CurPointers.push_back(*CV);
7483 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7484 // Copy to the device as an argument. No need to retrieve it.
7485 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7486 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7487 } else {
7488 // If we have any information in the map clause, we use it, otherwise we
7489 // just do a default mapping.
7490 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7491 CurSizes, CurMapTypes);
7492 if (CurBasePointers.empty())
7493 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7494 CurPointers, CurSizes, CurMapTypes);
7495 }
7496 // We expect to have at least an element of information for this capture.
7497 assert(!CurBasePointers.empty() &&
7498 "Non-existing map pointer for capture!");
7499 assert(CurBasePointers.size() == CurPointers.size() &&
7500 CurBasePointers.size() == CurSizes.size() &&
7501 CurBasePointers.size() == CurMapTypes.size() &&
7502 "Inconsistent map information sizes!");
7503
7504 // We need to append the results of this capture to what we already have.
7505 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7506 Pointers.append(CurPointers.begin(), CurPointers.end());
7507 Sizes.append(CurSizes.begin(), CurSizes.end());
7508 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7509 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007510 // Map other list items in the map clause which are not captured variables
7511 // but "declare target link" global variables.
7512 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
7513 for (auto L : C->component_lists()) {
7514 if (!L.first)
7515 continue;
7516 const auto *VD = dyn_cast<VarDecl>(L.first);
7517 if (!VD)
7518 continue;
7519 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7520 isDeclareTargetDeclaration(VD);
7521 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7522 continue;
7523 MEHandler.generateInfoForComponentList(
7524 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7525 Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7526 C->isImplicit());
7527 }
7528 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00007529
7530 TargetDataInfo Info;
7531 // Fill up the arrays and create the arguments.
7532 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7533 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7534 Info.PointersArray, Info.SizesArray,
7535 Info.MapTypesArray, Info);
7536 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7537 InputInfo.BasePointersArray =
7538 Address(Info.BasePointersArray, CGM.getPointerAlign());
7539 InputInfo.PointersArray =
7540 Address(Info.PointersArray, CGM.getPointerAlign());
7541 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7542 MapTypesArray = Info.MapTypesArray;
7543 if (RequiresOuterTask)
7544 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7545 else
7546 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7547 };
7548
7549 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7550 CodeGenFunction &CGF, PrePostActionTy &) {
7551 if (RequiresOuterTask) {
7552 CodeGenFunction::OMPTargetDataInfo InputInfo;
7553 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7554 } else {
7555 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7556 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007557 };
7558
7559 // If we have a target function ID it means that we need to support
7560 // offloading, otherwise, just execute on the host. We need to execute on host
7561 // regardless of the conditional in the if clause if, e.g., the user do not
7562 // specify target triples.
7563 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007564 if (IfCond) {
7565 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7566 } else {
7567 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007568 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007569 }
7570 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007571 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007572 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007573 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007574}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007575
7576void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7577 StringRef ParentName) {
7578 if (!S)
7579 return;
7580
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007581 // Codegen OMP target directives that offload compute to the device.
7582 bool requiresDeviceCodegen =
7583 isa<OMPExecutableDirective>(S) &&
7584 isOpenMPTargetExecutionDirective(
7585 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007586
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007587 if (requiresDeviceCodegen) {
7588 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007589 unsigned DeviceID;
7590 unsigned FileID;
7591 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007592 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007593 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007594
7595 // Is this a target region that should not be emitted as an entry point? If
7596 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007597 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7598 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007599 return;
7600
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007601 switch (S->getStmtClass()) {
7602 case Stmt::OMPTargetDirectiveClass:
7603 CodeGenFunction::EmitOMPTargetDeviceFunction(
7604 CGM, ParentName, cast<OMPTargetDirective>(*S));
7605 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007606 case Stmt::OMPTargetParallelDirectiveClass:
7607 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7608 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7609 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007610 case Stmt::OMPTargetTeamsDirectiveClass:
7611 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7612 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7613 break;
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007614 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
7615 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
7616 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(*S));
7617 break;
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007618 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
7619 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
7620 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(*S));
7621 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007622 case Stmt::OMPTargetParallelForDirectiveClass:
7623 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7624 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7625 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007626 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7627 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7628 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7629 break;
Alexey Bataevf8365372017-11-17 17:57:25 +00007630 case Stmt::OMPTargetSimdDirectiveClass:
7631 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7632 CGM, ParentName, cast<OMPTargetSimdDirective>(*S));
7633 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007634 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
7635 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7636 CGM, ParentName,
7637 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
7638 break;
Alexey Bataev647dd842018-01-15 20:59:40 +00007639 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
7640 CodeGenFunction::
7641 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7642 CGM, ParentName,
7643 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
7644 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007645 default:
7646 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7647 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007648 return;
7649 }
7650
7651 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007652 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007653 return;
7654
7655 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007656 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007657 return;
7658 }
7659
7660 // If this is a lambda function, look into its body.
7661 if (auto *L = dyn_cast<LambdaExpr>(S))
7662 S = L->getBody();
7663
7664 // Keep looking for target regions recursively.
7665 for (auto *II : S->children())
7666 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007667}
7668
7669bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7670 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7671
7672 // If emitting code for the host, we do not process FD here. Instead we do
7673 // the normal code generation.
7674 if (!CGM.getLangOpts().OpenMPIsDevice)
7675 return false;
7676
7677 // Try to detect target regions in the function.
7678 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7679
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007680 // Do not to emit function if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007681 return !isDeclareTargetDeclaration(&FD);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007682}
7683
7684bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7685 if (!CGM.getLangOpts().OpenMPIsDevice)
7686 return false;
7687
7688 // Check if there are Ctors/Dtors in this declaration and look for target
7689 // regions in it. We use the complete variant to produce the kernel name
7690 // mangling.
7691 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7692 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7693 for (auto *Ctor : RD->ctors()) {
7694 StringRef ParentName =
7695 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7696 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7697 }
7698 auto *Dtor = RD->getDestructor();
7699 if (Dtor) {
7700 StringRef ParentName =
7701 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7702 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7703 }
7704 }
7705
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007706 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007707 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev03f270c2018-03-30 18:31:07 +00007708 isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
Alexey Bataev92327c52018-03-26 16:40:55 +00007709 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007710}
7711
Alexey Bataev03f270c2018-03-30 18:31:07 +00007712void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
7713 llvm::Constant *Addr) {
7714 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7715 isDeclareTargetDeclaration(VD)) {
7716 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
7717 StringRef VarName;
7718 CharUnits VarSize;
7719 llvm::GlobalValue::LinkageTypes Linkage;
7720 switch (*Res) {
7721 case OMPDeclareTargetDeclAttr::MT_To:
7722 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7723 VarName = CGM.getMangledName(VD);
7724 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
7725 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
7726 break;
7727 case OMPDeclareTargetDeclAttr::MT_Link:
7728 // Map type 'to' because we do not map the original variable but the
7729 // reference.
7730 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7731 if (!CGM.getLangOpts().OpenMPIsDevice) {
7732 Addr =
7733 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
7734 }
7735 VarName = Addr->getName();
7736 VarSize = CGM.getPointerSize();
7737 Linkage = llvm::GlobalValue::WeakAnyLinkage;
7738 break;
7739 }
7740 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
7741 VarName, Addr, VarSize, Flags, Linkage);
7742 }
7743}
7744
Samuel Antaoee8fb302016-01-06 13:42:12 +00007745bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7746 auto *VD = GD.getDecl();
7747 if (isa<FunctionDecl>(VD))
7748 return emitTargetFunctions(GD);
7749
7750 return emitTargetGlobalVariable(GD);
7751}
7752
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007753CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7754 CodeGenModule &CGM)
7755 : CGM(CGM) {
7756 if (CGM.getLangOpts().OpenMPIsDevice) {
7757 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7758 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7759 }
7760}
7761
7762CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7763 if (CGM.getLangOpts().OpenMPIsDevice)
7764 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7765}
7766
7767bool CGOpenMPRuntime::markAsGlobalTarget(const FunctionDecl *D) {
7768 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7769 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007770
7771 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00007772 // Do not to emit function if it is marked as declare target as it was already
7773 // emitted.
7774 if (isDeclareTargetDeclaration(D)) {
7775 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
7776 if (auto *F = dyn_cast_or_null<llvm::Function>(
7777 CGM.GetGlobalValue(CGM.getMangledName(D))))
7778 return !F->isDeclaration();
7779 return false;
7780 }
7781 return true;
7782 }
7783
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007784 // Do not mark member functions except for static.
7785 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD))
7786 if (!Method->isStatic())
7787 return true;
7788
7789 return !AlreadyEmittedTargetFunctions.insert(FD).second;
7790}
7791
Samuel Antaoee8fb302016-01-06 13:42:12 +00007792llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7793 // If we have offloading in the current module, we need to emit the entries
7794 // now and register the offloading descriptor.
7795 createOffloadEntriesAndInfoMetadata();
7796
7797 // Create and register the offloading binary descriptors. This is the main
7798 // entity that captures all the information about offloading in the current
7799 // compilation unit.
7800 return createOffloadingBinaryDescriptorRegistration();
7801}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007802
7803void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7804 const OMPExecutableDirective &D,
7805 SourceLocation Loc,
7806 llvm::Value *OutlinedFn,
7807 ArrayRef<llvm::Value *> CapturedVars) {
7808 if (!CGF.HaveInsertPoint())
7809 return;
7810
7811 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7812 CodeGenFunction::RunCleanupsScope Scope(CGF);
7813
7814 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7815 llvm::Value *Args[] = {
7816 RTLoc,
7817 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7818 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7819 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7820 RealArgs.append(std::begin(Args), std::end(Args));
7821 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7822
7823 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7824 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7825}
7826
7827void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007828 const Expr *NumTeams,
7829 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007830 SourceLocation Loc) {
7831 if (!CGF.HaveInsertPoint())
7832 return;
7833
7834 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7835
Carlo Bertollic6872252016-04-04 15:55:02 +00007836 llvm::Value *NumTeamsVal =
7837 (NumTeams)
7838 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7839 CGF.CGM.Int32Ty, /* isSigned = */ true)
7840 : CGF.Builder.getInt32(0);
7841
7842 llvm::Value *ThreadLimitVal =
7843 (ThreadLimit)
7844 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7845 CGF.CGM.Int32Ty, /* isSigned = */ true)
7846 : CGF.Builder.getInt32(0);
7847
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007848 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007849 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7850 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007851 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7852 PushNumTeamsArgs);
7853}
Samuel Antaodf158d52016-04-27 22:58:19 +00007854
Samuel Antaocc10b852016-07-28 14:23:26 +00007855void CGOpenMPRuntime::emitTargetDataCalls(
7856 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7857 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007858 if (!CGF.HaveInsertPoint())
7859 return;
7860
Samuel Antaocc10b852016-07-28 14:23:26 +00007861 // Action used to replace the default codegen action and turn privatization
7862 // off.
7863 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007864
7865 // Generate the code for the opening of the data environment. Capture all the
7866 // arguments of the runtime call by reference because they are used in the
7867 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007868 auto &&BeginThenGen = [this, &D, Device, &Info,
7869 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007870 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007871 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007872 MappableExprsHandler::MapValuesArrayTy Pointers;
7873 MappableExprsHandler::MapValuesArrayTy Sizes;
7874 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7875
7876 // Get map clause information.
7877 MappableExprsHandler MCHandler(D, CGF);
7878 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007879
7880 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007881 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007882
7883 llvm::Value *BasePointersArrayArg = nullptr;
7884 llvm::Value *PointersArrayArg = nullptr;
7885 llvm::Value *SizesArrayArg = nullptr;
7886 llvm::Value *MapTypesArrayArg = nullptr;
7887 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007888 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007889
7890 // Emit device ID if any.
7891 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007892 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007893 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007894 CGF.Int64Ty, /*isSigned=*/true);
7895 } else {
7896 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7897 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007898
7899 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007900 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007901
7902 llvm::Value *OffloadingArgs[] = {
7903 DeviceID, PointerNum, BasePointersArrayArg,
7904 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007905 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00007906 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007907
7908 // If device pointer privatization is required, emit the body of the region
7909 // here. It will have to be duplicated: with and without privatization.
7910 if (!Info.CaptureDeviceAddrMap.empty())
7911 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007912 };
7913
7914 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007915 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
7916 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007917 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007918
7919 llvm::Value *BasePointersArrayArg = nullptr;
7920 llvm::Value *PointersArrayArg = nullptr;
7921 llvm::Value *SizesArrayArg = nullptr;
7922 llvm::Value *MapTypesArrayArg = nullptr;
7923 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007924 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007925
7926 // Emit device ID if any.
7927 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007928 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007929 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007930 CGF.Int64Ty, /*isSigned=*/true);
7931 } else {
7932 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7933 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007934
7935 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007936 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007937
7938 llvm::Value *OffloadingArgs[] = {
7939 DeviceID, PointerNum, BasePointersArrayArg,
7940 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007941 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00007942 OffloadingArgs);
7943 };
7944
Samuel Antaocc10b852016-07-28 14:23:26 +00007945 // If we need device pointer privatization, we need to emit the body of the
7946 // region with no privatization in the 'else' branch of the conditional.
7947 // Otherwise, we don't have to do anything.
7948 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7949 PrePostActionTy &) {
7950 if (!Info.CaptureDeviceAddrMap.empty()) {
7951 CodeGen.setAction(NoPrivAction);
7952 CodeGen(CGF);
7953 }
7954 };
7955
7956 // We don't have to do anything to close the region if the if clause evaluates
7957 // to false.
7958 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007959
7960 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007961 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007962 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007963 RegionCodeGenTy RCG(BeginThenGen);
7964 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007965 }
7966
Samuel Antaocc10b852016-07-28 14:23:26 +00007967 // If we don't require privatization of device pointers, we emit the body in
7968 // between the runtime calls. This avoids duplicating the body code.
7969 if (Info.CaptureDeviceAddrMap.empty()) {
7970 CodeGen.setAction(NoPrivAction);
7971 CodeGen(CGF);
7972 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007973
7974 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007975 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007976 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007977 RegionCodeGenTy RCG(EndThenGen);
7978 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007979 }
7980}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007981
Samuel Antao8d2d7302016-05-26 18:30:22 +00007982void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007983 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7984 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007985 if (!CGF.HaveInsertPoint())
7986 return;
7987
Samuel Antao8dd66282016-04-27 23:14:30 +00007988 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007989 isa<OMPTargetExitDataDirective>(D) ||
7990 isa<OMPTargetUpdateDirective>(D)) &&
7991 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007992
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007993 CodeGenFunction::OMPTargetDataInfo InputInfo;
7994 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007995 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007996 auto &&ThenGen = [this, &D, Device, &InputInfo,
7997 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007998 // Emit device ID if any.
7999 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008000 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008001 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008002 CGF.Int64Ty, /*isSigned=*/true);
8003 } else {
8004 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8005 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008006
8007 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008008 llvm::Constant *PointerNum =
8009 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008010
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008011 llvm::Value *OffloadingArgs[] = {DeviceID,
8012 PointerNum,
8013 InputInfo.BasePointersArray.getPointer(),
8014 InputInfo.PointersArray.getPointer(),
8015 InputInfo.SizesArray.getPointer(),
8016 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008017
Samuel Antao8d2d7302016-05-26 18:30:22 +00008018 // Select the right runtime function call for each expected standalone
8019 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008020 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008021 OpenMPRTLFunction RTLFn;
8022 switch (D.getDirectiveKind()) {
8023 default:
8024 llvm_unreachable("Unexpected standalone target data directive.");
8025 break;
8026 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008027 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8028 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008029 break;
8030 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008031 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8032 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008033 break;
8034 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008035 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8036 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008037 break;
8038 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008039 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008040 };
8041
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008042 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8043 CodeGenFunction &CGF, PrePostActionTy &) {
8044 // Fill up the arrays with all the mapped variables.
8045 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8046 MappableExprsHandler::MapValuesArrayTy Pointers;
8047 MappableExprsHandler::MapValuesArrayTy Sizes;
8048 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008049
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008050 // Get map clause information.
8051 MappableExprsHandler MEHandler(D, CGF);
8052 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8053
8054 TargetDataInfo Info;
8055 // Fill up the arrays and create the arguments.
8056 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8057 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8058 Info.PointersArray, Info.SizesArray,
8059 Info.MapTypesArray, Info);
8060 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8061 InputInfo.BasePointersArray =
8062 Address(Info.BasePointersArray, CGM.getPointerAlign());
8063 InputInfo.PointersArray =
8064 Address(Info.PointersArray, CGM.getPointerAlign());
8065 InputInfo.SizesArray =
8066 Address(Info.SizesArray, CGM.getPointerAlign());
8067 MapTypesArray = Info.MapTypesArray;
8068 if (D.hasClausesOfKind<OMPDependClause>())
8069 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8070 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008071 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008072 };
8073
8074 if (IfCond)
8075 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8076 [](CodeGenFunction &CGF, PrePostActionTy &) {});
8077 else {
8078 RegionCodeGenTy ThenRCG(TargetThenGen);
8079 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008080 }
8081}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008082
8083namespace {
8084 /// Kind of parameter in a function with 'declare simd' directive.
8085 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8086 /// Attribute set of the parameter.
8087 struct ParamAttrTy {
8088 ParamKindTy Kind = Vector;
8089 llvm::APSInt StrideOrArg;
8090 llvm::APSInt Alignment;
8091 };
8092} // namespace
8093
8094static unsigned evaluateCDTSize(const FunctionDecl *FD,
8095 ArrayRef<ParamAttrTy> ParamAttrs) {
8096 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8097 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8098 // of that clause. The VLEN value must be power of 2.
8099 // In other case the notion of the function`s "characteristic data type" (CDT)
8100 // is used to compute the vector length.
8101 // CDT is defined in the following order:
8102 // a) For non-void function, the CDT is the return type.
8103 // b) If the function has any non-uniform, non-linear parameters, then the
8104 // CDT is the type of the first such parameter.
8105 // c) If the CDT determined by a) or b) above is struct, union, or class
8106 // type which is pass-by-value (except for the type that maps to the
8107 // built-in complex data type), the characteristic data type is int.
8108 // d) If none of the above three cases is applicable, the CDT is int.
8109 // The VLEN is then determined based on the CDT and the size of vector
8110 // register of that ISA for which current vector version is generated. The
8111 // VLEN is computed using the formula below:
8112 // VLEN = sizeof(vector_register) / sizeof(CDT),
8113 // where vector register size specified in section 3.2.1 Registers and the
8114 // Stack Frame of original AMD64 ABI document.
8115 QualType RetType = FD->getReturnType();
8116 if (RetType.isNull())
8117 return 0;
8118 ASTContext &C = FD->getASTContext();
8119 QualType CDT;
8120 if (!RetType.isNull() && !RetType->isVoidType())
8121 CDT = RetType;
8122 else {
8123 unsigned Offset = 0;
8124 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8125 if (ParamAttrs[Offset].Kind == Vector)
8126 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8127 ++Offset;
8128 }
8129 if (CDT.isNull()) {
8130 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8131 if (ParamAttrs[I + Offset].Kind == Vector) {
8132 CDT = FD->getParamDecl(I)->getType();
8133 break;
8134 }
8135 }
8136 }
8137 }
8138 if (CDT.isNull())
8139 CDT = C.IntTy;
8140 CDT = CDT->getCanonicalTypeUnqualified();
8141 if (CDT->isRecordType() || CDT->isUnionType())
8142 CDT = C.IntTy;
8143 return C.getTypeSize(CDT);
8144}
8145
8146static void
8147emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008148 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008149 ArrayRef<ParamAttrTy> ParamAttrs,
8150 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8151 struct ISADataTy {
8152 char ISA;
8153 unsigned VecRegSize;
8154 };
8155 ISADataTy ISAData[] = {
8156 {
8157 'b', 128
8158 }, // SSE
8159 {
8160 'c', 256
8161 }, // AVX
8162 {
8163 'd', 256
8164 }, // AVX2
8165 {
8166 'e', 512
8167 }, // AVX512
8168 };
8169 llvm::SmallVector<char, 2> Masked;
8170 switch (State) {
8171 case OMPDeclareSimdDeclAttr::BS_Undefined:
8172 Masked.push_back('N');
8173 Masked.push_back('M');
8174 break;
8175 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8176 Masked.push_back('N');
8177 break;
8178 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8179 Masked.push_back('M');
8180 break;
8181 }
8182 for (auto Mask : Masked) {
8183 for (auto &Data : ISAData) {
8184 SmallString<256> Buffer;
8185 llvm::raw_svector_ostream Out(Buffer);
8186 Out << "_ZGV" << Data.ISA << Mask;
8187 if (!VLENVal) {
8188 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8189 evaluateCDTSize(FD, ParamAttrs));
8190 } else
8191 Out << VLENVal;
8192 for (auto &ParamAttr : ParamAttrs) {
8193 switch (ParamAttr.Kind){
8194 case LinearWithVarStride:
8195 Out << 's' << ParamAttr.StrideOrArg;
8196 break;
8197 case Linear:
8198 Out << 'l';
8199 if (!!ParamAttr.StrideOrArg)
8200 Out << ParamAttr.StrideOrArg;
8201 break;
8202 case Uniform:
8203 Out << 'u';
8204 break;
8205 case Vector:
8206 Out << 'v';
8207 break;
8208 }
8209 if (!!ParamAttr.Alignment)
8210 Out << 'a' << ParamAttr.Alignment;
8211 }
8212 Out << '_' << Fn->getName();
8213 Fn->addFnAttr(Out.str());
8214 }
8215 }
8216}
8217
8218void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8219 llvm::Function *Fn) {
8220 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008221 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008222 // Map params to their positions in function decl.
8223 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8224 if (isa<CXXMethodDecl>(FD))
8225 ParamPositions.insert({FD, 0});
8226 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00008227 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008228 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
8229 ++ParamPos;
8230 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008231 while (FD) {
8232 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
8233 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8234 // Mark uniform parameters.
8235 for (auto *E : Attr->uniforms()) {
8236 E = E->IgnoreParenImpCasts();
8237 unsigned Pos;
8238 if (isa<CXXThisExpr>(E))
8239 Pos = ParamPositions[FD];
8240 else {
8241 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8242 ->getCanonicalDecl();
8243 Pos = ParamPositions[PVD];
8244 }
8245 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008246 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008247 // Get alignment info.
8248 auto NI = Attr->alignments_begin();
8249 for (auto *E : Attr->aligneds()) {
8250 E = E->IgnoreParenImpCasts();
8251 unsigned Pos;
8252 QualType ParmTy;
8253 if (isa<CXXThisExpr>(E)) {
8254 Pos = ParamPositions[FD];
8255 ParmTy = E->getType();
8256 } else {
8257 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8258 ->getCanonicalDecl();
8259 Pos = ParamPositions[PVD];
8260 ParmTy = PVD->getType();
8261 }
8262 ParamAttrs[Pos].Alignment =
8263 (*NI)
8264 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008265 : llvm::APSInt::getUnsigned(
8266 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8267 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008268 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008269 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008270 // Mark linear parameters.
8271 auto SI = Attr->steps_begin();
8272 auto MI = Attr->modifiers_begin();
8273 for (auto *E : Attr->linears()) {
8274 E = E->IgnoreParenImpCasts();
8275 unsigned Pos;
8276 if (isa<CXXThisExpr>(E))
8277 Pos = ParamPositions[FD];
8278 else {
8279 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8280 ->getCanonicalDecl();
8281 Pos = ParamPositions[PVD];
8282 }
8283 auto &ParamAttr = ParamAttrs[Pos];
8284 ParamAttr.Kind = Linear;
8285 if (*SI) {
8286 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8287 Expr::SE_AllowSideEffects)) {
8288 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8289 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
8290 ParamAttr.Kind = LinearWithVarStride;
8291 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8292 ParamPositions[StridePVD->getCanonicalDecl()]);
8293 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008294 }
8295 }
8296 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008297 ++SI;
8298 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008299 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008300 llvm::APSInt VLENVal;
8301 if (const Expr *VLEN = Attr->getSimdlen())
8302 VLENVal = VLEN->EvaluateKnownConstInt(C);
8303 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8304 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8305 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8306 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008307 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008308 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008309 }
8310}
Alexey Bataev8b427062016-05-25 12:36:08 +00008311
8312namespace {
8313/// Cleanup action for doacross support.
8314class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8315public:
8316 static const int DoacrossFinArgs = 2;
8317
8318private:
8319 llvm::Value *RTLFn;
8320 llvm::Value *Args[DoacrossFinArgs];
8321
8322public:
8323 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8324 : RTLFn(RTLFn) {
8325 assert(CallArgs.size() == DoacrossFinArgs);
8326 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8327 }
8328 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8329 if (!CGF.HaveInsertPoint())
8330 return;
8331 CGF.EmitRuntimeCall(RTLFn, Args);
8332 }
8333};
8334} // namespace
8335
8336void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8337 const OMPLoopDirective &D) {
8338 if (!CGF.HaveInsertPoint())
8339 return;
8340
8341 ASTContext &C = CGM.getContext();
8342 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8343 RecordDecl *RD;
8344 if (KmpDimTy.isNull()) {
8345 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8346 // kmp_int64 lo; // lower
8347 // kmp_int64 up; // upper
8348 // kmp_int64 st; // stride
8349 // };
8350 RD = C.buildImplicitRecord("kmp_dim");
8351 RD->startDefinition();
8352 addFieldToRecordDecl(C, RD, Int64Ty);
8353 addFieldToRecordDecl(C, RD, Int64Ty);
8354 addFieldToRecordDecl(C, RD, Int64Ty);
8355 RD->completeDefinition();
8356 KmpDimTy = C.getRecordType(RD);
8357 } else
8358 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
8359
8360 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8361 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8362 enum { LowerFD = 0, UpperFD, StrideFD };
8363 // Fill dims with data.
8364 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8365 // dims.upper = num_iterations;
8366 LValue UpperLVal =
8367 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8368 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8369 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8370 Int64Ty, D.getNumIterations()->getExprLoc());
8371 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8372 // dims.stride = 1;
8373 LValue StrideLVal =
8374 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8375 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8376 StrideLVal);
8377
8378 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8379 // kmp_int32 num_dims, struct kmp_dim * dims);
8380 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8381 getThreadID(CGF, D.getLocStart()),
8382 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8383 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8384 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8385
8386 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8387 CGF.EmitRuntimeCall(RTLFn, Args);
8388 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8389 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8390 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8391 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8392 llvm::makeArrayRef(FiniArgs));
8393}
8394
8395void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8396 const OMPDependClause *C) {
8397 QualType Int64Ty =
8398 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8399 const Expr *CounterVal = C->getCounterValue();
8400 assert(CounterVal);
8401 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8402 CounterVal->getType(), Int64Ty,
8403 CounterVal->getExprLoc());
8404 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8405 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8406 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8407 getThreadID(CGF, C->getLocStart()),
8408 CntAddr.getPointer()};
8409 llvm::Value *RTLFn;
8410 if (C->getDependencyKind() == OMPC_DEPEND_source)
8411 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
8412 else {
8413 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8414 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8415 }
8416 CGF.EmitRuntimeCall(RTLFn, Args);
8417}
8418
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008419void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8420 llvm::Value *Callee,
8421 ArrayRef<llvm::Value *> Args) const {
8422 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008423 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8424
8425 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008426 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008427 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008428 return;
8429 }
8430 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008431 CGF.EmitRuntimeCall(Callee, Args);
8432}
8433
8434void CGOpenMPRuntime::emitOutlinedFunctionCall(
8435 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8436 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008437 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008438}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008439
8440Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8441 const VarDecl *NativeParam,
8442 const VarDecl *TargetParam) const {
8443 return CGF.GetAddrOfLocalVar(NativeParam);
8444}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008445
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008446Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8447 const VarDecl *VD) {
8448 return Address::invalid();
8449}
8450
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008451llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8452 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8453 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8454 llvm_unreachable("Not supported in SIMD-only mode");
8455}
8456
8457llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8458 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8459 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8460 llvm_unreachable("Not supported in SIMD-only mode");
8461}
8462
8463llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8464 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8465 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8466 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8467 bool Tied, unsigned &NumberOfParts) {
8468 llvm_unreachable("Not supported in SIMD-only mode");
8469}
8470
8471void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8472 SourceLocation Loc,
8473 llvm::Value *OutlinedFn,
8474 ArrayRef<llvm::Value *> CapturedVars,
8475 const Expr *IfCond) {
8476 llvm_unreachable("Not supported in SIMD-only mode");
8477}
8478
8479void CGOpenMPSIMDRuntime::emitCriticalRegion(
8480 CodeGenFunction &CGF, StringRef CriticalName,
8481 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8482 const Expr *Hint) {
8483 llvm_unreachable("Not supported in SIMD-only mode");
8484}
8485
8486void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8487 const RegionCodeGenTy &MasterOpGen,
8488 SourceLocation Loc) {
8489 llvm_unreachable("Not supported in SIMD-only mode");
8490}
8491
8492void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8493 SourceLocation Loc) {
8494 llvm_unreachable("Not supported in SIMD-only mode");
8495}
8496
8497void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8498 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8499 SourceLocation Loc) {
8500 llvm_unreachable("Not supported in SIMD-only mode");
8501}
8502
8503void CGOpenMPSIMDRuntime::emitSingleRegion(
8504 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8505 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8506 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8507 ArrayRef<const Expr *> AssignmentOps) {
8508 llvm_unreachable("Not supported in SIMD-only mode");
8509}
8510
8511void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8512 const RegionCodeGenTy &OrderedOpGen,
8513 SourceLocation Loc,
8514 bool IsThreads) {
8515 llvm_unreachable("Not supported in SIMD-only mode");
8516}
8517
8518void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8519 SourceLocation Loc,
8520 OpenMPDirectiveKind Kind,
8521 bool EmitChecks,
8522 bool ForceSimpleCall) {
8523 llvm_unreachable("Not supported in SIMD-only mode");
8524}
8525
8526void CGOpenMPSIMDRuntime::emitForDispatchInit(
8527 CodeGenFunction &CGF, SourceLocation Loc,
8528 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8529 bool Ordered, const DispatchRTInput &DispatchValues) {
8530 llvm_unreachable("Not supported in SIMD-only mode");
8531}
8532
8533void CGOpenMPSIMDRuntime::emitForStaticInit(
8534 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8535 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8536 llvm_unreachable("Not supported in SIMD-only mode");
8537}
8538
8539void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8540 CodeGenFunction &CGF, SourceLocation Loc,
8541 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8542 llvm_unreachable("Not supported in SIMD-only mode");
8543}
8544
8545void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8546 SourceLocation Loc,
8547 unsigned IVSize,
8548 bool IVSigned) {
8549 llvm_unreachable("Not supported in SIMD-only mode");
8550}
8551
8552void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8553 SourceLocation Loc,
8554 OpenMPDirectiveKind DKind) {
8555 llvm_unreachable("Not supported in SIMD-only mode");
8556}
8557
8558llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8559 SourceLocation Loc,
8560 unsigned IVSize, bool IVSigned,
8561 Address IL, Address LB,
8562 Address UB, Address ST) {
8563 llvm_unreachable("Not supported in SIMD-only mode");
8564}
8565
8566void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8567 llvm::Value *NumThreads,
8568 SourceLocation Loc) {
8569 llvm_unreachable("Not supported in SIMD-only mode");
8570}
8571
8572void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8573 OpenMPProcBindClauseKind ProcBind,
8574 SourceLocation Loc) {
8575 llvm_unreachable("Not supported in SIMD-only mode");
8576}
8577
8578Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8579 const VarDecl *VD,
8580 Address VDAddr,
8581 SourceLocation Loc) {
8582 llvm_unreachable("Not supported in SIMD-only mode");
8583}
8584
8585llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8586 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8587 CodeGenFunction *CGF) {
8588 llvm_unreachable("Not supported in SIMD-only mode");
8589}
8590
8591Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8592 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8593 llvm_unreachable("Not supported in SIMD-only mode");
8594}
8595
8596void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8597 ArrayRef<const Expr *> Vars,
8598 SourceLocation Loc) {
8599 llvm_unreachable("Not supported in SIMD-only mode");
8600}
8601
8602void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8603 const OMPExecutableDirective &D,
8604 llvm::Value *TaskFunction,
8605 QualType SharedsTy, Address Shareds,
8606 const Expr *IfCond,
8607 const OMPTaskDataTy &Data) {
8608 llvm_unreachable("Not supported in SIMD-only mode");
8609}
8610
8611void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8612 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8613 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8614 const Expr *IfCond, const OMPTaskDataTy &Data) {
8615 llvm_unreachable("Not supported in SIMD-only mode");
8616}
8617
8618void CGOpenMPSIMDRuntime::emitReduction(
8619 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8620 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8621 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8622 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8623 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8624 ReductionOps, Options);
8625}
8626
8627llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8628 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8629 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8630 llvm_unreachable("Not supported in SIMD-only mode");
8631}
8632
8633void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8634 SourceLocation Loc,
8635 ReductionCodeGen &RCG,
8636 unsigned N) {
8637 llvm_unreachable("Not supported in SIMD-only mode");
8638}
8639
8640Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8641 SourceLocation Loc,
8642 llvm::Value *ReductionsPtr,
8643 LValue SharedLVal) {
8644 llvm_unreachable("Not supported in SIMD-only mode");
8645}
8646
8647void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8648 SourceLocation Loc) {
8649 llvm_unreachable("Not supported in SIMD-only mode");
8650}
8651
8652void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8653 CodeGenFunction &CGF, SourceLocation Loc,
8654 OpenMPDirectiveKind CancelRegion) {
8655 llvm_unreachable("Not supported in SIMD-only mode");
8656}
8657
8658void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8659 SourceLocation Loc, const Expr *IfCond,
8660 OpenMPDirectiveKind CancelRegion) {
8661 llvm_unreachable("Not supported in SIMD-only mode");
8662}
8663
8664void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8665 const OMPExecutableDirective &D, StringRef ParentName,
8666 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8667 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8668 llvm_unreachable("Not supported in SIMD-only mode");
8669}
8670
8671void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8672 const OMPExecutableDirective &D,
8673 llvm::Value *OutlinedFn,
8674 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008675 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008676 llvm_unreachable("Not supported in SIMD-only mode");
8677}
8678
8679bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8680 llvm_unreachable("Not supported in SIMD-only mode");
8681}
8682
8683bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8684 llvm_unreachable("Not supported in SIMD-only mode");
8685}
8686
8687bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8688 return false;
8689}
8690
8691llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8692 return nullptr;
8693}
8694
8695void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8696 const OMPExecutableDirective &D,
8697 SourceLocation Loc,
8698 llvm::Value *OutlinedFn,
8699 ArrayRef<llvm::Value *> CapturedVars) {
8700 llvm_unreachable("Not supported in SIMD-only mode");
8701}
8702
8703void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8704 const Expr *NumTeams,
8705 const Expr *ThreadLimit,
8706 SourceLocation Loc) {
8707 llvm_unreachable("Not supported in SIMD-only mode");
8708}
8709
8710void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8711 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8712 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8713 llvm_unreachable("Not supported in SIMD-only mode");
8714}
8715
8716void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8717 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8718 const Expr *Device) {
8719 llvm_unreachable("Not supported in SIMD-only mode");
8720}
8721
8722void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8723 const OMPLoopDirective &D) {
8724 llvm_unreachable("Not supported in SIMD-only mode");
8725}
8726
8727void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8728 const OMPDependClause *C) {
8729 llvm_unreachable("Not supported in SIMD-only mode");
8730}
8731
8732const VarDecl *
8733CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8734 const VarDecl *NativeParam) const {
8735 llvm_unreachable("Not supported in SIMD-only mode");
8736}
8737
8738Address
8739CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8740 const VarDecl *NativeParam,
8741 const VarDecl *TargetParam) const {
8742 llvm_unreachable("Not supported in SIMD-only mode");
8743}
8744