blob: f98ff85565faa5301ab8d40a871a227c516ee86e [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>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151 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,
357 SourceLocation());
358 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 Bataev6f1ffc02015-04-10 04:50:10 +0000400
401public:
402 /// \brief Constructs region for combined constructs.
403 /// \param CodeGen Code generation sequence for combined directives. Includes
404 /// a list of functions used for code generation of implicitly inlined
405 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000406 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000407 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 : CGF(CGF) {
409 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000410 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
411 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
413 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
414 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000415 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000416
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 ~InlinedOpenMPRegionRAII() {
418 // Restore original CapturedStmtInfo only if we're done with code emission.
419 auto *OldCSI =
420 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
421 delete CGF.CapturedStmtInfo;
422 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000423 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
424 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000425 }
426};
427
Alexey Bataev50b3c952016-02-19 10:38:26 +0000428/// \brief Values for bit flags used in the ident_t to describe the fields.
429/// All enumeric elements are named and described in accordance with the code
430/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000431enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432 /// \brief Use trampoline for internal microtask.
433 OMP_IDENT_IMD = 0x01,
434 /// \brief Use c-style ident structure.
435 OMP_IDENT_KMPC = 0x02,
436 /// \brief Atomic reduction option for kmpc_reduce.
437 OMP_ATOMIC_REDUCE = 0x10,
438 /// \brief Explicit 'barrier' directive.
439 OMP_IDENT_BARRIER_EXPL = 0x20,
440 /// \brief Implicit barrier in code.
441 OMP_IDENT_BARRIER_IMPL = 0x40,
442 /// \brief Implicit barrier in 'for' directive.
443 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
444 /// \brief Implicit barrier in 'sections' directive.
445 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
446 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000447 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
448 /// Call of __kmp_for_static_init for static loop.
449 OMP_IDENT_WORK_LOOP = 0x200,
450 /// Call of __kmp_for_static_init for sections.
451 OMP_IDENT_WORK_SECTIONS = 0x400,
452 /// Call of __kmp_for_static_init for distribute.
453 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
454 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000455};
456
457/// \brief Describes ident structure that describes a source location.
458/// All descriptions are taken from
459/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
460/// Original structure:
461/// typedef struct ident {
462/// kmp_int32 reserved_1; /**< might be used in Fortran;
463/// see above */
464/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
465/// KMP_IDENT_KMPC identifies this union
466/// member */
467/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
468/// see above */
469///#if USE_ITT_BUILD
470/// /* but currently used for storing
471/// region-specific ITT */
472/// /* contextual information. */
473///#endif /* USE_ITT_BUILD */
474/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
475/// C++ */
476/// char const *psource; /**< String describing the source location.
477/// The string is composed of semi-colon separated
478// fields which describe the source file,
479/// the function and a pair of line numbers that
480/// delimit the construct.
481/// */
482/// } ident_t;
483enum IdentFieldIndex {
484 /// \brief might be used in Fortran
485 IdentField_Reserved_1,
486 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
487 IdentField_Flags,
488 /// \brief Not really used in Fortran any more
489 IdentField_Reserved_2,
490 /// \brief Source[4] in Fortran, do not use for C++
491 IdentField_Reserved_3,
492 /// \brief String describing the source location. The string is composed of
493 /// semi-colon separated fields which describe the source file, the function
494 /// and a pair of line numbers that delimit the construct.
495 IdentField_PSource
496};
497
498/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
499/// the enum sched_type in kmp.h).
500enum OpenMPSchedType {
501 /// \brief Lower bound for default (unordered) versions.
502 OMP_sch_lower = 32,
503 OMP_sch_static_chunked = 33,
504 OMP_sch_static = 34,
505 OMP_sch_dynamic_chunked = 35,
506 OMP_sch_guided_chunked = 36,
507 OMP_sch_runtime = 37,
508 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000509 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000510 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000511 /// \brief Lower bound for 'ordered' versions.
512 OMP_ord_lower = 64,
513 OMP_ord_static_chunked = 65,
514 OMP_ord_static = 66,
515 OMP_ord_dynamic_chunked = 67,
516 OMP_ord_guided_chunked = 68,
517 OMP_ord_runtime = 69,
518 OMP_ord_auto = 70,
519 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000520 /// \brief dist_schedule types
521 OMP_dist_sch_static_chunked = 91,
522 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000523 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
524 /// Set if the monotonic schedule modifier was present.
525 OMP_sch_modifier_monotonic = (1 << 29),
526 /// Set if the nonmonotonic schedule modifier was present.
527 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000528};
529
530enum OpenMPRTLFunction {
531 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
532 /// kmpc_micro microtask, ...);
533 OMPRTL__kmpc_fork_call,
534 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
535 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
536 OMPRTL__kmpc_threadprivate_cached,
537 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
538 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
539 OMPRTL__kmpc_threadprivate_register,
540 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
541 OMPRTL__kmpc_global_thread_num,
542 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
543 // kmp_critical_name *crit);
544 OMPRTL__kmpc_critical,
545 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
546 // global_tid, kmp_critical_name *crit, uintptr_t hint);
547 OMPRTL__kmpc_critical_with_hint,
548 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
549 // kmp_critical_name *crit);
550 OMPRTL__kmpc_end_critical,
551 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
552 // global_tid);
553 OMPRTL__kmpc_cancel_barrier,
554 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
555 OMPRTL__kmpc_barrier,
556 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
557 OMPRTL__kmpc_for_static_fini,
558 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
559 // global_tid);
560 OMPRTL__kmpc_serialized_parallel,
561 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 OMPRTL__kmpc_end_serialized_parallel,
564 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
565 // kmp_int32 num_threads);
566 OMPRTL__kmpc_push_num_threads,
567 // Call to void __kmpc_flush(ident_t *loc);
568 OMPRTL__kmpc_flush,
569 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
570 OMPRTL__kmpc_master,
571 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
572 OMPRTL__kmpc_end_master,
573 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
574 // int end_part);
575 OMPRTL__kmpc_omp_taskyield,
576 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_single,
578 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
579 OMPRTL__kmpc_end_single,
580 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
581 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
582 // kmp_routine_entry_t *task_entry);
583 OMPRTL__kmpc_omp_task_alloc,
584 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
585 // new_task);
586 OMPRTL__kmpc_omp_task,
587 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
588 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
589 // kmp_int32 didit);
590 OMPRTL__kmpc_copyprivate,
591 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
592 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
593 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
594 OMPRTL__kmpc_reduce,
595 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
596 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
597 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
598 // *lck);
599 OMPRTL__kmpc_reduce_nowait,
600 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
601 // kmp_critical_name *lck);
602 OMPRTL__kmpc_end_reduce,
603 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
604 // kmp_critical_name *lck);
605 OMPRTL__kmpc_end_reduce_nowait,
606 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
607 // kmp_task_t * new_task);
608 OMPRTL__kmpc_omp_task_begin_if0,
609 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
610 // kmp_task_t * new_task);
611 OMPRTL__kmpc_omp_task_complete_if0,
612 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
613 OMPRTL__kmpc_ordered,
614 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
615 OMPRTL__kmpc_end_ordered,
616 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
617 // global_tid);
618 OMPRTL__kmpc_omp_taskwait,
619 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_taskgroup,
621 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
622 OMPRTL__kmpc_end_taskgroup,
623 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
624 // int proc_bind);
625 OMPRTL__kmpc_push_proc_bind,
626 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
627 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
628 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
629 OMPRTL__kmpc_omp_task_with_deps,
630 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
632 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_wait_deps,
634 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
635 // global_tid, kmp_int32 cncl_kind);
636 OMPRTL__kmpc_cancellationpoint,
637 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
638 // kmp_int32 cncl_kind);
639 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000640 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
641 // kmp_int32 num_teams, kmp_int32 thread_limit);
642 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000643 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
644 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000646 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
647 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
648 // sched, kmp_uint64 grainsize, void *task_dup);
649 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000650 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
651 // num_dims, struct kmp_dim *dims);
652 OMPRTL__kmpc_doacross_init,
653 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
654 OMPRTL__kmpc_doacross_fini,
655 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
656 // *vec);
657 OMPRTL__kmpc_doacross_post,
658 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
659 // *vec);
660 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000661 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
662 // *data);
663 OMPRTL__kmpc_task_reduction_init,
664 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
665 // *d);
666 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000667
668 //
669 // Offloading related calls
670 //
671 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
672 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
673 // *arg_types);
674 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000675 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
676 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
677 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
678 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000679 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
680 OMPRTL__tgt_register_lib,
681 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
682 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000683 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
684 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
685 OMPRTL__tgt_target_data_begin,
686 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
687 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
688 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000689 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
690 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
691 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692};
693
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000694/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
695/// region.
696class CleanupTy final : public EHScopeStack::Cleanup {
697 PrePostActionTy *Action;
698
699public:
700 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
701 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
702 if (!CGF.HaveInsertPoint())
703 return;
704 Action->Exit(CGF);
705 }
706};
707
Hans Wennborg7eb54642015-09-10 17:07:54 +0000708} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000709
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000710void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
711 CodeGenFunction::RunCleanupsScope Scope(CGF);
712 if (PrePostAction) {
713 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
714 Callback(CodeGen, CGF, *PrePostAction);
715 } else {
716 PrePostActionTy Action;
717 Callback(CodeGen, CGF, Action);
718 }
719}
720
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000721/// Check if the combiner is a call to UDR combiner and if it is so return the
722/// UDR decl used for reduction.
723static const OMPDeclareReductionDecl *
724getReductionInit(const Expr *ReductionOp) {
725 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
726 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
727 if (auto *DRE =
728 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
729 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
730 return DRD;
731 return nullptr;
732}
733
734static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
735 const OMPDeclareReductionDecl *DRD,
736 const Expr *InitOp,
737 Address Private, Address Original,
738 QualType Ty) {
739 if (DRD->getInitializer()) {
740 std::pair<llvm::Function *, llvm::Function *> Reduction =
741 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
742 auto *CE = cast<CallExpr>(InitOp);
743 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
744 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
745 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
746 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
747 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
748 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
749 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
750 [=]() -> Address { return Private; });
751 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
752 [=]() -> Address { return Original; });
753 (void)PrivateScope.Privatize();
754 RValue Func = RValue::get(Reduction.second);
755 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
756 CGF.EmitIgnoredExpr(InitOp);
757 } else {
758 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
759 auto *GV = new llvm::GlobalVariable(
760 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
761 llvm::GlobalValue::PrivateLinkage, Init, ".init");
762 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
763 RValue InitRVal;
764 switch (CGF.getEvaluationKind(Ty)) {
765 case TEK_Scalar:
766 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
767 break;
768 case TEK_Complex:
769 InitRVal =
770 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
771 break;
772 case TEK_Aggregate:
773 InitRVal = RValue::getAggregate(LV.getAddress());
774 break;
775 }
776 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
777 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
778 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
779 /*IsInitializer=*/false);
780 }
781}
782
783/// \brief Emit initialization of arrays of complex types.
784/// \param DestAddr Address of the array.
785/// \param Type Type of array.
786/// \param Init Initial expression of array.
787/// \param SrcAddr Address of the original array.
788static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000789 QualType Type, bool EmitDeclareReductionInit,
790 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000791 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000792 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000793 // Perform element-by-element initialization.
794 QualType ElementTy;
795
796 // Drill down to the base element type on both arrays.
797 auto ArrayTy = Type->getAsArrayTypeUnsafe();
798 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
799 DestAddr =
800 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
801 if (DRD)
802 SrcAddr =
803 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
804
805 llvm::Value *SrcBegin = nullptr;
806 if (DRD)
807 SrcBegin = SrcAddr.getPointer();
808 auto DestBegin = DestAddr.getPointer();
809 // Cast from pointer to array type to pointer to single element.
810 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
811 // The basic structure here is a while-do loop.
812 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
813 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
814 auto IsEmpty =
815 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
816 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
817
818 // Enter the loop body, making that address the current address.
819 auto EntryBB = CGF.Builder.GetInsertBlock();
820 CGF.EmitBlock(BodyBB);
821
822 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
823
824 llvm::PHINode *SrcElementPHI = nullptr;
825 Address SrcElementCurrent = Address::invalid();
826 if (DRD) {
827 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
828 "omp.arraycpy.srcElementPast");
829 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
830 SrcElementCurrent =
831 Address(SrcElementPHI,
832 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
833 }
834 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
835 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
836 DestElementPHI->addIncoming(DestBegin, EntryBB);
837 Address DestElementCurrent =
838 Address(DestElementPHI,
839 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
840
841 // Emit copy.
842 {
843 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000844 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000845 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
846 SrcElementCurrent, ElementTy);
847 } else
848 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
849 /*IsInitializer=*/false);
850 }
851
852 if (DRD) {
853 // Shift the address forward by one element.
854 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
855 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
856 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
857 }
858
859 // Shift the address forward by one element.
860 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
861 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
862 // Check whether we've reached the end.
863 auto Done =
864 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
865 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
866 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
867
868 // Done.
869 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
870}
871
872LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000873 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000874}
875
876LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
877 const Expr *E) {
878 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
879 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
880 return LValue();
881}
882
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000883void ReductionCodeGen::emitAggregateInitialization(
884 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
885 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000886 // Emit VarDecl with copy init for arrays.
887 // Get the address of the original variable captured in current
888 // captured region.
889 auto *PrivateVD =
890 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000891 bool EmitDeclareReductionInit =
892 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000893 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000894 EmitDeclareReductionInit,
895 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
896 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000897 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000898}
899
900ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
901 ArrayRef<const Expr *> Privates,
902 ArrayRef<const Expr *> ReductionOps) {
903 ClausesData.reserve(Shareds.size());
904 SharedAddresses.reserve(Shareds.size());
905 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000906 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000907 auto IPriv = Privates.begin();
908 auto IRed = ReductionOps.begin();
909 for (const auto *Ref : Shareds) {
910 ClausesData.emplace_back(Ref, *IPriv, *IRed);
911 std::advance(IPriv, 1);
912 std::advance(IRed, 1);
913 }
914}
915
916void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
917 assert(SharedAddresses.size() == N &&
918 "Number of generated lvalues must be exactly N.");
919 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
920 emitSharedLValueUB(CGF, ClausesData[N].Ref));
921}
922
923void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
924 auto *PrivateVD =
925 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
926 QualType PrivateType = PrivateVD->getType();
927 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
928 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000929 Sizes.emplace_back(
930 CGF.getTypeSize(
931 SharedAddresses[N].first.getType().getNonReferenceType()),
932 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933 return;
934 }
935 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000936 llvm::Value *SizeInChars;
937 llvm::Type *ElemType =
938 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
939 ->getElementType();
940 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000941 if (AsArraySection) {
942 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
943 SharedAddresses[N].first.getPointer());
944 Size = CGF.Builder.CreateNUWAdd(
945 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000946 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000947 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000948 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000949 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000950 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000951 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000952 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000953 CodeGenFunction::OpaqueValueMapping OpaqueMap(
954 CGF,
955 cast<OpaqueValueExpr>(
956 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
957 RValue::get(Size));
958 CGF.EmitVariablyModifiedType(PrivateType);
959}
960
961void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
962 llvm::Value *Size) {
963 auto *PrivateVD =
964 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
965 QualType PrivateType = PrivateVD->getType();
966 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
967 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000968 assert(!Size && !Sizes[N].second &&
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969 "Size should be nullptr for non-variably modified redution "
970 "items.");
971 return;
972 }
973 CodeGenFunction::OpaqueValueMapping OpaqueMap(
974 CGF,
975 cast<OpaqueValueExpr>(
976 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
977 RValue::get(Size));
978 CGF.EmitVariablyModifiedType(PrivateType);
979}
980
981void ReductionCodeGen::emitInitialization(
982 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
983 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
984 assert(SharedAddresses.size() > N && "No variable was generated");
985 auto *PrivateVD =
986 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
987 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
988 QualType PrivateType = PrivateVD->getType();
989 PrivateAddr = CGF.Builder.CreateElementBitCast(
990 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
991 QualType SharedType = SharedAddresses[N].first.getType();
992 SharedLVal = CGF.MakeAddrLValue(
993 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
994 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +0000995 SharedType, SharedAddresses[N].first.getBaseInfo(),
996 CGF.CGM.getTBAAAccessInfo(SharedType));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000997 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
998 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000999 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001000 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1001 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1002 PrivateAddr, SharedLVal.getAddress(),
1003 SharedLVal.getType());
1004 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1005 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1006 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1007 PrivateVD->getType().getQualifiers(),
1008 /*IsInitializer=*/false);
1009 }
1010}
1011
1012bool ReductionCodeGen::needCleanups(unsigned N) {
1013 auto *PrivateVD =
1014 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1015 QualType PrivateType = PrivateVD->getType();
1016 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1017 return DTorKind != QualType::DK_none;
1018}
1019
1020void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1021 Address PrivateAddr) {
1022 auto *PrivateVD =
1023 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1024 QualType PrivateType = PrivateVD->getType();
1025 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1026 if (needCleanups(N)) {
1027 PrivateAddr = CGF.Builder.CreateElementBitCast(
1028 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1029 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1030 }
1031}
1032
1033static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1034 LValue BaseLV) {
1035 BaseTy = BaseTy.getNonReferenceType();
1036 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1037 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1038 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1039 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1040 else {
1041 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1042 BaseTy->castAs<ReferenceType>());
1043 }
1044 BaseTy = BaseTy->getPointeeType();
1045 }
1046 return CGF.MakeAddrLValue(
1047 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1048 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001049 BaseLV.getType(), BaseLV.getBaseInfo(),
1050 CGF.CGM.getTBAAAccessInfo(BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001051}
1052
1053static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1054 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1055 llvm::Value *Addr) {
1056 Address Tmp = Address::invalid();
1057 Address TopTmp = Address::invalid();
1058 Address MostTopTmp = Address::invalid();
1059 BaseTy = BaseTy.getNonReferenceType();
1060 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1061 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1062 Tmp = CGF.CreateMemTemp(BaseTy);
1063 if (TopTmp.isValid())
1064 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1065 else
1066 MostTopTmp = Tmp;
1067 TopTmp = Tmp;
1068 BaseTy = BaseTy->getPointeeType();
1069 }
1070 llvm::Type *Ty = BaseLVType;
1071 if (Tmp.isValid())
1072 Ty = Tmp.getElementType();
1073 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1074 if (Tmp.isValid()) {
1075 CGF.Builder.CreateStore(Addr, Tmp);
1076 return MostTopTmp;
1077 }
1078 return Address(Addr, BaseLVAlignment);
1079}
1080
1081Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1082 Address PrivateAddr) {
1083 const DeclRefExpr *DE;
1084 const VarDecl *OrigVD = nullptr;
1085 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1086 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1087 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1088 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1089 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1090 Base = TempASE->getBase()->IgnoreParenImpCasts();
1091 DE = cast<DeclRefExpr>(Base);
1092 OrigVD = cast<VarDecl>(DE->getDecl());
1093 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1094 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1095 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1096 Base = TempASE->getBase()->IgnoreParenImpCasts();
1097 DE = cast<DeclRefExpr>(Base);
1098 OrigVD = cast<VarDecl>(DE->getDecl());
1099 }
1100 if (OrigVD) {
1101 BaseDecls.emplace_back(OrigVD);
1102 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1103 LValue BaseLValue =
1104 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1105 OriginalBaseLValue);
1106 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1107 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1108 llvm::Value *Ptr =
1109 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1110 return castToBase(CGF, OrigVD->getType(),
1111 SharedAddresses[N].first.getType(),
1112 OriginalBaseLValue.getPointer()->getType(),
1113 OriginalBaseLValue.getAlignment(), Ptr);
1114 }
1115 BaseDecls.emplace_back(
1116 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1117 return PrivateAddr;
1118}
1119
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001120bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1121 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1122 return DRD && DRD->getInitializer();
1123}
1124
Alexey Bataev18095712014-10-10 12:19:54 +00001125LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001126 return CGF.EmitLoadOfPointerLValue(
1127 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1128 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001129}
1130
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001131void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001132 if (!CGF.HaveInsertPoint())
1133 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134 // 1.2.2 OpenMP Language Terminology
1135 // Structured block - An executable statement with a single entry at the
1136 // top and a single exit at the bottom.
1137 // The point of exit cannot be a branch out of the structured block.
1138 // longjmp() and throw() must not violate the entry/exit criteria.
1139 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001140 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001141 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001142}
1143
Alexey Bataev62b63b12015-03-10 07:28:44 +00001144LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1145 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001146 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1147 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001148 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001149}
1150
Alexey Bataev9959db52014-05-06 10:08:46 +00001151CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001152 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001153 IdentTy = llvm::StructType::create(
1154 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1155 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001156 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001157 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001158
1159 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001160}
1161
Alexey Bataev91797552015-03-18 04:13:55 +00001162void CGOpenMPRuntime::clear() {
1163 InternalVars.clear();
1164}
1165
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001166static llvm::Function *
1167emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1168 const Expr *CombinerInitializer, const VarDecl *In,
1169 const VarDecl *Out, bool IsCombiner) {
1170 // void .omp_combiner.(Ty *in, Ty *out);
1171 auto &C = CGM.getContext();
1172 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1173 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001174 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001175 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001176 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001177 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001178 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001179 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001180 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001181 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001182 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1183 auto *Fn = llvm::Function::Create(
1184 FnTy, llvm::GlobalValue::InternalLinkage,
1185 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1186 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001187 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001188 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001189 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001190 CodeGenFunction CGF(CGM);
1191 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1192 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1193 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1194 CodeGenFunction::OMPPrivateScope Scope(CGF);
1195 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1196 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1197 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1198 .getAddress();
1199 });
1200 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1201 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1202 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1203 .getAddress();
1204 });
1205 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001206 if (!IsCombiner && Out->hasInit() &&
1207 !CGF.isTrivialInitializer(Out->getInit())) {
1208 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1209 Out->getType().getQualifiers(),
1210 /*IsInitializer=*/true);
1211 }
1212 if (CombinerInitializer)
1213 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001214 Scope.ForceCleanup();
1215 CGF.FinishFunction();
1216 return Fn;
1217}
1218
1219void CGOpenMPRuntime::emitUserDefinedReduction(
1220 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1221 if (UDRMap.count(D) > 0)
1222 return;
1223 auto &C = CGM.getContext();
1224 if (!In || !Out) {
1225 In = &C.Idents.get("omp_in");
1226 Out = &C.Idents.get("omp_out");
1227 }
1228 llvm::Function *Combiner = emitCombinerOrInitializer(
1229 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1230 cast<VarDecl>(D->lookup(Out).front()),
1231 /*IsCombiner=*/true);
1232 llvm::Function *Initializer = nullptr;
1233 if (auto *Init = D->getInitializer()) {
1234 if (!Priv || !Orig) {
1235 Priv = &C.Idents.get("omp_priv");
1236 Orig = &C.Idents.get("omp_orig");
1237 }
1238 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001239 CGM, D->getType(),
1240 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1241 : nullptr,
1242 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001243 cast<VarDecl>(D->lookup(Priv).front()),
1244 /*IsCombiner=*/false);
1245 }
1246 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1247 if (CGF) {
1248 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1249 Decls.second.push_back(D);
1250 }
1251}
1252
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001253std::pair<llvm::Function *, llvm::Function *>
1254CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1255 auto I = UDRMap.find(D);
1256 if (I != UDRMap.end())
1257 return I->second;
1258 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1259 return UDRMap.lookup(D);
1260}
1261
John McCall7f416cc2015-09-08 08:05:57 +00001262// Layout information for ident_t.
1263static CharUnits getIdentAlign(CodeGenModule &CGM) {
1264 return CGM.getPointerAlign();
1265}
1266static CharUnits getIdentSize(CodeGenModule &CGM) {
1267 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1268 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1269}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001270static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001271 // All the fields except the last are i32, so this works beautifully.
1272 return unsigned(Field) * CharUnits::fromQuantity(4);
1273}
1274static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001275 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001276 const llvm::Twine &Name = "") {
1277 auto Offset = getOffsetOfIdentField(Field);
1278 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1279}
1280
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001281static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1282 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1283 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1284 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001285 assert(ThreadIDVar->getType()->isPointerType() &&
1286 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001287 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001288 bool HasCancel = false;
1289 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1290 HasCancel = OPD->hasCancel();
1291 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1292 HasCancel = OPSD->hasCancel();
1293 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1294 HasCancel = OPFD->hasCancel();
1295 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001296 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001297 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001298 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001299}
1300
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001301llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1302 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1303 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1304 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1305 return emitParallelOrTeamsOutlinedFunction(
1306 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1307}
1308
1309llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1310 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1311 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1312 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1313 return emitParallelOrTeamsOutlinedFunction(
1314 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1315}
1316
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001317llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1318 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001319 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1320 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1321 bool Tied, unsigned &NumberOfParts) {
1322 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1323 PrePostActionTy &) {
1324 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1325 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1326 llvm::Value *TaskArgs[] = {
1327 UpLoc, ThreadID,
1328 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1329 TaskTVar->getType()->castAs<PointerType>())
1330 .getPointer()};
1331 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1332 };
1333 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1334 UntiedCodeGen);
1335 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001336 assert(!ThreadIDVar->getType()->isPointerType() &&
1337 "thread id variable must be of type kmp_int32 for tasks");
1338 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001339 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001340 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001341 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1342 InnermostKind,
1343 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001344 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001345 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1346 if (!Tied)
1347 NumberOfParts = Action.getNumberOfParts();
1348 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001349}
1350
Alexey Bataev50b3c952016-02-19 10:38:26 +00001351Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001352 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001353 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001354 if (!Entry) {
1355 if (!DefaultOpenMPPSource) {
1356 // Initialize default location for psource field of ident_t structure of
1357 // all ident_t objects. Format is ";file;function;line;column;;".
1358 // Taken from
1359 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1360 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001361 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001362 DefaultOpenMPPSource =
1363 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1364 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001365
John McCall23c9dc62016-11-28 22:18:27 +00001366 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001367 auto fields = builder.beginStruct(IdentTy);
1368 fields.addInt(CGM.Int32Ty, 0);
1369 fields.addInt(CGM.Int32Ty, Flags);
1370 fields.addInt(CGM.Int32Ty, 0);
1371 fields.addInt(CGM.Int32Ty, 0);
1372 fields.add(DefaultOpenMPPSource);
1373 auto DefaultOpenMPLocation =
1374 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1375 llvm::GlobalValue::PrivateLinkage);
1376 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1377
John McCall7f416cc2015-09-08 08:05:57 +00001378 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001379 }
John McCall7f416cc2015-09-08 08:05:57 +00001380 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001381}
1382
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001383llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1384 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001385 unsigned Flags) {
1386 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001387 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001388 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001389 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001390 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001391
1392 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1393
John McCall7f416cc2015-09-08 08:05:57 +00001394 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001395 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1396 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001397 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1398
Alexander Musmanc6388682014-12-15 07:07:06 +00001399 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1400 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001401 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001402 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001403 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1404 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001405 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001406 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001407 LocValue = AI;
1408
1409 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1410 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001411 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001412 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001413 }
1414
1415 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001416 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001417
Alexey Bataevf002aca2014-05-30 05:48:40 +00001418 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1419 if (OMPDebugLoc == nullptr) {
1420 SmallString<128> Buffer2;
1421 llvm::raw_svector_ostream OS2(Buffer2);
1422 // Build debug location
1423 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1424 OS2 << ";" << PLoc.getFilename() << ";";
1425 if (const FunctionDecl *FD =
1426 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1427 OS2 << FD->getQualifiedNameAsString();
1428 }
1429 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1430 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1431 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001432 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001433 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001434 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1435
John McCall7f416cc2015-09-08 08:05:57 +00001436 // Our callers always pass this to a runtime function, so for
1437 // convenience, go ahead and return a naked pointer.
1438 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001439}
1440
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001441llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1442 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001443 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1444
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001445 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001446 // Check whether we've already cached a load of the thread id in this
1447 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001448 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001449 if (I != OpenMPLocThreadIDMap.end()) {
1450 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001451 if (ThreadID != nullptr)
1452 return ThreadID;
1453 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001454 // If exceptions are enabled, do not use parameter to avoid possible crash.
1455 if (!CGF.getInvokeDest()) {
1456 if (auto *OMPRegionInfo =
1457 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1458 if (OMPRegionInfo->getThreadIDVariable()) {
1459 // Check if this an outlined function with thread id passed as argument.
1460 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1461 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1462 // If value loaded in entry block, cache it and use it everywhere in
1463 // function.
1464 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1465 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1466 Elem.second.ThreadID = ThreadID;
1467 }
1468 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001469 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001470 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001471 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001472
1473 // This is not an outlined function region - need to call __kmpc_int32
1474 // kmpc_global_thread_num(ident_t *loc).
1475 // Generate thread id value and cache this value for use across the
1476 // function.
1477 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1478 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1479 ThreadID =
1480 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1481 emitUpdateLocation(CGF, Loc));
1482 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1483 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001484 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001485}
1486
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001487void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001488 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001489 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1490 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001491 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1492 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1493 UDRMap.erase(D);
1494 }
1495 FunctionUDRMap.erase(CGF.CurFn);
1496 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001497}
1498
1499llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001500 if (!IdentTy) {
1501 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001502 return llvm::PointerType::getUnqual(IdentTy);
1503}
1504
1505llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001506 if (!Kmpc_MicroTy) {
1507 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1508 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1509 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1510 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1511 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001512 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1513}
1514
1515llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001516CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001517 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001518 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001519 case OMPRTL__kmpc_fork_call: {
1520 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1521 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001522 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1523 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001524 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001525 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001526 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1527 break;
1528 }
1529 case OMPRTL__kmpc_global_thread_num: {
1530 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001531 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001532 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001533 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001534 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1535 break;
1536 }
Alexey Bataev97720002014-11-11 04:05:39 +00001537 case OMPRTL__kmpc_threadprivate_cached: {
1538 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1539 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1540 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1541 CGM.VoidPtrTy, CGM.SizeTy,
1542 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1543 llvm::FunctionType *FnTy =
1544 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1545 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1546 break;
1547 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001548 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001549 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1550 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001551 llvm::Type *TypeParams[] = {
1552 getIdentTyPointerTy(), CGM.Int32Ty,
1553 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1554 llvm::FunctionType *FnTy =
1555 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1556 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1557 break;
1558 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001559 case OMPRTL__kmpc_critical_with_hint: {
1560 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1561 // kmp_critical_name *crit, uintptr_t hint);
1562 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1563 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1564 CGM.IntPtrTy};
1565 llvm::FunctionType *FnTy =
1566 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1568 break;
1569 }
Alexey Bataev97720002014-11-11 04:05:39 +00001570 case OMPRTL__kmpc_threadprivate_register: {
1571 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1572 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1573 // typedef void *(*kmpc_ctor)(void *);
1574 auto KmpcCtorTy =
1575 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1576 /*isVarArg*/ false)->getPointerTo();
1577 // typedef void *(*kmpc_cctor)(void *, void *);
1578 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1579 auto KmpcCopyCtorTy =
1580 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1581 /*isVarArg*/ false)->getPointerTo();
1582 // typedef void (*kmpc_dtor)(void *);
1583 auto KmpcDtorTy =
1584 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1585 ->getPointerTo();
1586 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1587 KmpcCopyCtorTy, KmpcDtorTy};
1588 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1589 /*isVarArg*/ false);
1590 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1591 break;
1592 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001593 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001594 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1595 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001596 llvm::Type *TypeParams[] = {
1597 getIdentTyPointerTy(), CGM.Int32Ty,
1598 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1599 llvm::FunctionType *FnTy =
1600 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1602 break;
1603 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001604 case OMPRTL__kmpc_cancel_barrier: {
1605 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1606 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001607 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1608 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001609 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1610 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001611 break;
1612 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001613 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001614 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001615 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1616 llvm::FunctionType *FnTy =
1617 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1618 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1619 break;
1620 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001621 case OMPRTL__kmpc_for_static_fini: {
1622 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1623 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1624 llvm::FunctionType *FnTy =
1625 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1626 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1627 break;
1628 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001629 case OMPRTL__kmpc_push_num_threads: {
1630 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1631 // kmp_int32 num_threads)
1632 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1633 CGM.Int32Ty};
1634 llvm::FunctionType *FnTy =
1635 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1636 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1637 break;
1638 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001639 case OMPRTL__kmpc_serialized_parallel: {
1640 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1641 // global_tid);
1642 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1643 llvm::FunctionType *FnTy =
1644 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1645 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1646 break;
1647 }
1648 case OMPRTL__kmpc_end_serialized_parallel: {
1649 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1650 // global_tid);
1651 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1652 llvm::FunctionType *FnTy =
1653 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1654 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1655 break;
1656 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001657 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001658 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001659 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1660 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001662 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1663 break;
1664 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001665 case OMPRTL__kmpc_master: {
1666 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1667 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1668 llvm::FunctionType *FnTy =
1669 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1670 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1671 break;
1672 }
1673 case OMPRTL__kmpc_end_master: {
1674 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1675 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1676 llvm::FunctionType *FnTy =
1677 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1678 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1679 break;
1680 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001681 case OMPRTL__kmpc_omp_taskyield: {
1682 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1683 // int end_part);
1684 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1685 llvm::FunctionType *FnTy =
1686 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1688 break;
1689 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001690 case OMPRTL__kmpc_single: {
1691 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1692 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1693 llvm::FunctionType *FnTy =
1694 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1695 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1696 break;
1697 }
1698 case OMPRTL__kmpc_end_single: {
1699 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1700 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1701 llvm::FunctionType *FnTy =
1702 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1703 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1704 break;
1705 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001706 case OMPRTL__kmpc_omp_task_alloc: {
1707 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1708 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1709 // kmp_routine_entry_t *task_entry);
1710 assert(KmpRoutineEntryPtrTy != nullptr &&
1711 "Type kmp_routine_entry_t must be created.");
1712 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1713 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1714 // Return void * and then cast to particular kmp_task_t type.
1715 llvm::FunctionType *FnTy =
1716 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1717 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1718 break;
1719 }
1720 case OMPRTL__kmpc_omp_task: {
1721 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1722 // *new_task);
1723 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1724 CGM.VoidPtrTy};
1725 llvm::FunctionType *FnTy =
1726 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1727 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1728 break;
1729 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001730 case OMPRTL__kmpc_copyprivate: {
1731 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001732 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001733 // kmp_int32 didit);
1734 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1735 auto *CpyFnTy =
1736 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001737 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001738 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1739 CGM.Int32Ty};
1740 llvm::FunctionType *FnTy =
1741 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1743 break;
1744 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001745 case OMPRTL__kmpc_reduce: {
1746 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1747 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1748 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1749 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1750 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1751 /*isVarArg=*/false);
1752 llvm::Type *TypeParams[] = {
1753 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1754 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1755 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1756 llvm::FunctionType *FnTy =
1757 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1758 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1759 break;
1760 }
1761 case OMPRTL__kmpc_reduce_nowait: {
1762 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1763 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1764 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1765 // *lck);
1766 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1767 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1768 /*isVarArg=*/false);
1769 llvm::Type *TypeParams[] = {
1770 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1771 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1772 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1773 llvm::FunctionType *FnTy =
1774 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1775 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1776 break;
1777 }
1778 case OMPRTL__kmpc_end_reduce: {
1779 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1780 // kmp_critical_name *lck);
1781 llvm::Type *TypeParams[] = {
1782 getIdentTyPointerTy(), CGM.Int32Ty,
1783 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1784 llvm::FunctionType *FnTy =
1785 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1787 break;
1788 }
1789 case OMPRTL__kmpc_end_reduce_nowait: {
1790 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1791 // kmp_critical_name *lck);
1792 llvm::Type *TypeParams[] = {
1793 getIdentTyPointerTy(), CGM.Int32Ty,
1794 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1795 llvm::FunctionType *FnTy =
1796 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1797 RTLFn =
1798 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1799 break;
1800 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001801 case OMPRTL__kmpc_omp_task_begin_if0: {
1802 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1803 // *new_task);
1804 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1805 CGM.VoidPtrTy};
1806 llvm::FunctionType *FnTy =
1807 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1808 RTLFn =
1809 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1810 break;
1811 }
1812 case OMPRTL__kmpc_omp_task_complete_if0: {
1813 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1814 // *new_task);
1815 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1816 CGM.VoidPtrTy};
1817 llvm::FunctionType *FnTy =
1818 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1819 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1820 /*Name=*/"__kmpc_omp_task_complete_if0");
1821 break;
1822 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001823 case OMPRTL__kmpc_ordered: {
1824 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1825 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1826 llvm::FunctionType *FnTy =
1827 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1828 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1829 break;
1830 }
1831 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001832 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001833 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1834 llvm::FunctionType *FnTy =
1835 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1836 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1837 break;
1838 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001839 case OMPRTL__kmpc_omp_taskwait: {
1840 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1841 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1842 llvm::FunctionType *FnTy =
1843 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1844 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1845 break;
1846 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001847 case OMPRTL__kmpc_taskgroup: {
1848 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1849 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1850 llvm::FunctionType *FnTy =
1851 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1852 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1853 break;
1854 }
1855 case OMPRTL__kmpc_end_taskgroup: {
1856 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1857 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1858 llvm::FunctionType *FnTy =
1859 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1860 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1861 break;
1862 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001863 case OMPRTL__kmpc_push_proc_bind: {
1864 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1865 // int proc_bind)
1866 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1867 llvm::FunctionType *FnTy =
1868 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1869 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1870 break;
1871 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001872 case OMPRTL__kmpc_omp_task_with_deps: {
1873 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1874 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1875 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1876 llvm::Type *TypeParams[] = {
1877 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1878 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1879 llvm::FunctionType *FnTy =
1880 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1881 RTLFn =
1882 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1883 break;
1884 }
1885 case OMPRTL__kmpc_omp_wait_deps: {
1886 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1887 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1888 // kmp_depend_info_t *noalias_dep_list);
1889 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1890 CGM.Int32Ty, CGM.VoidPtrTy,
1891 CGM.Int32Ty, CGM.VoidPtrTy};
1892 llvm::FunctionType *FnTy =
1893 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1894 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1895 break;
1896 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001897 case OMPRTL__kmpc_cancellationpoint: {
1898 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1899 // global_tid, kmp_int32 cncl_kind)
1900 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1901 llvm::FunctionType *FnTy =
1902 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1903 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1904 break;
1905 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001906 case OMPRTL__kmpc_cancel: {
1907 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1908 // kmp_int32 cncl_kind)
1909 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1910 llvm::FunctionType *FnTy =
1911 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1912 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1913 break;
1914 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001915 case OMPRTL__kmpc_push_num_teams: {
1916 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1917 // kmp_int32 num_teams, kmp_int32 num_threads)
1918 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1919 CGM.Int32Ty};
1920 llvm::FunctionType *FnTy =
1921 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1922 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1923 break;
1924 }
1925 case OMPRTL__kmpc_fork_teams: {
1926 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1927 // microtask, ...);
1928 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1929 getKmpc_MicroPointerTy()};
1930 llvm::FunctionType *FnTy =
1931 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1932 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1933 break;
1934 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001935 case OMPRTL__kmpc_taskloop: {
1936 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1937 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1938 // sched, kmp_uint64 grainsize, void *task_dup);
1939 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1940 CGM.IntTy,
1941 CGM.VoidPtrTy,
1942 CGM.IntTy,
1943 CGM.Int64Ty->getPointerTo(),
1944 CGM.Int64Ty->getPointerTo(),
1945 CGM.Int64Ty,
1946 CGM.IntTy,
1947 CGM.IntTy,
1948 CGM.Int64Ty,
1949 CGM.VoidPtrTy};
1950 llvm::FunctionType *FnTy =
1951 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1952 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1953 break;
1954 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001955 case OMPRTL__kmpc_doacross_init: {
1956 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1957 // num_dims, struct kmp_dim *dims);
1958 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1959 CGM.Int32Ty,
1960 CGM.Int32Ty,
1961 CGM.VoidPtrTy};
1962 llvm::FunctionType *FnTy =
1963 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1964 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1965 break;
1966 }
1967 case OMPRTL__kmpc_doacross_fini: {
1968 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1969 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1970 llvm::FunctionType *FnTy =
1971 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1972 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1973 break;
1974 }
1975 case OMPRTL__kmpc_doacross_post: {
1976 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1977 // *vec);
1978 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1979 CGM.Int64Ty->getPointerTo()};
1980 llvm::FunctionType *FnTy =
1981 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1982 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1983 break;
1984 }
1985 case OMPRTL__kmpc_doacross_wait: {
1986 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1987 // *vec);
1988 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1989 CGM.Int64Ty->getPointerTo()};
1990 llvm::FunctionType *FnTy =
1991 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1992 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1993 break;
1994 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001995 case OMPRTL__kmpc_task_reduction_init: {
1996 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1997 // *data);
1998 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1999 llvm::FunctionType *FnTy =
2000 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2001 RTLFn =
2002 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2003 break;
2004 }
2005 case OMPRTL__kmpc_task_reduction_get_th_data: {
2006 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2007 // *d);
2008 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2009 llvm::FunctionType *FnTy =
2010 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2011 RTLFn = CGM.CreateRuntimeFunction(
2012 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2013 break;
2014 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002015 case OMPRTL__tgt_target: {
2016 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2017 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2018 // *arg_types);
2019 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2020 CGM.VoidPtrTy,
2021 CGM.Int32Ty,
2022 CGM.VoidPtrPtrTy,
2023 CGM.VoidPtrPtrTy,
2024 CGM.SizeTy->getPointerTo(),
2025 CGM.Int32Ty->getPointerTo()};
2026 llvm::FunctionType *FnTy =
2027 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2028 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2029 break;
2030 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002031 case OMPRTL__tgt_target_teams: {
2032 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2033 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2034 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2035 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2036 CGM.VoidPtrTy,
2037 CGM.Int32Ty,
2038 CGM.VoidPtrPtrTy,
2039 CGM.VoidPtrPtrTy,
2040 CGM.SizeTy->getPointerTo(),
2041 CGM.Int32Ty->getPointerTo(),
2042 CGM.Int32Ty,
2043 CGM.Int32Ty};
2044 llvm::FunctionType *FnTy =
2045 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2046 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2047 break;
2048 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002049 case OMPRTL__tgt_register_lib: {
2050 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2051 QualType ParamTy =
2052 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2053 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2054 llvm::FunctionType *FnTy =
2055 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2056 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2057 break;
2058 }
2059 case OMPRTL__tgt_unregister_lib: {
2060 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2061 QualType ParamTy =
2062 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2063 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2064 llvm::FunctionType *FnTy =
2065 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2066 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2067 break;
2068 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002069 case OMPRTL__tgt_target_data_begin: {
2070 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2071 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2072 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2073 CGM.Int32Ty,
2074 CGM.VoidPtrPtrTy,
2075 CGM.VoidPtrPtrTy,
2076 CGM.SizeTy->getPointerTo(),
2077 CGM.Int32Ty->getPointerTo()};
2078 llvm::FunctionType *FnTy =
2079 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2080 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2081 break;
2082 }
2083 case OMPRTL__tgt_target_data_end: {
2084 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2085 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2086 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2087 CGM.Int32Ty,
2088 CGM.VoidPtrPtrTy,
2089 CGM.VoidPtrPtrTy,
2090 CGM.SizeTy->getPointerTo(),
2091 CGM.Int32Ty->getPointerTo()};
2092 llvm::FunctionType *FnTy =
2093 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2094 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2095 break;
2096 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002097 case OMPRTL__tgt_target_data_update: {
2098 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2099 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2100 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2101 CGM.Int32Ty,
2102 CGM.VoidPtrPtrTy,
2103 CGM.VoidPtrPtrTy,
2104 CGM.SizeTy->getPointerTo(),
2105 CGM.Int32Ty->getPointerTo()};
2106 llvm::FunctionType *FnTy =
2107 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2108 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2109 break;
2110 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002111 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002112 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002113 return RTLFn;
2114}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002115
Alexander Musman21212e42015-03-13 10:38:23 +00002116llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2117 bool IVSigned) {
2118 assert((IVSize == 32 || IVSize == 64) &&
2119 "IV size is not compatible with the omp runtime");
2120 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2121 : "__kmpc_for_static_init_4u")
2122 : (IVSigned ? "__kmpc_for_static_init_8"
2123 : "__kmpc_for_static_init_8u");
2124 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2125 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2126 llvm::Type *TypeParams[] = {
2127 getIdentTyPointerTy(), // loc
2128 CGM.Int32Ty, // tid
2129 CGM.Int32Ty, // schedtype
2130 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2131 PtrTy, // p_lower
2132 PtrTy, // p_upper
2133 PtrTy, // p_stride
2134 ITy, // incr
2135 ITy // chunk
2136 };
2137 llvm::FunctionType *FnTy =
2138 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2139 return CGM.CreateRuntimeFunction(FnTy, Name);
2140}
2141
Alexander Musman92bdaab2015-03-12 13:37:50 +00002142llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2143 bool IVSigned) {
2144 assert((IVSize == 32 || IVSize == 64) &&
2145 "IV size is not compatible with the omp runtime");
2146 auto Name =
2147 IVSize == 32
2148 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2149 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2150 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2151 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2152 CGM.Int32Ty, // tid
2153 CGM.Int32Ty, // schedtype
2154 ITy, // lower
2155 ITy, // upper
2156 ITy, // stride
2157 ITy // chunk
2158 };
2159 llvm::FunctionType *FnTy =
2160 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2161 return CGM.CreateRuntimeFunction(FnTy, Name);
2162}
2163
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002164llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2165 bool IVSigned) {
2166 assert((IVSize == 32 || IVSize == 64) &&
2167 "IV size is not compatible with the omp runtime");
2168 auto Name =
2169 IVSize == 32
2170 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2171 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2172 llvm::Type *TypeParams[] = {
2173 getIdentTyPointerTy(), // loc
2174 CGM.Int32Ty, // tid
2175 };
2176 llvm::FunctionType *FnTy =
2177 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2178 return CGM.CreateRuntimeFunction(FnTy, Name);
2179}
2180
Alexander Musman92bdaab2015-03-12 13:37:50 +00002181llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2182 bool IVSigned) {
2183 assert((IVSize == 32 || IVSize == 64) &&
2184 "IV size is not compatible with the omp runtime");
2185 auto Name =
2186 IVSize == 32
2187 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2188 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2189 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2190 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2191 llvm::Type *TypeParams[] = {
2192 getIdentTyPointerTy(), // loc
2193 CGM.Int32Ty, // tid
2194 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2195 PtrTy, // p_lower
2196 PtrTy, // p_upper
2197 PtrTy // p_stride
2198 };
2199 llvm::FunctionType *FnTy =
2200 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2201 return CGM.CreateRuntimeFunction(FnTy, Name);
2202}
2203
Alexey Bataev97720002014-11-11 04:05:39 +00002204llvm::Constant *
2205CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002206 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2207 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002208 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002209 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002210 Twine(CGM.getMangledName(VD)) + ".cache.");
2211}
2212
John McCall7f416cc2015-09-08 08:05:57 +00002213Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2214 const VarDecl *VD,
2215 Address VDAddr,
2216 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002217 if (CGM.getLangOpts().OpenMPUseTLS &&
2218 CGM.getContext().getTargetInfo().isTLSSupported())
2219 return VDAddr;
2220
John McCall7f416cc2015-09-08 08:05:57 +00002221 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002222 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002223 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2224 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002225 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2226 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002227 return Address(CGF.EmitRuntimeCall(
2228 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2229 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002230}
2231
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002232void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002233 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002234 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2235 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2236 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002237 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2238 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002239 OMPLoc);
2240 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2241 // to register constructor/destructor for variable.
2242 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002243 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2244 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002245 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002246 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002247 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002248}
2249
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002250llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002251 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002252 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002253 if (CGM.getLangOpts().OpenMPUseTLS &&
2254 CGM.getContext().getTargetInfo().isTLSSupported())
2255 return nullptr;
2256
Alexey Bataev97720002014-11-11 04:05:39 +00002257 VD = VD->getDefinition(CGM.getContext());
2258 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2259 ThreadPrivateWithDefinition.insert(VD);
2260 QualType ASTTy = VD->getType();
2261
2262 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2263 auto Init = VD->getAnyInitializer();
2264 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2265 // Generate function that re-emits the declaration's initializer into the
2266 // threadprivate copy of the variable VD
2267 CodeGenFunction CtorCGF(CGM);
2268 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002269 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2270 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002271 Args.push_back(&Dst);
2272
John McCallc56a8b32016-03-11 04:30:31 +00002273 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2274 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002275 auto FTy = CGM.getTypes().GetFunctionType(FI);
2276 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002277 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002278 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2279 Args, SourceLocation());
2280 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002281 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002282 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002283 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2284 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2285 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002286 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2287 /*IsInitializer=*/true);
2288 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002289 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002290 CGM.getContext().VoidPtrTy, Dst.getLocation());
2291 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2292 CtorCGF.FinishFunction();
2293 Ctor = Fn;
2294 }
2295 if (VD->getType().isDestructedType() != QualType::DK_none) {
2296 // Generate function that emits destructor call for the threadprivate copy
2297 // of the variable VD
2298 CodeGenFunction DtorCGF(CGM);
2299 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002300 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2301 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002302 Args.push_back(&Dst);
2303
John McCallc56a8b32016-03-11 04:30:31 +00002304 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2305 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002306 auto FTy = CGM.getTypes().GetFunctionType(FI);
2307 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002308 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002309 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002310 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2311 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002312 // Create a scope with an artificial location for the body of this function.
2313 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002314 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2315 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002316 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2317 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002318 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2319 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2320 DtorCGF.FinishFunction();
2321 Dtor = Fn;
2322 }
2323 // Do not emit init function if it is not required.
2324 if (!Ctor && !Dtor)
2325 return nullptr;
2326
2327 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2328 auto CopyCtorTy =
2329 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2330 /*isVarArg=*/false)->getPointerTo();
2331 // Copying constructor for the threadprivate variable.
2332 // Must be NULL - reserved by runtime, but currently it requires that this
2333 // parameter is always NULL. Otherwise it fires assertion.
2334 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2335 if (Ctor == nullptr) {
2336 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2337 /*isVarArg=*/false)->getPointerTo();
2338 Ctor = llvm::Constant::getNullValue(CtorTy);
2339 }
2340 if (Dtor == nullptr) {
2341 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2342 /*isVarArg=*/false)->getPointerTo();
2343 Dtor = llvm::Constant::getNullValue(DtorTy);
2344 }
2345 if (!CGF) {
2346 auto InitFunctionTy =
2347 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2348 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002349 InitFunctionTy, ".__omp_threadprivate_init_.",
2350 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002351 CodeGenFunction InitCGF(CGM);
2352 FunctionArgList ArgList;
2353 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2354 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2355 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002356 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002357 InitCGF.FinishFunction();
2358 return InitFunction;
2359 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002360 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002361 }
2362 return nullptr;
2363}
2364
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002365Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2366 QualType VarType,
2367 StringRef Name) {
2368 llvm::Twine VarName(Name, ".artificial.");
2369 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2370 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2371 llvm::Value *Args[] = {
2372 emitUpdateLocation(CGF, SourceLocation()),
2373 getThreadID(CGF, SourceLocation()),
2374 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2375 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2376 /*IsSigned=*/false),
2377 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2378 return Address(
2379 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2380 CGF.EmitRuntimeCall(
2381 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2382 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2383 CGM.getPointerAlign());
2384}
2385
Alexey Bataev1d677132015-04-22 13:57:31 +00002386/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2387/// function. Here is the logic:
2388/// if (Cond) {
2389/// ThenGen();
2390/// } else {
2391/// ElseGen();
2392/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002393void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2394 const RegionCodeGenTy &ThenGen,
2395 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002396 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2397
2398 // If the condition constant folds and can be elided, try to avoid emitting
2399 // the condition and the dead arm of the if/else.
2400 bool CondConstant;
2401 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002402 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002403 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002404 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002405 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002406 return;
2407 }
2408
2409 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2410 // emit the conditional branch.
2411 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2412 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2413 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2414 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2415
2416 // Emit the 'then' code.
2417 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002418 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002419 CGF.EmitBranch(ContBlock);
2420 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002421 // There is no need to emit line number for unconditional branch.
2422 (void)ApplyDebugLocation::CreateEmpty(CGF);
2423 CGF.EmitBlock(ElseBlock);
2424 ElseGen(CGF);
2425 // There is no need to emit line number for unconditional branch.
2426 (void)ApplyDebugLocation::CreateEmpty(CGF);
2427 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002428 // Emit the continuation block for code after the if.
2429 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002430}
2431
Alexey Bataev1d677132015-04-22 13:57:31 +00002432void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2433 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002434 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002435 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002436 if (!CGF.HaveInsertPoint())
2437 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002438 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002439 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2440 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002441 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002442 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002443 llvm::Value *Args[] = {
2444 RTLoc,
2445 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002446 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002447 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2448 RealArgs.append(std::begin(Args), std::end(Args));
2449 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2450
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002451 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002452 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2453 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002454 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2455 PrePostActionTy &) {
2456 auto &RT = CGF.CGM.getOpenMPRuntime();
2457 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002458 // Build calls:
2459 // __kmpc_serialized_parallel(&Loc, GTid);
2460 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002461 CGF.EmitRuntimeCall(
2462 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002463
Alexey Bataev1d677132015-04-22 13:57:31 +00002464 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002465 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002466 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002467 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2468 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002469 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002470 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2471 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2472 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2473 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002474 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002475
Alexey Bataev1d677132015-04-22 13:57:31 +00002476 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002477 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002478 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002479 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2480 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002481 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002482 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002483 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002484 else {
2485 RegionCodeGenTy ThenRCG(ThenGen);
2486 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002487 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002488}
2489
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002490// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002491// thread-ID variable (it is passed in a first argument of the outlined function
2492// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2493// regular serial code region, get thread ID by calling kmp_int32
2494// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2495// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002496Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2497 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002498 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002499 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002500 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002501 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002502
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002503 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002504 auto Int32Ty =
2505 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2506 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2507 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002508 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002509
2510 return ThreadIDTemp;
2511}
2512
Alexey Bataev97720002014-11-11 04:05:39 +00002513llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002514CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002515 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002516 SmallString<256> Buffer;
2517 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002518 Out << Name;
2519 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002520 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2521 if (Elem.second) {
2522 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002523 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002524 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002525 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002526
David Blaikie13156b62014-11-19 03:06:06 +00002527 return Elem.second = new llvm::GlobalVariable(
2528 CGM.getModule(), Ty, /*IsConstant*/ false,
2529 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2530 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002531}
2532
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002533llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002534 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002535 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002536}
2537
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002538namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002539/// Common pre(post)-action for different OpenMP constructs.
2540class CommonActionTy final : public PrePostActionTy {
2541 llvm::Value *EnterCallee;
2542 ArrayRef<llvm::Value *> EnterArgs;
2543 llvm::Value *ExitCallee;
2544 ArrayRef<llvm::Value *> ExitArgs;
2545 bool Conditional;
2546 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002547
2548public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002549 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2550 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2551 bool Conditional = false)
2552 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2553 ExitArgs(ExitArgs), Conditional(Conditional) {}
2554 void Enter(CodeGenFunction &CGF) override {
2555 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2556 if (Conditional) {
2557 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2558 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2559 ContBlock = CGF.createBasicBlock("omp_if.end");
2560 // Generate the branch (If-stmt)
2561 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2562 CGF.EmitBlock(ThenBlock);
2563 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002564 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002565 void Done(CodeGenFunction &CGF) {
2566 // Emit the rest of blocks/branches
2567 CGF.EmitBranch(ContBlock);
2568 CGF.EmitBlock(ContBlock, true);
2569 }
2570 void Exit(CodeGenFunction &CGF) override {
2571 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002572 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002573};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002574} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002575
2576void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2577 StringRef CriticalName,
2578 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002579 SourceLocation Loc, const Expr *Hint) {
2580 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002581 // CriticalOpGen();
2582 // __kmpc_end_critical(ident_t *, gtid, Lock);
2583 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002584 if (!CGF.HaveInsertPoint())
2585 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002586 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2587 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002588 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2589 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002590 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002591 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2592 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2593 }
2594 CommonActionTy Action(
2595 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2596 : OMPRTL__kmpc_critical),
2597 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2598 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002599 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002600}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002601
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002602void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002603 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002604 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002605 if (!CGF.HaveInsertPoint())
2606 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002607 // if(__kmpc_master(ident_t *, gtid)) {
2608 // MasterOpGen();
2609 // __kmpc_end_master(ident_t *, gtid);
2610 // }
2611 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002612 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002613 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2614 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2615 /*Conditional=*/true);
2616 MasterOpGen.setAction(Action);
2617 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2618 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002619}
2620
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002621void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2622 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002623 if (!CGF.HaveInsertPoint())
2624 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002625 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2626 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002627 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002628 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002629 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002630 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2631 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002632}
2633
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002634void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2635 const RegionCodeGenTy &TaskgroupOpGen,
2636 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002637 if (!CGF.HaveInsertPoint())
2638 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002639 // __kmpc_taskgroup(ident_t *, gtid);
2640 // TaskgroupOpGen();
2641 // __kmpc_end_taskgroup(ident_t *, gtid);
2642 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002643 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2644 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2645 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2646 Args);
2647 TaskgroupOpGen.setAction(Action);
2648 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002649}
2650
John McCall7f416cc2015-09-08 08:05:57 +00002651/// Given an array of pointers to variables, project the address of a
2652/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002653static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2654 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002655 // Pull out the pointer to the variable.
2656 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002657 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002658 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2659
2660 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002661 Addr = CGF.Builder.CreateElementBitCast(
2662 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002663 return Addr;
2664}
2665
Alexey Bataeva63048e2015-03-23 06:18:07 +00002666static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002667 CodeGenModule &CGM, llvm::Type *ArgsType,
2668 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2669 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002670 auto &C = CGM.getContext();
2671 // void copy_func(void *LHSArg, void *RHSArg);
2672 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002673 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2674 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002675 Args.push_back(&LHSArg);
2676 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002677 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002678 auto *Fn = llvm::Function::Create(
2679 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2680 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002681 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002682 CodeGenFunction CGF(CGM);
2683 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002684 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002685 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002686 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2687 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2688 ArgsType), CGF.getPointerAlign());
2689 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2690 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2691 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002692 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2693 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2694 // ...
2695 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002696 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002697 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2698 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2699
2700 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2701 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2702
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002703 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2704 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002705 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002706 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002707 CGF.FinishFunction();
2708 return Fn;
2709}
2710
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002711void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002712 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002713 SourceLocation Loc,
2714 ArrayRef<const Expr *> CopyprivateVars,
2715 ArrayRef<const Expr *> SrcExprs,
2716 ArrayRef<const Expr *> DstExprs,
2717 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002718 if (!CGF.HaveInsertPoint())
2719 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002720 assert(CopyprivateVars.size() == SrcExprs.size() &&
2721 CopyprivateVars.size() == DstExprs.size() &&
2722 CopyprivateVars.size() == AssignmentOps.size());
2723 auto &C = CGM.getContext();
2724 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002725 // if(__kmpc_single(ident_t *, gtid)) {
2726 // SingleOpGen();
2727 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002728 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002729 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002730 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2731 // <copy_func>, did_it);
2732
John McCall7f416cc2015-09-08 08:05:57 +00002733 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002734 if (!CopyprivateVars.empty()) {
2735 // int32 did_it = 0;
2736 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2737 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002738 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002739 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002740 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002741 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002742 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2743 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2744 /*Conditional=*/true);
2745 SingleOpGen.setAction(Action);
2746 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2747 if (DidIt.isValid()) {
2748 // did_it = 1;
2749 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2750 }
2751 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002752 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2753 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002754 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002755 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2756 auto CopyprivateArrayTy =
2757 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2758 /*IndexTypeQuals=*/0);
2759 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002760 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002761 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2762 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002763 Address Elem = CGF.Builder.CreateConstArrayGEP(
2764 CopyprivateList, I, CGF.getPointerSize());
2765 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002766 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002767 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2768 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002769 }
2770 // Build function that copies private values from single region to all other
2771 // threads in the corresponding parallel region.
2772 auto *CpyFn = emitCopyprivateCopyFunction(
2773 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002774 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002775 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002776 Address CL =
2777 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2778 CGF.VoidPtrTy);
2779 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002780 llvm::Value *Args[] = {
2781 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2782 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002783 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002784 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002785 CpyFn, // void (*) (void *, void *) <copy_func>
2786 DidItVal // i32 did_it
2787 };
2788 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2789 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002790}
2791
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002792void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2793 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002794 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002795 if (!CGF.HaveInsertPoint())
2796 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002797 // __kmpc_ordered(ident_t *, gtid);
2798 // OrderedOpGen();
2799 // __kmpc_end_ordered(ident_t *, gtid);
2800 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002801 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002802 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002803 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2804 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2805 Args);
2806 OrderedOpGen.setAction(Action);
2807 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2808 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002809 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002810 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002811}
2812
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002813void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002814 OpenMPDirectiveKind Kind, bool EmitChecks,
2815 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002816 if (!CGF.HaveInsertPoint())
2817 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002818 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002819 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002820 unsigned Flags;
2821 if (Kind == OMPD_for)
2822 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2823 else if (Kind == OMPD_sections)
2824 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2825 else if (Kind == OMPD_single)
2826 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2827 else if (Kind == OMPD_barrier)
2828 Flags = OMP_IDENT_BARRIER_EXPL;
2829 else
2830 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002831 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2832 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002833 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2834 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002835 if (auto *OMPRegionInfo =
2836 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002837 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002838 auto *Result = CGF.EmitRuntimeCall(
2839 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002840 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002841 // if (__kmpc_cancel_barrier()) {
2842 // exit from construct;
2843 // }
2844 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2845 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2846 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2847 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2848 CGF.EmitBlock(ExitBB);
2849 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002850 auto CancelDestination =
2851 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002852 CGF.EmitBranchThroughCleanup(CancelDestination);
2853 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2854 }
2855 return;
2856 }
2857 }
2858 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002859}
2860
Alexander Musmanc6388682014-12-15 07:07:06 +00002861/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2862static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002863 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002864 switch (ScheduleKind) {
2865 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002866 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2867 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002868 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002869 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002870 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002871 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002872 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002873 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2874 case OMPC_SCHEDULE_auto:
2875 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002876 case OMPC_SCHEDULE_unknown:
2877 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002878 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002879 }
2880 llvm_unreachable("Unexpected runtime schedule");
2881}
2882
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002883/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2884static OpenMPSchedType
2885getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2886 // only static is allowed for dist_schedule
2887 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2888}
2889
Alexander Musmanc6388682014-12-15 07:07:06 +00002890bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2891 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002892 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002893 return Schedule == OMP_sch_static;
2894}
2895
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002896bool CGOpenMPRuntime::isStaticNonchunked(
2897 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2898 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2899 return Schedule == OMP_dist_sch_static;
2900}
2901
2902
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002903bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002904 auto Schedule =
2905 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002906 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2907 return Schedule != OMP_sch_static;
2908}
2909
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002910static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2911 OpenMPScheduleClauseModifier M1,
2912 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002913 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002914 switch (M1) {
2915 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002916 Modifier = OMP_sch_modifier_monotonic;
2917 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002918 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002919 Modifier = OMP_sch_modifier_nonmonotonic;
2920 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002921 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002922 if (Schedule == OMP_sch_static_chunked)
2923 Schedule = OMP_sch_static_balanced_chunked;
2924 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002925 case OMPC_SCHEDULE_MODIFIER_last:
2926 case OMPC_SCHEDULE_MODIFIER_unknown:
2927 break;
2928 }
2929 switch (M2) {
2930 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002931 Modifier = OMP_sch_modifier_monotonic;
2932 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002933 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002934 Modifier = OMP_sch_modifier_nonmonotonic;
2935 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002936 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002937 if (Schedule == OMP_sch_static_chunked)
2938 Schedule = OMP_sch_static_balanced_chunked;
2939 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002940 case OMPC_SCHEDULE_MODIFIER_last:
2941 case OMPC_SCHEDULE_MODIFIER_unknown:
2942 break;
2943 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002944 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002945}
2946
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002947void CGOpenMPRuntime::emitForDispatchInit(
2948 CodeGenFunction &CGF, SourceLocation Loc,
2949 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2950 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002951 if (!CGF.HaveInsertPoint())
2952 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002953 OpenMPSchedType Schedule = getRuntimeSchedule(
2954 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002955 assert(Ordered ||
2956 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002957 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2958 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002959 // Call __kmpc_dispatch_init(
2960 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2961 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2962 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002963
John McCall7f416cc2015-09-08 08:05:57 +00002964 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002965 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2966 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002967 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002968 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2969 CGF.Builder.getInt32(addMonoNonMonoModifier(
2970 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002971 DispatchValues.LB, // Lower
2972 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002973 CGF.Builder.getIntN(IVSize, 1), // Stride
2974 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002975 };
2976 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2977}
2978
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002979static void emitForStaticInitCall(
2980 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2981 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2982 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002983 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002984 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002985 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002986
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002987 assert(!Values.Ordered);
2988 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2989 Schedule == OMP_sch_static_balanced_chunked ||
2990 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2991 Schedule == OMP_dist_sch_static ||
2992 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002993
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002994 // Call __kmpc_for_static_init(
2995 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2996 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2997 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2998 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2999 llvm::Value *Chunk = Values.Chunk;
3000 if (Chunk == nullptr) {
3001 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3002 Schedule == OMP_dist_sch_static) &&
3003 "expected static non-chunked schedule");
3004 // If the Chunk was not specified in the clause - use default value 1.
3005 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3006 } else {
3007 assert((Schedule == OMP_sch_static_chunked ||
3008 Schedule == OMP_sch_static_balanced_chunked ||
3009 Schedule == OMP_ord_static_chunked ||
3010 Schedule == OMP_dist_sch_static_chunked) &&
3011 "expected static chunked schedule");
3012 }
3013 llvm::Value *Args[] = {
3014 UpdateLocation,
3015 ThreadId,
3016 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3017 M2)), // Schedule type
3018 Values.IL.getPointer(), // &isLastIter
3019 Values.LB.getPointer(), // &LB
3020 Values.UB.getPointer(), // &UB
3021 Values.ST.getPointer(), // &Stride
3022 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3023 Chunk // Chunk
3024 };
3025 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003026}
3027
John McCall7f416cc2015-09-08 08:05:57 +00003028void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3029 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003030 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003031 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003032 const StaticRTInput &Values) {
3033 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3034 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3035 assert(isOpenMPWorksharingDirective(DKind) &&
3036 "Expected loop-based or sections-based directive.");
3037 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3038 isOpenMPLoopDirective(DKind)
3039 ? OMP_IDENT_WORK_LOOP
3040 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003041 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003042 auto *StaticInitFunction =
3043 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003044 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003045 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003046}
John McCall7f416cc2015-09-08 08:05:57 +00003047
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003048void CGOpenMPRuntime::emitDistributeStaticInit(
3049 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003050 OpenMPDistScheduleClauseKind SchedKind,
3051 const CGOpenMPRuntime::StaticRTInput &Values) {
3052 OpenMPSchedType ScheduleNum =
3053 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3054 auto *UpdatedLocation =
3055 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003056 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003057 auto *StaticInitFunction =
3058 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003059 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3060 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003061 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003062}
3063
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003064void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003065 SourceLocation Loc,
3066 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003067 if (!CGF.HaveInsertPoint())
3068 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003069 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003070 llvm::Value *Args[] = {
3071 emitUpdateLocation(CGF, Loc,
3072 isOpenMPDistributeDirective(DKind)
3073 ? OMP_IDENT_WORK_DISTRIBUTE
3074 : isOpenMPLoopDirective(DKind)
3075 ? OMP_IDENT_WORK_LOOP
3076 : OMP_IDENT_WORK_SECTIONS),
3077 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003078 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3079 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003080}
3081
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003082void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3083 SourceLocation Loc,
3084 unsigned IVSize,
3085 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003086 if (!CGF.HaveInsertPoint())
3087 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003088 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003089 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003090 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3091}
3092
Alexander Musman92bdaab2015-03-12 13:37:50 +00003093llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3094 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003095 bool IVSigned, Address IL,
3096 Address LB, Address UB,
3097 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003098 // Call __kmpc_dispatch_next(
3099 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3100 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3101 // kmp_int[32|64] *p_stride);
3102 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003103 emitUpdateLocation(CGF, Loc),
3104 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003105 IL.getPointer(), // &isLastIter
3106 LB.getPointer(), // &Lower
3107 UB.getPointer(), // &Upper
3108 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003109 };
3110 llvm::Value *Call =
3111 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3112 return CGF.EmitScalarConversion(
3113 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003114 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003115}
3116
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003117void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3118 llvm::Value *NumThreads,
3119 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003120 if (!CGF.HaveInsertPoint())
3121 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003122 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3123 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003124 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003125 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003126 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3127 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003128}
3129
Alexey Bataev7f210c62015-06-18 13:40:03 +00003130void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3131 OpenMPProcBindClauseKind ProcBind,
3132 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003133 if (!CGF.HaveInsertPoint())
3134 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003135 // Constants for proc bind value accepted by the runtime.
3136 enum ProcBindTy {
3137 ProcBindFalse = 0,
3138 ProcBindTrue,
3139 ProcBindMaster,
3140 ProcBindClose,
3141 ProcBindSpread,
3142 ProcBindIntel,
3143 ProcBindDefault
3144 } RuntimeProcBind;
3145 switch (ProcBind) {
3146 case OMPC_PROC_BIND_master:
3147 RuntimeProcBind = ProcBindMaster;
3148 break;
3149 case OMPC_PROC_BIND_close:
3150 RuntimeProcBind = ProcBindClose;
3151 break;
3152 case OMPC_PROC_BIND_spread:
3153 RuntimeProcBind = ProcBindSpread;
3154 break;
3155 case OMPC_PROC_BIND_unknown:
3156 llvm_unreachable("Unsupported proc_bind value.");
3157 }
3158 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3159 llvm::Value *Args[] = {
3160 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3161 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3162 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3163}
3164
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003165void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3166 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003167 if (!CGF.HaveInsertPoint())
3168 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003169 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003170 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3171 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003172}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003173
Alexey Bataev62b63b12015-03-10 07:28:44 +00003174namespace {
3175/// \brief Indexes of fields for type kmp_task_t.
3176enum KmpTaskTFields {
3177 /// \brief List of shared variables.
3178 KmpTaskTShareds,
3179 /// \brief Task routine.
3180 KmpTaskTRoutine,
3181 /// \brief Partition id for the untied tasks.
3182 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003183 /// Function with call of destructors for private variables.
3184 Data1,
3185 /// Task priority.
3186 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003187 /// (Taskloops only) Lower bound.
3188 KmpTaskTLowerBound,
3189 /// (Taskloops only) Upper bound.
3190 KmpTaskTUpperBound,
3191 /// (Taskloops only) Stride.
3192 KmpTaskTStride,
3193 /// (Taskloops only) Is last iteration flag.
3194 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003195 /// (Taskloops only) Reduction data.
3196 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003197};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003198} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003199
Samuel Antaoee8fb302016-01-06 13:42:12 +00003200bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3201 // FIXME: Add other entries type when they become supported.
3202 return OffloadEntriesTargetRegion.empty();
3203}
3204
3205/// \brief Initialize target region entry.
3206void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3207 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3208 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003209 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003210 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3211 "only required for the device "
3212 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003213 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003214 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3215 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003216 ++OffloadingEntriesNum;
3217}
3218
3219void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3220 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3221 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003222 llvm::Constant *Addr, llvm::Constant *ID,
3223 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003224 // If we are emitting code for a target, the entry is already initialized,
3225 // only has to be registered.
3226 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003227 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003228 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003229 auto &Entry =
3230 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003231 assert(Entry.isValid() && "Entry not initialized!");
3232 Entry.setAddress(Addr);
3233 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003234 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003235 return;
3236 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003237 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003238 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003239 }
3240}
3241
3242bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003243 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3244 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003245 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3246 if (PerDevice == OffloadEntriesTargetRegion.end())
3247 return false;
3248 auto PerFile = PerDevice->second.find(FileID);
3249 if (PerFile == PerDevice->second.end())
3250 return false;
3251 auto PerParentName = PerFile->second.find(ParentName);
3252 if (PerParentName == PerFile->second.end())
3253 return false;
3254 auto PerLine = PerParentName->second.find(LineNum);
3255 if (PerLine == PerParentName->second.end())
3256 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003257 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003258 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003259 return false;
3260 return true;
3261}
3262
3263void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3264 const OffloadTargetRegionEntryInfoActTy &Action) {
3265 // Scan all target region entries and perform the provided action.
3266 for (auto &D : OffloadEntriesTargetRegion)
3267 for (auto &F : D.second)
3268 for (auto &P : F.second)
3269 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003270 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003271}
3272
3273/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3274/// \a Codegen. This is used to emit the two functions that register and
3275/// unregister the descriptor of the current compilation unit.
3276static llvm::Function *
3277createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3278 const RegionCodeGenTy &Codegen) {
3279 auto &C = CGM.getContext();
3280 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003281 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003282 Args.push_back(&DummyPtr);
3283
3284 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003285 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003286 auto FTy = CGM.getTypes().GetFunctionType(FI);
3287 auto *Fn =
3288 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3289 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3290 Codegen(CGF);
3291 CGF.FinishFunction();
3292 return Fn;
3293}
3294
3295llvm::Function *
3296CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3297
3298 // If we don't have entries or if we are emitting code for the device, we
3299 // don't need to do anything.
3300 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3301 return nullptr;
3302
3303 auto &M = CGM.getModule();
3304 auto &C = CGM.getContext();
3305
3306 // Get list of devices we care about
3307 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3308
3309 // We should be creating an offloading descriptor only if there are devices
3310 // specified.
3311 assert(!Devices.empty() && "No OpenMP offloading devices??");
3312
3313 // Create the external variables that will point to the begin and end of the
3314 // host entries section. These will be defined by the linker.
3315 auto *OffloadEntryTy =
3316 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3317 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3318 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003319 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003320 ".omp_offloading.entries_begin");
3321 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3322 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003323 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003324 ".omp_offloading.entries_end");
3325
3326 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003327 auto *DeviceImageTy = cast<llvm::StructType>(
3328 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003329 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003330 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003331
3332 for (unsigned i = 0; i < Devices.size(); ++i) {
3333 StringRef T = Devices[i].getTriple();
3334 auto *ImgBegin = new llvm::GlobalVariable(
3335 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003336 /*Initializer=*/nullptr,
3337 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003338 auto *ImgEnd = new llvm::GlobalVariable(
3339 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003340 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003341
John McCall6c9f1fdb2016-11-19 08:17:24 +00003342 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3343 Dev.add(ImgBegin);
3344 Dev.add(ImgEnd);
3345 Dev.add(HostEntriesBegin);
3346 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003347 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003348 }
3349
3350 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003351 llvm::GlobalVariable *DeviceImages =
3352 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3353 CGM.getPointerAlign(),
3354 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003355 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003356
3357 // This is a Zero array to be used in the creation of the constant expressions
3358 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3359 llvm::Constant::getNullValue(CGM.Int32Ty)};
3360
3361 // Create the target region descriptor.
3362 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3363 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003364 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003365 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3366 DescInit.addInt(CGM.Int32Ty, Devices.size());
3367 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3368 DeviceImages,
3369 Index));
3370 DescInit.add(HostEntriesBegin);
3371 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003372
John McCall6c9f1fdb2016-11-19 08:17:24 +00003373 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3374 CGM.getPointerAlign(),
3375 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003376
3377 // Emit code to register or unregister the descriptor at execution
3378 // startup or closing, respectively.
3379
3380 // Create a variable to drive the registration and unregistration of the
3381 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3382 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3383 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003384 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003385
3386 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003387 CGM, ".omp_offloading.descriptor_unreg",
3388 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003389 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3390 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003391 });
3392 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003393 CGM, ".omp_offloading.descriptor_reg",
3394 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003395 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3396 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003397 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3398 });
George Rokos29d0f002017-05-27 03:03:13 +00003399 if (CGM.supportsCOMDAT()) {
3400 // It is sufficient to call registration function only once, so create a
3401 // COMDAT group for registration/unregistration functions and associated
3402 // data. That would reduce startup time and code size. Registration
3403 // function serves as a COMDAT group key.
3404 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3405 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3406 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3407 RegFn->setComdat(ComdatKey);
3408 UnRegFn->setComdat(ComdatKey);
3409 DeviceImages->setComdat(ComdatKey);
3410 Desc->setComdat(ComdatKey);
3411 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003412 return RegFn;
3413}
3414
Samuel Antao2de62b02016-02-13 23:35:10 +00003415void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003416 llvm::Constant *Addr, uint64_t Size,
3417 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003418 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003419 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3420 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3421 llvm::LLVMContext &C = CGM.getModule().getContext();
3422 llvm::Module &M = CGM.getModule();
3423
3424 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003425 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003426
3427 // Create constant string with the name.
3428 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3429
3430 llvm::GlobalVariable *Str =
3431 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3432 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3433 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003434 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003435 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3436
John McCall6c9f1fdb2016-11-19 08:17:24 +00003437 // We can't have any padding between symbols, so we need to have 1-byte
3438 // alignment.
3439 auto Align = CharUnits::fromQuantity(1);
3440
Samuel Antaoee8fb302016-01-06 13:42:12 +00003441 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003442 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003443 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3444 EntryInit.add(AddrPtr);
3445 EntryInit.add(StrPtr);
3446 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003447 EntryInit.addInt(CGM.Int32Ty, Flags);
3448 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003449 llvm::GlobalVariable *Entry =
3450 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3451 Align,
3452 /*constant*/ true,
3453 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003454
3455 // The entry has to be created in the section the linker expects it to be.
3456 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003457}
3458
3459void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3460 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003461 // can easily figure out what to emit. The produced metadata looks like
3462 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003463 //
3464 // !omp_offload.info = !{!1, ...}
3465 //
3466 // Right now we only generate metadata for function that contain target
3467 // regions.
3468
3469 // If we do not have entries, we dont need to do anything.
3470 if (OffloadEntriesInfoManager.empty())
3471 return;
3472
3473 llvm::Module &M = CGM.getModule();
3474 llvm::LLVMContext &C = M.getContext();
3475 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3476 OrderedEntries(OffloadEntriesInfoManager.size());
3477
3478 // Create the offloading info metadata node.
3479 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3480
Simon Pilgrim2c518802017-03-30 14:13:19 +00003481 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003482 auto getMDInt = [&](unsigned v) {
3483 return llvm::ConstantAsMetadata::get(
3484 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3485 };
3486
3487 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3488
3489 // Create function that emits metadata for each target region entry;
3490 auto &&TargetRegionMetadataEmitter = [&](
3491 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003492 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3493 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3494 // Generate metadata for target regions. Each entry of this metadata
3495 // contains:
3496 // - Entry 0 -> Kind of this type of metadata (0).
3497 // - Entry 1 -> Device ID of the file where the entry was identified.
3498 // - Entry 2 -> File ID of the file where the entry was identified.
3499 // - Entry 3 -> Mangled name of the function where the entry was identified.
3500 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003501 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003502 // The first element of the metadata node is the kind.
3503 Ops.push_back(getMDInt(E.getKind()));
3504 Ops.push_back(getMDInt(DeviceID));
3505 Ops.push_back(getMDInt(FileID));
3506 Ops.push_back(getMDString(ParentName));
3507 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003508 Ops.push_back(getMDInt(E.getOrder()));
3509
3510 // Save this entry in the right position of the ordered entries array.
3511 OrderedEntries[E.getOrder()] = &E;
3512
3513 // Add metadata to the named metadata node.
3514 MD->addOperand(llvm::MDNode::get(C, Ops));
3515 };
3516
3517 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3518 TargetRegionMetadataEmitter);
3519
3520 for (auto *E : OrderedEntries) {
3521 assert(E && "All ordered entries must exist!");
3522 if (auto *CE =
3523 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3524 E)) {
3525 assert(CE->getID() && CE->getAddress() &&
3526 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003527 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003528 } else
3529 llvm_unreachable("Unsupported entry kind.");
3530 }
3531}
3532
3533/// \brief Loads all the offload entries information from the host IR
3534/// metadata.
3535void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3536 // If we are in target mode, load the metadata from the host IR. This code has
3537 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3538
3539 if (!CGM.getLangOpts().OpenMPIsDevice)
3540 return;
3541
3542 if (CGM.getLangOpts().OMPHostIRFile.empty())
3543 return;
3544
3545 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3546 if (Buf.getError())
3547 return;
3548
3549 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003550 auto ME = expectedToErrorOrAndEmitErrors(
3551 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003552
3553 if (ME.getError())
3554 return;
3555
3556 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3557 if (!MD)
3558 return;
3559
3560 for (auto I : MD->operands()) {
3561 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3562
3563 auto getMDInt = [&](unsigned Idx) {
3564 llvm::ConstantAsMetadata *V =
3565 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3566 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3567 };
3568
3569 auto getMDString = [&](unsigned Idx) {
3570 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3571 return V->getString();
3572 };
3573
3574 switch (getMDInt(0)) {
3575 default:
3576 llvm_unreachable("Unexpected metadata!");
3577 break;
3578 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3579 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3580 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3581 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3582 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003583 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003584 break;
3585 }
3586 }
3587}
3588
Alexey Bataev62b63b12015-03-10 07:28:44 +00003589void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3590 if (!KmpRoutineEntryPtrTy) {
3591 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3592 auto &C = CGM.getContext();
3593 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3594 FunctionProtoType::ExtProtoInfo EPI;
3595 KmpRoutineEntryPtrQTy = C.getPointerType(
3596 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3597 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3598 }
3599}
3600
Alexey Bataevc71a4092015-09-11 10:29:41 +00003601static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3602 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003603 auto *Field = FieldDecl::Create(
3604 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3605 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3606 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3607 Field->setAccess(AS_public);
3608 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003609 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003610}
3611
Samuel Antaoee8fb302016-01-06 13:42:12 +00003612QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3613
3614 // Make sure the type of the entry is already created. This is the type we
3615 // have to create:
3616 // struct __tgt_offload_entry{
3617 // void *addr; // Pointer to the offload entry info.
3618 // // (function or global)
3619 // char *name; // Name of the function or global.
3620 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003621 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3622 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003623 // };
3624 if (TgtOffloadEntryQTy.isNull()) {
3625 ASTContext &C = CGM.getContext();
3626 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3627 RD->startDefinition();
3628 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3629 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3630 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003631 addFieldToRecordDecl(
3632 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3633 addFieldToRecordDecl(
3634 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003635 RD->completeDefinition();
3636 TgtOffloadEntryQTy = C.getRecordType(RD);
3637 }
3638 return TgtOffloadEntryQTy;
3639}
3640
3641QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3642 // These are the types we need to build:
3643 // struct __tgt_device_image{
3644 // void *ImageStart; // Pointer to the target code start.
3645 // void *ImageEnd; // Pointer to the target code end.
3646 // // We also add the host entries to the device image, as it may be useful
3647 // // for the target runtime to have access to that information.
3648 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3649 // // the entries.
3650 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3651 // // entries (non inclusive).
3652 // };
3653 if (TgtDeviceImageQTy.isNull()) {
3654 ASTContext &C = CGM.getContext();
3655 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3656 RD->startDefinition();
3657 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3658 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3659 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3660 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3661 RD->completeDefinition();
3662 TgtDeviceImageQTy = C.getRecordType(RD);
3663 }
3664 return TgtDeviceImageQTy;
3665}
3666
3667QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3668 // struct __tgt_bin_desc{
3669 // int32_t NumDevices; // Number of devices supported.
3670 // __tgt_device_image *DeviceImages; // Arrays of device images
3671 // // (one per device).
3672 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3673 // // entries.
3674 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3675 // // entries (non inclusive).
3676 // };
3677 if (TgtBinaryDescriptorQTy.isNull()) {
3678 ASTContext &C = CGM.getContext();
3679 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3680 RD->startDefinition();
3681 addFieldToRecordDecl(
3682 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3683 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3684 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3685 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3686 RD->completeDefinition();
3687 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3688 }
3689 return TgtBinaryDescriptorQTy;
3690}
3691
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003692namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003693struct PrivateHelpersTy {
3694 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3695 const VarDecl *PrivateElemInit)
3696 : Original(Original), PrivateCopy(PrivateCopy),
3697 PrivateElemInit(PrivateElemInit) {}
3698 const VarDecl *Original;
3699 const VarDecl *PrivateCopy;
3700 const VarDecl *PrivateElemInit;
3701};
3702typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003703} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003704
Alexey Bataev9e034042015-05-05 04:05:12 +00003705static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003706createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003707 if (!Privates.empty()) {
3708 auto &C = CGM.getContext();
3709 // Build struct .kmp_privates_t. {
3710 // /* private vars */
3711 // };
3712 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3713 RD->startDefinition();
3714 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003715 auto *VD = Pair.second.Original;
3716 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003717 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003718 auto *FD = addFieldToRecordDecl(C, RD, Type);
3719 if (VD->hasAttrs()) {
3720 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3721 E(VD->getAttrs().end());
3722 I != E; ++I)
3723 FD->addAttr(*I);
3724 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003725 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003726 RD->completeDefinition();
3727 return RD;
3728 }
3729 return nullptr;
3730}
3731
Alexey Bataev9e034042015-05-05 04:05:12 +00003732static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003733createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3734 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003735 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003736 auto &C = CGM.getContext();
3737 // Build struct kmp_task_t {
3738 // void * shareds;
3739 // kmp_routine_entry_t routine;
3740 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003741 // kmp_cmplrdata_t data1;
3742 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003743 // For taskloops additional fields:
3744 // kmp_uint64 lb;
3745 // kmp_uint64 ub;
3746 // kmp_int64 st;
3747 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003748 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003749 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003750 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3751 UD->startDefinition();
3752 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3753 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3754 UD->completeDefinition();
3755 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003756 auto *RD = C.buildImplicitRecord("kmp_task_t");
3757 RD->startDefinition();
3758 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3759 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3760 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003761 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3762 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003763 if (isOpenMPTaskLoopDirective(Kind)) {
3764 QualType KmpUInt64Ty =
3765 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3766 QualType KmpInt64Ty =
3767 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3768 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3769 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3770 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3771 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003772 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003773 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003774 RD->completeDefinition();
3775 return RD;
3776}
3777
3778static RecordDecl *
3779createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003780 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003781 auto &C = CGM.getContext();
3782 // Build struct kmp_task_t_with_privates {
3783 // kmp_task_t task_data;
3784 // .kmp_privates_t. privates;
3785 // };
3786 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3787 RD->startDefinition();
3788 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003789 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3790 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3791 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003792 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003793 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003794}
3795
3796/// \brief Emit a proxy function which accepts kmp_task_t as the second
3797/// argument.
3798/// \code
3799/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003800/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003801/// For taskloops:
3802/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003803/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003804/// return 0;
3805/// }
3806/// \endcode
3807static llvm::Value *
3808emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003809 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3810 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003811 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003812 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3813 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003814 auto &C = CGM.getContext();
3815 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003816 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3817 ImplicitParamDecl::Other);
3818 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3819 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3820 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003821 Args.push_back(&GtidArg);
3822 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003823 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003824 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003825 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3826 auto *TaskEntry =
3827 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3828 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003829 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003830 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003831 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3832
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003833 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003834 // tt,
3835 // For taskloops:
3836 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3837 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003838 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003839 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003840 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3841 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3842 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003843 auto *KmpTaskTWithPrivatesQTyRD =
3844 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003845 LValue Base =
3846 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003847 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3848 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3849 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003850 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003851
3852 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3853 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003854 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003855 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003856 CGF.ConvertTypeForMem(SharedsPtrTy));
3857
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003858 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3859 llvm::Value *PrivatesParam;
3860 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3861 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3862 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003863 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003864 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003865 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003866
Alexey Bataev7292c292016-04-25 12:22:29 +00003867 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3868 TaskPrivatesMap,
3869 CGF.Builder
3870 .CreatePointerBitCastOrAddrSpaceCast(
3871 TDBase.getAddress(), CGF.VoidPtrTy)
3872 .getPointer()};
3873 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3874 std::end(CommonArgs));
3875 if (isOpenMPTaskLoopDirective(Kind)) {
3876 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3877 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3878 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3879 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3880 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3881 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3882 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3883 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3884 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3885 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3886 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3887 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003888 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3889 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3890 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003891 CallArgs.push_back(LBParam);
3892 CallArgs.push_back(UBParam);
3893 CallArgs.push_back(StParam);
3894 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003895 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003896 }
3897 CallArgs.push_back(SharedsParam);
3898
Alexey Bataev3c595a62017-08-14 15:01:03 +00003899 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3900 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003901 CGF.EmitStoreThroughLValue(
3902 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003903 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003904 CGF.FinishFunction();
3905 return TaskEntry;
3906}
3907
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003908static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3909 SourceLocation Loc,
3910 QualType KmpInt32Ty,
3911 QualType KmpTaskTWithPrivatesPtrQTy,
3912 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003913 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003914 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003915 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3916 ImplicitParamDecl::Other);
3917 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3918 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3919 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003920 Args.push_back(&GtidArg);
3921 Args.push_back(&TaskTypeArg);
3922 FunctionType::ExtInfo Info;
3923 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003924 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003925 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3926 auto *DestructorFn =
3927 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3928 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003929 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3930 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003931 CodeGenFunction CGF(CGM);
3932 CGF.disableDebugInfo();
3933 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3934 Args);
3935
Alexey Bataev31300ed2016-02-04 11:27:03 +00003936 LValue Base = CGF.EmitLoadOfPointerLValue(
3937 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3938 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003939 auto *KmpTaskTWithPrivatesQTyRD =
3940 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3941 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003942 Base = CGF.EmitLValueForField(Base, *FI);
3943 for (auto *Field :
3944 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3945 if (auto DtorKind = Field->getType().isDestructedType()) {
3946 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3947 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3948 }
3949 }
3950 CGF.FinishFunction();
3951 return DestructorFn;
3952}
3953
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003954/// \brief Emit a privates mapping function for correct handling of private and
3955/// firstprivate variables.
3956/// \code
3957/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3958/// **noalias priv1,..., <tyn> **noalias privn) {
3959/// *priv1 = &.privates.priv1;
3960/// ...;
3961/// *privn = &.privates.privn;
3962/// }
3963/// \endcode
3964static llvm::Value *
3965emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003966 ArrayRef<const Expr *> PrivateVars,
3967 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003968 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003969 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003970 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003971 auto &C = CGM.getContext();
3972 FunctionArgList Args;
3973 ImplicitParamDecl TaskPrivatesArg(
3974 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003975 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3976 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003977 Args.push_back(&TaskPrivatesArg);
3978 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3979 unsigned Counter = 1;
3980 for (auto *E: PrivateVars) {
3981 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003982 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3983 C.getPointerType(C.getPointerType(E->getType()))
3984 .withConst()
3985 .withRestrict(),
3986 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003987 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3988 PrivateVarsPos[VD] = Counter;
3989 ++Counter;
3990 }
3991 for (auto *E : FirstprivateVars) {
3992 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003993 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3994 C.getPointerType(C.getPointerType(E->getType()))
3995 .withConst()
3996 .withRestrict(),
3997 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003998 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3999 PrivateVarsPos[VD] = Counter;
4000 ++Counter;
4001 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004002 for (auto *E: LastprivateVars) {
4003 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004004 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4005 C.getPointerType(C.getPointerType(E->getType()))
4006 .withConst()
4007 .withRestrict(),
4008 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004009 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4010 PrivateVarsPos[VD] = Counter;
4011 ++Counter;
4012 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004013 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004014 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004015 auto *TaskPrivatesMapTy =
4016 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4017 auto *TaskPrivatesMap = llvm::Function::Create(
4018 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4019 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004020 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4021 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004022 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004023 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004024 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004025 CodeGenFunction CGF(CGM);
4026 CGF.disableDebugInfo();
4027 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4028 TaskPrivatesMapFnInfo, Args);
4029
4030 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004031 LValue Base = CGF.EmitLoadOfPointerLValue(
4032 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4033 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004034 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4035 Counter = 0;
4036 for (auto *Field : PrivatesQTyRD->fields()) {
4037 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4038 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004039 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004040 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4041 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004042 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004043 ++Counter;
4044 }
4045 CGF.FinishFunction();
4046 return TaskPrivatesMap;
4047}
4048
Alexey Bataev9e034042015-05-05 04:05:12 +00004049static int array_pod_sort_comparator(const PrivateDataTy *P1,
4050 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004051 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4052}
4053
Alexey Bataevf93095a2016-05-05 08:46:22 +00004054/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004055static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004056 const OMPExecutableDirective &D,
4057 Address KmpTaskSharedsPtr, LValue TDBase,
4058 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4059 QualType SharedsTy, QualType SharedsPtrTy,
4060 const OMPTaskDataTy &Data,
4061 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4062 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004063 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4064 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4065 LValue SrcBase;
4066 if (!Data.FirstprivateVars.empty()) {
4067 SrcBase = CGF.MakeAddrLValue(
4068 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4069 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4070 SharedsTy);
4071 }
4072 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4073 cast<CapturedStmt>(*D.getAssociatedStmt()));
4074 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4075 for (auto &&Pair : Privates) {
4076 auto *VD = Pair.second.PrivateCopy;
4077 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004078 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4079 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004080 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004081 if (auto *Elem = Pair.second.PrivateElemInit) {
4082 auto *OriginalVD = Pair.second.Original;
4083 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4084 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4085 SharedRefLValue = CGF.MakeAddrLValue(
4086 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004087 SharedRefLValue.getType(),
4088 LValueBaseInfo(AlignmentSource::Decl,
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004089 SharedRefLValue.getBaseInfo().getMayAlias()),
4090 CGF.CGM.getTBAAAccessInfo(SharedRefLValue.getType()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004091 QualType Type = OriginalVD->getType();
4092 if (Type->isArrayType()) {
4093 // Initialize firstprivate array.
4094 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4095 // Perform simple memcpy.
4096 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4097 SharedRefLValue.getAddress(), Type);
4098 } else {
4099 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004100 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004101 CGF.EmitOMPAggregateAssign(
4102 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4103 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4104 Address SrcElement) {
4105 // Clean up any temporaries needed by the initialization.
4106 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4107 InitScope.addPrivate(
4108 Elem, [SrcElement]() -> Address { return SrcElement; });
4109 (void)InitScope.Privatize();
4110 // Emit initialization for single element.
4111 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4112 CGF, &CapturesInfo);
4113 CGF.EmitAnyExprToMem(Init, DestElement,
4114 Init->getType().getQualifiers(),
4115 /*IsInitializer=*/false);
4116 });
4117 }
4118 } else {
4119 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4120 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4121 return SharedRefLValue.getAddress();
4122 });
4123 (void)InitScope.Privatize();
4124 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4125 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4126 /*capturedByInit=*/false);
4127 }
4128 } else
4129 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4130 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004131 ++FI;
4132 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004133}
4134
4135/// Check if duplication function is required for taskloops.
4136static bool checkInitIsRequired(CodeGenFunction &CGF,
4137 ArrayRef<PrivateDataTy> Privates) {
4138 bool InitRequired = false;
4139 for (auto &&Pair : Privates) {
4140 auto *VD = Pair.second.PrivateCopy;
4141 auto *Init = VD->getAnyInitializer();
4142 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4143 !CGF.isTrivialInitializer(Init));
4144 }
4145 return InitRequired;
4146}
4147
4148
4149/// Emit task_dup function (for initialization of
4150/// private/firstprivate/lastprivate vars and last_iter flag)
4151/// \code
4152/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4153/// lastpriv) {
4154/// // setup lastprivate flag
4155/// task_dst->last = lastpriv;
4156/// // could be constructor calls here...
4157/// }
4158/// \endcode
4159static llvm::Value *
4160emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4161 const OMPExecutableDirective &D,
4162 QualType KmpTaskTWithPrivatesPtrQTy,
4163 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4164 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4165 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4166 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4167 auto &C = CGM.getContext();
4168 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004169 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4170 KmpTaskTWithPrivatesPtrQTy,
4171 ImplicitParamDecl::Other);
4172 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4173 KmpTaskTWithPrivatesPtrQTy,
4174 ImplicitParamDecl::Other);
4175 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4176 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004177 Args.push_back(&DstArg);
4178 Args.push_back(&SrcArg);
4179 Args.push_back(&LastprivArg);
4180 auto &TaskDupFnInfo =
4181 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4182 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4183 auto *TaskDup =
4184 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4185 ".omp_task_dup.", &CGM.getModule());
4186 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4187 CodeGenFunction CGF(CGM);
4188 CGF.disableDebugInfo();
4189 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4190
4191 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4192 CGF.GetAddrOfLocalVar(&DstArg),
4193 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4194 // task_dst->liter = lastpriv;
4195 if (WithLastIter) {
4196 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4197 LValue Base = CGF.EmitLValueForField(
4198 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4199 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4200 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4201 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4202 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4203 }
4204
4205 // Emit initial values for private copies (if any).
4206 assert(!Privates.empty());
4207 Address KmpTaskSharedsPtr = Address::invalid();
4208 if (!Data.FirstprivateVars.empty()) {
4209 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4210 CGF.GetAddrOfLocalVar(&SrcArg),
4211 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4212 LValue Base = CGF.EmitLValueForField(
4213 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4214 KmpTaskSharedsPtr = Address(
4215 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4216 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4217 KmpTaskTShareds)),
4218 Loc),
4219 CGF.getNaturalTypeAlignment(SharedsTy));
4220 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004221 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4222 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004223 CGF.FinishFunction();
4224 return TaskDup;
4225}
4226
Alexey Bataev8a831592016-05-10 10:36:51 +00004227/// Checks if destructor function is required to be generated.
4228/// \return true if cleanups are required, false otherwise.
4229static bool
4230checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4231 bool NeedsCleanup = false;
4232 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4233 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4234 for (auto *FD : PrivateRD->fields()) {
4235 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4236 if (NeedsCleanup)
4237 break;
4238 }
4239 return NeedsCleanup;
4240}
4241
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004242CGOpenMPRuntime::TaskResultTy
4243CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4244 const OMPExecutableDirective &D,
4245 llvm::Value *TaskFunction, QualType SharedsTy,
4246 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004247 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004248 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004249 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004250 auto I = Data.PrivateCopies.begin();
4251 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004252 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4253 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004254 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004255 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4256 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004257 ++I;
4258 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004259 I = Data.FirstprivateCopies.begin();
4260 auto IElemInitRef = Data.FirstprivateInits.begin();
4261 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004262 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4263 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004264 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004265 PrivateHelpersTy(
4266 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4267 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004268 ++I;
4269 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004270 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004271 I = Data.LastprivateCopies.begin();
4272 for (auto *E : Data.LastprivateVars) {
4273 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4274 Privates.push_back(std::make_pair(
4275 C.getDeclAlign(VD),
4276 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4277 /*PrivateElemInit=*/nullptr)));
4278 ++I;
4279 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004280 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4281 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004282 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4283 // Build type kmp_routine_entry_t (if not built yet).
4284 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004285 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004286 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4287 if (SavedKmpTaskloopTQTy.isNull()) {
4288 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4289 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4290 }
4291 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004292 } else {
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004293 assert(D.getDirectiveKind() == OMPD_task &&
4294 "Expected taskloop or task directive");
4295 if (SavedKmpTaskTQTy.isNull()) {
4296 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4297 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4298 }
4299 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004300 }
4301 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004302 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004303 auto *KmpTaskTWithPrivatesQTyRD =
4304 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4305 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4306 QualType KmpTaskTWithPrivatesPtrQTy =
4307 C.getPointerType(KmpTaskTWithPrivatesQTy);
4308 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4309 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004310 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004311 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4312
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004313 // Emit initial values for private copies (if any).
4314 llvm::Value *TaskPrivatesMap = nullptr;
4315 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004316 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004317 if (!Privates.empty()) {
4318 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004319 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4320 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4321 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004322 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4323 TaskPrivatesMap, TaskPrivatesMapTy);
4324 } else {
4325 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4326 cast<llvm::PointerType>(TaskPrivatesMapTy));
4327 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004328 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4329 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004330 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004331 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4332 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4333 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004334
4335 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4336 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4337 // kmp_routine_entry_t *task_entry);
4338 // Task flags. Format is taken from
4339 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4340 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004341 enum {
4342 TiedFlag = 0x1,
4343 FinalFlag = 0x2,
4344 DestructorsFlag = 0x8,
4345 PriorityFlag = 0x20
4346 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004347 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004348 bool NeedsCleanup = false;
4349 if (!Privates.empty()) {
4350 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4351 if (NeedsCleanup)
4352 Flags = Flags | DestructorsFlag;
4353 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004354 if (Data.Priority.getInt())
4355 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004356 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004357 Data.Final.getPointer()
4358 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004359 CGF.Builder.getInt32(FinalFlag),
4360 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004361 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004362 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004363 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004364 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4365 getThreadID(CGF, Loc), TaskFlags,
4366 KmpTaskTWithPrivatesTySize, SharedsSize,
4367 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4368 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004369 auto *NewTask = CGF.EmitRuntimeCall(
4370 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004371 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4372 NewTask, KmpTaskTWithPrivatesPtrTy);
4373 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4374 KmpTaskTWithPrivatesQTy);
4375 LValue TDBase =
4376 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004377 // Fill the data in the resulting kmp_task_t record.
4378 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004379 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004380 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004381 KmpTaskSharedsPtr =
4382 Address(CGF.EmitLoadOfScalar(
4383 CGF.EmitLValueForField(
4384 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4385 KmpTaskTShareds)),
4386 Loc),
4387 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004388 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004389 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004390 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004391 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004392 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004393 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4394 SharedsTy, SharedsPtrTy, Data, Privates,
4395 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004396 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4397 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4398 Result.TaskDupFn = emitTaskDupFunction(
4399 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4400 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4401 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004402 }
4403 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004404 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4405 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004406 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004407 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4408 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4409 if (NeedsCleanup) {
4410 llvm::Value *DestructorFn = emitDestructorsFunction(
4411 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4412 KmpTaskTWithPrivatesQTy);
4413 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4414 LValue DestructorsLV = CGF.EmitLValueForField(
4415 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4416 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4417 DestructorFn, KmpRoutineEntryPtrTy),
4418 DestructorsLV);
4419 }
4420 // Set priority.
4421 if (Data.Priority.getInt()) {
4422 LValue Data2LV = CGF.EmitLValueForField(
4423 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4424 LValue PriorityLV = CGF.EmitLValueForField(
4425 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4426 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4427 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004428 Result.NewTask = NewTask;
4429 Result.TaskEntry = TaskEntry;
4430 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4431 Result.TDBase = TDBase;
4432 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4433 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004434}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004435
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004436void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4437 const OMPExecutableDirective &D,
4438 llvm::Value *TaskFunction,
4439 QualType SharedsTy, Address Shareds,
4440 const Expr *IfCond,
4441 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004442 if (!CGF.HaveInsertPoint())
4443 return;
4444
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004445 TaskResultTy Result =
4446 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4447 llvm::Value *NewTask = Result.NewTask;
4448 llvm::Value *TaskEntry = Result.TaskEntry;
4449 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4450 LValue TDBase = Result.TDBase;
4451 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004452 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004453 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004454 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004455 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004456 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004457 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004458 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004459 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4460 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004461 QualType FlagsTy =
4462 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004463 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4464 if (KmpDependInfoTy.isNull()) {
4465 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4466 KmpDependInfoRD->startDefinition();
4467 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4468 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4469 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4470 KmpDependInfoRD->completeDefinition();
4471 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004472 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004473 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004474 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004475 // Define type kmp_depend_info[<Dependences.size()>];
4476 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004477 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004478 ArrayType::Normal, /*IndexTypeQuals=*/0);
4479 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004480 DependenciesArray =
4481 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004482 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004483 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004484 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004485 llvm::Value *Size;
4486 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004487 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4488 LValue UpAddrLVal =
4489 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4490 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004491 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004492 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004493 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004494 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4495 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004496 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004497 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004498 auto Base = CGF.MakeAddrLValue(
4499 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004500 KmpDependInfoTy);
4501 // deps[i].base_addr = &<Dependences[i].second>;
4502 auto BaseAddrLVal = CGF.EmitLValueForField(
4503 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004504 CGF.EmitStoreOfScalar(
4505 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4506 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004507 // deps[i].len = sizeof(<Dependences[i].second>);
4508 auto LenLVal = CGF.EmitLValueForField(
4509 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4510 CGF.EmitStoreOfScalar(Size, LenLVal);
4511 // deps[i].flags = <Dependences[i].first>;
4512 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004513 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004514 case OMPC_DEPEND_in:
4515 DepKind = DepIn;
4516 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004517 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004518 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004519 case OMPC_DEPEND_inout:
4520 DepKind = DepInOut;
4521 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004522 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004523 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004524 case OMPC_DEPEND_unknown:
4525 llvm_unreachable("Unknown task dependence type");
4526 }
4527 auto FlagsLVal = CGF.EmitLValueForField(
4528 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4529 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4530 FlagsLVal);
4531 }
John McCall7f416cc2015-09-08 08:05:57 +00004532 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4533 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004534 CGF.VoidPtrTy);
4535 }
4536
Alexey Bataev62b63b12015-03-10 07:28:44 +00004537 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4538 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004539 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4540 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4541 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4542 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004543 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004544 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004545 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4546 llvm::Value *DepTaskArgs[7];
4547 if (NumDependencies) {
4548 DepTaskArgs[0] = UpLoc;
4549 DepTaskArgs[1] = ThreadID;
4550 DepTaskArgs[2] = NewTask;
4551 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4552 DepTaskArgs[4] = DependenciesArray.getPointer();
4553 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4554 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4555 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004556 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4557 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004558 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004559 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004560 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4561 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4562 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4563 }
John McCall7f416cc2015-09-08 08:05:57 +00004564 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004565 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004566 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004567 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004568 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004569 TaskArgs);
4570 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004571 // Check if parent region is untied and build return for untied task;
4572 if (auto *Region =
4573 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4574 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004575 };
John McCall7f416cc2015-09-08 08:05:57 +00004576
4577 llvm::Value *DepWaitTaskArgs[6];
4578 if (NumDependencies) {
4579 DepWaitTaskArgs[0] = UpLoc;
4580 DepWaitTaskArgs[1] = ThreadID;
4581 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4582 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4583 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4584 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4585 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004586 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004587 NumDependencies, &DepWaitTaskArgs,
4588 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004589 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004590 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4591 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4592 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4593 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4594 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004595 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004596 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004597 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004598 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004599 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4600 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004601 Action.Enter(CGF);
4602 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004603 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004604 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004605 };
4606
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004607 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4608 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004609 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4610 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004611 RegionCodeGenTy RCG(CodeGen);
4612 CommonActionTy Action(
4613 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4614 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4615 RCG.setAction(Action);
4616 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004617 };
John McCall7f416cc2015-09-08 08:05:57 +00004618
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004619 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004620 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004621 else {
4622 RegionCodeGenTy ThenRCG(ThenCodeGen);
4623 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004624 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004625}
4626
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004627void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4628 const OMPLoopDirective &D,
4629 llvm::Value *TaskFunction,
4630 QualType SharedsTy, Address Shareds,
4631 const Expr *IfCond,
4632 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004633 if (!CGF.HaveInsertPoint())
4634 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004635 TaskResultTy Result =
4636 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004637 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4638 // libcall.
4639 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4640 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4641 // sched, kmp_uint64 grainsize, void *task_dup);
4642 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4643 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4644 llvm::Value *IfVal;
4645 if (IfCond) {
4646 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4647 /*isSigned=*/true);
4648 } else
4649 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4650
4651 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004652 Result.TDBase,
4653 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004654 auto *LBVar =
4655 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4656 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4657 /*IsInitializer=*/true);
4658 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004659 Result.TDBase,
4660 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004661 auto *UBVar =
4662 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4663 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4664 /*IsInitializer=*/true);
4665 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004666 Result.TDBase,
4667 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004668 auto *StVar =
4669 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4670 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4671 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004672 // Store reductions address.
4673 LValue RedLVal = CGF.EmitLValueForField(
4674 Result.TDBase,
4675 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4676 if (Data.Reductions)
4677 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4678 else {
4679 CGF.EmitNullInitialization(RedLVal.getAddress(),
4680 CGF.getContext().VoidPtrTy);
4681 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004682 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004683 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004684 UpLoc,
4685 ThreadID,
4686 Result.NewTask,
4687 IfVal,
4688 LBLVal.getPointer(),
4689 UBLVal.getPointer(),
4690 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4691 llvm::ConstantInt::getNullValue(
4692 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004693 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004694 CGF.IntTy, Data.Schedule.getPointer()
4695 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004696 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004697 Data.Schedule.getPointer()
4698 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004699 /*isSigned=*/false)
4700 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004701 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4702 Result.TaskDupFn, CGF.VoidPtrTy)
4703 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004704 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4705}
4706
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004707/// \brief Emit reduction operation for each element of array (required for
4708/// array sections) LHS op = RHS.
4709/// \param Type Type of array.
4710/// \param LHSVar Variable on the left side of the reduction operation
4711/// (references element of array in original variable).
4712/// \param RHSVar Variable on the right side of the reduction operation
4713/// (references element of array in original variable).
4714/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4715/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004716static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004717 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4718 const VarDecl *RHSVar,
4719 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4720 const Expr *, const Expr *)> &RedOpGen,
4721 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4722 const Expr *UpExpr = nullptr) {
4723 // Perform element-by-element initialization.
4724 QualType ElementTy;
4725 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4726 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4727
4728 // Drill down to the base element type on both arrays.
4729 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4730 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4731
4732 auto RHSBegin = RHSAddr.getPointer();
4733 auto LHSBegin = LHSAddr.getPointer();
4734 // Cast from pointer to array type to pointer to single element.
4735 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4736 // The basic structure here is a while-do loop.
4737 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4738 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4739 auto IsEmpty =
4740 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4741 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4742
4743 // Enter the loop body, making that address the current address.
4744 auto EntryBB = CGF.Builder.GetInsertBlock();
4745 CGF.EmitBlock(BodyBB);
4746
4747 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4748
4749 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4750 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4751 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4752 Address RHSElementCurrent =
4753 Address(RHSElementPHI,
4754 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4755
4756 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4757 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4758 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4759 Address LHSElementCurrent =
4760 Address(LHSElementPHI,
4761 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4762
4763 // Emit copy.
4764 CodeGenFunction::OMPPrivateScope Scope(CGF);
4765 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4766 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4767 Scope.Privatize();
4768 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4769 Scope.ForceCleanup();
4770
4771 // Shift the address forward by one element.
4772 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4773 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4774 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4775 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4776 // Check whether we've reached the end.
4777 auto Done =
4778 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4779 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4780 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4781 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4782
4783 // Done.
4784 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4785}
4786
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004787/// Emit reduction combiner. If the combiner is a simple expression emit it as
4788/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4789/// UDR combiner function.
4790static void emitReductionCombiner(CodeGenFunction &CGF,
4791 const Expr *ReductionOp) {
4792 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4793 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4794 if (auto *DRE =
4795 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4796 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4797 std::pair<llvm::Function *, llvm::Function *> Reduction =
4798 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4799 RValue Func = RValue::get(Reduction.first);
4800 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4801 CGF.EmitIgnoredExpr(ReductionOp);
4802 return;
4803 }
4804 CGF.EmitIgnoredExpr(ReductionOp);
4805}
4806
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004807llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4808 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4809 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4810 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004811 auto &C = CGM.getContext();
4812
4813 // void reduction_func(void *LHSArg, void *RHSArg);
4814 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004815 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4816 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004817 Args.push_back(&LHSArg);
4818 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004819 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004820 auto *Fn = llvm::Function::Create(
4821 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4822 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004823 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004824 CodeGenFunction CGF(CGM);
4825 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4826
4827 // Dst = (void*[n])(LHSArg);
4828 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004829 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4830 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4831 ArgsType), CGF.getPointerAlign());
4832 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4833 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4834 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004835
4836 // ...
4837 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4838 // ...
4839 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004840 auto IPriv = Privates.begin();
4841 unsigned Idx = 0;
4842 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004843 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4844 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004845 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004846 });
4847 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4848 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004849 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004850 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004851 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004852 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004853 // Get array size and emit VLA type.
4854 ++Idx;
4855 Address Elem =
4856 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4857 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004858 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4859 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004860 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004861 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004862 CGF.EmitVariablyModifiedType(PrivTy);
4863 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004864 }
4865 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004866 IPriv = Privates.begin();
4867 auto ILHS = LHSExprs.begin();
4868 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004869 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004870 if ((*IPriv)->getType()->isArrayType()) {
4871 // Emit reduction for array section.
4872 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4873 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004874 EmitOMPAggregateReduction(
4875 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4876 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4877 emitReductionCombiner(CGF, E);
4878 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004879 } else
4880 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004881 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004882 ++IPriv;
4883 ++ILHS;
4884 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004885 }
4886 Scope.ForceCleanup();
4887 CGF.FinishFunction();
4888 return Fn;
4889}
4890
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004891void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4892 const Expr *ReductionOp,
4893 const Expr *PrivateRef,
4894 const DeclRefExpr *LHS,
4895 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004896 if (PrivateRef->getType()->isArrayType()) {
4897 // Emit reduction for array section.
4898 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4899 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4900 EmitOMPAggregateReduction(
4901 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4902 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4903 emitReductionCombiner(CGF, ReductionOp);
4904 });
4905 } else
4906 // Emit reduction for array subscript or single variable.
4907 emitReductionCombiner(CGF, ReductionOp);
4908}
4909
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004910void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004911 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004912 ArrayRef<const Expr *> LHSExprs,
4913 ArrayRef<const Expr *> RHSExprs,
4914 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004915 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004916 if (!CGF.HaveInsertPoint())
4917 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004918
4919 bool WithNowait = Options.WithNowait;
4920 bool SimpleReduction = Options.SimpleReduction;
4921
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004922 // Next code should be emitted for reduction:
4923 //
4924 // static kmp_critical_name lock = { 0 };
4925 //
4926 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4927 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4928 // ...
4929 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4930 // *(Type<n>-1*)rhs[<n>-1]);
4931 // }
4932 //
4933 // ...
4934 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4935 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4936 // RedList, reduce_func, &<lock>)) {
4937 // case 1:
4938 // ...
4939 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4940 // ...
4941 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4942 // break;
4943 // case 2:
4944 // ...
4945 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4946 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004947 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004948 // break;
4949 // default:;
4950 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004951 //
4952 // if SimpleReduction is true, only the next code is generated:
4953 // ...
4954 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4955 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004956
4957 auto &C = CGM.getContext();
4958
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004959 if (SimpleReduction) {
4960 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004961 auto IPriv = Privates.begin();
4962 auto ILHS = LHSExprs.begin();
4963 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004964 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004965 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4966 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004967 ++IPriv;
4968 ++ILHS;
4969 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004970 }
4971 return;
4972 }
4973
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004974 // 1. Build a list of reduction variables.
4975 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004976 auto Size = RHSExprs.size();
4977 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004978 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004979 // Reserve place for array size.
4980 ++Size;
4981 }
4982 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004983 QualType ReductionArrayTy =
4984 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4985 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004986 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004987 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004988 auto IPriv = Privates.begin();
4989 unsigned Idx = 0;
4990 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004991 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004992 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004993 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004994 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004995 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4996 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004997 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004998 // Store array size.
4999 ++Idx;
5000 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5001 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005002 llvm::Value *Size = CGF.Builder.CreateIntCast(
5003 CGF.getVLASize(
5004 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5005 .first,
5006 CGF.SizeTy, /*isSigned=*/false);
5007 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5008 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005009 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005010 }
5011
5012 // 2. Emit reduce_func().
5013 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005014 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5015 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005016
5017 // 3. Create static kmp_critical_name lock = { 0 };
5018 auto *Lock = getCriticalRegionLock(".reduction");
5019
5020 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5021 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005022 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005023 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005024 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005025 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5026 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005027 llvm::Value *Args[] = {
5028 IdentTLoc, // ident_t *<loc>
5029 ThreadId, // i32 <gtid>
5030 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5031 ReductionArrayTySize, // size_type sizeof(RedList)
5032 RL, // void *RedList
5033 ReductionFn, // void (*) (void *, void *) <reduce_func>
5034 Lock // kmp_critical_name *&<lock>
5035 };
5036 auto Res = CGF.EmitRuntimeCall(
5037 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5038 : OMPRTL__kmpc_reduce),
5039 Args);
5040
5041 // 5. Build switch(res)
5042 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5043 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5044
5045 // 6. Build case 1:
5046 // ...
5047 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5048 // ...
5049 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5050 // break;
5051 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5052 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5053 CGF.EmitBlock(Case1BB);
5054
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005055 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5056 llvm::Value *EndArgs[] = {
5057 IdentTLoc, // ident_t *<loc>
5058 ThreadId, // i32 <gtid>
5059 Lock // kmp_critical_name *&<lock>
5060 };
5061 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5062 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005063 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005064 auto IPriv = Privates.begin();
5065 auto ILHS = LHSExprs.begin();
5066 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005067 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005068 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5069 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005070 ++IPriv;
5071 ++ILHS;
5072 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005073 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005074 };
5075 RegionCodeGenTy RCG(CodeGen);
5076 CommonActionTy Action(
5077 nullptr, llvm::None,
5078 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5079 : OMPRTL__kmpc_end_reduce),
5080 EndArgs);
5081 RCG.setAction(Action);
5082 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005083
5084 CGF.EmitBranch(DefaultBB);
5085
5086 // 7. Build case 2:
5087 // ...
5088 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5089 // ...
5090 // break;
5091 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5092 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5093 CGF.EmitBlock(Case2BB);
5094
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005095 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5096 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005097 auto ILHS = LHSExprs.begin();
5098 auto IRHS = RHSExprs.begin();
5099 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005100 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005101 const Expr *XExpr = nullptr;
5102 const Expr *EExpr = nullptr;
5103 const Expr *UpExpr = nullptr;
5104 BinaryOperatorKind BO = BO_Comma;
5105 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5106 if (BO->getOpcode() == BO_Assign) {
5107 XExpr = BO->getLHS();
5108 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005109 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005110 }
5111 // Try to emit update expression as a simple atomic.
5112 auto *RHSExpr = UpExpr;
5113 if (RHSExpr) {
5114 // Analyze RHS part of the whole expression.
5115 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5116 RHSExpr->IgnoreParenImpCasts())) {
5117 // If this is a conditional operator, analyze its condition for
5118 // min/max reduction operator.
5119 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005120 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005121 if (auto *BORHS =
5122 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5123 EExpr = BORHS->getRHS();
5124 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005125 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005126 }
5127 if (XExpr) {
5128 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005129 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005130 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5131 const Expr *EExpr, const Expr *UpExpr) {
5132 LValue X = CGF.EmitLValue(XExpr);
5133 RValue E;
5134 if (EExpr)
5135 E = CGF.EmitAnyExpr(EExpr);
5136 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005137 X, E, BO, /*IsXLHSInRHSPart=*/true,
5138 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005139 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005140 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5141 PrivateScope.addPrivate(
5142 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5143 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5144 CGF.emitOMPSimpleStore(
5145 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5146 VD->getType().getNonReferenceType(), Loc);
5147 return LHSTemp;
5148 });
5149 (void)PrivateScope.Privatize();
5150 return CGF.EmitAnyExpr(UpExpr);
5151 });
5152 };
5153 if ((*IPriv)->getType()->isArrayType()) {
5154 // Emit atomic reduction for array section.
5155 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5156 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5157 AtomicRedGen, XExpr, EExpr, UpExpr);
5158 } else
5159 // Emit atomic reduction for array subscript or single variable.
5160 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5161 } else {
5162 // Emit as a critical region.
5163 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5164 const Expr *, const Expr *) {
5165 auto &RT = CGF.CGM.getOpenMPRuntime();
5166 RT.emitCriticalRegion(
5167 CGF, ".atomic_reduction",
5168 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5169 Action.Enter(CGF);
5170 emitReductionCombiner(CGF, E);
5171 },
5172 Loc);
5173 };
5174 if ((*IPriv)->getType()->isArrayType()) {
5175 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5176 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5177 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5178 CritRedGen);
5179 } else
5180 CritRedGen(CGF, nullptr, nullptr, nullptr);
5181 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005182 ++ILHS;
5183 ++IRHS;
5184 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005185 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005186 };
5187 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5188 if (!WithNowait) {
5189 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5190 llvm::Value *EndArgs[] = {
5191 IdentTLoc, // ident_t *<loc>
5192 ThreadId, // i32 <gtid>
5193 Lock // kmp_critical_name *&<lock>
5194 };
5195 CommonActionTy Action(nullptr, llvm::None,
5196 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5197 EndArgs);
5198 AtomicRCG.setAction(Action);
5199 AtomicRCG(CGF);
5200 } else
5201 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005202
5203 CGF.EmitBranch(DefaultBB);
5204 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5205}
5206
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005207/// Generates unique name for artificial threadprivate variables.
5208/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5209static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5210 unsigned N) {
5211 SmallString<256> Buffer;
5212 llvm::raw_svector_ostream Out(Buffer);
5213 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5214 return Out.str();
5215}
5216
5217/// Emits reduction initializer function:
5218/// \code
5219/// void @.red_init(void* %arg) {
5220/// %0 = bitcast void* %arg to <type>*
5221/// store <type> <init>, <type>* %0
5222/// ret void
5223/// }
5224/// \endcode
5225static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5226 SourceLocation Loc,
5227 ReductionCodeGen &RCG, unsigned N) {
5228 auto &C = CGM.getContext();
5229 FunctionArgList Args;
5230 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5231 Args.emplace_back(&Param);
5232 auto &FnInfo =
5233 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5234 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5235 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5236 ".red_init.", &CGM.getModule());
5237 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5238 CodeGenFunction CGF(CGM);
5239 CGF.disableDebugInfo();
5240 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5241 Address PrivateAddr = CGF.EmitLoadOfPointer(
5242 CGF.GetAddrOfLocalVar(&Param),
5243 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5244 llvm::Value *Size = nullptr;
5245 // If the size of the reduction item is non-constant, load it from global
5246 // threadprivate variable.
5247 if (RCG.getSizes(N).second) {
5248 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5249 CGF, CGM.getContext().getSizeType(),
5250 generateUniqueName("reduction_size", Loc, N));
5251 Size =
5252 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5253 CGM.getContext().getSizeType(), SourceLocation());
5254 }
5255 RCG.emitAggregateType(CGF, N, Size);
5256 LValue SharedLVal;
5257 // If initializer uses initializer from declare reduction construct, emit a
5258 // pointer to the address of the original reduction item (reuired by reduction
5259 // initializer)
5260 if (RCG.usesReductionInitializer(N)) {
5261 Address SharedAddr =
5262 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5263 CGF, CGM.getContext().VoidPtrTy,
5264 generateUniqueName("reduction", Loc, N));
5265 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5266 } else {
5267 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5268 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5269 CGM.getContext().VoidPtrTy);
5270 }
5271 // Emit the initializer:
5272 // %0 = bitcast void* %arg to <type>*
5273 // store <type> <init>, <type>* %0
5274 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5275 [](CodeGenFunction &) { return false; });
5276 CGF.FinishFunction();
5277 return Fn;
5278}
5279
5280/// Emits reduction combiner function:
5281/// \code
5282/// void @.red_comb(void* %arg0, void* %arg1) {
5283/// %lhs = bitcast void* %arg0 to <type>*
5284/// %rhs = bitcast void* %arg1 to <type>*
5285/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5286/// store <type> %2, <type>* %lhs
5287/// ret void
5288/// }
5289/// \endcode
5290static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5291 SourceLocation Loc,
5292 ReductionCodeGen &RCG, unsigned N,
5293 const Expr *ReductionOp,
5294 const Expr *LHS, const Expr *RHS,
5295 const Expr *PrivateRef) {
5296 auto &C = CGM.getContext();
5297 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5298 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5299 FunctionArgList Args;
5300 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5301 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5302 Args.emplace_back(&ParamInOut);
5303 Args.emplace_back(&ParamIn);
5304 auto &FnInfo =
5305 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5306 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5307 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5308 ".red_comb.", &CGM.getModule());
5309 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5310 CodeGenFunction CGF(CGM);
5311 CGF.disableDebugInfo();
5312 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5313 llvm::Value *Size = nullptr;
5314 // If the size of the reduction item is non-constant, load it from global
5315 // threadprivate variable.
5316 if (RCG.getSizes(N).second) {
5317 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5318 CGF, CGM.getContext().getSizeType(),
5319 generateUniqueName("reduction_size", Loc, N));
5320 Size =
5321 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5322 CGM.getContext().getSizeType(), SourceLocation());
5323 }
5324 RCG.emitAggregateType(CGF, N, Size);
5325 // Remap lhs and rhs variables to the addresses of the function arguments.
5326 // %lhs = bitcast void* %arg0 to <type>*
5327 // %rhs = bitcast void* %arg1 to <type>*
5328 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5329 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5330 // Pull out the pointer to the variable.
5331 Address PtrAddr = CGF.EmitLoadOfPointer(
5332 CGF.GetAddrOfLocalVar(&ParamInOut),
5333 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5334 return CGF.Builder.CreateElementBitCast(
5335 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5336 });
5337 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5338 // Pull out the pointer to the variable.
5339 Address PtrAddr = CGF.EmitLoadOfPointer(
5340 CGF.GetAddrOfLocalVar(&ParamIn),
5341 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5342 return CGF.Builder.CreateElementBitCast(
5343 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5344 });
5345 PrivateScope.Privatize();
5346 // Emit the combiner body:
5347 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5348 // store <type> %2, <type>* %lhs
5349 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5350 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5351 cast<DeclRefExpr>(RHS));
5352 CGF.FinishFunction();
5353 return Fn;
5354}
5355
5356/// Emits reduction finalizer function:
5357/// \code
5358/// void @.red_fini(void* %arg) {
5359/// %0 = bitcast void* %arg to <type>*
5360/// <destroy>(<type>* %0)
5361/// ret void
5362/// }
5363/// \endcode
5364static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5365 SourceLocation Loc,
5366 ReductionCodeGen &RCG, unsigned N) {
5367 if (!RCG.needCleanups(N))
5368 return nullptr;
5369 auto &C = CGM.getContext();
5370 FunctionArgList Args;
5371 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5372 Args.emplace_back(&Param);
5373 auto &FnInfo =
5374 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5375 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5376 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5377 ".red_fini.", &CGM.getModule());
5378 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5379 CodeGenFunction CGF(CGM);
5380 CGF.disableDebugInfo();
5381 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5382 Address PrivateAddr = CGF.EmitLoadOfPointer(
5383 CGF.GetAddrOfLocalVar(&Param),
5384 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5385 llvm::Value *Size = nullptr;
5386 // If the size of the reduction item is non-constant, load it from global
5387 // threadprivate variable.
5388 if (RCG.getSizes(N).second) {
5389 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5390 CGF, CGM.getContext().getSizeType(),
5391 generateUniqueName("reduction_size", Loc, N));
5392 Size =
5393 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5394 CGM.getContext().getSizeType(), SourceLocation());
5395 }
5396 RCG.emitAggregateType(CGF, N, Size);
5397 // Emit the finalizer body:
5398 // <destroy>(<type>* %0)
5399 RCG.emitCleanups(CGF, N, PrivateAddr);
5400 CGF.FinishFunction();
5401 return Fn;
5402}
5403
5404llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5405 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5406 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5407 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5408 return nullptr;
5409
5410 // Build typedef struct:
5411 // kmp_task_red_input {
5412 // void *reduce_shar; // shared reduction item
5413 // size_t reduce_size; // size of data item
5414 // void *reduce_init; // data initialization routine
5415 // void *reduce_fini; // data finalization routine
5416 // void *reduce_comb; // data combiner routine
5417 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5418 // } kmp_task_red_input_t;
5419 ASTContext &C = CGM.getContext();
5420 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5421 RD->startDefinition();
5422 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5423 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5424 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5425 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5426 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5427 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5428 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5429 RD->completeDefinition();
5430 QualType RDType = C.getRecordType(RD);
5431 unsigned Size = Data.ReductionVars.size();
5432 llvm::APInt ArraySize(/*numBits=*/64, Size);
5433 QualType ArrayRDType = C.getConstantArrayType(
5434 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5435 // kmp_task_red_input_t .rd_input.[Size];
5436 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5437 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5438 Data.ReductionOps);
5439 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5440 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5441 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5442 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5443 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5444 TaskRedInput.getPointer(), Idxs,
5445 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5446 ".rd_input.gep.");
5447 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5448 // ElemLVal.reduce_shar = &Shareds[Cnt];
5449 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5450 RCG.emitSharedLValue(CGF, Cnt);
5451 llvm::Value *CastedShared =
5452 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5453 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5454 RCG.emitAggregateType(CGF, Cnt);
5455 llvm::Value *SizeValInChars;
5456 llvm::Value *SizeVal;
5457 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5458 // We use delayed creation/initialization for VLAs, array sections and
5459 // custom reduction initializations. It is required because runtime does not
5460 // provide the way to pass the sizes of VLAs/array sections to
5461 // initializer/combiner/finalizer functions and does not pass the pointer to
5462 // original reduction item to the initializer. Instead threadprivate global
5463 // variables are used to store these values and use them in the functions.
5464 bool DelayedCreation = !!SizeVal;
5465 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5466 /*isSigned=*/false);
5467 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5468 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5469 // ElemLVal.reduce_init = init;
5470 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5471 llvm::Value *InitAddr =
5472 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5473 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5474 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5475 // ElemLVal.reduce_fini = fini;
5476 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5477 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5478 llvm::Value *FiniAddr = Fini
5479 ? CGF.EmitCastToVoidPtr(Fini)
5480 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5481 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5482 // ElemLVal.reduce_comb = comb;
5483 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5484 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5485 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5486 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5487 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5488 // ElemLVal.flags = 0;
5489 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5490 if (DelayedCreation) {
5491 CGF.EmitStoreOfScalar(
5492 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5493 FlagsLVal);
5494 } else
5495 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5496 }
5497 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5498 // *data);
5499 llvm::Value *Args[] = {
5500 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5501 /*isSigned=*/true),
5502 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5503 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5504 CGM.VoidPtrTy)};
5505 return CGF.EmitRuntimeCall(
5506 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5507}
5508
5509void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5510 SourceLocation Loc,
5511 ReductionCodeGen &RCG,
5512 unsigned N) {
5513 auto Sizes = RCG.getSizes(N);
5514 // Emit threadprivate global variable if the type is non-constant
5515 // (Sizes.second = nullptr).
5516 if (Sizes.second) {
5517 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5518 /*isSigned=*/false);
5519 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5520 CGF, CGM.getContext().getSizeType(),
5521 generateUniqueName("reduction_size", Loc, N));
5522 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5523 }
5524 // Store address of the original reduction item if custom initializer is used.
5525 if (RCG.usesReductionInitializer(N)) {
5526 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5527 CGF, CGM.getContext().VoidPtrTy,
5528 generateUniqueName("reduction", Loc, N));
5529 CGF.Builder.CreateStore(
5530 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5531 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5532 SharedAddr, /*IsVolatile=*/false);
5533 }
5534}
5535
5536Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5537 SourceLocation Loc,
5538 llvm::Value *ReductionsPtr,
5539 LValue SharedLVal) {
5540 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5541 // *d);
5542 llvm::Value *Args[] = {
5543 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5544 /*isSigned=*/true),
5545 ReductionsPtr,
5546 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5547 CGM.VoidPtrTy)};
5548 return Address(
5549 CGF.EmitRuntimeCall(
5550 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5551 SharedLVal.getAlignment());
5552}
5553
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005554void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5555 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005556 if (!CGF.HaveInsertPoint())
5557 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005558 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5559 // global_tid);
5560 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5561 // Ignore return result until untied tasks are supported.
5562 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005563 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5564 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005565}
5566
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005567void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005568 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005569 const RegionCodeGenTy &CodeGen,
5570 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005571 if (!CGF.HaveInsertPoint())
5572 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005573 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005574 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005575}
5576
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005577namespace {
5578enum RTCancelKind {
5579 CancelNoreq = 0,
5580 CancelParallel = 1,
5581 CancelLoop = 2,
5582 CancelSections = 3,
5583 CancelTaskgroup = 4
5584};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005585} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005586
5587static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5588 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005589 if (CancelRegion == OMPD_parallel)
5590 CancelKind = CancelParallel;
5591 else if (CancelRegion == OMPD_for)
5592 CancelKind = CancelLoop;
5593 else if (CancelRegion == OMPD_sections)
5594 CancelKind = CancelSections;
5595 else {
5596 assert(CancelRegion == OMPD_taskgroup);
5597 CancelKind = CancelTaskgroup;
5598 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005599 return CancelKind;
5600}
5601
5602void CGOpenMPRuntime::emitCancellationPointCall(
5603 CodeGenFunction &CGF, SourceLocation Loc,
5604 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005605 if (!CGF.HaveInsertPoint())
5606 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005607 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5608 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005609 if (auto *OMPRegionInfo =
5610 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005611 // For 'cancellation point taskgroup', the task region info may not have a
5612 // cancel. This may instead happen in another adjacent task.
5613 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005614 llvm::Value *Args[] = {
5615 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5616 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005617 // Ignore return result until untied tasks are supported.
5618 auto *Result = CGF.EmitRuntimeCall(
5619 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5620 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005621 // exit from construct;
5622 // }
5623 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5624 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5625 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5626 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5627 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005628 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005629 auto CancelDest =
5630 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005631 CGF.EmitBranchThroughCleanup(CancelDest);
5632 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5633 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005634 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005635}
5636
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005637void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005638 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005639 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005640 if (!CGF.HaveInsertPoint())
5641 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005642 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5643 // kmp_int32 cncl_kind);
5644 if (auto *OMPRegionInfo =
5645 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005646 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5647 PrePostActionTy &) {
5648 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005649 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005650 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005651 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5652 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005653 auto *Result = CGF.EmitRuntimeCall(
5654 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005655 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005656 // exit from construct;
5657 // }
5658 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5659 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5660 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5661 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5662 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005663 // exit from construct;
5664 auto CancelDest =
5665 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5666 CGF.EmitBranchThroughCleanup(CancelDest);
5667 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5668 };
5669 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005670 emitOMPIfClause(CGF, IfCond, ThenGen,
5671 [](CodeGenFunction &, PrePostActionTy &) {});
5672 else {
5673 RegionCodeGenTy ThenRCG(ThenGen);
5674 ThenRCG(CGF);
5675 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005676 }
5677}
Samuel Antaobed3c462015-10-02 16:14:20 +00005678
Samuel Antaoee8fb302016-01-06 13:42:12 +00005679/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005680/// consists of the file and device IDs as well as line number associated with
5681/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005682static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5683 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005684 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005685
5686 auto &SM = C.getSourceManager();
5687
5688 // The loc should be always valid and have a file ID (the user cannot use
5689 // #pragma directives in macros)
5690
5691 assert(Loc.isValid() && "Source location is expected to be always valid.");
5692 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5693
5694 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5695 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5696
5697 llvm::sys::fs::UniqueID ID;
5698 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5699 llvm_unreachable("Source file with target region no longer exists!");
5700
5701 DeviceID = ID.getDevice();
5702 FileID = ID.getFile();
5703 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005704}
5705
5706void CGOpenMPRuntime::emitTargetOutlinedFunction(
5707 const OMPExecutableDirective &D, StringRef ParentName,
5708 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005709 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005710 assert(!ParentName.empty() && "Invalid target region parent name!");
5711
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005712 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5713 IsOffloadEntry, CodeGen);
5714}
5715
5716void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5717 const OMPExecutableDirective &D, StringRef ParentName,
5718 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5719 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005720 // Create a unique name for the entry function using the source location
5721 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005722 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005723 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005724 //
5725 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005726 // mangled name of the function that encloses the target region and BB is the
5727 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005728
5729 unsigned DeviceID;
5730 unsigned FileID;
5731 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005732 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005733 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005734 SmallString<64> EntryFnName;
5735 {
5736 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005737 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5738 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005739 }
5740
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005741 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5742
Samuel Antaobed3c462015-10-02 16:14:20 +00005743 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005744 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005745 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005746
Samuel Antao6d004262016-06-16 18:39:34 +00005747 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005748
5749 // If this target outline function is not an offload entry, we don't need to
5750 // register it.
5751 if (!IsOffloadEntry)
5752 return;
5753
5754 // The target region ID is used by the runtime library to identify the current
5755 // target region, so it only has to be unique and not necessarily point to
5756 // anything. It could be the pointer to the outlined function that implements
5757 // the target region, but we aren't using that so that the compiler doesn't
5758 // need to keep that, and could therefore inline the host function if proven
5759 // worthwhile during optimization. In the other hand, if emitting code for the
5760 // device, the ID has to be the function address so that it can retrieved from
5761 // the offloading entry and launched by the runtime library. We also mark the
5762 // outlined function to have external linkage in case we are emitting code for
5763 // the device, because these functions will be entry points to the device.
5764
5765 if (CGM.getLangOpts().OpenMPIsDevice) {
5766 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5767 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5768 } else
5769 OutlinedFnID = new llvm::GlobalVariable(
5770 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5771 llvm::GlobalValue::PrivateLinkage,
5772 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5773
5774 // Register the information for the entry associated with this target region.
5775 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005776 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5777 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005778}
5779
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005780/// discard all CompoundStmts intervening between two constructs
5781static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5782 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5783 Body = CS->body_front();
5784
5785 return Body;
5786}
5787
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005788/// Emit the number of teams for a target directive. Inspect the num_teams
5789/// clause associated with a teams construct combined or closely nested
5790/// with the target directive.
5791///
5792/// Emit a team of size one for directives such as 'target parallel' that
5793/// have no associated teams construct.
5794///
5795/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005796static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005797emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5798 CodeGenFunction &CGF,
5799 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005800
5801 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5802 "teams directive expected to be "
5803 "emitted only for the host!");
5804
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005805 auto &Bld = CGF.Builder;
5806
5807 // If the target directive is combined with a teams directive:
5808 // Return the value in the num_teams clause, if any.
5809 // Otherwise, return 0 to denote the runtime default.
5810 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5811 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5812 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5813 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5814 /*IgnoreResultAssign*/ true);
5815 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5816 /*IsSigned=*/true);
5817 }
5818
5819 // The default value is 0.
5820 return Bld.getInt32(0);
5821 }
5822
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005823 // If the target directive is combined with a parallel directive but not a
5824 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005825 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5826 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005827
5828 // If the current target region has a teams region enclosed, we need to get
5829 // the number of teams to pass to the runtime function call. This is done
5830 // by generating the expression in a inlined region. This is required because
5831 // the expression is captured in the enclosing target environment when the
5832 // teams directive is not combined with target.
5833
5834 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5835
5836 // FIXME: Accommodate other combined directives with teams when they become
5837 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005838 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5839 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005840 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5841 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5842 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5843 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005844 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5845 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005846 }
5847
5848 // If we have an enclosed teams directive but no num_teams clause we use
5849 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005850 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005851 }
5852
5853 // No teams associated with the directive.
5854 return nullptr;
5855}
5856
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005857/// Emit the number of threads for a target directive. Inspect the
5858/// thread_limit clause associated with a teams construct combined or closely
5859/// nested with the target directive.
5860///
5861/// Emit the num_threads clause for directives such as 'target parallel' that
5862/// have no associated teams construct.
5863///
5864/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005865static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005866emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5867 CodeGenFunction &CGF,
5868 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005869
5870 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5871 "teams directive expected to be "
5872 "emitted only for the host!");
5873
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005874 auto &Bld = CGF.Builder;
5875
5876 //
5877 // If the target directive is combined with a teams directive:
5878 // Return the value in the thread_limit clause, if any.
5879 //
5880 // If the target directive is combined with a parallel directive:
5881 // Return the value in the num_threads clause, if any.
5882 //
5883 // If both clauses are set, select the minimum of the two.
5884 //
5885 // If neither teams or parallel combined directives set the number of threads
5886 // in a team, return 0 to denote the runtime default.
5887 //
5888 // If this is not a teams directive return nullptr.
5889
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005890 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5891 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005892 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5893 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005894 llvm::Value *ThreadLimitVal = nullptr;
5895
5896 if (const auto *ThreadLimitClause =
5897 D.getSingleClause<OMPThreadLimitClause>()) {
5898 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5899 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5900 /*IgnoreResultAssign*/ true);
5901 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5902 /*IsSigned=*/true);
5903 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005904
5905 if (const auto *NumThreadsClause =
5906 D.getSingleClause<OMPNumThreadsClause>()) {
5907 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5908 llvm::Value *NumThreads =
5909 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5910 /*IgnoreResultAssign*/ true);
5911 NumThreadsVal =
5912 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5913 }
5914
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005915 // Select the lesser of thread_limit and num_threads.
5916 if (NumThreadsVal)
5917 ThreadLimitVal = ThreadLimitVal
5918 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5919 ThreadLimitVal),
5920 NumThreadsVal, ThreadLimitVal)
5921 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005922
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005923 // Set default value passed to the runtime if either teams or a target
5924 // parallel type directive is found but no clause is specified.
5925 if (!ThreadLimitVal)
5926 ThreadLimitVal = DefaultThreadLimitVal;
5927
5928 return ThreadLimitVal;
5929 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005930
Samuel Antaob68e2db2016-03-03 16:20:23 +00005931 // If the current target region has a teams region enclosed, we need to get
5932 // the thread limit to pass to the runtime function call. This is done
5933 // by generating the expression in a inlined region. This is required because
5934 // the expression is captured in the enclosing target environment when the
5935 // teams directive is not combined with target.
5936
5937 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5938
5939 // FIXME: Accommodate other combined directives with teams when they become
5940 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005941 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5942 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005943 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5944 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5945 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5946 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5947 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5948 /*IsSigned=*/true);
5949 }
5950
5951 // If we have an enclosed teams directive but no thread_limit clause we use
5952 // the default value 0.
5953 return CGF.Builder.getInt32(0);
5954 }
5955
5956 // No teams associated with the directive.
5957 return nullptr;
5958}
5959
Samuel Antao86ace552016-04-27 22:40:57 +00005960namespace {
5961// \brief Utility to handle information from clauses associated with a given
5962// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5963// It provides a convenient interface to obtain the information and generate
5964// code for that information.
5965class MappableExprsHandler {
5966public:
5967 /// \brief Values for bit flags used to specify the mapping type for
5968 /// offloading.
5969 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005970 /// \brief Allocate memory on the device and move data from host to device.
5971 OMP_MAP_TO = 0x01,
5972 /// \brief Allocate memory on the device and move data from device to host.
5973 OMP_MAP_FROM = 0x02,
5974 /// \brief Always perform the requested mapping action on the element, even
5975 /// if it was already mapped before.
5976 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005977 /// \brief Delete the element from the device environment, ignoring the
5978 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005979 OMP_MAP_DELETE = 0x08,
5980 /// \brief The element being mapped is a pointer, therefore the pointee
5981 /// should be mapped as well.
5982 OMP_MAP_IS_PTR = 0x10,
5983 /// \brief This flags signals that an argument is the first one relating to
5984 /// a map/private clause expression. For some cases a single
5985 /// map/privatization results in multiple arguments passed to the runtime
5986 /// library.
5987 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005988 /// \brief Signal that the runtime library has to return the device pointer
5989 /// in the current position for the data being mapped.
5990 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005991 /// \brief This flag signals that the reference being passed is a pointer to
5992 /// private data.
5993 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005994 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005995 OMP_MAP_PRIVATE_VAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00005996 /// Implicit map
5997 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00005998 };
5999
Samuel Antaocc10b852016-07-28 14:23:26 +00006000 /// Class that associates information with a base pointer to be passed to the
6001 /// runtime library.
6002 class BasePointerInfo {
6003 /// The base pointer.
6004 llvm::Value *Ptr = nullptr;
6005 /// The base declaration that refers to this device pointer, or null if
6006 /// there is none.
6007 const ValueDecl *DevPtrDecl = nullptr;
6008
6009 public:
6010 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6011 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6012 llvm::Value *operator*() const { return Ptr; }
6013 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6014 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6015 };
6016
6017 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006018 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
6019 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
6020
6021private:
6022 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006023 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006024
6025 /// \brief Function the directive is being generated for.
6026 CodeGenFunction &CGF;
6027
Samuel Antaod486f842016-05-26 16:53:38 +00006028 /// \brief Set of all first private variables in the current directive.
6029 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6030
Samuel Antao6890b092016-07-28 14:25:09 +00006031 /// Map between device pointer declarations and their expression components.
6032 /// The key value for declarations in 'this' is null.
6033 llvm::DenseMap<
6034 const ValueDecl *,
6035 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6036 DevPointersMap;
6037
Samuel Antao86ace552016-04-27 22:40:57 +00006038 llvm::Value *getExprTypeSize(const Expr *E) const {
6039 auto ExprTy = E->getType().getCanonicalType();
6040
6041 // Reference types are ignored for mapping purposes.
6042 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6043 ExprTy = RefTy->getPointeeType().getCanonicalType();
6044
6045 // Given that an array section is considered a built-in type, we need to
6046 // do the calculation based on the length of the section instead of relying
6047 // on CGF.getTypeSize(E->getType()).
6048 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6049 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6050 OAE->getBase()->IgnoreParenImpCasts())
6051 .getCanonicalType();
6052
6053 // If there is no length associated with the expression, that means we
6054 // are using the whole length of the base.
6055 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6056 return CGF.getTypeSize(BaseTy);
6057
6058 llvm::Value *ElemSize;
6059 if (auto *PTy = BaseTy->getAs<PointerType>())
6060 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6061 else {
6062 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6063 assert(ATy && "Expecting array type if not a pointer type.");
6064 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6065 }
6066
6067 // If we don't have a length at this point, that is because we have an
6068 // array section with a single element.
6069 if (!OAE->getLength())
6070 return ElemSize;
6071
6072 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6073 LengthVal =
6074 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6075 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6076 }
6077 return CGF.getTypeSize(ExprTy);
6078 }
6079
6080 /// \brief Return the corresponding bits for a given map clause modifier. Add
6081 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006082 /// map as the first one of a series of maps that relate to the same map
6083 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006084 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6085 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006086 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006087 unsigned Bits = 0u;
6088 switch (MapType) {
6089 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006090 case OMPC_MAP_release:
6091 // alloc and release is the default behavior in the runtime library, i.e.
6092 // if we don't pass any bits alloc/release that is what the runtime is
6093 // going to do. Therefore, we don't need to signal anything for these two
6094 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006095 break;
6096 case OMPC_MAP_to:
6097 Bits = OMP_MAP_TO;
6098 break;
6099 case OMPC_MAP_from:
6100 Bits = OMP_MAP_FROM;
6101 break;
6102 case OMPC_MAP_tofrom:
6103 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6104 break;
6105 case OMPC_MAP_delete:
6106 Bits = OMP_MAP_DELETE;
6107 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006108 default:
6109 llvm_unreachable("Unexpected map type!");
6110 break;
6111 }
6112 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006113 Bits |= OMP_MAP_IS_PTR;
6114 if (AddIsFirstFlag)
6115 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006116 if (MapTypeModifier == OMPC_MAP_always)
6117 Bits |= OMP_MAP_ALWAYS;
6118 return Bits;
6119 }
6120
6121 /// \brief Return true if the provided expression is a final array section. A
6122 /// final array section, is one whose length can't be proved to be one.
6123 bool isFinalArraySectionExpression(const Expr *E) const {
6124 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6125
6126 // It is not an array section and therefore not a unity-size one.
6127 if (!OASE)
6128 return false;
6129
6130 // An array section with no colon always refer to a single element.
6131 if (OASE->getColonLoc().isInvalid())
6132 return false;
6133
6134 auto *Length = OASE->getLength();
6135
6136 // If we don't have a length we have to check if the array has size 1
6137 // for this dimension. Also, we should always expect a length if the
6138 // base type is pointer.
6139 if (!Length) {
6140 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6141 OASE->getBase()->IgnoreParenImpCasts())
6142 .getCanonicalType();
6143 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6144 return ATy->getSize().getSExtValue() != 1;
6145 // If we don't have a constant dimension length, we have to consider
6146 // the current section as having any size, so it is not necessarily
6147 // unitary. If it happen to be unity size, that's user fault.
6148 return true;
6149 }
6150
6151 // Check if the length evaluates to 1.
6152 llvm::APSInt ConstLength;
6153 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6154 return true; // Can have more that size 1.
6155
6156 return ConstLength.getSExtValue() != 1;
6157 }
6158
6159 /// \brief Generate the base pointers, section pointers, sizes and map type
6160 /// bits for the provided map type, map modifier, and expression components.
6161 /// \a IsFirstComponent should be set to true if the provided set of
6162 /// components is the first associated with a capture.
6163 void generateInfoForComponentList(
6164 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6165 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006166 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006167 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006168 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006169
6170 // The following summarizes what has to be generated for each map and the
6171 // types bellow. The generated information is expressed in this order:
6172 // base pointer, section pointer, size, flags
6173 // (to add to the ones that come from the map type and modifier).
6174 //
6175 // double d;
6176 // int i[100];
6177 // float *p;
6178 //
6179 // struct S1 {
6180 // int i;
6181 // float f[50];
6182 // }
6183 // struct S2 {
6184 // int i;
6185 // float f[50];
6186 // S1 s;
6187 // double *p;
6188 // struct S2 *ps;
6189 // }
6190 // S2 s;
6191 // S2 *ps;
6192 //
6193 // map(d)
6194 // &d, &d, sizeof(double), noflags
6195 //
6196 // map(i)
6197 // &i, &i, 100*sizeof(int), noflags
6198 //
6199 // map(i[1:23])
6200 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6201 //
6202 // map(p)
6203 // &p, &p, sizeof(float*), noflags
6204 //
6205 // map(p[1:24])
6206 // p, &p[1], 24*sizeof(float), noflags
6207 //
6208 // map(s)
6209 // &s, &s, sizeof(S2), noflags
6210 //
6211 // map(s.i)
6212 // &s, &(s.i), sizeof(int), noflags
6213 //
6214 // map(s.s.f)
6215 // &s, &(s.i.f), 50*sizeof(int), noflags
6216 //
6217 // map(s.p)
6218 // &s, &(s.p), sizeof(double*), noflags
6219 //
6220 // map(s.p[:22], s.a s.b)
6221 // &s, &(s.p), sizeof(double*), noflags
6222 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6223 //
6224 // map(s.ps)
6225 // &s, &(s.ps), sizeof(S2*), noflags
6226 //
6227 // map(s.ps->s.i)
6228 // &s, &(s.ps), sizeof(S2*), noflags
6229 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6230 //
6231 // map(s.ps->ps)
6232 // &s, &(s.ps), sizeof(S2*), noflags
6233 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6234 //
6235 // map(s.ps->ps->ps)
6236 // &s, &(s.ps), sizeof(S2*), noflags
6237 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6238 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6239 //
6240 // map(s.ps->ps->s.f[:22])
6241 // &s, &(s.ps), sizeof(S2*), noflags
6242 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6243 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6244 //
6245 // map(ps)
6246 // &ps, &ps, sizeof(S2*), noflags
6247 //
6248 // map(ps->i)
6249 // ps, &(ps->i), sizeof(int), noflags
6250 //
6251 // map(ps->s.f)
6252 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6253 //
6254 // map(ps->p)
6255 // ps, &(ps->p), sizeof(double*), noflags
6256 //
6257 // map(ps->p[:22])
6258 // ps, &(ps->p), sizeof(double*), noflags
6259 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6260 //
6261 // map(ps->ps)
6262 // ps, &(ps->ps), sizeof(S2*), noflags
6263 //
6264 // map(ps->ps->s.i)
6265 // ps, &(ps->ps), sizeof(S2*), noflags
6266 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6267 //
6268 // map(ps->ps->ps)
6269 // ps, &(ps->ps), sizeof(S2*), noflags
6270 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6271 //
6272 // map(ps->ps->ps->ps)
6273 // ps, &(ps->ps), sizeof(S2*), noflags
6274 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6275 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6276 //
6277 // map(ps->ps->ps->s.f[:22])
6278 // ps, &(ps->ps), sizeof(S2*), noflags
6279 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6280 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6281 // extra_flag
6282
6283 // Track if the map information being generated is the first for a capture.
6284 bool IsCaptureFirstInfo = IsFirstComponentList;
6285
6286 // Scan the components from the base to the complete expression.
6287 auto CI = Components.rbegin();
6288 auto CE = Components.rend();
6289 auto I = CI;
6290
6291 // Track if the map information being generated is the first for a list of
6292 // components.
6293 bool IsExpressionFirstInfo = true;
6294 llvm::Value *BP = nullptr;
6295
6296 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6297 // The base is the 'this' pointer. The content of the pointer is going
6298 // to be the base of the field being mapped.
6299 BP = CGF.EmitScalarExpr(ME->getBase());
6300 } else {
6301 // The base is the reference to the variable.
6302 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006303 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006304
6305 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006306 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006307 // reference. References are ignored for mapping purposes.
6308 QualType Ty =
6309 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6310 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6311 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006312 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006313 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006314 .getPointer();
6315
6316 // We do not need to generate individual map information for the
6317 // pointer, it can be associated with the combined storage.
6318 ++I;
6319 }
6320 }
6321
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006322 unsigned DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006323 for (; I != CE; ++I) {
6324 auto Next = std::next(I);
6325
6326 // We need to generate the addresses and sizes if this is the last
6327 // component, if the component is a pointer or if it is an array section
6328 // whose length can't be proved to be one. If this is a pointer, it
6329 // becomes the base address for the following components.
6330
6331 // A final array section, is one whose length can't be proved to be one.
6332 bool IsFinalArraySection =
6333 isFinalArraySectionExpression(I->getAssociatedExpression());
6334
6335 // Get information on whether the element is a pointer. Have to do a
6336 // special treatment for array sections given that they are built-in
6337 // types.
6338 const auto *OASE =
6339 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6340 bool IsPointer =
6341 (OASE &&
6342 OMPArraySectionExpr::getBaseOriginalType(OASE)
6343 .getCanonicalType()
6344 ->isAnyPointerType()) ||
6345 I->getAssociatedExpression()->getType()->isAnyPointerType();
6346
6347 if (Next == CE || IsPointer || IsFinalArraySection) {
6348
6349 // If this is not the last component, we expect the pointer to be
6350 // associated with an array expression or member expression.
6351 assert((Next == CE ||
6352 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6353 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6354 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6355 "Unexpected expression");
6356
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006357 llvm::Value *LB =
6358 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006359 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6360
Samuel Antao03a3cec2016-07-27 22:52:16 +00006361 // If we have a member expression and the current component is a
6362 // reference, we have to map the reference too. Whenever we have a
6363 // reference, the section that reference refers to is going to be a
6364 // load instruction from the storage assigned to the reference.
6365 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6366 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6367 auto *LI = cast<llvm::LoadInst>(LB);
6368 auto *RefAddr = LI->getPointerOperand();
6369
6370 BasePointers.push_back(BP);
6371 Pointers.push_back(RefAddr);
6372 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006373 Types.push_back(DefaultFlags |
6374 getMapTypeBits(
6375 /*MapType*/ OMPC_MAP_alloc,
6376 /*MapTypeModifier=*/OMPC_MAP_unknown,
6377 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006378 IsExpressionFirstInfo = false;
6379 IsCaptureFirstInfo = false;
6380 // The reference will be the next base address.
6381 BP = RefAddr;
6382 }
6383
6384 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006385 Pointers.push_back(LB);
6386 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006387
Samuel Antao6782e942016-05-26 16:48:10 +00006388 // We need to add a pointer flag for each map that comes from the
6389 // same expression except for the first one. We also need to signal
6390 // this map is the first one that relates with the current capture
6391 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006392 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6393 !IsExpressionFirstInfo,
6394 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006395
6396 // If we have a final array section, we are done with this expression.
6397 if (IsFinalArraySection)
6398 break;
6399
6400 // The pointer becomes the base for the next element.
6401 if (Next != CE)
6402 BP = LB;
6403
6404 IsExpressionFirstInfo = false;
6405 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006406 }
6407 }
6408 }
6409
Samuel Antaod486f842016-05-26 16:53:38 +00006410 /// \brief Return the adjusted map modifiers if the declaration a capture
6411 /// refers to appears in a first-private clause. This is expected to be used
6412 /// only with directives that start with 'target'.
6413 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6414 unsigned CurrentModifiers) {
6415 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6416
6417 // A first private variable captured by reference will use only the
6418 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6419 // declaration is known as first-private in this handler.
6420 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6421 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6422 MappableExprsHandler::OMP_MAP_TO;
6423
6424 // We didn't modify anything.
6425 return CurrentModifiers;
6426 }
6427
Samuel Antao86ace552016-04-27 22:40:57 +00006428public:
6429 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006430 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006431 // Extract firstprivate clause information.
6432 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6433 for (const auto *D : C->varlists())
6434 FirstPrivateDecls.insert(
6435 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006436 // Extract device pointer clause information.
6437 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6438 for (auto L : C->component_lists())
6439 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006440 }
Samuel Antao86ace552016-04-27 22:40:57 +00006441
6442 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006443 /// types for the extracted mappable expressions. Also, for each item that
6444 /// relates with a device pointer, a pair of the relevant declaration and
6445 /// index where it occurs is appended to the device pointers info array.
6446 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006447 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6448 MapFlagsArrayTy &Types) const {
6449 BasePointers.clear();
6450 Pointers.clear();
6451 Sizes.clear();
6452 Types.clear();
6453
6454 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006455 /// Kind that defines how a device pointer has to be returned.
6456 enum ReturnPointerKind {
6457 // Don't have to return any pointer.
6458 RPK_None,
6459 // Pointer is the base of the declaration.
6460 RPK_Base,
6461 // Pointer is a member of the base declaration - 'this'
6462 RPK_Member,
6463 // Pointer is a reference and a member of the base declaration - 'this'
6464 RPK_MemberReference,
6465 };
Samuel Antao86ace552016-04-27 22:40:57 +00006466 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006467 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6468 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6469 ReturnPointerKind ReturnDevicePointer = RPK_None;
6470 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006471
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006472 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006473 MapInfo(
6474 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6475 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006476 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006477 : Components(Components), MapType(MapType),
6478 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006479 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006480 };
6481
6482 // We have to process the component lists that relate with the same
6483 // declaration in a single chunk so that we can generate the map flags
6484 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006485 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006486
6487 // Helper function to fill the information map for the different supported
6488 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006489 auto &&InfoGen = [&Info](
6490 const ValueDecl *D,
6491 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6492 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006493 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006494 const ValueDecl *VD =
6495 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006496 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6497 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006498 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006499
Paul Robinson78fb1322016-08-01 22:12:46 +00006500 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006501 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006502 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006503 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006504 MapInfo::RPK_None, C->isImplicit());
6505 }
Paul Robinson15c84002016-07-29 20:46:16 +00006506 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006507 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006508 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006509 MapInfo::RPK_None, C->isImplicit());
6510 }
Paul Robinson15c84002016-07-29 20:46:16 +00006511 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006512 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006513 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006514 MapInfo::RPK_None, C->isImplicit());
6515 }
Samuel Antao86ace552016-04-27 22:40:57 +00006516
Samuel Antaocc10b852016-07-28 14:23:26 +00006517 // Look at the use_device_ptr clause information and mark the existing map
6518 // entries as such. If there is no map information for an entry in the
6519 // use_device_ptr list, we create one with map type 'alloc' and zero size
6520 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006521 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006522 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006523 for (auto L : C->component_lists()) {
6524 assert(!L.second.empty() && "Not expecting empty list of components!");
6525 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6526 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6527 auto *IE = L.second.back().getAssociatedExpression();
6528 // If the first component is a member expression, we have to look into
6529 // 'this', which maps to null in the map of map information. Otherwise
6530 // look directly for the information.
6531 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6532
6533 // We potentially have map information for this declaration already.
6534 // Look for the first set of components that refer to it.
6535 if (It != Info.end()) {
6536 auto CI = std::find_if(
6537 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6538 return MI.Components.back().getAssociatedDeclaration() == VD;
6539 });
6540 // If we found a map entry, signal that the pointer has to be returned
6541 // and move on to the next declaration.
6542 if (CI != It->second.end()) {
6543 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6544 ? (VD->getType()->isReferenceType()
6545 ? MapInfo::RPK_MemberReference
6546 : MapInfo::RPK_Member)
6547 : MapInfo::RPK_Base;
6548 continue;
6549 }
6550 }
6551
6552 // We didn't find any match in our map information - generate a zero
6553 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006554 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006555 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006556 this->CGF
6557 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006558 .getScalarVal();
6559 BasePointers.push_back({Ptr, VD});
6560 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006561 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006562 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6563 }
6564
Samuel Antao86ace552016-04-27 22:40:57 +00006565 for (auto &M : Info) {
6566 // We need to know when we generate information for the first component
6567 // associated with a capture, because the mapping flags depend on it.
6568 bool IsFirstComponentList = true;
6569 for (MapInfo &L : M.second) {
6570 assert(!L.Components.empty() &&
6571 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006572
6573 // Remember the current base pointer index.
6574 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006575 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006576 this->generateInfoForComponentList(
6577 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6578 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006579
6580 // If this entry relates with a device pointer, set the relevant
6581 // declaration and add the 'return pointer' flag.
6582 if (IsFirstComponentList &&
6583 L.ReturnDevicePointer != MapInfo::RPK_None) {
6584 // If the pointer is not the base of the map, we need to skip the
6585 // base. If it is a reference in a member field, we also need to skip
6586 // the map of the reference.
6587 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6588 ++CurrentBasePointersIdx;
6589 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6590 ++CurrentBasePointersIdx;
6591 }
6592 assert(BasePointers.size() > CurrentBasePointersIdx &&
6593 "Unexpected number of mapped base pointers.");
6594
6595 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6596 assert(RelevantVD &&
6597 "No relevant declaration related with device pointer??");
6598
6599 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6600 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6601 }
Samuel Antao86ace552016-04-27 22:40:57 +00006602 IsFirstComponentList = false;
6603 }
6604 }
6605 }
6606
6607 /// \brief Generate the base pointers, section pointers, sizes and map types
6608 /// associated to a given capture.
6609 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006610 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006611 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006612 MapValuesArrayTy &Pointers,
6613 MapValuesArrayTy &Sizes,
6614 MapFlagsArrayTy &Types) const {
6615 assert(!Cap->capturesVariableArrayType() &&
6616 "Not expecting to generate map info for a variable array type!");
6617
6618 BasePointers.clear();
6619 Pointers.clear();
6620 Sizes.clear();
6621 Types.clear();
6622
Samuel Antao6890b092016-07-28 14:25:09 +00006623 // We need to know when we generating information for the first component
6624 // associated with a capture, because the mapping flags depend on it.
6625 bool IsFirstComponentList = true;
6626
Samuel Antao86ace552016-04-27 22:40:57 +00006627 const ValueDecl *VD =
6628 Cap->capturesThis()
6629 ? nullptr
6630 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6631
Samuel Antao6890b092016-07-28 14:25:09 +00006632 // If this declaration appears in a is_device_ptr clause we just have to
6633 // pass the pointer by value. If it is a reference to a declaration, we just
6634 // pass its value, otherwise, if it is a member expression, we need to map
6635 // 'to' the field.
6636 if (!VD) {
6637 auto It = DevPointersMap.find(VD);
6638 if (It != DevPointersMap.end()) {
6639 for (auto L : It->second) {
6640 generateInfoForComponentList(
6641 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006642 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6643 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006644 IsFirstComponentList = false;
6645 }
6646 return;
6647 }
6648 } else if (DevPointersMap.count(VD)) {
6649 BasePointers.push_back({Arg, VD});
6650 Pointers.push_back(Arg);
6651 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6652 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6653 return;
6654 }
6655
Paul Robinson78fb1322016-08-01 22:12:46 +00006656 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006657 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006658 for (auto L : C->decl_component_lists(VD)) {
6659 assert(L.first == VD &&
6660 "We got information for the wrong declaration??");
6661 assert(!L.second.empty() &&
6662 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006663 generateInfoForComponentList(
6664 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6665 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006666 IsFirstComponentList = false;
6667 }
6668
6669 return;
6670 }
Samuel Antaod486f842016-05-26 16:53:38 +00006671
6672 /// \brief Generate the default map information for a given capture \a CI,
6673 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006674 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6675 const FieldDecl &RI, llvm::Value *CV,
6676 MapBaseValuesArrayTy &CurBasePointers,
6677 MapValuesArrayTy &CurPointers,
6678 MapValuesArrayTy &CurSizes,
6679 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006680
6681 // Do the default mapping.
6682 if (CI.capturesThis()) {
6683 CurBasePointers.push_back(CV);
6684 CurPointers.push_back(CV);
6685 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6686 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6687 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006688 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006689 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006690 CurBasePointers.push_back(CV);
6691 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006692 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006693 // We have to signal to the runtime captures passed by value that are
6694 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006695 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006696 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6697 } else {
6698 // Pointers are implicitly mapped with a zero size and no flags
6699 // (other than first map that is added for all implicit maps).
6700 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006701 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6702 }
6703 } else {
6704 assert(CI.capturesVariable() && "Expected captured reference.");
6705 CurBasePointers.push_back(CV);
6706 CurPointers.push_back(CV);
6707
6708 const ReferenceType *PtrTy =
6709 cast<ReferenceType>(RI.getType().getTypePtr());
6710 QualType ElementType = PtrTy->getPointeeType();
6711 CurSizes.push_back(CGF.getTypeSize(ElementType));
6712 // The default map type for a scalar/complex type is 'to' because by
6713 // default the value doesn't have to be retrieved. For an aggregate
6714 // type, the default is 'tofrom'.
6715 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006716 ? (OMP_MAP_TO | OMP_MAP_FROM)
6717 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006718
6719 // If we have a capture by reference we may need to add the private
6720 // pointer flag if the base declaration shows in some first-private
6721 // clause.
6722 CurMapTypes.back() =
6723 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6724 }
6725 // Every default map produces a single argument, so, it is always the
6726 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006727 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006728 }
Samuel Antao86ace552016-04-27 22:40:57 +00006729};
Samuel Antaodf158d52016-04-27 22:58:19 +00006730
6731enum OpenMPOffloadingReservedDeviceIDs {
6732 /// \brief Device ID if the device was not defined, runtime should get it
6733 /// from environment variables in the spec.
6734 OMP_DEVICEID_UNDEF = -1,
6735};
6736} // anonymous namespace
6737
6738/// \brief Emit the arrays used to pass the captures and map information to the
6739/// offloading runtime library. If there is no map or capture information,
6740/// return nullptr by reference.
6741static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006742emitOffloadingArrays(CodeGenFunction &CGF,
6743 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006744 MappableExprsHandler::MapValuesArrayTy &Pointers,
6745 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006746 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6747 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006748 auto &CGM = CGF.CGM;
6749 auto &Ctx = CGF.getContext();
6750
Samuel Antaocc10b852016-07-28 14:23:26 +00006751 // Reset the array information.
6752 Info.clearArrayInfo();
6753 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006754
Samuel Antaocc10b852016-07-28 14:23:26 +00006755 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006756 // Detect if we have any capture size requiring runtime evaluation of the
6757 // size so that a constant array could be eventually used.
6758 bool hasRuntimeEvaluationCaptureSize = false;
6759 for (auto *S : Sizes)
6760 if (!isa<llvm::Constant>(S)) {
6761 hasRuntimeEvaluationCaptureSize = true;
6762 break;
6763 }
6764
Samuel Antaocc10b852016-07-28 14:23:26 +00006765 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006766 QualType PointerArrayType =
6767 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6768 /*IndexTypeQuals=*/0);
6769
Samuel Antaocc10b852016-07-28 14:23:26 +00006770 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006771 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006772 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006773 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6774
6775 // If we don't have any VLA types or other types that require runtime
6776 // evaluation, we can use a constant array for the map sizes, otherwise we
6777 // need to fill up the arrays as we do for the pointers.
6778 if (hasRuntimeEvaluationCaptureSize) {
6779 QualType SizeArrayType = Ctx.getConstantArrayType(
6780 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6781 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006782 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006783 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6784 } else {
6785 // We expect all the sizes to be constant, so we collect them to create
6786 // a constant array.
6787 SmallVector<llvm::Constant *, 16> ConstSizes;
6788 for (auto S : Sizes)
6789 ConstSizes.push_back(cast<llvm::Constant>(S));
6790
6791 auto *SizesArrayInit = llvm::ConstantArray::get(
6792 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6793 auto *SizesArrayGbl = new llvm::GlobalVariable(
6794 CGM.getModule(), SizesArrayInit->getType(),
6795 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6796 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006797 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006798 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006799 }
6800
6801 // The map types are always constant so we don't need to generate code to
6802 // fill arrays. Instead, we create an array constant.
6803 llvm::Constant *MapTypesArrayInit =
6804 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6805 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6806 CGM.getModule(), MapTypesArrayInit->getType(),
6807 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6808 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006809 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006810 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006811
Samuel Antaocc10b852016-07-28 14:23:26 +00006812 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6813 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006814 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006815 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6816 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006817 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6818 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006819 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6820 CGF.Builder.CreateStore(BPVal, BPAddr);
6821
Samuel Antaocc10b852016-07-28 14:23:26 +00006822 if (Info.requiresDevicePointerInfo())
6823 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6824 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6825
Samuel Antaodf158d52016-04-27 22:58:19 +00006826 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006827 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006828 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6829 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006830 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6831 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006832 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6833 CGF.Builder.CreateStore(PVal, PAddr);
6834
6835 if (hasRuntimeEvaluationCaptureSize) {
6836 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006837 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6838 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006839 /*Idx0=*/0,
6840 /*Idx1=*/i);
6841 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6842 CGF.Builder.CreateStore(
6843 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6844 SAddr);
6845 }
6846 }
6847 }
6848}
6849/// \brief Emit the arguments to be passed to the runtime library based on the
6850/// arrays of pointers, sizes and map types.
6851static void emitOffloadingArraysArgument(
6852 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6853 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006854 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006855 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006856 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006857 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006858 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6859 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006860 /*Idx0=*/0, /*Idx1=*/0);
6861 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006862 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6863 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006864 /*Idx0=*/0,
6865 /*Idx1=*/0);
6866 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006867 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006868 /*Idx0=*/0, /*Idx1=*/0);
6869 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006870 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6871 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006872 /*Idx0=*/0,
6873 /*Idx1=*/0);
6874 } else {
6875 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6876 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6877 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6878 MapTypesArrayArg =
6879 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6880 }
Samuel Antao86ace552016-04-27 22:40:57 +00006881}
6882
Samuel Antaobed3c462015-10-02 16:14:20 +00006883void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6884 const OMPExecutableDirective &D,
6885 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006886 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006887 const Expr *IfCond, const Expr *Device,
6888 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006889 if (!CGF.HaveInsertPoint())
6890 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006891
Samuel Antaoee8fb302016-01-06 13:42:12 +00006892 assert(OutlinedFn && "Invalid outlined function!");
6893
Samuel Antao86ace552016-04-27 22:40:57 +00006894 // Fill up the arrays with all the captured variables.
6895 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006896 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006897 MappableExprsHandler::MapValuesArrayTy Pointers;
6898 MappableExprsHandler::MapValuesArrayTy Sizes;
6899 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006900
Samuel Antaocc10b852016-07-28 14:23:26 +00006901 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006902 MappableExprsHandler::MapValuesArrayTy CurPointers;
6903 MappableExprsHandler::MapValuesArrayTy CurSizes;
6904 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6905
Samuel Antaod486f842016-05-26 16:53:38 +00006906 // Get mappable expression information.
6907 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006908
6909 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6910 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006911 auto CV = CapturedVars.begin();
6912 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6913 CE = CS.capture_end();
6914 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00006915 CurBasePointers.clear();
6916 CurPointers.clear();
6917 CurSizes.clear();
6918 CurMapTypes.clear();
6919
6920 // VLA sizes are passed to the outlined region by copy and do not have map
6921 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006922 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006923 CurBasePointers.push_back(*CV);
6924 CurPointers.push_back(*CV);
6925 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006926 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006927 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6928 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006929 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006930 // If we have any information in the map clause, we use it, otherwise we
6931 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006932 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006933 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006934 if (CurBasePointers.empty())
6935 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6936 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006937 }
Samuel Antao86ace552016-04-27 22:40:57 +00006938 // We expect to have at least an element of information for this capture.
6939 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6940 assert(CurBasePointers.size() == CurPointers.size() &&
6941 CurBasePointers.size() == CurSizes.size() &&
6942 CurBasePointers.size() == CurMapTypes.size() &&
6943 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006944
Samuel Antao86ace552016-04-27 22:40:57 +00006945 // The kernel args are always the first elements of the base pointers
6946 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006947 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006948 // We need to append the results of this capture to what we already have.
6949 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6950 Pointers.append(CurPointers.begin(), CurPointers.end());
6951 Sizes.append(CurSizes.begin(), CurSizes.end());
6952 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006953 }
6954
Samuel Antaobed3c462015-10-02 16:14:20 +00006955 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00006956 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6957 OutlinedFn, OutlinedFnID, &D,
6958 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006959 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006960 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006961 TargetDataInfo Info;
6962 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6963 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6964 Info.PointersArray, Info.SizesArray,
6965 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006966
6967 // On top of the arrays that were filled up, the target offloading call
6968 // takes as arguments the device id as well as the host pointer. The host
6969 // pointer is used by the runtime library to identify the current target
6970 // region, so it only has to be unique and not necessarily point to
6971 // anything. It could be the pointer to the outlined function that
6972 // implements the target region, but we aren't using that so that the
6973 // compiler doesn't need to keep that, and could therefore inline the host
6974 // function if proven worthwhile during optimization.
6975
Samuel Antaoee8fb302016-01-06 13:42:12 +00006976 // From this point on, we need to have an ID of the target region defined.
6977 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006978
6979 // Emit device ID if any.
6980 llvm::Value *DeviceID;
6981 if (Device)
6982 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006983 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006984 else
6985 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6986
Samuel Antaodf158d52016-04-27 22:58:19 +00006987 // Emit the number of elements in the offloading arrays.
6988 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6989
Samuel Antaob68e2db2016-03-03 16:20:23 +00006990 // Return value of the runtime offloading call.
6991 llvm::Value *Return;
6992
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006993 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6994 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006995
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006996 // The target region is an outlined function launched by the runtime
6997 // via calls __tgt_target() or __tgt_target_teams().
6998 //
6999 // __tgt_target() launches a target region with one team and one thread,
7000 // executing a serial region. This master thread may in turn launch
7001 // more threads within its team upon encountering a parallel region,
7002 // however, no additional teams can be launched on the device.
7003 //
7004 // __tgt_target_teams() launches a target region with one or more teams,
7005 // each with one or more threads. This call is required for target
7006 // constructs such as:
7007 // 'target teams'
7008 // 'target' / 'teams'
7009 // 'target teams distribute parallel for'
7010 // 'target parallel'
7011 // and so on.
7012 //
7013 // Note that on the host and CPU targets, the runtime implementation of
7014 // these calls simply call the outlined function without forking threads.
7015 // The outlined functions themselves have runtime calls to
7016 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7017 // the compiler in emitTeamsCall() and emitParallelCall().
7018 //
7019 // In contrast, on the NVPTX target, the implementation of
7020 // __tgt_target_teams() launches a GPU kernel with the requested number
7021 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007022 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007023 // If we have NumTeams defined this means that we have an enclosed teams
7024 // region. Therefore we also expect to have NumThreads defined. These two
7025 // values should be defined in the presence of a teams directive,
7026 // regardless of having any clauses associated. If the user is using teams
7027 // but no clauses, these two values will be the default that should be
7028 // passed to the runtime library - a 32-bit integer with the value zero.
7029 assert(NumThreads && "Thread limit expression should be available along "
7030 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007031 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007032 DeviceID, OutlinedFnID,
7033 PointerNum, Info.BasePointersArray,
7034 Info.PointersArray, Info.SizesArray,
7035 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007036 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007037 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007038 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007039 } else {
7040 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007041 DeviceID, OutlinedFnID,
7042 PointerNum, Info.BasePointersArray,
7043 Info.PointersArray, Info.SizesArray,
7044 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007045 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007046 OffloadingArgs);
7047 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007048
Alexey Bataev2a007e02017-10-02 14:20:58 +00007049 // Check the error code and execute the host version if required.
7050 llvm::BasicBlock *OffloadFailedBlock =
7051 CGF.createBasicBlock("omp_offload.failed");
7052 llvm::BasicBlock *OffloadContBlock =
7053 CGF.createBasicBlock("omp_offload.cont");
7054 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7055 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7056
7057 CGF.EmitBlock(OffloadFailedBlock);
7058 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7059 CGF.EmitBranch(OffloadContBlock);
7060
7061 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007062 };
7063
Samuel Antaoee8fb302016-01-06 13:42:12 +00007064 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007065 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7066 PrePostActionTy &) {
7067 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7068 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007069 };
7070
7071 // If we have a target function ID it means that we need to support
7072 // offloading, otherwise, just execute on the host. We need to execute on host
7073 // regardless of the conditional in the if clause if, e.g., the user do not
7074 // specify target triples.
7075 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007076 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007077 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007078 else {
7079 RegionCodeGenTy ThenRCG(ThenGen);
7080 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007081 }
7082 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007083 RegionCodeGenTy ElseRCG(ElseGen);
7084 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007085 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007086}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007087
7088void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7089 StringRef ParentName) {
7090 if (!S)
7091 return;
7092
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007093 // Codegen OMP target directives that offload compute to the device.
7094 bool requiresDeviceCodegen =
7095 isa<OMPExecutableDirective>(S) &&
7096 isOpenMPTargetExecutionDirective(
7097 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007098
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007099 if (requiresDeviceCodegen) {
7100 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007101 unsigned DeviceID;
7102 unsigned FileID;
7103 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007104 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007105 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007106
7107 // Is this a target region that should not be emitted as an entry point? If
7108 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007109 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7110 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007111 return;
7112
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007113 switch (S->getStmtClass()) {
7114 case Stmt::OMPTargetDirectiveClass:
7115 CodeGenFunction::EmitOMPTargetDeviceFunction(
7116 CGM, ParentName, cast<OMPTargetDirective>(*S));
7117 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007118 case Stmt::OMPTargetParallelDirectiveClass:
7119 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7120 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7121 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007122 case Stmt::OMPTargetTeamsDirectiveClass:
7123 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7124 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7125 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007126 default:
7127 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7128 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007129 return;
7130 }
7131
7132 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007133 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007134 return;
7135
7136 scanForTargetRegionsFunctions(
7137 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7138 ParentName);
7139 return;
7140 }
7141
7142 // If this is a lambda function, look into its body.
7143 if (auto *L = dyn_cast<LambdaExpr>(S))
7144 S = L->getBody();
7145
7146 // Keep looking for target regions recursively.
7147 for (auto *II : S->children())
7148 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007149}
7150
7151bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7152 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7153
7154 // If emitting code for the host, we do not process FD here. Instead we do
7155 // the normal code generation.
7156 if (!CGM.getLangOpts().OpenMPIsDevice)
7157 return false;
7158
7159 // Try to detect target regions in the function.
7160 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7161
Samuel Antao4b75b872016-12-12 19:26:31 +00007162 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007163 // scanning. Therefore, we signal that this function is completely dealt
7164 // with.
7165 return true;
7166}
7167
7168bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7169 if (!CGM.getLangOpts().OpenMPIsDevice)
7170 return false;
7171
7172 // Check if there are Ctors/Dtors in this declaration and look for target
7173 // regions in it. We use the complete variant to produce the kernel name
7174 // mangling.
7175 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7176 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7177 for (auto *Ctor : RD->ctors()) {
7178 StringRef ParentName =
7179 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7180 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7181 }
7182 auto *Dtor = RD->getDestructor();
7183 if (Dtor) {
7184 StringRef ParentName =
7185 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7186 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7187 }
7188 }
7189
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007190 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007191 // implemented yet). Therefore we signal that GD was processed in this case.
7192 return true;
7193}
7194
7195bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7196 auto *VD = GD.getDecl();
7197 if (isa<FunctionDecl>(VD))
7198 return emitTargetFunctions(GD);
7199
7200 return emitTargetGlobalVariable(GD);
7201}
7202
7203llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7204 // If we have offloading in the current module, we need to emit the entries
7205 // now and register the offloading descriptor.
7206 createOffloadEntriesAndInfoMetadata();
7207
7208 // Create and register the offloading binary descriptors. This is the main
7209 // entity that captures all the information about offloading in the current
7210 // compilation unit.
7211 return createOffloadingBinaryDescriptorRegistration();
7212}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007213
7214void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7215 const OMPExecutableDirective &D,
7216 SourceLocation Loc,
7217 llvm::Value *OutlinedFn,
7218 ArrayRef<llvm::Value *> CapturedVars) {
7219 if (!CGF.HaveInsertPoint())
7220 return;
7221
7222 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7223 CodeGenFunction::RunCleanupsScope Scope(CGF);
7224
7225 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7226 llvm::Value *Args[] = {
7227 RTLoc,
7228 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7229 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7230 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7231 RealArgs.append(std::begin(Args), std::end(Args));
7232 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7233
7234 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7235 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7236}
7237
7238void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007239 const Expr *NumTeams,
7240 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007241 SourceLocation Loc) {
7242 if (!CGF.HaveInsertPoint())
7243 return;
7244
7245 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7246
Carlo Bertollic6872252016-04-04 15:55:02 +00007247 llvm::Value *NumTeamsVal =
7248 (NumTeams)
7249 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7250 CGF.CGM.Int32Ty, /* isSigned = */ true)
7251 : CGF.Builder.getInt32(0);
7252
7253 llvm::Value *ThreadLimitVal =
7254 (ThreadLimit)
7255 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7256 CGF.CGM.Int32Ty, /* isSigned = */ true)
7257 : CGF.Builder.getInt32(0);
7258
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007259 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007260 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7261 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007262 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7263 PushNumTeamsArgs);
7264}
Samuel Antaodf158d52016-04-27 22:58:19 +00007265
Samuel Antaocc10b852016-07-28 14:23:26 +00007266void CGOpenMPRuntime::emitTargetDataCalls(
7267 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7268 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007269 if (!CGF.HaveInsertPoint())
7270 return;
7271
Samuel Antaocc10b852016-07-28 14:23:26 +00007272 // Action used to replace the default codegen action and turn privatization
7273 // off.
7274 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007275
7276 // Generate the code for the opening of the data environment. Capture all the
7277 // arguments of the runtime call by reference because they are used in the
7278 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007279 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7280 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007281 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007282 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007283 MappableExprsHandler::MapValuesArrayTy Pointers;
7284 MappableExprsHandler::MapValuesArrayTy Sizes;
7285 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7286
7287 // Get map clause information.
7288 MappableExprsHandler MCHandler(D, CGF);
7289 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007290
7291 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007292 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007293
7294 llvm::Value *BasePointersArrayArg = nullptr;
7295 llvm::Value *PointersArrayArg = nullptr;
7296 llvm::Value *SizesArrayArg = nullptr;
7297 llvm::Value *MapTypesArrayArg = nullptr;
7298 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007299 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007300
7301 // Emit device ID if any.
7302 llvm::Value *DeviceID = nullptr;
7303 if (Device)
7304 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7305 CGF.Int32Ty, /*isSigned=*/true);
7306 else
7307 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7308
7309 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007310 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007311
7312 llvm::Value *OffloadingArgs[] = {
7313 DeviceID, PointerNum, BasePointersArrayArg,
7314 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7315 auto &RT = CGF.CGM.getOpenMPRuntime();
7316 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7317 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007318
7319 // If device pointer privatization is required, emit the body of the region
7320 // here. It will have to be duplicated: with and without privatization.
7321 if (!Info.CaptureDeviceAddrMap.empty())
7322 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007323 };
7324
7325 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007326 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007327 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007328
7329 llvm::Value *BasePointersArrayArg = nullptr;
7330 llvm::Value *PointersArrayArg = nullptr;
7331 llvm::Value *SizesArrayArg = nullptr;
7332 llvm::Value *MapTypesArrayArg = nullptr;
7333 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007334 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007335
7336 // Emit device ID if any.
7337 llvm::Value *DeviceID = nullptr;
7338 if (Device)
7339 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7340 CGF.Int32Ty, /*isSigned=*/true);
7341 else
7342 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7343
7344 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007345 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007346
7347 llvm::Value *OffloadingArgs[] = {
7348 DeviceID, PointerNum, BasePointersArrayArg,
7349 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7350 auto &RT = CGF.CGM.getOpenMPRuntime();
7351 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7352 OffloadingArgs);
7353 };
7354
Samuel Antaocc10b852016-07-28 14:23:26 +00007355 // If we need device pointer privatization, we need to emit the body of the
7356 // region with no privatization in the 'else' branch of the conditional.
7357 // Otherwise, we don't have to do anything.
7358 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7359 PrePostActionTy &) {
7360 if (!Info.CaptureDeviceAddrMap.empty()) {
7361 CodeGen.setAction(NoPrivAction);
7362 CodeGen(CGF);
7363 }
7364 };
7365
7366 // We don't have to do anything to close the region if the if clause evaluates
7367 // to false.
7368 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007369
7370 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007371 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007372 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007373 RegionCodeGenTy RCG(BeginThenGen);
7374 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007375 }
7376
Samuel Antaocc10b852016-07-28 14:23:26 +00007377 // If we don't require privatization of device pointers, we emit the body in
7378 // between the runtime calls. This avoids duplicating the body code.
7379 if (Info.CaptureDeviceAddrMap.empty()) {
7380 CodeGen.setAction(NoPrivAction);
7381 CodeGen(CGF);
7382 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007383
7384 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007385 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007386 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007387 RegionCodeGenTy RCG(EndThenGen);
7388 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007389 }
7390}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007391
Samuel Antao8d2d7302016-05-26 18:30:22 +00007392void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007393 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7394 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007395 if (!CGF.HaveInsertPoint())
7396 return;
7397
Samuel Antao8dd66282016-04-27 23:14:30 +00007398 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007399 isa<OMPTargetExitDataDirective>(D) ||
7400 isa<OMPTargetUpdateDirective>(D)) &&
7401 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007402
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007403 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007404 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007405 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007406 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007407 MappableExprsHandler::MapValuesArrayTy Pointers;
7408 MappableExprsHandler::MapValuesArrayTy Sizes;
7409 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7410
7411 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007412 MappableExprsHandler MEHandler(D, CGF);
7413 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007414
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007415 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007416 TargetDataInfo Info;
7417 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7418 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7419 Info.PointersArray, Info.SizesArray,
7420 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007421
7422 // Emit device ID if any.
7423 llvm::Value *DeviceID = nullptr;
7424 if (Device)
7425 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7426 CGF.Int32Ty, /*isSigned=*/true);
7427 else
7428 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7429
7430 // Emit the number of elements in the offloading arrays.
7431 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7432
7433 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007434 DeviceID, PointerNum, Info.BasePointersArray,
7435 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007436
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007437 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007438 // Select the right runtime function call for each expected standalone
7439 // directive.
7440 OpenMPRTLFunction RTLFn;
7441 switch (D.getDirectiveKind()) {
7442 default:
7443 llvm_unreachable("Unexpected standalone target data directive.");
7444 break;
7445 case OMPD_target_enter_data:
7446 RTLFn = OMPRTL__tgt_target_data_begin;
7447 break;
7448 case OMPD_target_exit_data:
7449 RTLFn = OMPRTL__tgt_target_data_end;
7450 break;
7451 case OMPD_target_update:
7452 RTLFn = OMPRTL__tgt_target_data_update;
7453 break;
7454 }
7455 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007456 };
7457
7458 // In the event we get an if clause, we don't have to take any action on the
7459 // else side.
7460 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7461
7462 if (IfCond) {
7463 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7464 } else {
7465 RegionCodeGenTy ThenGenRCG(ThenGen);
7466 ThenGenRCG(CGF);
7467 }
7468}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007469
7470namespace {
7471 /// Kind of parameter in a function with 'declare simd' directive.
7472 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7473 /// Attribute set of the parameter.
7474 struct ParamAttrTy {
7475 ParamKindTy Kind = Vector;
7476 llvm::APSInt StrideOrArg;
7477 llvm::APSInt Alignment;
7478 };
7479} // namespace
7480
7481static unsigned evaluateCDTSize(const FunctionDecl *FD,
7482 ArrayRef<ParamAttrTy> ParamAttrs) {
7483 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7484 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7485 // of that clause. The VLEN value must be power of 2.
7486 // In other case the notion of the function`s "characteristic data type" (CDT)
7487 // is used to compute the vector length.
7488 // CDT is defined in the following order:
7489 // a) For non-void function, the CDT is the return type.
7490 // b) If the function has any non-uniform, non-linear parameters, then the
7491 // CDT is the type of the first such parameter.
7492 // c) If the CDT determined by a) or b) above is struct, union, or class
7493 // type which is pass-by-value (except for the type that maps to the
7494 // built-in complex data type), the characteristic data type is int.
7495 // d) If none of the above three cases is applicable, the CDT is int.
7496 // The VLEN is then determined based on the CDT and the size of vector
7497 // register of that ISA for which current vector version is generated. The
7498 // VLEN is computed using the formula below:
7499 // VLEN = sizeof(vector_register) / sizeof(CDT),
7500 // where vector register size specified in section 3.2.1 Registers and the
7501 // Stack Frame of original AMD64 ABI document.
7502 QualType RetType = FD->getReturnType();
7503 if (RetType.isNull())
7504 return 0;
7505 ASTContext &C = FD->getASTContext();
7506 QualType CDT;
7507 if (!RetType.isNull() && !RetType->isVoidType())
7508 CDT = RetType;
7509 else {
7510 unsigned Offset = 0;
7511 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7512 if (ParamAttrs[Offset].Kind == Vector)
7513 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7514 ++Offset;
7515 }
7516 if (CDT.isNull()) {
7517 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7518 if (ParamAttrs[I + Offset].Kind == Vector) {
7519 CDT = FD->getParamDecl(I)->getType();
7520 break;
7521 }
7522 }
7523 }
7524 }
7525 if (CDT.isNull())
7526 CDT = C.IntTy;
7527 CDT = CDT->getCanonicalTypeUnqualified();
7528 if (CDT->isRecordType() || CDT->isUnionType())
7529 CDT = C.IntTy;
7530 return C.getTypeSize(CDT);
7531}
7532
7533static void
7534emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007535 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007536 ArrayRef<ParamAttrTy> ParamAttrs,
7537 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7538 struct ISADataTy {
7539 char ISA;
7540 unsigned VecRegSize;
7541 };
7542 ISADataTy ISAData[] = {
7543 {
7544 'b', 128
7545 }, // SSE
7546 {
7547 'c', 256
7548 }, // AVX
7549 {
7550 'd', 256
7551 }, // AVX2
7552 {
7553 'e', 512
7554 }, // AVX512
7555 };
7556 llvm::SmallVector<char, 2> Masked;
7557 switch (State) {
7558 case OMPDeclareSimdDeclAttr::BS_Undefined:
7559 Masked.push_back('N');
7560 Masked.push_back('M');
7561 break;
7562 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7563 Masked.push_back('N');
7564 break;
7565 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7566 Masked.push_back('M');
7567 break;
7568 }
7569 for (auto Mask : Masked) {
7570 for (auto &Data : ISAData) {
7571 SmallString<256> Buffer;
7572 llvm::raw_svector_ostream Out(Buffer);
7573 Out << "_ZGV" << Data.ISA << Mask;
7574 if (!VLENVal) {
7575 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7576 evaluateCDTSize(FD, ParamAttrs));
7577 } else
7578 Out << VLENVal;
7579 for (auto &ParamAttr : ParamAttrs) {
7580 switch (ParamAttr.Kind){
7581 case LinearWithVarStride:
7582 Out << 's' << ParamAttr.StrideOrArg;
7583 break;
7584 case Linear:
7585 Out << 'l';
7586 if (!!ParamAttr.StrideOrArg)
7587 Out << ParamAttr.StrideOrArg;
7588 break;
7589 case Uniform:
7590 Out << 'u';
7591 break;
7592 case Vector:
7593 Out << 'v';
7594 break;
7595 }
7596 if (!!ParamAttr.Alignment)
7597 Out << 'a' << ParamAttr.Alignment;
7598 }
7599 Out << '_' << Fn->getName();
7600 Fn->addFnAttr(Out.str());
7601 }
7602 }
7603}
7604
7605void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7606 llvm::Function *Fn) {
7607 ASTContext &C = CGM.getContext();
7608 FD = FD->getCanonicalDecl();
7609 // Map params to their positions in function decl.
7610 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7611 if (isa<CXXMethodDecl>(FD))
7612 ParamPositions.insert({FD, 0});
7613 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007614 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007615 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7616 ++ParamPos;
7617 }
7618 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7619 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7620 // Mark uniform parameters.
7621 for (auto *E : Attr->uniforms()) {
7622 E = E->IgnoreParenImpCasts();
7623 unsigned Pos;
7624 if (isa<CXXThisExpr>(E))
7625 Pos = ParamPositions[FD];
7626 else {
7627 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7628 ->getCanonicalDecl();
7629 Pos = ParamPositions[PVD];
7630 }
7631 ParamAttrs[Pos].Kind = Uniform;
7632 }
7633 // Get alignment info.
7634 auto NI = Attr->alignments_begin();
7635 for (auto *E : Attr->aligneds()) {
7636 E = E->IgnoreParenImpCasts();
7637 unsigned Pos;
7638 QualType ParmTy;
7639 if (isa<CXXThisExpr>(E)) {
7640 Pos = ParamPositions[FD];
7641 ParmTy = E->getType();
7642 } else {
7643 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7644 ->getCanonicalDecl();
7645 Pos = ParamPositions[PVD];
7646 ParmTy = PVD->getType();
7647 }
7648 ParamAttrs[Pos].Alignment =
7649 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7650 : llvm::APSInt::getUnsigned(
7651 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7652 .getQuantity());
7653 ++NI;
7654 }
7655 // Mark linear parameters.
7656 auto SI = Attr->steps_begin();
7657 auto MI = Attr->modifiers_begin();
7658 for (auto *E : Attr->linears()) {
7659 E = E->IgnoreParenImpCasts();
7660 unsigned Pos;
7661 if (isa<CXXThisExpr>(E))
7662 Pos = ParamPositions[FD];
7663 else {
7664 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7665 ->getCanonicalDecl();
7666 Pos = ParamPositions[PVD];
7667 }
7668 auto &ParamAttr = ParamAttrs[Pos];
7669 ParamAttr.Kind = Linear;
7670 if (*SI) {
7671 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7672 Expr::SE_AllowSideEffects)) {
7673 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7674 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7675 ParamAttr.Kind = LinearWithVarStride;
7676 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7677 ParamPositions[StridePVD->getCanonicalDecl()]);
7678 }
7679 }
7680 }
7681 }
7682 ++SI;
7683 ++MI;
7684 }
7685 llvm::APSInt VLENVal;
7686 if (const Expr *VLEN = Attr->getSimdlen())
7687 VLENVal = VLEN->EvaluateKnownConstInt(C);
7688 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7689 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7690 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7691 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7692 }
7693}
Alexey Bataev8b427062016-05-25 12:36:08 +00007694
7695namespace {
7696/// Cleanup action for doacross support.
7697class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7698public:
7699 static const int DoacrossFinArgs = 2;
7700
7701private:
7702 llvm::Value *RTLFn;
7703 llvm::Value *Args[DoacrossFinArgs];
7704
7705public:
7706 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7707 : RTLFn(RTLFn) {
7708 assert(CallArgs.size() == DoacrossFinArgs);
7709 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7710 }
7711 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7712 if (!CGF.HaveInsertPoint())
7713 return;
7714 CGF.EmitRuntimeCall(RTLFn, Args);
7715 }
7716};
7717} // namespace
7718
7719void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7720 const OMPLoopDirective &D) {
7721 if (!CGF.HaveInsertPoint())
7722 return;
7723
7724 ASTContext &C = CGM.getContext();
7725 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7726 RecordDecl *RD;
7727 if (KmpDimTy.isNull()) {
7728 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7729 // kmp_int64 lo; // lower
7730 // kmp_int64 up; // upper
7731 // kmp_int64 st; // stride
7732 // };
7733 RD = C.buildImplicitRecord("kmp_dim");
7734 RD->startDefinition();
7735 addFieldToRecordDecl(C, RD, Int64Ty);
7736 addFieldToRecordDecl(C, RD, Int64Ty);
7737 addFieldToRecordDecl(C, RD, Int64Ty);
7738 RD->completeDefinition();
7739 KmpDimTy = C.getRecordType(RD);
7740 } else
7741 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7742
7743 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7744 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7745 enum { LowerFD = 0, UpperFD, StrideFD };
7746 // Fill dims with data.
7747 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7748 // dims.upper = num_iterations;
7749 LValue UpperLVal =
7750 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7751 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7752 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7753 Int64Ty, D.getNumIterations()->getExprLoc());
7754 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7755 // dims.stride = 1;
7756 LValue StrideLVal =
7757 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7758 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7759 StrideLVal);
7760
7761 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7762 // kmp_int32 num_dims, struct kmp_dim * dims);
7763 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7764 getThreadID(CGF, D.getLocStart()),
7765 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7766 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7767 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7768
7769 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7770 CGF.EmitRuntimeCall(RTLFn, Args);
7771 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7772 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7773 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7774 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7775 llvm::makeArrayRef(FiniArgs));
7776}
7777
7778void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7779 const OMPDependClause *C) {
7780 QualType Int64Ty =
7781 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7782 const Expr *CounterVal = C->getCounterValue();
7783 assert(CounterVal);
7784 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7785 CounterVal->getType(), Int64Ty,
7786 CounterVal->getExprLoc());
7787 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7788 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7789 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7790 getThreadID(CGF, C->getLocStart()),
7791 CntAddr.getPointer()};
7792 llvm::Value *RTLFn;
7793 if (C->getDependencyKind() == OMPC_DEPEND_source)
7794 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7795 else {
7796 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7797 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7798 }
7799 CGF.EmitRuntimeCall(RTLFn, Args);
7800}
7801
Alexey Bataev3c595a62017-08-14 15:01:03 +00007802void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7803 ArrayRef<llvm::Value *> Args,
7804 SourceLocation Loc) const {
7805 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7806
7807 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007808 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007809 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007810 return;
7811 }
7812 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007813 CGF.EmitRuntimeCall(Callee, Args);
7814}
7815
7816void CGOpenMPRuntime::emitOutlinedFunctionCall(
7817 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7818 ArrayRef<llvm::Value *> Args) const {
7819 assert(Loc.isValid() && "Outlined function call location must be valid.");
7820 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007821}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007822
7823Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7824 const VarDecl *NativeParam,
7825 const VarDecl *TargetParam) const {
7826 return CGF.GetAddrOfLocalVar(NativeParam);
7827}